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