1 //===-- lldb-gdbserver.cpp --------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
23 #include "LLDBServerUtilities.h"
24 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
25 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
26 #include "lldb/Core/PluginManager.h"
27 #include "lldb/Host/ConnectionFileDescriptor.h"
28 #include "lldb/Host/FileSystem.h"
29 #include "lldb/Host/HostGetOpt.h"
30 #include "lldb/Host/OptionParser.h"
31 #include "lldb/Host/Pipe.h"
32 #include "lldb/Host/Socket.h"
33 #include "lldb/Host/StringConvert.h"
34 #include "lldb/Host/common/NativeProcessProtocol.h"
35 #include "lldb/Utility/Status.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/Support/Errno.h"
39 #if defined(__linux__)
40 #include "Plugins/Process/Linux/NativeProcessLinux.h"
41 #elif defined(__NetBSD__)
42 #include "Plugins/Process/NetBSD/NativeProcessNetBSD.h"
45 #ifndef LLGS_PROGRAM_NAME
46 #define LLGS_PROGRAM_NAME "lldb-server"
49 #ifndef LLGS_VERSION_STR
50 #define LLGS_VERSION_STR "local_build"
55 using namespace lldb_private;
56 using namespace lldb_private::lldb_server;
57 using namespace lldb_private::process_gdb_remote;
60 #if defined(__linux__)
61 typedef process_linux::NativeProcessLinux::Factory NativeProcessFactory;
62 #elif defined(__NetBSD__)
63 typedef process_netbsd::NativeProcessNetBSD::Factory NativeProcessFactory;
65 // Dummy implementation to make sure the code compiles
66 class NativeProcessFactory : public NativeProcessProtocol::Factory {
68 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
69 Launch(ProcessLaunchInfo &launch_info,
70 NativeProcessProtocol::NativeDelegate &delegate,
71 MainLoop &mainloop) const override {
72 llvm_unreachable("Not implemented");
74 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
75 Attach(lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &delegate,
76 MainLoop &mainloop) const override {
77 llvm_unreachable("Not implemented");
83 //----------------------------------------------------------------------
84 // option descriptors for getopt_long_only()
85 //----------------------------------------------------------------------
87 static int g_debug = 0;
88 static int g_verbose = 0;
90 static struct option g_long_options[] = {
91 {"debug", no_argument, &g_debug, 1},
92 {"verbose", no_argument, &g_verbose, 1},
93 {"log-file", required_argument, NULL, 'l'},
94 {"log-channels", required_argument, NULL, 'c'},
95 {"attach", required_argument, NULL, 'a'},
96 {"named-pipe", required_argument, NULL, 'N'},
97 {"pipe", required_argument, NULL, 'U'},
98 {"native-regs", no_argument, NULL,
99 'r'}, // Specify to use the native registers instead of the gdb defaults
100 // for the architecture. NOTE: this is a do-nothing arg as it's
101 // behavior is default now. FIXME remove call from lldb-platform.
102 {"reverse-connect", no_argument, NULL,
103 'R'}, // Specifies that llgs attaches to the client address:port rather
104 // than llgs listening for a connection from address on port.
105 {"setsid", no_argument, NULL,
106 'S'}, // Call setsid() to make llgs run in its own session.
107 {"fd", required_argument, NULL, 'F'},
110 //----------------------------------------------------------------------
112 //----------------------------------------------------------------------
113 static int g_sighup_received_count = 0;
116 static void sighup_handler(MainLoopBase &mainloop) {
117 ++g_sighup_received_count;
119 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
121 log->Printf("lldb-server:%s swallowing SIGHUP (receive count=%d)",
122 __FUNCTION__, g_sighup_received_count);
124 if (g_sighup_received_count >= 2)
125 mainloop.RequestTermination();
127 #endif // #ifndef _WIN32
129 static void display_usage(const char *progname, const char *subcommand) {
130 fprintf(stderr, "Usage:\n %s %s "
131 "[--log-file log-file-name] "
132 "[--log-channels log-channel-list] "
134 "[--fd file-descriptor]"
135 "[--named-pipe named-pipe-path] "
139 "[-- PROGRAM ARG1 ARG2 ...]\n",
140 progname, subcommand);
143 void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS &gdb_server,
145 Status error = gdb_server.AttachToProcess(pid);
147 fprintf(stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid,
153 void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS &gdb_server,
154 const std::string &process_name) {
158 void handle_attach(GDBRemoteCommunicationServerLLGS &gdb_server,
159 const std::string &attach_target) {
160 assert(!attach_target.empty() && "attach_target cannot be empty");
162 // First check if the attach_target is convertible to a long. If so, we'll use
164 char *end_p = nullptr;
165 const long int pid = strtol(attach_target.c_str(), &end_p, 10);
167 // We'll call it a match if the entire argument is consumed.
169 static_cast<size_t>(end_p - attach_target.c_str()) ==
170 attach_target.size())
171 handle_attach_to_pid(gdb_server, static_cast<lldb::pid_t>(pid));
173 handle_attach_to_process_name(gdb_server, attach_target);
176 void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server, int argc,
177 const char *const argv[]) {
178 ProcessLaunchInfo info;
179 info.GetFlags().Set(eLaunchFlagStopAtEntry | eLaunchFlagDebug |
180 eLaunchFlagDisableASLR);
181 info.SetArguments(const_cast<const char **>(argv), true);
183 llvm::SmallString<64> cwd;
184 if (std::error_code ec = llvm::sys::fs::current_path(cwd)) {
185 llvm::errs() << "Error getting current directory: " << ec.message() << "\n";
188 FileSpec cwd_spec(cwd);
189 FileSystem::Instance().Resolve(cwd_spec);
190 info.SetWorkingDirectory(cwd_spec);
191 info.GetEnvironment() = Host::GetEnvironment();
193 gdb_server.SetLaunchInfo(info);
195 Status error = gdb_server.LaunchProcess();
197 llvm::errs() << llvm::formatv("error: failed to launch '{0}': {1}\n",
203 Status writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id) {
204 size_t bytes_written = 0;
205 // Write the port number as a C string with the NULL terminator.
206 return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1,
210 Status writeSocketIdToPipe(const char *const named_pipe_path,
211 const std::string &socket_id) {
213 // Wait for 10 seconds for pipe to be opened.
214 auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
215 std::chrono::seconds{10});
218 return writeSocketIdToPipe(port_name_pipe, socket_id);
221 Status writeSocketIdToPipe(lldb::pipe_t unnamed_pipe,
222 const std::string &socket_id) {
223 Pipe port_pipe{LLDB_INVALID_PIPE, unnamed_pipe};
224 return writeSocketIdToPipe(port_pipe, socket_id);
227 void ConnectToRemote(MainLoop &mainloop,
228 GDBRemoteCommunicationServerLLGS &gdb_server,
229 bool reverse_connect, const char *const host_and_port,
230 const char *const progname, const char *const subcommand,
231 const char *const named_pipe_path, pipe_t unnamed_pipe,
235 std::unique_ptr<Connection> connection_up;
236 if (connection_fd != -1) {
237 // Build the connection string.
238 char connection_url[512];
239 snprintf(connection_url, sizeof(connection_url), "fd://%d", connection_fd);
241 // Create the connection.
242 #if !defined LLDB_DISABLE_POSIX && !defined _WIN32
243 ::fcntl(connection_fd, F_SETFD, FD_CLOEXEC);
245 connection_up.reset(new ConnectionFileDescriptor);
246 auto connection_result = connection_up->Connect(connection_url, &error);
247 if (connection_result != eConnectionStatusSuccess) {
248 fprintf(stderr, "error: failed to connect to client at '%s' "
249 "(connection status: %d)\n",
250 connection_url, static_cast<int>(connection_result));
254 fprintf(stderr, "error: failed to connect to client at '%s': %s\n",
255 connection_url, error.AsCString());
258 } else if (host_and_port && host_and_port[0]) {
259 // Parse out host and port.
260 std::string final_host_and_port;
261 std::string connection_host;
262 std::string connection_port;
263 uint32_t connection_portno = 0;
265 // If host_and_port starts with ':', default the host to be "localhost" and
266 // expect the remainder to be the port.
267 if (host_and_port[0] == ':')
268 final_host_and_port.append("localhost");
269 final_host_and_port.append(host_and_port);
271 const std::string::size_type colon_pos = final_host_and_port.find(':');
272 if (colon_pos != std::string::npos) {
273 connection_host = final_host_and_port.substr(0, colon_pos);
274 connection_port = final_host_and_port.substr(colon_pos + 1);
275 connection_portno = StringConvert::ToUInt32(connection_port.c_str(), 0);
279 if (reverse_connect) {
280 // llgs will connect to the gdb-remote client.
282 // Ensure we have a port number for the connection.
283 if (connection_portno == 0) {
284 fprintf(stderr, "error: port number must be specified on when using "
285 "reverse connect\n");
289 // Build the connection string.
290 char connection_url[512];
291 snprintf(connection_url, sizeof(connection_url), "connect://%s",
292 final_host_and_port.c_str());
294 // Create the connection.
295 connection_up.reset(new ConnectionFileDescriptor);
296 auto connection_result = connection_up->Connect(connection_url, &error);
297 if (connection_result != eConnectionStatusSuccess) {
298 fprintf(stderr, "error: failed to connect to client at '%s' "
299 "(connection status: %d)\n",
300 connection_url, static_cast<int>(connection_result));
304 fprintf(stderr, "error: failed to connect to client at '%s': %s\n",
305 connection_url, error.AsCString());
309 std::unique_ptr<Acceptor> acceptor_up(
310 Acceptor::Create(final_host_and_port, false, error));
312 fprintf(stderr, "failed to create acceptor: %s\n", error.AsCString());
315 error = acceptor_up->Listen(1);
317 fprintf(stderr, "failed to listen: %s\n", error.AsCString());
320 const std::string socket_id = acceptor_up->GetLocalSocketId();
321 if (!socket_id.empty()) {
322 // If we have a named pipe to write the socket id back to, do that now.
323 if (named_pipe_path && named_pipe_path[0]) {
324 error = writeSocketIdToPipe(named_pipe_path, socket_id);
326 fprintf(stderr, "failed to write to the named pipe \'%s\': %s\n",
327 named_pipe_path, error.AsCString());
329 // If we have an unnamed pipe to write the socket id back to, do that
331 else if (unnamed_pipe != LLDB_INVALID_PIPE) {
332 error = writeSocketIdToPipe(unnamed_pipe, socket_id);
334 fprintf(stderr, "failed to write to the unnamed pipe: %s\n",
339 "unable to get the socket id for the listening connection\n");
342 Connection *conn = nullptr;
343 error = acceptor_up->Accept(false, conn);
345 printf("failed to accept new connection: %s\n", error.AsCString());
348 connection_up.reset(conn);
351 error = gdb_server.InitializeConnection(std::move(connection_up));
353 fprintf(stderr, "Failed to initialize connection: %s\n",
357 printf("Connection established.\n");
360 //----------------------------------------------------------------------
362 //----------------------------------------------------------------------
363 int main_gdbserver(int argc, char *argv[]) {
367 // Setup signal handlers first thing.
368 signal(SIGPIPE, SIG_IGN);
369 MainLoop::SignalHandleUP sighup_handle =
370 mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
373 const char *progname = argv[0];
374 const char *subcommand = argv[1];
377 int long_option_index = 0;
379 std::string attach_target;
380 std::string named_pipe_path;
381 std::string log_file;
383 log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
384 lldb::pipe_t unnamed_pipe = LLDB_INVALID_PIPE;
385 bool reverse_connect = false;
386 int connection_fd = -1;
388 // ProcessLaunchInfo launch_info;
389 ProcessAttachInfo attach_info;
391 bool show_usage = false;
392 int option_error = 0;
400 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
402 while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
403 g_long_options, &long_option_index)) != -1) {
405 case 0: // Any optional that auto set themselves will return 0
408 case 'l': // Set Log File
409 if (optarg && optarg[0])
410 log_file.assign(optarg);
413 case 'c': // Log Channels
414 if (optarg && optarg[0])
415 log_channels = StringRef(optarg);
418 case 'N': // named pipe
419 if (optarg && optarg[0])
420 named_pipe_path = optarg;
423 case 'U': // unnamed pipe
424 if (optarg && optarg[0])
425 unnamed_pipe = (pipe_t)StringConvert::ToUInt64(optarg, -1);
429 // Do nothing, native regs is the default these days
433 reverse_connect = true;
437 connection_fd = StringConvert::ToUInt32(optarg, -1);
442 // Put llgs into a new session. Terminals group processes
443 // into sessions and when a special terminal key sequences
444 // (like control+c) are typed they can cause signals to go out to
445 // all processes in a session. Using this --setsid (-S) option
446 // will cause debugserver to run in its own sessions and be free
449 // This is useful when llgs is spawned from a command
450 // line application that uses llgs to do the debugging,
451 // yet that application doesn't want llgs receiving the
452 // signals sent to the session (i.e. dying when anyone hits ^C).
454 const ::pid_t new_sid = setsid();
456 llvm::errs() << llvm::formatv(
457 "failed to set new session id for {0} ({1})\n", LLGS_PROGRAM_NAME,
458 llvm::sys::StrError());
464 case 'a': // attach {pid|process_name}
465 if (optarg && optarg[0])
466 attach_target = optarg;
469 case 'h': /* fall-through is intentional */
476 if (show_usage || option_error) {
477 display_usage(progname, subcommand);
481 if (!LLDBServerUtilities::SetupLogging(
482 log_file, log_channels,
483 LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
484 LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION))
487 Log *log(lldb_private::GetLogIfAnyCategoriesSet(GDBR_LOG_PROCESS));
489 log->Printf("lldb-server launch");
490 for (int i = 0; i < argc; i++) {
491 log->Printf("argv[%i] = '%s'", i, argv[i]);
495 // Skip any options we consumed with getopt_long_only.
499 if (argc == 0 && connection_fd == -1) {
500 fputs("No arguments\n", stderr);
501 display_usage(progname, subcommand);
505 NativeProcessFactory factory;
506 GDBRemoteCommunicationServerLLGS gdb_server(mainloop, factory);
508 const char *const host_and_port = argv[0];
512 // Any arguments left over are for the program that we need to launch. If
514 // are no arguments, then the GDB server will start up and wait for an 'A'
516 // to launch a program, or a vAttach packet to attach to an existing process,
518 // explicitly asked to attach with the --attach={pid|program_name} form.
519 if (!attach_target.empty())
520 handle_attach(gdb_server, attach_target);
522 handle_launch(gdb_server, argc, argv);
524 // Print version info.
525 printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
527 ConnectToRemote(mainloop, gdb_server, reverse_connect, host_and_port,
528 progname, subcommand, named_pipe_path.c_str(),
529 unnamed_pipe, connection_fd);
531 if (!gdb_server.IsConnected()) {
532 fprintf(stderr, "no connection information provided, unable to run\n");
533 display_usage(progname, subcommand);
538 fprintf(stderr, "lldb-server exiting...\n");