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 //===----------------------------------------------------------------------===//
24 // Other libraries and framework includes
25 #include "llvm/ADT/StringRef.h"
27 #include "lldb/Core/Error.h"
28 #include "lldb/Core/PluginManager.h"
29 #include "lldb/Host/ConnectionFileDescriptor.h"
30 #include "lldb/Host/HostGetOpt.h"
31 #include "lldb/Host/OptionParser.h"
32 #include "lldb/Host/Pipe.h"
33 #include "lldb/Host/Socket.h"
34 #include "lldb/Host/StringConvert.h"
36 #include "LLDBServerUtilities.h"
37 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
38 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
40 #ifndef LLGS_PROGRAM_NAME
41 #define LLGS_PROGRAM_NAME "lldb-server"
44 #ifndef LLGS_VERSION_STR
45 #define LLGS_VERSION_STR "local_build"
50 using namespace lldb_private;
51 using namespace lldb_private::lldb_server;
52 using namespace lldb_private::process_gdb_remote;
54 //----------------------------------------------------------------------
55 // option descriptors for getopt_long_only()
56 //----------------------------------------------------------------------
58 static int g_debug = 0;
59 static int g_verbose = 0;
61 static struct option g_long_options[] =
63 { "debug", no_argument, &g_debug, 1 },
64 { "verbose", no_argument, &g_verbose, 1 },
65 { "log-file", required_argument, NULL, 'l' },
66 { "log-channels", required_argument, NULL, 'c' },
67 { "attach", required_argument, NULL, 'a' },
68 { "named-pipe", required_argument, NULL, 'N' },
69 { "pipe", required_argument, NULL, 'U' },
70 { "native-regs", no_argument, NULL, 'r' }, // Specify to use the native registers instead of the gdb defaults for the architecture. NOTE: this is a do-nothing arg as it's behavior is default now. FIXME remove call from lldb-platform.
71 { "reverse-connect", no_argument, NULL, 'R' }, // Specifies that llgs attaches to the client address:port rather than llgs listening for a connection from address on port.
72 { "setsid", no_argument, NULL, 'S' }, // Call setsid() to make llgs run in its own session.
77 //----------------------------------------------------------------------
79 //----------------------------------------------------------------------
80 static int g_sighup_received_count = 0;
84 sighup_handler(MainLoopBase &mainloop)
86 ++g_sighup_received_count;
88 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
90 log->Printf ("lldb-server:%s swallowing SIGHUP (receive count=%d)", __FUNCTION__, g_sighup_received_count);
92 if (g_sighup_received_count >= 2)
93 mainloop.RequestTermination();
95 #endif // #ifndef _WIN32
98 display_usage (const char *progname, const char* subcommand)
100 fprintf(stderr, "Usage:\n %s %s "
101 "[--log-file log-file-name] "
102 "[--log-channels log-channel-list] "
104 "[--named-pipe named-pipe-path] "
108 "[-- PROGRAM ARG1 ARG2 ...]\n", progname, subcommand);
113 handle_attach_to_pid (GDBRemoteCommunicationServerLLGS &gdb_server, lldb::pid_t pid)
115 Error error = gdb_server.AttachToProcess (pid);
118 fprintf (stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid, error.AsCString());
124 handle_attach_to_process_name (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &process_name)
130 handle_attach (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &attach_target)
132 assert (!attach_target.empty () && "attach_target cannot be empty");
134 // First check if the attach_target is convertible to a long. If so, we'll use it as a pid.
135 char *end_p = nullptr;
136 const long int pid = strtol (attach_target.c_str (), &end_p, 10);
138 // We'll call it a match if the entire argument is consumed.
139 if (end_p && static_cast<size_t> (end_p - attach_target.c_str ()) == attach_target.size ())
140 handle_attach_to_pid (gdb_server, static_cast<lldb::pid_t> (pid));
142 handle_attach_to_process_name (gdb_server, attach_target);
146 handle_launch (GDBRemoteCommunicationServerLLGS &gdb_server, int argc, const char *const argv[])
149 error = gdb_server.SetLaunchArguments (argv, argc);
152 fprintf (stderr, "error: failed to set launch args for '%s': %s\n", argv[0], error.AsCString());
156 unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
158 error = gdb_server.SetLaunchFlags (launch_flags);
161 fprintf (stderr, "error: failed to set launch flags for '%s': %s\n", argv[0], error.AsCString());
165 error = gdb_server.LaunchProcess ();
168 fprintf (stderr, "error: failed to launch '%s': %s\n", argv[0], error.AsCString());
174 writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id)
176 size_t bytes_written = 0;
177 // Write the port number as a C string with the NULL terminator.
178 return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1, bytes_written);
182 writeSocketIdToPipe(const char *const named_pipe_path, const std::string &socket_id)
185 // Wait for 10 seconds for pipe to be opened.
186 auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
187 std::chrono::seconds{10});
190 return writeSocketIdToPipe(port_name_pipe, socket_id);
194 writeSocketIdToPipe(int unnamed_pipe_fd, const std::string &socket_id)
197 return Error("Unnamed pipes are not supported on Windows.");
199 Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
200 return writeSocketIdToPipe(port_pipe, socket_id);
205 ConnectToRemote(MainLoop &mainloop, GDBRemoteCommunicationServerLLGS &gdb_server,
206 bool reverse_connect, const char *const host_and_port,
207 const char *const progname, const char *const subcommand,
208 const char *const named_pipe_path, int unnamed_pipe_fd)
212 if (host_and_port && host_and_port[0])
214 // Parse out host and port.
215 std::string final_host_and_port;
216 std::string connection_host;
217 std::string connection_port;
218 uint32_t connection_portno = 0;
220 // If host_and_port starts with ':', default the host to be "localhost" and expect the remainder to be the port.
221 if (host_and_port[0] == ':')
222 final_host_and_port.append ("localhost");
223 final_host_and_port.append (host_and_port);
225 const std::string::size_type colon_pos = final_host_and_port.find (':');
226 if (colon_pos != std::string::npos)
228 connection_host = final_host_and_port.substr (0, colon_pos);
229 connection_port = final_host_and_port.substr (colon_pos + 1);
230 connection_portno = StringConvert::ToUInt32 (connection_port.c_str (), 0);
233 std::unique_ptr<Connection> connection_up;
237 // llgs will connect to the gdb-remote client.
239 // Ensure we have a port number for the connection.
240 if (connection_portno == 0)
242 fprintf (stderr, "error: port number must be specified on when using reverse connect");
246 // Build the connection string.
247 char connection_url[512];
248 snprintf(connection_url, sizeof(connection_url), "connect://%s", final_host_and_port.c_str ());
250 // Create the connection.
251 connection_up.reset(new ConnectionFileDescriptor);
252 auto connection_result = connection_up->Connect (connection_url, &error);
253 if (connection_result != eConnectionStatusSuccess)
255 fprintf (stderr, "error: failed to connect to client at '%s' (connection status: %d)", connection_url, static_cast<int> (connection_result));
260 fprintf (stderr, "error: failed to connect to client at '%s': %s", connection_url, error.AsCString ());
266 std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create(final_host_and_port, false, error));
269 fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
272 error = acceptor_up->Listen(1);
275 fprintf(stderr, "failed to listen: %s\n", error.AsCString());
278 const std::string socket_id = acceptor_up->GetLocalSocketId();
279 if (!socket_id.empty())
281 // If we have a named pipe to write the socket id back to, do that now.
282 if (named_pipe_path && named_pipe_path[0])
284 error = writeSocketIdToPipe (named_pipe_path, socket_id);
286 fprintf (stderr, "failed to write to the named pipe \'%s\': %s",
287 named_pipe_path, error.AsCString());
289 // If we have an unnamed pipe to write the socket id back to, do that now.
290 else if (unnamed_pipe_fd >= 0)
292 error = writeSocketIdToPipe(unnamed_pipe_fd, socket_id);
294 fprintf(stderr, "failed to write to the unnamed pipe: %s",
300 fprintf (stderr, "unable to get the socket id for the listening connection\n");
303 Connection* conn = nullptr;
304 error = acceptor_up->Accept(false, conn);
307 printf ("failed to accept new connection: %s\n", error.AsCString());
310 connection_up.reset(conn);
312 error = gdb_server.InitializeConnection (std::move(connection_up));
315 fprintf(stderr, "Failed to initialize connection: %s\n", error.AsCString());
318 printf ("Connection established.\n");
322 //----------------------------------------------------------------------
324 //----------------------------------------------------------------------
326 main_gdbserver (int argc, char *argv[])
331 // Setup signal handlers first thing.
332 signal(SIGPIPE, SIG_IGN);
333 MainLoop::SignalHandleUP sighup_handle = mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
336 const char *progname = argv[0];
337 const char *subcommand = argv[1];
340 int long_option_index = 0;
342 std::string attach_target;
343 std::string named_pipe_path;
344 std::string log_file;
345 StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
346 int unnamed_pipe_fd = -1;
347 bool reverse_connect = false;
349 // ProcessLaunchInfo launch_info;
350 ProcessAttachInfo attach_info;
352 bool show_usage = false;
353 int option_error = 0;
361 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
363 while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
367 case 0: // Any optional that auto set themselves will return 0
370 case 'l': // Set Log File
371 if (optarg && optarg[0])
372 log_file.assign(optarg);
375 case 'c': // Log Channels
376 if (optarg && optarg[0])
377 log_channels = StringRef(optarg);
380 case 'N': // named pipe
381 if (optarg && optarg[0])
382 named_pipe_path = optarg;
385 case 'U': // unnamed pipe
386 if (optarg && optarg[0])
387 unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
391 // Do nothing, native regs is the default these days
395 reverse_connect = true;
400 // Put llgs into a new session. Terminals group processes
401 // into sessions and when a special terminal key sequences
402 // (like control+c) are typed they can cause signals to go out to
403 // all processes in a session. Using this --setsid (-S) option
404 // will cause debugserver to run in its own sessions and be free
407 // This is useful when llgs is spawned from a command
408 // line application that uses llgs to do the debugging,
409 // yet that application doesn't want llgs receiving the
410 // signals sent to the session (i.e. dying when anyone hits ^C).
412 const ::pid_t new_sid = setsid();
415 const char *errno_str = strerror(errno);
416 fprintf (stderr, "failed to set new session id for %s (%s)\n", LLGS_PROGRAM_NAME, errno_str ? errno_str : "<no error string>");
422 case 'a': // attach {pid|process_name}
423 if (optarg && optarg[0])
424 attach_target = optarg;
427 case 'h': /* fall-through is intentional */
434 if (show_usage || option_error)
436 display_usage(progname, subcommand);
440 if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, LLDB_LOG_OPTION_PREPEND_TIMESTAMP))
443 Log *log(lldb_private::GetLogIfAnyCategoriesSet (GDBR_LOG_VERBOSE));
446 log->Printf ("lldb-server launch");
447 for (int i = 0; i < argc; i++)
449 log->Printf ("argv[%i] = '%s'", i, argv[i]);
453 // Skip any options we consumed with getopt_long_only.
459 display_usage(progname, subcommand);
463 GDBRemoteCommunicationServerLLGS gdb_server(mainloop);
465 const char *const host_and_port = argv[0];
469 // Any arguments left over are for the program that we need to launch. If there
470 // are no arguments, then the GDB server will start up and wait for an 'A' packet
471 // to launch a program, or a vAttach packet to attach to an existing process, unless
472 // explicitly asked to attach with the --attach={pid|program_name} form.
473 if (!attach_target.empty ())
474 handle_attach (gdb_server, attach_target);
476 handle_launch (gdb_server, argc, argv);
478 // Print version info.
479 printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
481 ConnectToRemote(mainloop, gdb_server, reverse_connect,
482 host_and_port, progname, subcommand,
483 named_pipe_path.c_str(), unnamed_pipe_fd);
486 if (! gdb_server.IsConnected())
488 fprintf (stderr, "no connection information provided, unable to run\n");
489 display_usage (progname, subcommand);
494 fprintf(stderr, "lldb-server exiting...\n");