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 //===----------------------------------------------------------------------===//
25 // Other libraries and framework includes
26 #include "llvm/ADT/StringRef.h"
28 #include "lldb/Core/ConnectionMachPort.h"
29 #include "lldb/Core/Error.h"
30 #include "lldb/Core/PluginManager.h"
31 #include "lldb/Host/ConnectionFileDescriptor.h"
32 #include "lldb/Host/HostThread.h"
33 #include "lldb/Host/OptionParser.h"
34 #include "lldb/Host/Pipe.h"
35 #include "lldb/Host/Socket.h"
36 #include "lldb/Host/StringConvert.h"
37 #include "lldb/Host/ThreadLauncher.h"
38 #include "lldb/Target/Platform.h"
39 #include "LLDBServerUtilities.h"
40 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
41 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
43 #ifndef LLGS_PROGRAM_NAME
44 #define LLGS_PROGRAM_NAME "lldb-server"
47 #ifndef LLGS_VERSION_STR
48 #define LLGS_VERSION_STR "local_build"
53 using namespace lldb_private;
54 using namespace lldb_private::lldb_server;
55 using namespace lldb_private::process_gdb_remote;
57 // lldb-gdbserver state
61 HostThread s_listen_thread;
62 std::unique_ptr<ConnectionFileDescriptor> s_listen_connection_up;
63 std::string s_listen_url;
66 //----------------------------------------------------------------------
67 // option descriptors for getopt_long_only()
68 //----------------------------------------------------------------------
70 static int g_debug = 0;
71 static int g_verbose = 0;
73 static struct option g_long_options[] =
75 { "debug", no_argument, &g_debug, 1 },
76 { "platform", required_argument, NULL, 'p' },
77 { "verbose", no_argument, &g_verbose, 1 },
78 { "log-file", required_argument, NULL, 'l' },
79 { "log-channels", required_argument, NULL, 'c' },
80 { "attach", required_argument, NULL, 'a' },
81 { "named-pipe", required_argument, NULL, 'N' },
82 { "pipe", required_argument, NULL, 'U' },
83 { "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.
84 { "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.
85 { "setsid", no_argument, NULL, 'S' }, // Call setsid() to make llgs run in its own session.
90 //----------------------------------------------------------------------
92 //----------------------------------------------------------------------
93 static int g_sigpipe_received = 0;
94 static int g_sighup_received_count = 0;
99 signal_handler(int signo)
101 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
103 fprintf (stderr, "lldb-server:%s received signal %d\n", __FUNCTION__, signo);
105 log->Printf ("lldb-server:%s received signal %d", __FUNCTION__, signo);
110 g_sigpipe_received = 1;
116 sighup_handler(MainLoopBase &mainloop)
118 ++g_sighup_received_count;
120 Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
122 log->Printf ("lldb-server:%s swallowing SIGHUP (receive count=%d)", __FUNCTION__, g_sighup_received_count);
124 if (g_sighup_received_count >= 2)
125 mainloop.RequestTermination();
127 #endif // #ifndef _WIN32
130 display_usage (const char *progname, const char* subcommand)
132 fprintf(stderr, "Usage:\n %s %s "
133 "[--log-file log-file-name] "
134 "[--log-channels log-channel-list] "
135 "[--platform platform_name] "
137 "[--named-pipe named-pipe-path] "
141 "[-- PROGRAM ARG1 ARG2 ...]\n", progname, subcommand);
146 dump_available_platforms (FILE *output_file)
148 fprintf (output_file, "Available platform plugins:\n");
149 for (int i = 0; ; ++i)
151 const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex (i);
152 const char *plugin_desc = PluginManager::GetPlatformPluginDescriptionAtIndex (i);
154 if (!plugin_name || !plugin_desc)
157 fprintf (output_file, "%s\t%s\n", plugin_name, plugin_desc);
160 if ( Platform::GetHostPlatform () )
162 // add this since the default platform doesn't necessarily get registered by
163 // the plugin name (e.g. 'host' doesn't show up as a
164 // registered platform plugin even though it's the default).
165 fprintf (output_file, "%s\tDefault platform for this host.\n", Platform::GetHostPlatform ()->GetPluginName ().AsCString ());
169 static lldb::PlatformSP
170 setup_platform (const std::string &platform_name)
172 lldb::PlatformSP platform_sp;
174 if (platform_name.empty())
176 printf ("using the default platform: ");
177 platform_sp = Platform::GetHostPlatform ();
178 printf ("%s\n", platform_sp->GetPluginName ().AsCString ());
183 platform_sp = Platform::Create (lldb_private::ConstString(platform_name), error);
186 // the host platform isn't registered with that name (at
187 // least, not always. Check if the given name matches
188 // the default platform name. If so, use it.
189 if ( Platform::GetHostPlatform () && ( Platform::GetHostPlatform ()->GetPluginName () == ConstString (platform_name.c_str()) ) )
191 platform_sp = Platform::GetHostPlatform ();
195 fprintf (stderr, "error: failed to create platform with name '%s'\n", platform_name.c_str());
196 dump_available_platforms (stderr);
200 printf ("using platform: %s\n", platform_name.c_str ());
206 handle_attach_to_pid (GDBRemoteCommunicationServerLLGS &gdb_server, lldb::pid_t pid)
208 Error error = gdb_server.AttachToProcess (pid);
211 fprintf (stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid, error.AsCString());
217 handle_attach_to_process_name (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &process_name)
223 handle_attach (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &attach_target)
225 assert (!attach_target.empty () && "attach_target cannot be empty");
227 // First check if the attach_target is convertible to a long. If so, we'll use it as a pid.
228 char *end_p = nullptr;
229 const long int pid = strtol (attach_target.c_str (), &end_p, 10);
231 // We'll call it a match if the entire argument is consumed.
232 if (end_p && static_cast<size_t> (end_p - attach_target.c_str ()) == attach_target.size ())
233 handle_attach_to_pid (gdb_server, static_cast<lldb::pid_t> (pid));
235 handle_attach_to_process_name (gdb_server, attach_target);
239 handle_launch (GDBRemoteCommunicationServerLLGS &gdb_server, int argc, const char *const argv[])
242 error = gdb_server.SetLaunchArguments (argv, argc);
245 fprintf (stderr, "error: failed to set launch args for '%s': %s\n", argv[0], error.AsCString());
249 unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
251 error = gdb_server.SetLaunchFlags (launch_flags);
254 fprintf (stderr, "error: failed to set launch flags for '%s': %s\n", argv[0], error.AsCString());
258 error = gdb_server.LaunchProcess ();
261 fprintf (stderr, "error: failed to launch '%s': %s\n", argv[0], error.AsCString());
266 static lldb::thread_result_t
267 ListenThread (lldb::thread_arg_t /* arg */)
271 if (s_listen_connection_up)
273 // Do the listen on another thread so we can continue on...
274 if (s_listen_connection_up->Connect(s_listen_url.c_str(), &error) != eConnectionStatusSuccess)
275 s_listen_connection_up.reset();
281 StartListenThread (const char *hostname, uint16_t port)
284 if (s_listen_thread.IsJoinable())
286 error.SetErrorString("listen thread already running");
290 char listen_url[512];
291 if (hostname && hostname[0])
292 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
294 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
296 s_listen_url = listen_url;
297 s_listen_connection_up.reset (new ConnectionFileDescriptor ());
298 s_listen_thread = ThreadLauncher::LaunchThread(listen_url, ListenThread, nullptr, &error);
306 if (s_listen_thread.IsJoinable())
307 s_listen_thread.Join(nullptr);
312 WritePortToPipe(Pipe &port_pipe, const uint16_t port)
315 const auto port_str_len = ::snprintf(port_str, sizeof(port_str), "%u", port);
317 size_t bytes_written = 0;
318 // Write the port number as a C string with the NULL terminator.
319 return port_pipe.Write(port_str, port_str_len + 1, bytes_written);
323 writePortToPipe(const char *const named_pipe_path, const uint16_t port)
326 // Wait for 10 seconds for pipe to be opened.
327 auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
328 std::chrono::seconds{10});
331 return WritePortToPipe(port_name_pipe, port);
335 writePortToPipe(int unnamed_pipe_fd, const uint16_t port)
338 return Error("Unnamed pipes are not supported on Windows.");
340 Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
341 return WritePortToPipe(port_pipe, port);
346 ConnectToRemote(MainLoop &mainloop, GDBRemoteCommunicationServerLLGS &gdb_server,
347 bool reverse_connect, const char *const host_and_port,
348 const char *const progname, const char *const subcommand,
349 const char *const named_pipe_path, int unnamed_pipe_fd)
353 if (host_and_port && host_and_port[0])
355 // Parse out host and port.
356 std::string final_host_and_port;
357 std::string connection_host;
358 std::string connection_port;
359 uint32_t connection_portno = 0;
361 // If host_and_port starts with ':', default the host to be "localhost" and expect the remainder to be the port.
362 if (host_and_port[0] == ':')
363 final_host_and_port.append ("localhost");
364 final_host_and_port.append (host_and_port);
366 const std::string::size_type colon_pos = final_host_and_port.find (':');
367 if (colon_pos != std::string::npos)
369 connection_host = final_host_and_port.substr (0, colon_pos);
370 connection_port = final_host_and_port.substr (colon_pos + 1);
371 connection_portno = StringConvert::ToUInt32 (connection_port.c_str (), 0);
375 fprintf (stderr, "failed to parse host and port from connection string '%s'\n", final_host_and_port.c_str ());
376 display_usage (progname, subcommand);
380 std::unique_ptr<ConnectionFileDescriptor> connection_up;
384 // llgs will connect to the gdb-remote client.
386 // Ensure we have a port number for the connection.
387 if (connection_portno == 0)
389 fprintf (stderr, "error: port number must be specified on when using reverse connect");
393 // Build the connection string.
394 char connection_url[512];
395 snprintf(connection_url, sizeof(connection_url), "connect://%s", final_host_and_port.c_str ());
397 // Create the connection.
398 connection_up.reset(new ConnectionFileDescriptor);
399 auto connection_result = connection_up->Connect (connection_url, &error);
400 if (connection_result != eConnectionStatusSuccess)
402 fprintf (stderr, "error: failed to connect to client at '%s' (connection status: %d)", connection_url, static_cast<int> (connection_result));
407 fprintf (stderr, "error: failed to connect to client at '%s': %s", connection_url, error.AsCString ());
413 // llgs will listen for connections on the given port from the given address.
414 // Start the listener on a new thread. We need to do this so we can resolve the
415 // bound listener port.
416 StartListenThread(connection_host.c_str (), static_cast<uint16_t> (connection_portno));
417 printf ("Listening to port %s for a connection from %s...\n", connection_port.c_str (), connection_host.c_str ());
419 // If we have a named pipe to write the port number back to, do that now.
420 if (named_pipe_path && named_pipe_path[0] && connection_portno == 0)
422 const uint16_t bound_port = s_listen_connection_up->GetListeningPort (10);
425 error = writePortToPipe (named_pipe_path, bound_port);
428 fprintf (stderr, "failed to write to the named pipe \'%s\': %s", named_pipe_path, error.AsCString());
433 fprintf (stderr, "unable to get the bound port for the listening connection\n");
437 // If we have an unnamed pipe to write the port number back to, do that now.
438 if (unnamed_pipe_fd >= 0 && connection_portno == 0)
440 const uint16_t bound_port = s_listen_connection_up->GetListeningPort(10);
443 error = writePortToPipe(unnamed_pipe_fd, bound_port);
446 fprintf(stderr, "failed to write to the unnamed pipe: %s",
452 fprintf(stderr, "unable to get the bound port for the listening connection\n");
456 // Join the listener thread.
457 if (!JoinListenThread ())
459 fprintf (stderr, "failed to join the listener thread\n");
460 display_usage (progname, subcommand);
464 // Ensure we connected.
465 if (s_listen_connection_up)
466 connection_up = std::move(s_listen_connection_up);
469 fprintf (stderr, "failed to connect to '%s': %s\n", final_host_and_port.c_str (), error.AsCString ());
470 display_usage (progname, subcommand);
474 error = gdb_server.InitializeConnection (std::move(connection_up));
477 fprintf(stderr, "Failed to initialize connection: %s\n", error.AsCString());
480 printf ("Connection established.\n");
484 //----------------------------------------------------------------------
486 //----------------------------------------------------------------------
488 main_gdbserver (int argc, char *argv[])
493 // Setup signal handlers first thing.
494 signal (SIGPIPE, signal_handler);
495 MainLoop::SignalHandleUP sighup_handle = mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
498 // Block delivery of SIGCHLD on linux. NativeProcessLinux will read it using signalfd.
501 sigaddset(&set, SIGCHLD);
502 pthread_sigmask(SIG_BLOCK, &set, NULL);
505 const char *progname = argv[0];
506 const char *subcommand = argv[1];
509 int long_option_index = 0;
511 std::string platform_name;
512 std::string attach_target;
513 std::string named_pipe_path;
514 std::string log_file;
515 StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
516 int unnamed_pipe_fd = -1;
517 bool reverse_connect = false;
519 // ProcessLaunchInfo launch_info;
520 ProcessAttachInfo attach_info;
522 bool show_usage = false;
523 int option_error = 0;
531 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
533 while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
537 case 0: // Any optional that auto set themselves will return 0
540 case 'l': // Set Log File
541 if (optarg && optarg[0])
542 log_file.assign(optarg);
545 case 'c': // Log Channels
546 if (optarg && optarg[0])
547 log_channels = StringRef(optarg);
550 case 'p': // platform name
551 if (optarg && optarg[0])
552 platform_name = optarg;
555 case 'N': // named pipe
556 if (optarg && optarg[0])
557 named_pipe_path = optarg;
560 case 'U': // unnamed pipe
561 if (optarg && optarg[0])
562 unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
565 // Do nothing, native regs is the default these days
569 reverse_connect = true;
574 // Put llgs into a new session. Terminals group processes
575 // into sessions and when a special terminal key sequences
576 // (like control+c) are typed they can cause signals to go out to
577 // all processes in a session. Using this --setsid (-S) option
578 // will cause debugserver to run in its own sessions and be free
581 // This is useful when llgs is spawned from a command
582 // line application that uses llgs to do the debugging,
583 // yet that application doesn't want llgs receiving the
584 // signals sent to the session (i.e. dying when anyone hits ^C).
586 const ::pid_t new_sid = setsid();
589 const char *errno_str = strerror(errno);
590 fprintf (stderr, "failed to set new session id for %s (%s)\n", LLGS_PROGRAM_NAME, errno_str ? errno_str : "<no error string>");
596 case 'a': // attach {pid|process_name}
597 if (optarg && optarg[0])
598 attach_target = optarg;
601 case 'h': /* fall-through is intentional */
608 if (show_usage || option_error)
610 display_usage(progname, subcommand);
614 if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
617 Log *log(lldb_private::GetLogIfAnyCategoriesSet (GDBR_LOG_VERBOSE));
620 log->Printf ("lldb-server launch");
621 for (int i = 0; i < argc; i++)
623 log->Printf ("argv[%i] = '%s'", i, argv[i]);
627 // Skip any options we consumed with getopt_long_only.
633 display_usage(progname, subcommand);
637 // Setup the platform that GDBRemoteCommunicationServerLLGS will use.
638 lldb::PlatformSP platform_sp = setup_platform (platform_name);
640 GDBRemoteCommunicationServerLLGS gdb_server (platform_sp, mainloop);
642 const char *const host_and_port = argv[0];
646 // Any arguments left over are for the program that we need to launch. If there
647 // are no arguments, then the GDB server will start up and wait for an 'A' packet
648 // to launch a program, or a vAttach packet to attach to an existing process, unless
649 // explicitly asked to attach with the --attach={pid|program_name} form.
650 if (!attach_target.empty ())
651 handle_attach (gdb_server, attach_target);
653 handle_launch (gdb_server, argc, argv);
655 // Print version info.
656 printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
658 ConnectToRemote(mainloop, gdb_server, reverse_connect,
659 host_and_port, progname, subcommand,
660 named_pipe_path.c_str(), unnamed_pipe_fd);
663 if (! gdb_server.IsConnected())
665 fprintf (stderr, "no connection information provided, unable to run\n");
666 display_usage (progname, subcommand);
671 fprintf(stderr, "lldb-server exiting...\n");