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