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