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"
35 #include "lldb/Target/Platform.h"
37 #include "LLDBServerUtilities.h"
38 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
39 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
41 #ifndef LLGS_PROGRAM_NAME
42 #define LLGS_PROGRAM_NAME "lldb-server"
45 #ifndef LLGS_VERSION_STR
46 #define LLGS_VERSION_STR "local_build"
51 using namespace lldb_private;
52 using namespace lldb_private::lldb_server;
53 using namespace lldb_private::process_gdb_remote;
55 //----------------------------------------------------------------------
56 // option descriptors for getopt_long_only()
57 //----------------------------------------------------------------------
59 static int g_debug = 0;
60 static int g_verbose = 0;
62 static struct option g_long_options[] =
64 { "debug", no_argument, &g_debug, 1 },
65 { "platform", required_argument, NULL, 'p' },
66 { "verbose", no_argument, &g_verbose, 1 },
67 { "log-file", required_argument, NULL, 'l' },
68 { "log-channels", required_argument, NULL, 'c' },
69 { "attach", required_argument, NULL, 'a' },
70 { "named-pipe", required_argument, NULL, 'N' },
71 { "pipe", required_argument, NULL, 'U' },
72 { "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.
73 { "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.
74 { "setsid", no_argument, NULL, 'S' }, // Call setsid() to make llgs run in its own session.
79 //----------------------------------------------------------------------
81 //----------------------------------------------------------------------
82 static int g_sigpipe_received = 0;
83 static int g_sighup_received_count = 0;
88 signal_handler(int signo)
90 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
92 fprintf (stderr, "lldb-server:%s received signal %d\n", __FUNCTION__, signo);
94 log->Printf ("lldb-server:%s received signal %d", __FUNCTION__, signo);
99 g_sigpipe_received = 1;
105 sighup_handler(MainLoopBase &mainloop)
107 ++g_sighup_received_count;
109 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
111 log->Printf ("lldb-server:%s swallowing SIGHUP (receive count=%d)", __FUNCTION__, g_sighup_received_count);
113 if (g_sighup_received_count >= 2)
114 mainloop.RequestTermination();
116 #endif // #ifndef _WIN32
119 display_usage (const char *progname, const char* subcommand)
121 fprintf(stderr, "Usage:\n %s %s "
122 "[--log-file log-file-name] "
123 "[--log-channels log-channel-list] "
124 "[--platform platform_name] "
126 "[--named-pipe named-pipe-path] "
130 "[-- PROGRAM ARG1 ARG2 ...]\n", progname, subcommand);
135 dump_available_platforms (FILE *output_file)
137 fprintf (output_file, "Available platform plugins:\n");
138 for (int i = 0; ; ++i)
140 const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex (i);
141 const char *plugin_desc = PluginManager::GetPlatformPluginDescriptionAtIndex (i);
143 if (!plugin_name || !plugin_desc)
146 fprintf (output_file, "%s\t%s\n", plugin_name, plugin_desc);
149 if ( Platform::GetHostPlatform () )
151 // add this since the default platform doesn't necessarily get registered by
152 // the plugin name (e.g. 'host' doesn't show up as a
153 // registered platform plugin even though it's the default).
154 fprintf (output_file, "%s\tDefault platform for this host.\n", Platform::GetHostPlatform ()->GetPluginName ().AsCString ());
158 static lldb::PlatformSP
159 setup_platform (const std::string &platform_name)
161 lldb::PlatformSP platform_sp;
163 if (platform_name.empty())
165 printf ("using the default platform: ");
166 platform_sp = Platform::GetHostPlatform ();
167 printf ("%s\n", platform_sp->GetPluginName ().AsCString ());
172 platform_sp = Platform::Create (lldb_private::ConstString(platform_name), error);
175 // the host platform isn't registered with that name (at
176 // least, not always. Check if the given name matches
177 // the default platform name. If so, use it.
178 if ( Platform::GetHostPlatform () && ( Platform::GetHostPlatform ()->GetPluginName () == ConstString (platform_name.c_str()) ) )
180 platform_sp = Platform::GetHostPlatform ();
184 fprintf (stderr, "error: failed to create platform with name '%s'\n", platform_name.c_str());
185 dump_available_platforms (stderr);
189 printf ("using platform: %s\n", platform_name.c_str ());
195 handle_attach_to_pid (GDBRemoteCommunicationServerLLGS &gdb_server, lldb::pid_t pid)
197 Error error = gdb_server.AttachToProcess (pid);
200 fprintf (stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid, error.AsCString());
206 handle_attach_to_process_name (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &process_name)
212 handle_attach (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &attach_target)
214 assert (!attach_target.empty () && "attach_target cannot be empty");
216 // First check if the attach_target is convertible to a long. If so, we'll use it as a pid.
217 char *end_p = nullptr;
218 const long int pid = strtol (attach_target.c_str (), &end_p, 10);
220 // We'll call it a match if the entire argument is consumed.
221 if (end_p && static_cast<size_t> (end_p - attach_target.c_str ()) == attach_target.size ())
222 handle_attach_to_pid (gdb_server, static_cast<lldb::pid_t> (pid));
224 handle_attach_to_process_name (gdb_server, attach_target);
228 handle_launch (GDBRemoteCommunicationServerLLGS &gdb_server, int argc, const char *const argv[])
231 error = gdb_server.SetLaunchArguments (argv, argc);
234 fprintf (stderr, "error: failed to set launch args for '%s': %s\n", argv[0], error.AsCString());
238 unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
240 error = gdb_server.SetLaunchFlags (launch_flags);
243 fprintf (stderr, "error: failed to set launch flags for '%s': %s\n", argv[0], error.AsCString());
247 error = gdb_server.LaunchProcess ();
250 fprintf (stderr, "error: failed to launch '%s': %s\n", argv[0], error.AsCString());
256 writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id)
258 size_t bytes_written = 0;
259 // Write the port number as a C string with the NULL terminator.
260 return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1, bytes_written);
264 writeSocketIdToPipe(const char *const named_pipe_path, const std::string &socket_id)
267 // Wait for 10 seconds for pipe to be opened.
268 auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
269 std::chrono::seconds{10});
272 return writeSocketIdToPipe(port_name_pipe, socket_id);
276 writeSocketIdToPipe(int unnamed_pipe_fd, const std::string &socket_id)
279 return Error("Unnamed pipes are not supported on Windows.");
281 Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
282 return writeSocketIdToPipe(port_pipe, socket_id);
287 ConnectToRemote(MainLoop &mainloop, GDBRemoteCommunicationServerLLGS &gdb_server,
288 bool reverse_connect, const char *const host_and_port,
289 const char *const progname, const char *const subcommand,
290 const char *const named_pipe_path, int unnamed_pipe_fd)
294 if (host_and_port && host_and_port[0])
296 // Parse out host and port.
297 std::string final_host_and_port;
298 std::string connection_host;
299 std::string connection_port;
300 uint32_t connection_portno = 0;
302 // If host_and_port starts with ':', default the host to be "localhost" and expect the remainder to be the port.
303 if (host_and_port[0] == ':')
304 final_host_and_port.append ("localhost");
305 final_host_and_port.append (host_and_port);
307 const std::string::size_type colon_pos = final_host_and_port.find (':');
308 if (colon_pos != std::string::npos)
310 connection_host = final_host_and_port.substr (0, colon_pos);
311 connection_port = final_host_and_port.substr (colon_pos + 1);
312 connection_portno = StringConvert::ToUInt32 (connection_port.c_str (), 0);
315 std::unique_ptr<Connection> connection_up;
319 // llgs will connect to the gdb-remote client.
321 // Ensure we have a port number for the connection.
322 if (connection_portno == 0)
324 fprintf (stderr, "error: port number must be specified on when using reverse connect");
328 // Build the connection string.
329 char connection_url[512];
330 snprintf(connection_url, sizeof(connection_url), "connect://%s", final_host_and_port.c_str ());
332 // Create the connection.
333 connection_up.reset(new ConnectionFileDescriptor);
334 auto connection_result = connection_up->Connect (connection_url, &error);
335 if (connection_result != eConnectionStatusSuccess)
337 fprintf (stderr, "error: failed to connect to client at '%s' (connection status: %d)", connection_url, static_cast<int> (connection_result));
342 fprintf (stderr, "error: failed to connect to client at '%s': %s", connection_url, error.AsCString ());
348 std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create(final_host_and_port, false, error));
351 fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
354 error = acceptor_up->Listen(1);
357 fprintf(stderr, "failed to listen: %s\n", error.AsCString());
360 const std::string socket_id = acceptor_up->GetLocalSocketId();
361 if (!socket_id.empty())
363 // If we have a named pipe to write the socket id back to, do that now.
364 if (named_pipe_path && named_pipe_path[0])
366 error = writeSocketIdToPipe (named_pipe_path, socket_id);
368 fprintf (stderr, "failed to write to the named pipe \'%s\': %s",
369 named_pipe_path, error.AsCString());
371 // If we have an unnamed pipe to write the socket id back to, do that now.
372 else if (unnamed_pipe_fd >= 0)
374 error = writeSocketIdToPipe(unnamed_pipe_fd, socket_id);
376 fprintf(stderr, "failed to write to the unnamed pipe: %s",
382 fprintf (stderr, "unable to get the socket id for the listening connection\n");
385 Connection* conn = nullptr;
386 error = acceptor_up->Accept(false, conn);
389 printf ("failed to accept new connection: %s\n", error.AsCString());
392 connection_up.reset(conn);
394 error = gdb_server.InitializeConnection (std::move(connection_up));
397 fprintf(stderr, "Failed to initialize connection: %s\n", error.AsCString());
400 printf ("Connection established.\n");
404 //----------------------------------------------------------------------
406 //----------------------------------------------------------------------
408 main_gdbserver (int argc, char *argv[])
413 // Setup signal handlers first thing.
414 signal (SIGPIPE, signal_handler);
415 MainLoop::SignalHandleUP sighup_handle = mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
418 // Block delivery of SIGCHLD on linux. NativeProcessLinux will read it using signalfd.
421 sigaddset(&set, SIGCHLD);
422 pthread_sigmask(SIG_BLOCK, &set, NULL);
425 const char *progname = argv[0];
426 const char *subcommand = argv[1];
429 int long_option_index = 0;
431 std::string platform_name;
432 std::string attach_target;
433 std::string named_pipe_path;
434 std::string log_file;
435 StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
436 int unnamed_pipe_fd = -1;
437 bool reverse_connect = false;
439 // ProcessLaunchInfo launch_info;
440 ProcessAttachInfo attach_info;
442 bool show_usage = false;
443 int option_error = 0;
451 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
453 while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
457 case 0: // Any optional that auto set themselves will return 0
460 case 'l': // Set Log File
461 if (optarg && optarg[0])
462 log_file.assign(optarg);
465 case 'c': // Log Channels
466 if (optarg && optarg[0])
467 log_channels = StringRef(optarg);
470 case 'p': // platform name
471 if (optarg && optarg[0])
472 platform_name = optarg;
475 case 'N': // named pipe
476 if (optarg && optarg[0])
477 named_pipe_path = optarg;
480 case 'U': // unnamed pipe
481 if (optarg && optarg[0])
482 unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
485 // Do nothing, native regs is the default these days
489 reverse_connect = true;
494 // Put llgs into a new session. Terminals group processes
495 // into sessions and when a special terminal key sequences
496 // (like control+c) are typed they can cause signals to go out to
497 // all processes in a session. Using this --setsid (-S) option
498 // will cause debugserver to run in its own sessions and be free
501 // This is useful when llgs is spawned from a command
502 // line application that uses llgs to do the debugging,
503 // yet that application doesn't want llgs receiving the
504 // signals sent to the session (i.e. dying when anyone hits ^C).
506 const ::pid_t new_sid = setsid();
509 const char *errno_str = strerror(errno);
510 fprintf (stderr, "failed to set new session id for %s (%s)\n", LLGS_PROGRAM_NAME, errno_str ? errno_str : "<no error string>");
516 case 'a': // attach {pid|process_name}
517 if (optarg && optarg[0])
518 attach_target = optarg;
521 case 'h': /* fall-through is intentional */
528 if (show_usage || option_error)
530 display_usage(progname, subcommand);
534 if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
537 Log *log(lldb_private::GetLogIfAnyCategoriesSet (GDBR_LOG_VERBOSE));
540 log->Printf ("lldb-server launch");
541 for (int i = 0; i < argc; i++)
543 log->Printf ("argv[%i] = '%s'", i, argv[i]);
547 // Skip any options we consumed with getopt_long_only.
553 display_usage(progname, subcommand);
557 // Setup the platform that GDBRemoteCommunicationServerLLGS will use.
558 lldb::PlatformSP platform_sp = setup_platform (platform_name);
560 GDBRemoteCommunicationServerLLGS gdb_server (platform_sp, mainloop);
562 const char *const host_and_port = argv[0];
566 // Any arguments left over are for the program that we need to launch. If there
567 // are no arguments, then the GDB server will start up and wait for an 'A' packet
568 // to launch a program, or a vAttach packet to attach to an existing process, unless
569 // explicitly asked to attach with the --attach={pid|program_name} form.
570 if (!attach_target.empty ())
571 handle_attach (gdb_server, attach_target);
573 handle_launch (gdb_server, argc, argv);
575 // Print version info.
576 printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
578 ConnectToRemote(mainloop, gdb_server, reverse_connect,
579 host_and_port, progname, subcommand,
580 named_pipe_path.c_str(), unnamed_pipe_fd);
583 if (! gdb_server.IsConnected())
585 fprintf (stderr, "no connection information provided, unable to run\n");
586 display_usage (progname, subcommand);
591 fprintf(stderr, "lldb-server exiting...\n");