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"
28 #include "LLDBServerUtilities.h"
29 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
30 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
31 #include "lldb/Core/PluginManager.h"
32 #include "lldb/Host/ConnectionFileDescriptor.h"
33 #include "lldb/Host/HostGetOpt.h"
34 #include "lldb/Host/OptionParser.h"
35 #include "lldb/Host/Pipe.h"
36 #include "lldb/Host/Socket.h"
37 #include "lldb/Host/StringConvert.h"
38 #include "lldb/Utility/Status.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[] = {
62 {"debug", no_argument, &g_debug, 1},
63 {"verbose", no_argument, &g_verbose, 1},
64 {"log-file", required_argument, NULL, 'l'},
65 {"log-channels", required_argument, NULL, 'c'},
66 {"attach", required_argument, NULL, 'a'},
67 {"named-pipe", required_argument, NULL, 'N'},
68 {"pipe", required_argument, NULL, 'U'},
69 {"native-regs", no_argument, NULL,
70 'r'}, // Specify to use the native registers instead of the gdb defaults
71 // for the architecture. NOTE: this is a do-nothing arg as it's
72 // behavior is default now. FIXME remove call from lldb-platform.
73 {"reverse-connect", no_argument, NULL,
74 'R'}, // Specifies that llgs attaches to the client address:port rather
75 // than llgs listening for a connection from address on port.
76 {"setsid", no_argument, NULL,
77 'S'}, // Call setsid() to make llgs run in its own session.
80 //----------------------------------------------------------------------
82 //----------------------------------------------------------------------
83 static int g_sighup_received_count = 0;
86 static void sighup_handler(MainLoopBase &mainloop) {
87 ++g_sighup_received_count;
89 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
91 log->Printf("lldb-server:%s swallowing SIGHUP (receive count=%d)",
92 __FUNCTION__, g_sighup_received_count);
94 if (g_sighup_received_count >= 2)
95 mainloop.RequestTermination();
97 #endif // #ifndef _WIN32
99 static void 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",
109 progname, subcommand);
113 void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS &gdb_server,
115 Status error = gdb_server.AttachToProcess(pid);
117 fprintf(stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid,
123 void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS &gdb_server,
124 const std::string &process_name) {
128 void handle_attach(GDBRemoteCommunicationServerLLGS &gdb_server,
129 const std::string &attach_target) {
130 assert(!attach_target.empty() && "attach_target cannot be empty");
132 // First check if the attach_target is convertible to a long. If so, we'll use
134 char *end_p = nullptr;
135 const long int pid = strtol(attach_target.c_str(), &end_p, 10);
137 // We'll call it a match if the entire argument is consumed.
139 static_cast<size_t>(end_p - attach_target.c_str()) ==
140 attach_target.size())
141 handle_attach_to_pid(gdb_server, static_cast<lldb::pid_t>(pid));
143 handle_attach_to_process_name(gdb_server, attach_target);
146 void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server, int argc,
147 const char *const argv[]) {
149 error = gdb_server.SetLaunchArguments(argv, argc);
151 fprintf(stderr, "error: failed to set launch args for '%s': %s\n", argv[0],
156 unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
158 error = gdb_server.SetLaunchFlags(launch_flags);
160 fprintf(stderr, "error: failed to set launch flags for '%s': %s\n", argv[0],
165 error = gdb_server.LaunchProcess();
167 fprintf(stderr, "error: failed to launch '%s': %s\n", argv[0],
173 Status writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id) {
174 size_t bytes_written = 0;
175 // Write the port number as a C string with the NULL terminator.
176 return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1,
180 Status writeSocketIdToPipe(const char *const named_pipe_path,
181 const std::string &socket_id) {
183 // Wait for 10 seconds for pipe to be opened.
184 auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
185 std::chrono::seconds{10});
188 return writeSocketIdToPipe(port_name_pipe, socket_id);
191 Status writeSocketIdToPipe(int unnamed_pipe_fd, const std::string &socket_id) {
193 return Status("Unnamed pipes are not supported on Windows.");
195 Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
196 return writeSocketIdToPipe(port_pipe, socket_id);
200 void ConnectToRemote(MainLoop &mainloop,
201 GDBRemoteCommunicationServerLLGS &gdb_server,
202 bool reverse_connect, const char *const host_and_port,
203 const char *const progname, const char *const subcommand,
204 const char *const named_pipe_path, int unnamed_pipe_fd) {
207 if (host_and_port && host_and_port[0]) {
208 // Parse out host and port.
209 std::string final_host_and_port;
210 std::string connection_host;
211 std::string connection_port;
212 uint32_t connection_portno = 0;
214 // If host_and_port starts with ':', default the host to be "localhost" and
215 // expect the remainder to be the port.
216 if (host_and_port[0] == ':')
217 final_host_and_port.append("localhost");
218 final_host_and_port.append(host_and_port);
220 const std::string::size_type colon_pos = final_host_and_port.find(':');
221 if (colon_pos != std::string::npos) {
222 connection_host = final_host_and_port.substr(0, colon_pos);
223 connection_port = final_host_and_port.substr(colon_pos + 1);
224 connection_portno = StringConvert::ToUInt32(connection_port.c_str(), 0);
227 std::unique_ptr<Connection> connection_up;
229 if (reverse_connect) {
230 // llgs will connect to the gdb-remote client.
232 // Ensure we have a port number for the connection.
233 if (connection_portno == 0) {
234 fprintf(stderr, "error: port number must be specified on when using "
239 // Build the connection string.
240 char connection_url[512];
241 snprintf(connection_url, sizeof(connection_url), "connect://%s",
242 final_host_and_port.c_str());
244 // Create the connection.
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)",
250 connection_url, static_cast<int>(connection_result));
254 fprintf(stderr, "error: failed to connect to client at '%s': %s",
255 connection_url, error.AsCString());
259 std::unique_ptr<Acceptor> acceptor_up(
260 Acceptor::Create(final_host_and_port, false, error));
262 fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
265 error = acceptor_up->Listen(1);
267 fprintf(stderr, "failed to listen: %s\n", error.AsCString());
270 const std::string socket_id = acceptor_up->GetLocalSocketId();
271 if (!socket_id.empty()) {
272 // If we have a named pipe to write the socket id back to, do that now.
273 if (named_pipe_path && named_pipe_path[0]) {
274 error = writeSocketIdToPipe(named_pipe_path, socket_id);
276 fprintf(stderr, "failed to write to the named pipe \'%s\': %s",
277 named_pipe_path, error.AsCString());
279 // If we have an unnamed pipe to write the socket id back to, do that
281 else if (unnamed_pipe_fd >= 0) {
282 error = writeSocketIdToPipe(unnamed_pipe_fd, socket_id);
284 fprintf(stderr, "failed to write to the unnamed pipe: %s",
289 "unable to get the socket id for the listening connection\n");
292 Connection *conn = nullptr;
293 error = acceptor_up->Accept(false, conn);
295 printf("failed to accept new connection: %s\n", error.AsCString());
298 connection_up.reset(conn);
300 error = gdb_server.InitializeConnection(std::move(connection_up));
302 fprintf(stderr, "Failed to initialize connection: %s\n",
306 printf("Connection established.\n");
310 //----------------------------------------------------------------------
312 //----------------------------------------------------------------------
313 int main_gdbserver(int argc, char *argv[]) {
317 // Setup signal handlers first thing.
318 signal(SIGPIPE, SIG_IGN);
319 MainLoop::SignalHandleUP sighup_handle =
320 mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
323 const char *progname = argv[0];
324 const char *subcommand = argv[1];
327 int long_option_index = 0;
329 std::string attach_target;
330 std::string named_pipe_path;
331 std::string log_file;
333 log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
334 int unnamed_pipe_fd = -1;
335 bool reverse_connect = false;
337 // ProcessLaunchInfo launch_info;
338 ProcessAttachInfo attach_info;
340 bool show_usage = false;
341 int option_error = 0;
349 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
351 while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
352 g_long_options, &long_option_index)) != -1) {
354 case 0: // Any optional that auto set themselves will return 0
357 case 'l': // Set Log File
358 if (optarg && optarg[0])
359 log_file.assign(optarg);
362 case 'c': // Log Channels
363 if (optarg && optarg[0])
364 log_channels = StringRef(optarg);
367 case 'N': // named pipe
368 if (optarg && optarg[0])
369 named_pipe_path = optarg;
372 case 'U': // unnamed pipe
373 if (optarg && optarg[0])
374 unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
378 // Do nothing, native regs is the default these days
382 reverse_connect = true;
387 // Put llgs into a new session. Terminals group processes
388 // into sessions and when a special terminal key sequences
389 // (like control+c) are typed they can cause signals to go out to
390 // all processes in a session. Using this --setsid (-S) option
391 // will cause debugserver to run in its own sessions and be free
394 // This is useful when llgs is spawned from a command
395 // line application that uses llgs to do the debugging,
396 // yet that application doesn't want llgs receiving the
397 // signals sent to the session (i.e. dying when anyone hits ^C).
399 const ::pid_t new_sid = setsid();
401 const char *errno_str = strerror(errno);
402 fprintf(stderr, "failed to set new session id for %s (%s)\n",
404 errno_str ? errno_str : "<no error string>");
410 case 'a': // attach {pid|process_name}
411 if (optarg && optarg[0])
412 attach_target = optarg;
415 case 'h': /* fall-through is intentional */
422 if (show_usage || option_error) {
423 display_usage(progname, subcommand);
427 if (!LLDBServerUtilities::SetupLogging(
428 log_file, log_channels,
429 LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
430 LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION))
433 Log *log(lldb_private::GetLogIfAnyCategoriesSet(GDBR_LOG_PROCESS));
435 log->Printf("lldb-server launch");
436 for (int i = 0; i < argc; i++) {
437 log->Printf("argv[%i] = '%s'", i, argv[i]);
441 // Skip any options we consumed with getopt_long_only.
446 display_usage(progname, subcommand);
450 GDBRemoteCommunicationServerLLGS gdb_server(mainloop);
452 const char *const host_and_port = argv[0];
456 // Any arguments left over are for the program that we need to launch. If
458 // are no arguments, then the GDB server will start up and wait for an 'A'
460 // to launch a program, or a vAttach packet to attach to an existing process,
462 // explicitly asked to attach with the --attach={pid|program_name} form.
463 if (!attach_target.empty())
464 handle_attach(gdb_server, attach_target);
466 handle_launch(gdb_server, argc, argv);
468 // Print version info.
469 printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
471 ConnectToRemote(mainloop, gdb_server, reverse_connect, host_and_port,
472 progname, subcommand, named_pipe_path.c_str(),
475 if (!gdb_server.IsConnected()) {
476 fprintf(stderr, "no connection information provided, unable to run\n");
477 display_usage(progname, subcommand);
482 fprintf(stderr, "lldb-server exiting...\n");