xref: /freebsd/contrib/llvm-project/lldb/tools/lldb-server/lldb-gdbserver.cpp (revision 5ffd83dbcc34f10e07f6d3e968ae6365869615f4)
1 //===-- lldb-gdbserver.cpp --------------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <errno.h>
10 #include <stdint.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 
15 #ifndef _WIN32
16 #include <signal.h>
17 #include <unistd.h>
18 #endif
19 
20 
21 #include "Acceptor.h"
22 #include "LLDBServerUtilities.h"
23 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
24 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
25 #include "lldb/Host/Config.h"
26 #include "lldb/Host/ConnectionFileDescriptor.h"
27 #include "lldb/Host/FileSystem.h"
28 #include "lldb/Host/HostGetOpt.h"
29 #include "lldb/Host/OptionParser.h"
30 #include "lldb/Host/Pipe.h"
31 #include "lldb/Host/Socket.h"
32 #include "lldb/Host/StringConvert.h"
33 #include "lldb/Host/common/NativeProcessProtocol.h"
34 #include "lldb/Target/Process.h"
35 #include "lldb/Utility/Status.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/Support/Errno.h"
38 
39 #if defined(__linux__)
40 #include "Plugins/Process/Linux/NativeProcessLinux.h"
41 #elif defined(__NetBSD__)
42 #include "Plugins/Process/NetBSD/NativeProcessNetBSD.h"
43 #elif defined(_WIN32)
44 #include "Plugins/Process/Windows/Common/NativeProcessWindows.h"
45 #endif
46 
47 #ifndef LLGS_PROGRAM_NAME
48 #define LLGS_PROGRAM_NAME "lldb-server"
49 #endif
50 
51 #ifndef LLGS_VERSION_STR
52 #define LLGS_VERSION_STR "local_build"
53 #endif
54 
55 using namespace llvm;
56 using namespace lldb;
57 using namespace lldb_private;
58 using namespace lldb_private::lldb_server;
59 using namespace lldb_private::process_gdb_remote;
60 
61 namespace {
62 #if defined(__linux__)
63 typedef process_linux::NativeProcessLinux::Factory NativeProcessFactory;
64 #elif defined(__NetBSD__)
65 typedef process_netbsd::NativeProcessNetBSD::Factory NativeProcessFactory;
66 #elif defined(_WIN32)
67 typedef NativeProcessWindows::Factory NativeProcessFactory;
68 #else
69 // Dummy implementation to make sure the code compiles
70 class NativeProcessFactory : public NativeProcessProtocol::Factory {
71 public:
72   llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
73   Launch(ProcessLaunchInfo &launch_info,
74          NativeProcessProtocol::NativeDelegate &delegate,
75          MainLoop &mainloop) const override {
76     llvm_unreachable("Not implemented");
77   }
78   llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
79   Attach(lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &delegate,
80          MainLoop &mainloop) const override {
81     llvm_unreachable("Not implemented");
82   }
83 };
84 #endif
85 }
86 
87 // option descriptors for getopt_long_only()
88 
89 static int g_debug = 0;
90 static int g_verbose = 0;
91 
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, nullptr, 'l'},
96     {"log-channels", required_argument, nullptr, 'c'},
97     {"attach", required_argument, nullptr, 'a'},
98     {"named-pipe", required_argument, nullptr, 'N'},
99     {"pipe", required_argument, nullptr, 'U'},
100     {"native-regs", no_argument, nullptr,
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, nullptr,
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, nullptr,
108      'S'}, // Call setsid() to make llgs run in its own session.
109     {"fd", required_argument, nullptr, 'F'},
110     {nullptr, 0, nullptr, 0}};
111 
112 #ifndef _WIN32
113 // Watch for signals
114 static int g_sighup_received_count = 0;
115 
116 static void sighup_handler(MainLoopBase &mainloop) {
117   ++g_sighup_received_count;
118 
119   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
120   LLDB_LOGF(log, "lldb-server:%s swallowing SIGHUP (receive count=%d)",
121             __FUNCTION__, g_sighup_received_count);
122 
123   if (g_sighup_received_count >= 2)
124     mainloop.RequestTermination();
125 }
126 #endif // #ifndef _WIN32
127 
128 static void display_usage(const char *progname, const char *subcommand) {
129   fprintf(stderr, "Usage:\n  %s %s "
130                   "[--log-file log-file-name] "
131                   "[--log-channels log-channel-list] "
132                   "[--setsid] "
133                   "[--fd file-descriptor]"
134                   "[--named-pipe named-pipe-path] "
135                   "[--native-regs] "
136                   "[--attach pid] "
137                   "[[HOST]:PORT] "
138                   "[-- PROGRAM ARG1 ARG2 ...]\n",
139           progname, subcommand);
140 }
141 
142 void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS &gdb_server,
143                           lldb::pid_t pid) {
144   Status error = gdb_server.AttachToProcess(pid);
145   if (error.Fail()) {
146     fprintf(stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid,
147             error.AsCString());
148     exit(1);
149   }
150 }
151 
152 void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS &gdb_server,
153                                    const std::string &process_name) {
154   // FIXME implement.
155 }
156 
157 void handle_attach(GDBRemoteCommunicationServerLLGS &gdb_server,
158                    const std::string &attach_target) {
159   assert(!attach_target.empty() && "attach_target cannot be empty");
160 
161   // First check if the attach_target is convertible to a long. If so, we'll use
162   // it as a pid.
163   char *end_p = nullptr;
164   const long int pid = strtol(attach_target.c_str(), &end_p, 10);
165 
166   // We'll call it a match if the entire argument is consumed.
167   if (end_p &&
168       static_cast<size_t>(end_p - attach_target.c_str()) ==
169           attach_target.size())
170     handle_attach_to_pid(gdb_server, static_cast<lldb::pid_t>(pid));
171   else
172     handle_attach_to_process_name(gdb_server, attach_target);
173 }
174 
175 void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server, int argc,
176                    const char *const argv[]) {
177   ProcessLaunchInfo info;
178   info.GetFlags().Set(eLaunchFlagStopAtEntry | eLaunchFlagDebug |
179                       eLaunchFlagDisableASLR);
180   info.SetArguments(const_cast<const char **>(argv), true);
181 
182   llvm::SmallString<64> cwd;
183   if (std::error_code ec = llvm::sys::fs::current_path(cwd)) {
184     llvm::errs() << "Error getting current directory: " << ec.message() << "\n";
185     exit(1);
186   }
187   FileSpec cwd_spec(cwd);
188   FileSystem::Instance().Resolve(cwd_spec);
189   info.SetWorkingDirectory(cwd_spec);
190   info.GetEnvironment() = Host::GetEnvironment();
191 
192   gdb_server.SetLaunchInfo(info);
193 
194   Status error = gdb_server.LaunchProcess();
195   if (error.Fail()) {
196     llvm::errs() << llvm::formatv("error: failed to launch '{0}': {1}\n",
197                                   argv[0], error);
198     exit(1);
199   }
200 }
201 
202 Status writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id) {
203   size_t bytes_written = 0;
204   // Write the port number as a C string with the NULL terminator.
205   return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1,
206                          bytes_written);
207 }
208 
209 Status writeSocketIdToPipe(const char *const named_pipe_path,
210                            const std::string &socket_id) {
211   Pipe port_name_pipe;
212   // Wait for 10 seconds for pipe to be opened.
213   auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
214                                                       std::chrono::seconds{10});
215   if (error.Fail())
216     return error;
217   return writeSocketIdToPipe(port_name_pipe, socket_id);
218 }
219 
220 Status writeSocketIdToPipe(lldb::pipe_t unnamed_pipe,
221                            const std::string &socket_id) {
222   Pipe port_pipe{LLDB_INVALID_PIPE, unnamed_pipe};
223   return writeSocketIdToPipe(port_pipe, socket_id);
224 }
225 
226 void ConnectToRemote(MainLoop &mainloop,
227                      GDBRemoteCommunicationServerLLGS &gdb_server,
228                      bool reverse_connect, const char *const host_and_port,
229                      const char *const progname, const char *const subcommand,
230                      const char *const named_pipe_path, pipe_t unnamed_pipe,
231                      int connection_fd) {
232   Status error;
233 
234   std::unique_ptr<Connection> connection_up;
235   if (connection_fd != -1) {
236     // Build the connection string.
237     char connection_url[512];
238     snprintf(connection_url, sizeof(connection_url), "fd://%d", connection_fd);
239 
240     // Create the connection.
241 #if LLDB_ENABLE_POSIX && !defined _WIN32
242     ::fcntl(connection_fd, F_SETFD, FD_CLOEXEC);
243 #endif
244     connection_up.reset(new ConnectionFileDescriptor);
245     auto connection_result = connection_up->Connect(connection_url, &error);
246     if (connection_result != eConnectionStatusSuccess) {
247       fprintf(stderr, "error: failed to connect to client at '%s' "
248                       "(connection status: %d)\n",
249               connection_url, static_cast<int>(connection_result));
250       exit(-1);
251     }
252     if (error.Fail()) {
253       fprintf(stderr, "error: failed to connect to client at '%s': %s\n",
254               connection_url, error.AsCString());
255       exit(-1);
256     }
257   } else if (host_and_port && host_and_port[0]) {
258     // Parse out host and port.
259     std::string final_host_and_port;
260     std::string connection_host;
261     std::string connection_port;
262     uint32_t connection_portno = 0;
263 
264     // If host_and_port starts with ':', default the host to be "localhost" and
265     // expect the remainder to be the port.
266     if (host_and_port[0] == ':')
267       final_host_and_port.append("localhost");
268     final_host_and_port.append(host_and_port);
269 
270     const std::string::size_type colon_pos = final_host_and_port.find(':');
271     if (colon_pos != std::string::npos) {
272       connection_host = final_host_and_port.substr(0, colon_pos);
273       connection_port = final_host_and_port.substr(colon_pos + 1);
274       connection_portno = StringConvert::ToUInt32(connection_port.c_str(), 0);
275     }
276 
277 
278     if (reverse_connect) {
279       // llgs will connect to the gdb-remote client.
280 
281       // Ensure we have a port number for the connection.
282       if (connection_portno == 0) {
283         fprintf(stderr, "error: port number must be specified on when using "
284                         "reverse connect\n");
285         exit(1);
286       }
287 
288       // Build the connection string.
289       char connection_url[512];
290       snprintf(connection_url, sizeof(connection_url), "connect://%s",
291                final_host_and_port.c_str());
292 
293       // Create the connection.
294       connection_up.reset(new ConnectionFileDescriptor);
295       auto connection_result = connection_up->Connect(connection_url, &error);
296       if (connection_result != eConnectionStatusSuccess) {
297         fprintf(stderr, "error: failed to connect to client at '%s' "
298                         "(connection status: %d)\n",
299                 connection_url, static_cast<int>(connection_result));
300         exit(-1);
301       }
302       if (error.Fail()) {
303         fprintf(stderr, "error: failed to connect to client at '%s': %s\n",
304                 connection_url, error.AsCString());
305         exit(-1);
306       }
307     } else {
308       std::unique_ptr<Acceptor> acceptor_up(
309           Acceptor::Create(final_host_and_port, false, error));
310       if (error.Fail()) {
311         fprintf(stderr, "failed to create acceptor: %s\n", error.AsCString());
312         exit(1);
313       }
314       error = acceptor_up->Listen(1);
315       if (error.Fail()) {
316         fprintf(stderr, "failed to listen: %s\n", error.AsCString());
317         exit(1);
318       }
319       const std::string socket_id = acceptor_up->GetLocalSocketId();
320       if (!socket_id.empty()) {
321         // If we have a named pipe to write the socket id back to, do that now.
322         if (named_pipe_path && named_pipe_path[0]) {
323           error = writeSocketIdToPipe(named_pipe_path, socket_id);
324           if (error.Fail())
325             fprintf(stderr, "failed to write to the named pipe \'%s\': %s\n",
326                     named_pipe_path, error.AsCString());
327         }
328         // If we have an unnamed pipe to write the socket id back to, do that
329         // now.
330         else if (unnamed_pipe != LLDB_INVALID_PIPE) {
331           error = writeSocketIdToPipe(unnamed_pipe, socket_id);
332           if (error.Fail())
333             fprintf(stderr, "failed to write to the unnamed pipe: %s\n",
334                     error.AsCString());
335         }
336       } else {
337         fprintf(stderr,
338                 "unable to get the socket id for the listening connection\n");
339       }
340 
341       Connection *conn = nullptr;
342       error = acceptor_up->Accept(false, conn);
343       if (error.Fail()) {
344         printf("failed to accept new connection: %s\n", error.AsCString());
345         exit(1);
346       }
347       connection_up.reset(conn);
348     }
349   }
350   error = gdb_server.InitializeConnection(std::move(connection_up));
351   if (error.Fail()) {
352     fprintf(stderr, "Failed to initialize connection: %s\n",
353             error.AsCString());
354     exit(-1);
355   }
356   printf("Connection established.\n");
357 }
358 
359 // main
360 int main_gdbserver(int argc, char *argv[]) {
361   Status error;
362   MainLoop mainloop;
363 #ifndef _WIN32
364   // Setup signal handlers first thing.
365   signal(SIGPIPE, SIG_IGN);
366   MainLoop::SignalHandleUP sighup_handle =
367       mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
368 #endif
369 
370   const char *progname = argv[0];
371   const char *subcommand = argv[1];
372   argc--;
373   argv++;
374   int long_option_index = 0;
375   int ch;
376   std::string attach_target;
377   std::string named_pipe_path;
378   std::string log_file;
379   StringRef
380       log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
381   lldb::pipe_t unnamed_pipe = LLDB_INVALID_PIPE;
382   bool reverse_connect = false;
383   int connection_fd = -1;
384 
385   // ProcessLaunchInfo launch_info;
386   ProcessAttachInfo attach_info;
387 
388   bool show_usage = false;
389   int option_error = 0;
390 #if __GLIBC__
391   optind = 0;
392 #else
393   optreset = 1;
394   optind = 1;
395 #endif
396 
397   std::string short_options(OptionParser::GetShortOptionString(g_long_options));
398 
399   while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
400                                 g_long_options, &long_option_index)) != -1) {
401     switch (ch) {
402     case 0: // Any optional that auto set themselves will return 0
403       break;
404 
405     case 'l': // Set Log File
406       if (optarg && optarg[0])
407         log_file.assign(optarg);
408       break;
409 
410     case 'c': // Log Channels
411       if (optarg && optarg[0])
412         log_channels = StringRef(optarg);
413       break;
414 
415     case 'N': // named pipe
416       if (optarg && optarg[0])
417         named_pipe_path = optarg;
418       break;
419 
420     case 'U': // unnamed pipe
421       if (optarg && optarg[0])
422         unnamed_pipe = (pipe_t)StringConvert::ToUInt64(optarg, -1);
423       break;
424 
425     case 'r':
426       // Do nothing, native regs is the default these days
427       break;
428 
429     case 'R':
430       reverse_connect = true;
431       break;
432 
433     case 'F':
434       connection_fd = StringConvert::ToUInt32(optarg, -1);
435       break;
436 
437 #ifndef _WIN32
438     case 'S':
439       // Put llgs into a new session. Terminals group processes
440       // into sessions and when a special terminal key sequences
441       // (like control+c) are typed they can cause signals to go out to
442       // all processes in a session. Using this --setsid (-S) option
443       // will cause debugserver to run in its own sessions and be free
444       // from such issues.
445       //
446       // This is useful when llgs is spawned from a command
447       // line application that uses llgs to do the debugging,
448       // yet that application doesn't want llgs receiving the
449       // signals sent to the session (i.e. dying when anyone hits ^C).
450       {
451         const ::pid_t new_sid = setsid();
452         if (new_sid == -1) {
453           llvm::errs() << llvm::formatv(
454               "failed to set new session id for {0} ({1})\n", LLGS_PROGRAM_NAME,
455               llvm::sys::StrError());
456         }
457       }
458       break;
459 #endif
460 
461     case 'a': // attach {pid|process_name}
462       if (optarg && optarg[0])
463         attach_target = optarg;
464       break;
465 
466     case 'h': /* fall-through is intentional */
467     case '?':
468       show_usage = true;
469       break;
470     }
471   }
472 
473   if (show_usage || option_error) {
474     display_usage(progname, subcommand);
475     exit(option_error);
476   }
477 
478   if (!LLDBServerUtilities::SetupLogging(
479           log_file, log_channels,
480           LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
481               LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION))
482     return -1;
483 
484   Log *log(lldb_private::GetLogIfAnyCategoriesSet(GDBR_LOG_PROCESS));
485   if (log) {
486     LLDB_LOGF(log, "lldb-server launch");
487     for (int i = 0; i < argc; i++) {
488       LLDB_LOGF(log, "argv[%i] = '%s'", i, argv[i]);
489     }
490   }
491 
492   // Skip any options we consumed with getopt_long_only.
493   argc -= optind;
494   argv += optind;
495 
496   if (argc == 0 && connection_fd == -1) {
497     fputs("No arguments\n", stderr);
498     display_usage(progname, subcommand);
499     exit(255);
500   }
501 
502   NativeProcessFactory factory;
503   GDBRemoteCommunicationServerLLGS gdb_server(mainloop, factory);
504 
505   const char *const host_and_port = argv[0];
506   argc -= 1;
507   argv += 1;
508 
509   // Any arguments left over are for the program that we need to launch. If
510   // there
511   // are no arguments, then the GDB server will start up and wait for an 'A'
512   // packet
513   // to launch a program, or a vAttach packet to attach to an existing process,
514   // unless
515   // explicitly asked to attach with the --attach={pid|program_name} form.
516   if (!attach_target.empty())
517     handle_attach(gdb_server, attach_target);
518   else if (argc > 0)
519     handle_launch(gdb_server, argc, argv);
520 
521   // Print version info.
522   printf("%s-%s\n", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
523 
524   ConnectToRemote(mainloop, gdb_server, reverse_connect, host_and_port,
525                   progname, subcommand, named_pipe_path.c_str(),
526                   unnamed_pipe, connection_fd);
527 
528   if (!gdb_server.IsConnected()) {
529     fprintf(stderr, "no connection information provided, unable to run\n");
530     display_usage(progname, subcommand);
531     return 1;
532   }
533 
534   Status ret = mainloop.Run();
535   if (ret.Fail()) {
536     fprintf(stderr, "lldb-server terminating due to error: %s\n",
537             ret.AsCString());
538     return 1;
539   }
540   fprintf(stderr, "lldb-server exiting...\n");
541 
542   return 0;
543 }
544