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