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