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;
113 ++g_sighup_received_count;
115 // For now, swallow SIGHUP.
117 log->Printf ("lldb-server:%s swallowing SIGHUP (receive count=%d)", __FUNCTION__, g_sighup_received_count);
118 signal (SIGHUP, signal_handler);
122 #endif // #ifndef _WIN32
125 display_usage (const char *progname, const char* subcommand)
127 fprintf(stderr, "Usage:\n %s %s "
128 "[--log-file log-file-name] "
129 "[--log-channels log-channel-list] "
130 "[--platform platform_name] "
132 "[--named-pipe named-pipe-path] "
136 "[-- PROGRAM ARG1 ARG2 ...]\n", progname, subcommand);
141 dump_available_platforms (FILE *output_file)
143 fprintf (output_file, "Available platform plugins:\n");
144 for (int i = 0; ; ++i)
146 const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex (i);
147 const char *plugin_desc = PluginManager::GetPlatformPluginDescriptionAtIndex (i);
149 if (!plugin_name || !plugin_desc)
152 fprintf (output_file, "%s\t%s\n", plugin_name, plugin_desc);
155 if ( Platform::GetHostPlatform () )
157 // add this since the default platform doesn't necessarily get registered by
158 // the plugin name (e.g. 'host' doesn't show up as a
159 // registered platform plugin even though it's the default).
160 fprintf (output_file, "%s\tDefault platform for this host.\n", Platform::GetHostPlatform ()->GetPluginName ().AsCString ());
164 static lldb::PlatformSP
165 setup_platform (const std::string &platform_name)
167 lldb::PlatformSP platform_sp;
169 if (platform_name.empty())
171 printf ("using the default platform: ");
172 platform_sp = Platform::GetHostPlatform ();
173 printf ("%s\n", platform_sp->GetPluginName ().AsCString ());
178 platform_sp = Platform::Create (lldb_private::ConstString(platform_name), error);
181 // the host platform isn't registered with that name (at
182 // least, not always. Check if the given name matches
183 // the default platform name. If so, use it.
184 if ( Platform::GetHostPlatform () && ( Platform::GetHostPlatform ()->GetPluginName () == ConstString (platform_name.c_str()) ) )
186 platform_sp = Platform::GetHostPlatform ();
190 fprintf (stderr, "error: failed to create platform with name '%s'\n", platform_name.c_str());
191 dump_available_platforms (stderr);
195 printf ("using platform: %s\n", platform_name.c_str ());
201 handle_attach_to_pid (GDBRemoteCommunicationServerLLGS &gdb_server, lldb::pid_t pid)
203 Error error = gdb_server.AttachToProcess (pid);
206 fprintf (stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid, error.AsCString());
212 handle_attach_to_process_name (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &process_name)
218 handle_attach (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &attach_target)
220 assert (!attach_target.empty () && "attach_target cannot be empty");
222 // First check if the attach_target is convertible to a long. If so, we'll use it as a pid.
223 char *end_p = nullptr;
224 const long int pid = strtol (attach_target.c_str (), &end_p, 10);
226 // We'll call it a match if the entire argument is consumed.
227 if (end_p && static_cast<size_t> (end_p - attach_target.c_str ()) == attach_target.size ())
228 handle_attach_to_pid (gdb_server, static_cast<lldb::pid_t> (pid));
230 handle_attach_to_process_name (gdb_server, attach_target);
234 handle_launch (GDBRemoteCommunicationServerLLGS &gdb_server, int argc, const char *const argv[])
237 error = gdb_server.SetLaunchArguments (argv, argc);
240 fprintf (stderr, "error: failed to set launch args for '%s': %s\n", argv[0], error.AsCString());
244 unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
246 error = gdb_server.SetLaunchFlags (launch_flags);
249 fprintf (stderr, "error: failed to set launch flags for '%s': %s\n", argv[0], error.AsCString());
253 error = gdb_server.LaunchProcess ();
256 fprintf (stderr, "error: failed to launch '%s': %s\n", argv[0], error.AsCString());
261 static lldb::thread_result_t
262 ListenThread (lldb::thread_arg_t /* arg */)
266 if (s_listen_connection_up)
268 // Do the listen on another thread so we can continue on...
269 if (s_listen_connection_up->Connect(s_listen_url.c_str(), &error) != eConnectionStatusSuccess)
270 s_listen_connection_up.reset();
276 StartListenThread (const char *hostname, uint16_t port)
279 if (s_listen_thread.IsJoinable())
281 error.SetErrorString("listen thread already running");
285 char listen_url[512];
286 if (hostname && hostname[0])
287 snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
289 snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
291 s_listen_url = listen_url;
292 s_listen_connection_up.reset (new ConnectionFileDescriptor ());
293 s_listen_thread = ThreadLauncher::LaunchThread(listen_url, ListenThread, nullptr, &error);
301 if (s_listen_thread.IsJoinable())
302 s_listen_thread.Join(nullptr);
307 WritePortToPipe(Pipe &port_pipe, const uint16_t port)
310 const auto port_str_len = ::snprintf(port_str, sizeof(port_str), "%u", port);
312 size_t bytes_written = 0;
313 // Write the port number as a C string with the NULL terminator.
314 return port_pipe.Write(port_str, port_str_len + 1, bytes_written);
318 writePortToPipe(const char *const named_pipe_path, const uint16_t port)
321 // Wait for 10 seconds for pipe to be opened.
322 auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
323 std::chrono::seconds{10});
326 return WritePortToPipe(port_name_pipe, port);
330 writePortToPipe(int unnamed_pipe_fd, const uint16_t port)
333 return Error("Unnamed pipes are not supported on Windows.");
335 Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
336 return WritePortToPipe(port_pipe, port);
341 ConnectToRemote(GDBRemoteCommunicationServerLLGS &gdb_server,
342 bool reverse_connect, const char *const host_and_port,
343 const char *const progname, const char *const subcommand,
344 const char *const named_pipe_path, int unnamed_pipe_fd)
348 if (host_and_port && host_and_port[0])
350 // Parse out host and port.
351 std::string final_host_and_port;
352 std::string connection_host;
353 std::string connection_port;
354 uint32_t connection_portno = 0;
356 // If host_and_port starts with ':', default the host to be "localhost" and expect the remainder to be the port.
357 if (host_and_port[0] == ':')
358 final_host_and_port.append ("localhost");
359 final_host_and_port.append (host_and_port);
361 const std::string::size_type colon_pos = final_host_and_port.find (':');
362 if (colon_pos != std::string::npos)
364 connection_host = final_host_and_port.substr (0, colon_pos);
365 connection_port = final_host_and_port.substr (colon_pos + 1);
366 connection_portno = StringConvert::ToUInt32 (connection_port.c_str (), 0);
370 fprintf (stderr, "failed to parse host and port from connection string '%s'\n", final_host_and_port.c_str ());
371 display_usage (progname, subcommand);
377 // llgs will connect to the gdb-remote client.
379 // Ensure we have a port number for the connection.
380 if (connection_portno == 0)
382 fprintf (stderr, "error: port number must be specified on when using reverse connect");
386 // Build the connection string.
387 char connection_url[512];
388 snprintf(connection_url, sizeof(connection_url), "connect://%s", final_host_and_port.c_str ());
390 // Create the connection.
391 std::unique_ptr<ConnectionFileDescriptor> connection_up (new ConnectionFileDescriptor ());
392 connection_up.reset (new ConnectionFileDescriptor ());
393 auto connection_result = connection_up->Connect (connection_url, &error);
394 if (connection_result != eConnectionStatusSuccess)
396 fprintf (stderr, "error: failed to connect to client at '%s' (connection status: %d)", connection_url, static_cast<int> (connection_result));
401 fprintf (stderr, "error: failed to connect to client at '%s': %s", connection_url, error.AsCString ());
406 printf ("Connection established.\n");
407 gdb_server.SetConnection (connection_up.release());
411 // llgs will listen for connections on the given port from the given address.
412 // Start the listener on a new thread. We need to do this so we can resolve the
413 // bound listener port.
414 StartListenThread(connection_host.c_str (), static_cast<uint16_t> (connection_portno));
415 printf ("Listening to port %s for a connection from %s...\n", connection_port.c_str (), connection_host.c_str ());
417 // If we have a named pipe to write the port number back to, do that now.
418 if (named_pipe_path && named_pipe_path[0] && connection_portno == 0)
420 const uint16_t bound_port = s_listen_connection_up->GetListeningPort (10);
423 error = writePortToPipe (named_pipe_path, bound_port);
426 fprintf (stderr, "failed to write to the named pipe \'%s\': %s", named_pipe_path, error.AsCString());
431 fprintf (stderr, "unable to get the bound port for the listening connection\n");
435 // If we have an unnamed pipe to write the port number back to, do that now.
436 if (unnamed_pipe_fd >= 0 && connection_portno == 0)
438 const uint16_t bound_port = s_listen_connection_up->GetListeningPort(10);
441 error = writePortToPipe(unnamed_pipe_fd, bound_port);
444 fprintf(stderr, "failed to write to the unnamed pipe: %s",
450 fprintf(stderr, "unable to get the bound port for the listening connection\n");
454 // Join the listener thread.
455 if (!JoinListenThread ())
457 fprintf (stderr, "failed to join the listener thread\n");
458 display_usage (progname, subcommand);
462 // Ensure we connected.
463 if (s_listen_connection_up)
465 printf ("Connection established '%s'\n", s_listen_connection_up->GetURI().c_str());
466 gdb_server.SetConnection (s_listen_connection_up.release());
470 fprintf (stderr, "failed to connect to '%s': %s\n", final_host_and_port.c_str (), error.AsCString ());
471 display_usage (progname, subcommand);
477 if (gdb_server.IsConnected())
479 // After we connected, we need to get an initial ack from...
480 if (gdb_server.HandshakeWithClient(&error))
482 // We'll use a half a second timeout interval so that an exit conditions can
483 // be checked that often.
484 const uint32_t TIMEOUT_USEC = 500000;
486 bool interrupt = false;
488 while (!interrupt && !done && (g_sighup_received_count < 2))
490 const GDBRemoteCommunication::PacketResult result = gdb_server.GetPacketAndSendResponse (TIMEOUT_USEC, error, interrupt, done);
491 if ((result != GDBRemoteCommunication::PacketResult::Success) &&
492 (result != GDBRemoteCommunication::PacketResult::ErrorReplyTimeout))
494 // We're bailing out - we only support successful handling and timeouts.
495 fprintf(stderr, "leaving packet loop due to PacketResult %d\n", result);
502 fprintf(stderr, "error: %s\n", error.AsCString());
507 fprintf(stderr, "error: handshake with client failed\n");
512 fprintf (stderr, "no connection information provided, unable to run\n");
513 display_usage (progname, subcommand);
518 //----------------------------------------------------------------------
520 //----------------------------------------------------------------------
522 main_gdbserver (int argc, char *argv[])
525 // Setup signal handlers first thing.
526 signal (SIGPIPE, signal_handler);
527 signal (SIGHUP, signal_handler);
530 // Block delivery of SIGCHLD on linux. NativeProcessLinux will read it using signalfd.
533 sigaddset(&set, SIGCHLD);
534 pthread_sigmask(SIG_BLOCK, &set, NULL);
537 const char *progname = argv[0];
538 const char *subcommand = argv[1];
541 int long_option_index = 0;
544 std::string platform_name;
545 std::string attach_target;
546 std::string named_pipe_path;
547 std::string log_file;
548 StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
549 int unnamed_pipe_fd = -1;
550 bool reverse_connect = false;
552 // ProcessLaunchInfo launch_info;
553 ProcessAttachInfo attach_info;
555 bool show_usage = false;
556 int option_error = 0;
564 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
566 while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
570 case 0: // Any optional that auto set themselves will return 0
573 case 'l': // Set Log File
574 if (optarg && optarg[0])
575 log_file.assign(optarg);
578 case 'c': // Log Channels
579 if (optarg && optarg[0])
580 log_channels = StringRef(optarg);
583 case 'p': // platform name
584 if (optarg && optarg[0])
585 platform_name = optarg;
588 case 'N': // named pipe
589 if (optarg && optarg[0])
590 named_pipe_path = optarg;
593 case 'U': // unnamed pipe
594 if (optarg && optarg[0])
595 unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
598 // Do nothing, native regs is the default these days
602 reverse_connect = true;
607 // Put llgs into a new session. Terminals group processes
608 // into sessions and when a special terminal key sequences
609 // (like control+c) are typed they can cause signals to go out to
610 // all processes in a session. Using this --setsid (-S) option
611 // will cause debugserver to run in its own sessions and be free
614 // This is useful when llgs is spawned from a command
615 // line application that uses llgs to do the debugging,
616 // yet that application doesn't want llgs receiving the
617 // signals sent to the session (i.e. dying when anyone hits ^C).
619 const ::pid_t new_sid = setsid();
622 const char *errno_str = strerror(errno);
623 fprintf (stderr, "failed to set new session id for %s (%s)\n", LLGS_PROGRAM_NAME, errno_str ? errno_str : "<no error string>");
629 case 'a': // attach {pid|process_name}
630 if (optarg && optarg[0])
631 attach_target = optarg;
634 case 'h': /* fall-through is intentional */
641 if (show_usage || option_error)
643 display_usage(progname, subcommand);
647 if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
650 Log *log(lldb_private::GetLogIfAnyCategoriesSet (GDBR_LOG_VERBOSE));
653 log->Printf ("lldb-server launch");
654 for (int i = 0; i < argc; i++)
656 log->Printf ("argv[%i] = '%s'", i, argv[i]);
660 // Skip any options we consumed with getopt_long_only.
666 display_usage(progname, subcommand);
670 // Setup the platform that GDBRemoteCommunicationServerLLGS will use.
671 lldb::PlatformSP platform_sp = setup_platform (platform_name);
673 GDBRemoteCommunicationServerLLGS gdb_server (platform_sp);
675 const char *const host_and_port = argv[0];
679 // Any arguments left over are for the program that we need to launch. If there
680 // are no arguments, then the GDB server will start up and wait for an 'A' packet
681 // to launch a program, or a vAttach packet to attach to an existing process, unless
682 // explicitly asked to attach with the --attach={pid|program_name} form.
683 if (!attach_target.empty ())
684 handle_attach (gdb_server, attach_target);
686 handle_launch (gdb_server, argc, argv);
688 // Print version info.
689 printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
691 ConnectToRemote(gdb_server, reverse_connect,
692 host_and_port, progname, subcommand,
693 named_pipe_path.c_str(), unnamed_pipe_fd);
695 fprintf(stderr, "lldb-server exiting...\n");