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 //===----------------------------------------------------------------------===//
26 #include "LLDBServerUtilities.h"
27 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
28 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
29 #include "lldb/Core/PluginManager.h"
30 #include "lldb/Host/ConnectionFileDescriptor.h"
31 #include "lldb/Host/HostGetOpt.h"
32 #include "lldb/Host/OptionParser.h"
33 #include "lldb/Host/Pipe.h"
34 #include "lldb/Host/Socket.h"
35 #include "lldb/Host/StringConvert.h"
36 #include "lldb/Host/common/NativeProcessProtocol.h"
37 #include "lldb/Utility/Status.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/Support/Errno.h"
41 #if defined(__linux__)
42 #include "Plugins/Process/Linux/NativeProcessLinux.h"
43 #elif defined(__NetBSD__)
44 #include "Plugins/Process/NetBSD/NativeProcessNetBSD.h"
47 #ifndef LLGS_PROGRAM_NAME
48 #define LLGS_PROGRAM_NAME "lldb-server"
51 #ifndef LLGS_VERSION_STR
52 #define LLGS_VERSION_STR "local_build"
57 using namespace lldb_private;
58 using namespace lldb_private::lldb_server;
59 using namespace lldb_private::process_gdb_remote;
62 #if defined(__linux__)
63 typedef process_linux::NativeProcessLinux::Factory NativeProcessFactory;
64 #elif defined(__NetBSD__)
65 typedef process_netbsd::NativeProcessNetBSD::Factory NativeProcessFactory;
67 // Dummy implementation to make sure the code compiles
68 class NativeProcessFactory : public NativeProcessProtocol::Factory {
70 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
71 Launch(ProcessLaunchInfo &launch_info,
72 NativeProcessProtocol::NativeDelegate &delegate,
73 MainLoop &mainloop) const override {
74 llvm_unreachable("Not implemented");
76 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
77 Attach(lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &delegate,
78 MainLoop &mainloop) const override {
79 llvm_unreachable("Not implemented");
85 //----------------------------------------------------------------------
86 // option descriptors for getopt_long_only()
87 //----------------------------------------------------------------------
89 static int g_debug = 0;
90 static int g_verbose = 0;
92 static struct option g_long_options[] = {
93 {"debug", no_argument, &g_debug, 1},
94 {"verbose", no_argument, &g_verbose, 1},
95 {"log-file", required_argument, NULL, 'l'},
96 {"log-channels", required_argument, NULL, 'c'},
97 {"attach", required_argument, NULL, 'a'},
98 {"named-pipe", required_argument, NULL, 'N'},
99 {"pipe", required_argument, NULL, 'U'},
100 {"native-regs", no_argument, NULL,
101 'r'}, // Specify to use the native registers instead of the gdb defaults
102 // for the architecture. NOTE: this is a do-nothing arg as it's
103 // behavior is default now. FIXME remove call from lldb-platform.
104 {"reverse-connect", no_argument, NULL,
105 'R'}, // Specifies that llgs attaches to the client address:port rather
106 // than llgs listening for a connection from address on port.
107 {"setsid", no_argument, NULL,
108 'S'}, // Call setsid() to make llgs run in its own session.
109 {"fd", required_argument, NULL, 'F'},
112 //----------------------------------------------------------------------
114 //----------------------------------------------------------------------
115 static int g_sighup_received_count = 0;
118 static void sighup_handler(MainLoopBase &mainloop) {
119 ++g_sighup_received_count;
121 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
123 log->Printf("lldb-server:%s swallowing SIGHUP (receive count=%d)",
124 __FUNCTION__, g_sighup_received_count);
126 if (g_sighup_received_count >= 2)
127 mainloop.RequestTermination();
129 #endif // #ifndef _WIN32
131 static void 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] "
136 "[--fd file-descriptor]"
137 "[--named-pipe named-pipe-path] "
141 "[-- PROGRAM ARG1 ARG2 ...]\n",
142 progname, subcommand);
145 void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS &gdb_server,
147 Status error = gdb_server.AttachToProcess(pid);
149 fprintf(stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid,
155 void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS &gdb_server,
156 const std::string &process_name) {
160 void handle_attach(GDBRemoteCommunicationServerLLGS &gdb_server,
161 const std::string &attach_target) {
162 assert(!attach_target.empty() && "attach_target cannot be empty");
164 // First check if the attach_target is convertible to a long. If so, we'll use
166 char *end_p = nullptr;
167 const long int pid = strtol(attach_target.c_str(), &end_p, 10);
169 // We'll call it a match if the entire argument is consumed.
171 static_cast<size_t>(end_p - attach_target.c_str()) ==
172 attach_target.size())
173 handle_attach_to_pid(gdb_server, static_cast<lldb::pid_t>(pid));
175 handle_attach_to_process_name(gdb_server, attach_target);
178 void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server, int argc,
179 const char *const argv[]) {
180 ProcessLaunchInfo info;
181 info.GetFlags().Set(eLaunchFlagStopAtEntry | eLaunchFlagDebug |
182 eLaunchFlagDisableASLR);
183 info.SetArguments(const_cast<const char **>(argv), true);
185 llvm::SmallString<64> cwd;
186 if (std::error_code ec = llvm::sys::fs::current_path(cwd)) {
187 llvm::errs() << "Error getting current directory: " << ec.message() << "\n";
190 info.SetWorkingDirectory(FileSpec(cwd, true));
193 Host::GetEnvironment(env);
194 info.GetEnvironmentEntries() = Args(env);
196 gdb_server.SetLaunchInfo(info);
198 Status error = gdb_server.LaunchProcess();
200 llvm::errs() << llvm::formatv("error: failed to launch '{0}': {1}\n",
206 Status writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id) {
207 size_t bytes_written = 0;
208 // Write the port number as a C string with the NULL terminator.
209 return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1,
213 Status writeSocketIdToPipe(const char *const named_pipe_path,
214 const std::string &socket_id) {
216 // Wait for 10 seconds for pipe to be opened.
217 auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
218 std::chrono::seconds{10});
221 return writeSocketIdToPipe(port_name_pipe, socket_id);
224 Status writeSocketIdToPipe(int unnamed_pipe_fd, const std::string &socket_id) {
226 return Status("Unnamed pipes are not supported on Windows.");
228 Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
229 return writeSocketIdToPipe(port_pipe, socket_id);
233 void ConnectToRemote(MainLoop &mainloop,
234 GDBRemoteCommunicationServerLLGS &gdb_server,
235 bool reverse_connect, const char *const host_and_port,
236 const char *const progname, const char *const subcommand,
237 const char *const named_pipe_path, int unnamed_pipe_fd,
241 std::unique_ptr<Connection> connection_up;
242 if (connection_fd != -1) {
243 // Build the connection string.
244 char connection_url[512];
245 snprintf(connection_url, sizeof(connection_url), "fd://%d", connection_fd);
247 // Create the connection.
248 #if !defined LLDB_DISABLE_POSIX && !defined _WIN32
249 ::fcntl(connection_fd, F_SETFD, FD_CLOEXEC);
251 connection_up.reset(new ConnectionFileDescriptor);
252 auto connection_result = connection_up->Connect(connection_url, &error);
253 if (connection_result != eConnectionStatusSuccess) {
254 fprintf(stderr, "error: failed to connect to client at '%s' "
255 "(connection status: %d)\n",
256 connection_url, static_cast<int>(connection_result));
260 fprintf(stderr, "error: failed to connect to client at '%s': %s\n",
261 connection_url, error.AsCString());
264 } else if (host_and_port && host_and_port[0]) {
265 // Parse out host and port.
266 std::string final_host_and_port;
267 std::string connection_host;
268 std::string connection_port;
269 uint32_t connection_portno = 0;
271 // If host_and_port starts with ':', default the host to be "localhost" and
272 // expect the remainder to be the port.
273 if (host_and_port[0] == ':')
274 final_host_and_port.append("localhost");
275 final_host_and_port.append(host_and_port);
277 const std::string::size_type colon_pos = final_host_and_port.find(':');
278 if (colon_pos != std::string::npos) {
279 connection_host = final_host_and_port.substr(0, colon_pos);
280 connection_port = final_host_and_port.substr(colon_pos + 1);
281 connection_portno = StringConvert::ToUInt32(connection_port.c_str(), 0);
285 if (reverse_connect) {
286 // llgs will connect to the gdb-remote client.
288 // Ensure we have a port number for the connection.
289 if (connection_portno == 0) {
290 fprintf(stderr, "error: port number must be specified on when using "
291 "reverse connect\n");
295 // Build the connection string.
296 char connection_url[512];
297 snprintf(connection_url, sizeof(connection_url), "connect://%s",
298 final_host_and_port.c_str());
300 // Create the connection.
301 connection_up.reset(new ConnectionFileDescriptor);
302 auto connection_result = connection_up->Connect(connection_url, &error);
303 if (connection_result != eConnectionStatusSuccess) {
304 fprintf(stderr, "error: failed to connect to client at '%s' "
305 "(connection status: %d)\n",
306 connection_url, static_cast<int>(connection_result));
310 fprintf(stderr, "error: failed to connect to client at '%s': %s\n",
311 connection_url, error.AsCString());
315 std::unique_ptr<Acceptor> acceptor_up(
316 Acceptor::Create(final_host_and_port, false, error));
318 fprintf(stderr, "failed to create acceptor: %s\n", error.AsCString());
321 error = acceptor_up->Listen(1);
323 fprintf(stderr, "failed to listen: %s\n", error.AsCString());
326 const std::string socket_id = acceptor_up->GetLocalSocketId();
327 if (!socket_id.empty()) {
328 // If we have a named pipe to write the socket id back to, do that now.
329 if (named_pipe_path && named_pipe_path[0]) {
330 error = writeSocketIdToPipe(named_pipe_path, socket_id);
332 fprintf(stderr, "failed to write to the named pipe \'%s\': %s\n",
333 named_pipe_path, error.AsCString());
335 // If we have an unnamed pipe to write the socket id back to, do that
337 else if (unnamed_pipe_fd >= 0) {
338 error = writeSocketIdToPipe(unnamed_pipe_fd, socket_id);
340 fprintf(stderr, "failed to write to the unnamed pipe: %s\n",
345 "unable to get the socket id for the listening connection\n");
348 Connection *conn = nullptr;
349 error = acceptor_up->Accept(false, conn);
351 printf("failed to accept new connection: %s\n", error.AsCString());
354 connection_up.reset(conn);
357 error = gdb_server.InitializeConnection(std::move(connection_up));
359 fprintf(stderr, "Failed to initialize connection: %s\n",
363 printf("Connection established.\n");
366 //----------------------------------------------------------------------
368 //----------------------------------------------------------------------
369 int main_gdbserver(int argc, char *argv[]) {
373 // Setup signal handlers first thing.
374 signal(SIGPIPE, SIG_IGN);
375 MainLoop::SignalHandleUP sighup_handle =
376 mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
379 const char *progname = argv[0];
380 const char *subcommand = argv[1];
383 int long_option_index = 0;
385 std::string attach_target;
386 std::string named_pipe_path;
387 std::string log_file;
389 log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
390 int unnamed_pipe_fd = -1;
391 bool reverse_connect = false;
392 int connection_fd = -1;
394 // ProcessLaunchInfo launch_info;
395 ProcessAttachInfo attach_info;
397 bool show_usage = false;
398 int option_error = 0;
406 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
408 while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
409 g_long_options, &long_option_index)) != -1) {
411 case 0: // Any optional that auto set themselves will return 0
414 case 'l': // Set Log File
415 if (optarg && optarg[0])
416 log_file.assign(optarg);
419 case 'c': // Log Channels
420 if (optarg && optarg[0])
421 log_channels = StringRef(optarg);
424 case 'N': // named pipe
425 if (optarg && optarg[0])
426 named_pipe_path = optarg;
429 case 'U': // unnamed pipe
430 if (optarg && optarg[0])
431 unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
435 // Do nothing, native regs is the default these days
439 reverse_connect = true;
443 connection_fd = StringConvert::ToUInt32(optarg, -1);
448 // Put llgs into a new session. Terminals group processes
449 // into sessions and when a special terminal key sequences
450 // (like control+c) are typed they can cause signals to go out to
451 // all processes in a session. Using this --setsid (-S) option
452 // will cause debugserver to run in its own sessions and be free
455 // This is useful when llgs is spawned from a command
456 // line application that uses llgs to do the debugging,
457 // yet that application doesn't want llgs receiving the
458 // signals sent to the session (i.e. dying when anyone hits ^C).
460 const ::pid_t new_sid = setsid();
462 llvm::errs() << llvm::formatv(
463 "failed to set new session id for {0} ({1})\n", LLGS_PROGRAM_NAME,
464 llvm::sys::StrError());
470 case 'a': // attach {pid|process_name}
471 if (optarg && optarg[0])
472 attach_target = optarg;
475 case 'h': /* fall-through is intentional */
482 if (show_usage || option_error) {
483 display_usage(progname, subcommand);
487 if (!LLDBServerUtilities::SetupLogging(
488 log_file, log_channels,
489 LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
490 LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION))
493 Log *log(lldb_private::GetLogIfAnyCategoriesSet(GDBR_LOG_PROCESS));
495 log->Printf("lldb-server launch");
496 for (int i = 0; i < argc; i++) {
497 log->Printf("argv[%i] = '%s'", i, argv[i]);
501 // Skip any options we consumed with getopt_long_only.
505 if (argc == 0 && connection_fd == -1) {
506 fputs("No arguments\n", stderr);
507 display_usage(progname, subcommand);
511 NativeProcessFactory factory;
512 GDBRemoteCommunicationServerLLGS gdb_server(mainloop, factory);
514 const char *const host_and_port = argv[0];
518 // Any arguments left over are for the program that we need to launch. If
520 // are no arguments, then the GDB server will start up and wait for an 'A'
522 // to launch a program, or a vAttach packet to attach to an existing process,
524 // explicitly asked to attach with the --attach={pid|program_name} form.
525 if (!attach_target.empty())
526 handle_attach(gdb_server, attach_target);
528 handle_launch(gdb_server, argc, argv);
530 // Print version info.
531 printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
533 ConnectToRemote(mainloop, gdb_server, reverse_connect, host_and_port,
534 progname, subcommand, named_pipe_path.c_str(),
535 unnamed_pipe_fd, connection_fd);
537 if (!gdb_server.IsConnected()) {
538 fprintf(stderr, "no connection information provided, unable to run\n");
539 display_usage(progname, subcommand);
544 fprintf(stderr, "lldb-server exiting...\n");