]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tools/lldb-server/lldb-gdbserver.cpp
Vendor import of (stripped) lldb trunk r242221:
[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 <getopt.h>
13 #include <stdint.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17
18 #ifndef _WIN32
19 #include <signal.h>
20 #include <unistd.h>
21 #endif
22
23 // C++ Includes
24
25 // Other libraries and framework includes
26 #include "llvm/ADT/StringRef.h"
27
28 #include "lldb/Core/ConnectionMachPort.h"
29 #include "lldb/Core/Error.h"
30 #include "lldb/Core/PluginManager.h"
31 #include "lldb/Host/ConnectionFileDescriptor.h"
32 #include "lldb/Host/HostThread.h"
33 #include "lldb/Host/OptionParser.h"
34 #include "lldb/Host/Pipe.h"
35 #include "lldb/Host/Socket.h"
36 #include "lldb/Host/StringConvert.h"
37 #include "lldb/Host/ThreadLauncher.h"
38 #include "lldb/Target/Platform.h"
39 #include "LLDBServerUtilities.h"
40 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
41 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
42
43 #ifndef LLGS_PROGRAM_NAME
44 #define LLGS_PROGRAM_NAME "lldb-server"
45 #endif
46
47 #ifndef LLGS_VERSION_STR
48 #define LLGS_VERSION_STR "local_build"
49 #endif
50
51 using namespace llvm;
52 using namespace lldb;
53 using namespace lldb_private;
54 using namespace lldb_private::lldb_server;
55 using namespace lldb_private::process_gdb_remote;
56
57 // lldb-gdbserver state
58
59 namespace
60 {
61 HostThread s_listen_thread;
62     std::unique_ptr<ConnectionFileDescriptor> s_listen_connection_up;
63     std::string s_listen_url;
64 }
65
66 //----------------------------------------------------------------------
67 // option descriptors for getopt_long_only()
68 //----------------------------------------------------------------------
69
70 static int g_debug = 0;
71 static int g_verbose = 0;
72
73 static struct option g_long_options[] =
74 {
75     { "debug",              no_argument,        &g_debug,           1   },
76     { "platform",           required_argument,  NULL,               'p' },
77     { "verbose",            no_argument,        &g_verbose,         1   },
78     { "log-file",           required_argument,  NULL,               'l' },
79     { "log-channels",       required_argument,  NULL,               'c' },
80     { "attach",             required_argument,  NULL,               'a' },
81     { "named-pipe",         required_argument,  NULL,               'N' },
82     { "pipe",               required_argument,  NULL,               'U' },
83     { "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.
84     { "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.
85     { "setsid",             no_argument,        NULL,               'S' },  // Call setsid() to make llgs run in its own session.
86     { NULL,                 0,                  NULL,               0   }
87 };
88
89
90 //----------------------------------------------------------------------
91 // Watch for signals
92 //----------------------------------------------------------------------
93 static int g_sigpipe_received = 0;
94 static int g_sighup_received_count = 0;
95
96 #ifndef _WIN32
97
98 static void
99 signal_handler(int signo)
100 {
101     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
102
103     fprintf (stderr, "lldb-server:%s received signal %d\n", __FUNCTION__, signo);
104     if (log)
105         log->Printf ("lldb-server:%s received signal %d", __FUNCTION__, signo);
106
107     switch (signo)
108     {
109     case SIGPIPE:
110         g_sigpipe_received = 1;
111         break;
112     }
113 }
114
115 static void
116 sighup_handler(MainLoopBase &mainloop)
117 {
118     ++g_sighup_received_count;
119
120     Log *log (GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
121     if (log)
122         log->Printf ("lldb-server:%s swallowing SIGHUP (receive count=%d)", __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
130 display_usage (const char *progname, const char* subcommand)
131 {
132     fprintf(stderr, "Usage:\n  %s %s "
133             "[--log-file log-file-name] "
134             "[--log-channels log-channel-list] "
135             "[--platform platform_name] "
136             "[--setsid] "
137             "[--named-pipe named-pipe-path] "
138             "[--native-regs] "
139             "[--attach pid] "
140             "[[HOST]:PORT] "
141             "[-- PROGRAM ARG1 ARG2 ...]\n", progname, subcommand);
142     exit(0);
143 }
144
145 static void
146 dump_available_platforms (FILE *output_file)
147 {
148     fprintf (output_file, "Available platform plugins:\n");
149     for (int i = 0; ; ++i)
150     {
151         const char *plugin_name = PluginManager::GetPlatformPluginNameAtIndex (i);
152         const char *plugin_desc = PluginManager::GetPlatformPluginDescriptionAtIndex (i);
153
154         if (!plugin_name || !plugin_desc)
155             break;
156
157         fprintf (output_file, "%s\t%s\n", plugin_name, plugin_desc);
158     }
159
160     if ( Platform::GetHostPlatform () )
161     {
162         // add this since the default platform doesn't necessarily get registered by
163         // the plugin name (e.g. 'host' doesn't show up as a
164         // registered platform plugin even though it's the default).
165         fprintf (output_file, "%s\tDefault platform for this host.\n", Platform::GetHostPlatform ()->GetPluginName ().AsCString ());
166     }
167 }
168
169 static lldb::PlatformSP
170 setup_platform (const std::string &platform_name)
171 {
172     lldb::PlatformSP platform_sp;
173
174     if (platform_name.empty())
175     {
176         printf ("using the default platform: ");
177         platform_sp = Platform::GetHostPlatform ();
178         printf ("%s\n", platform_sp->GetPluginName ().AsCString ());
179         return platform_sp;
180     }
181
182     Error error;
183     platform_sp = Platform::Create (lldb_private::ConstString(platform_name), error);
184     if (error.Fail ())
185     {
186         // the host platform isn't registered with that name (at
187         // least, not always.  Check if the given name matches
188         // the default platform name.  If so, use it.
189         if ( Platform::GetHostPlatform () && ( Platform::GetHostPlatform ()->GetPluginName () == ConstString (platform_name.c_str()) ) )
190         {
191             platform_sp = Platform::GetHostPlatform ();
192         }
193         else
194         {
195             fprintf (stderr, "error: failed to create platform with name '%s'\n", platform_name.c_str());
196             dump_available_platforms (stderr);
197             exit (1);
198         }
199     }
200     printf ("using platform: %s\n", platform_name.c_str ());
201
202     return platform_sp;
203 }
204
205 void
206 handle_attach_to_pid (GDBRemoteCommunicationServerLLGS &gdb_server, lldb::pid_t pid)
207 {
208     Error error = gdb_server.AttachToProcess (pid);
209     if (error.Fail ())
210     {
211         fprintf (stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid, error.AsCString());
212         exit(1);
213     }
214 }
215
216 void
217 handle_attach_to_process_name (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &process_name)
218 {
219     // FIXME implement.
220 }
221
222 void
223 handle_attach (GDBRemoteCommunicationServerLLGS &gdb_server, const std::string &attach_target)
224 {
225     assert (!attach_target.empty () && "attach_target cannot be empty");
226
227     // First check if the attach_target is convertible to a long. If so, we'll use it as a pid.
228     char *end_p = nullptr;
229     const long int pid = strtol (attach_target.c_str (), &end_p, 10);
230
231     // We'll call it a match if the entire argument is consumed.
232     if (end_p && static_cast<size_t> (end_p - attach_target.c_str ()) == attach_target.size ())
233         handle_attach_to_pid (gdb_server, static_cast<lldb::pid_t> (pid));
234     else
235         handle_attach_to_process_name (gdb_server, attach_target);
236 }
237
238 void
239 handle_launch (GDBRemoteCommunicationServerLLGS &gdb_server, int argc, const char *const argv[])
240 {
241     Error error;
242     error = gdb_server.SetLaunchArguments (argv, argc);
243     if (error.Fail ())
244     {
245         fprintf (stderr, "error: failed to set launch args for '%s': %s\n", argv[0], error.AsCString());
246         exit(1);
247     }
248
249     unsigned int launch_flags = eLaunchFlagStopAtEntry | eLaunchFlagDebug;
250
251     error = gdb_server.SetLaunchFlags (launch_flags);
252     if (error.Fail ())
253     {
254         fprintf (stderr, "error: failed to set launch flags for '%s': %s\n", argv[0], error.AsCString());
255         exit(1);
256     }
257
258     error = gdb_server.LaunchProcess ();
259     if (error.Fail ())
260     {
261         fprintf (stderr, "error: failed to launch '%s': %s\n", argv[0], error.AsCString());
262         exit(1);
263     }
264 }
265
266 static lldb::thread_result_t
267 ListenThread (lldb::thread_arg_t /* arg */)
268 {
269     Error error;
270
271     if (s_listen_connection_up)
272     {
273         // Do the listen on another thread so we can continue on...
274         if (s_listen_connection_up->Connect(s_listen_url.c_str(), &error) != eConnectionStatusSuccess)
275             s_listen_connection_up.reset();
276     }
277     return nullptr;
278 }
279
280 static Error
281 StartListenThread (const char *hostname, uint16_t port)
282 {
283     Error error;
284     if (s_listen_thread.IsJoinable())
285     {
286         error.SetErrorString("listen thread already running");
287     }
288     else
289     {
290         char listen_url[512];
291         if (hostname && hostname[0])
292             snprintf(listen_url, sizeof(listen_url), "listen://%s:%i", hostname, port);
293         else
294             snprintf(listen_url, sizeof(listen_url), "listen://%i", port);
295
296         s_listen_url = listen_url;
297         s_listen_connection_up.reset (new ConnectionFileDescriptor ());
298         s_listen_thread = ThreadLauncher::LaunchThread(listen_url, ListenThread, nullptr, &error);
299     }
300     return error;
301 }
302
303 static bool
304 JoinListenThread ()
305 {
306     if (s_listen_thread.IsJoinable())
307         s_listen_thread.Join(nullptr);
308     return true;
309 }
310
311 Error
312 WritePortToPipe(Pipe &port_pipe, const uint16_t port)
313 {
314     char port_str[64];
315     const auto port_str_len = ::snprintf(port_str, sizeof(port_str), "%u", port);
316
317     size_t bytes_written = 0;
318     // Write the port number as a C string with the NULL terminator.
319     return port_pipe.Write(port_str, port_str_len + 1, bytes_written);
320 }
321
322 Error
323 writePortToPipe(const char *const named_pipe_path, const uint16_t port)
324 {
325     Pipe port_name_pipe;
326     // Wait for 10 seconds for pipe to be opened.
327     auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
328             std::chrono::seconds{10});
329     if (error.Fail())
330         return error;
331     return WritePortToPipe(port_name_pipe, port);
332 }
333
334 Error
335 writePortToPipe(int unnamed_pipe_fd, const uint16_t port)
336 {
337 #if defined(_WIN32)
338     return Error("Unnamed pipes are not supported on Windows.");
339 #else
340     Pipe port_pipe{Pipe::kInvalidDescriptor, unnamed_pipe_fd};
341     return WritePortToPipe(port_pipe, port);
342 #endif
343 }
344
345 void
346 ConnectToRemote(MainLoop &mainloop, GDBRemoteCommunicationServerLLGS &gdb_server,
347         bool reverse_connect, const char *const host_and_port,
348         const char *const progname, const char *const subcommand,
349         const char *const named_pipe_path, int unnamed_pipe_fd)
350 {
351     Error error;
352
353     if (host_and_port && host_and_port[0])
354     {
355         // Parse out host and port.
356         std::string final_host_and_port;
357         std::string connection_host;
358         std::string connection_port;
359         uint32_t connection_portno = 0;
360
361         // If host_and_port starts with ':', default the host to be "localhost" and expect the remainder to be the port.
362         if (host_and_port[0] == ':')
363             final_host_and_port.append ("localhost");
364         final_host_and_port.append (host_and_port);
365
366         const std::string::size_type colon_pos = final_host_and_port.find (':');
367         if (colon_pos != std::string::npos)
368         {
369             connection_host = final_host_and_port.substr (0, colon_pos);
370             connection_port = final_host_and_port.substr (colon_pos + 1);
371             connection_portno = StringConvert::ToUInt32 (connection_port.c_str (), 0);
372         }
373         else
374         {
375             fprintf (stderr, "failed to parse host and port from connection string '%s'\n", final_host_and_port.c_str ());
376             display_usage (progname, subcommand);
377             exit (1);
378         }
379
380         std::unique_ptr<ConnectionFileDescriptor> connection_up;
381
382         if (reverse_connect)
383         {
384             // llgs will connect to the gdb-remote client.
385
386             // Ensure we have a port number for the connection.
387             if (connection_portno == 0)
388             {
389                 fprintf (stderr, "error: port number must be specified on when using reverse connect");
390                 exit (1);
391             }
392
393             // Build the connection string.
394             char connection_url[512];
395             snprintf(connection_url, sizeof(connection_url), "connect://%s", final_host_and_port.c_str ());
396
397             // Create the connection.
398             connection_up.reset(new ConnectionFileDescriptor);
399             auto connection_result = connection_up->Connect (connection_url, &error);
400             if (connection_result != eConnectionStatusSuccess)
401             {
402                 fprintf (stderr, "error: failed to connect to client at '%s' (connection status: %d)", connection_url, static_cast<int> (connection_result));
403                 exit (-1);
404             }
405             if (error.Fail ())
406             {
407                 fprintf (stderr, "error: failed to connect to client at '%s': %s", connection_url, error.AsCString ());
408                 exit (-1);
409             }
410         }
411         else
412         {
413             // llgs will listen for connections on the given port from the given address.
414             // Start the listener on a new thread.  We need to do this so we can resolve the
415             // bound listener port.
416             StartListenThread(connection_host.c_str (), static_cast<uint16_t> (connection_portno));
417             printf ("Listening to port %s for a connection from %s...\n", connection_port.c_str (), connection_host.c_str ());
418
419             // If we have a named pipe to write the port number back to, do that now.
420             if (named_pipe_path && named_pipe_path[0] && connection_portno == 0)
421             {
422                 const uint16_t bound_port = s_listen_connection_up->GetListeningPort (10);
423                 if (bound_port > 0)
424                 {
425                     error = writePortToPipe (named_pipe_path, bound_port);
426                     if (error.Fail ())
427                     {
428                         fprintf (stderr, "failed to write to the named pipe \'%s\': %s", named_pipe_path, error.AsCString());
429                     }
430                 }
431                 else
432                 {
433                     fprintf (stderr, "unable to get the bound port for the listening connection\n");
434                 }
435             }
436
437             // If we have an unnamed pipe to write the port number back to, do that now.
438             if (unnamed_pipe_fd >= 0 && connection_portno == 0)
439             {
440                 const uint16_t bound_port = s_listen_connection_up->GetListeningPort(10);
441                 if (bound_port > 0)
442                 {
443                     error = writePortToPipe(unnamed_pipe_fd, bound_port);
444                     if (error.Fail())
445                     {
446                         fprintf(stderr, "failed to write to the unnamed pipe: %s",
447                                 error.AsCString());
448                     }
449                 }
450                 else
451                 {
452                     fprintf(stderr, "unable to get the bound port for the listening connection\n");
453                 }
454             }
455
456             // Join the listener thread.
457             if (!JoinListenThread ())
458             {
459                 fprintf (stderr, "failed to join the listener thread\n");
460                 display_usage (progname, subcommand);
461                 exit (1);
462             }
463
464             // Ensure we connected.
465             if (s_listen_connection_up)
466                 connection_up = std::move(s_listen_connection_up);
467             else
468             {
469                 fprintf (stderr, "failed to connect to '%s': %s\n", final_host_and_port.c_str (), error.AsCString ());
470                 display_usage (progname, subcommand);
471                 exit (1);
472             }
473         }
474         error = gdb_server.InitializeConnection (std::move(connection_up));
475         if (error.Fail())
476         {
477             fprintf(stderr, "Failed to initialize connection: %s\n", error.AsCString());
478             exit(-1);
479         }
480         printf ("Connection established.\n");
481     }
482 }
483
484 //----------------------------------------------------------------------
485 // main
486 //----------------------------------------------------------------------
487 int
488 main_gdbserver (int argc, char *argv[])
489 {
490     Error error;
491     MainLoop mainloop;
492 #ifndef _WIN32
493     // Setup signal handlers first thing.
494     signal (SIGPIPE, signal_handler);
495     MainLoop::SignalHandleUP sighup_handle = mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
496 #endif
497 #ifdef __linux__
498     // Block delivery of SIGCHLD on linux. NativeProcessLinux will read it using signalfd.
499     sigset_t set;
500     sigemptyset(&set);
501     sigaddset(&set, SIGCHLD);
502     pthread_sigmask(SIG_BLOCK, &set, NULL);
503 #endif
504
505     const char *progname = argv[0];
506     const char *subcommand = argv[1];
507     argc--;
508     argv++;
509     int long_option_index = 0;
510     int ch;
511     std::string platform_name;
512     std::string attach_target;
513     std::string named_pipe_path;
514     std::string log_file;
515     StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
516     int unnamed_pipe_fd = -1;
517     bool reverse_connect = false;
518
519     // ProcessLaunchInfo launch_info;
520     ProcessAttachInfo attach_info;
521
522     bool show_usage = false;
523     int option_error = 0;
524 #if __GLIBC__
525     optind = 0;
526 #else
527     optreset = 1;
528     optind = 1;
529 #endif
530
531     std::string short_options(OptionParser::GetShortOptionString(g_long_options));
532
533     while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
534     {
535         switch (ch)
536         {
537         case 0:   // Any optional that auto set themselves will return 0
538             break;
539
540         case 'l': // Set Log File
541             if (optarg && optarg[0])
542                 log_file.assign(optarg);
543             break;
544
545         case 'c': // Log Channels
546             if (optarg && optarg[0])
547                 log_channels = StringRef(optarg);
548             break;
549
550         case 'p': // platform name
551             if (optarg && optarg[0])
552                 platform_name = optarg;
553             break;
554
555         case 'N': // named pipe
556             if (optarg && optarg[0])
557                 named_pipe_path = optarg;
558             break;
559
560         case 'U': // unnamed pipe
561             if (optarg && optarg[0])
562                 unnamed_pipe_fd = StringConvert::ToUInt32(optarg, -1);
563
564         case 'r':
565             // Do nothing, native regs is the default these days
566             break;
567
568         case 'R':
569             reverse_connect = true;
570             break;
571
572 #ifndef _WIN32
573         case 'S':
574             // Put llgs into a new session. Terminals group processes
575             // into sessions and when a special terminal key sequences
576             // (like control+c) are typed they can cause signals to go out to
577             // all processes in a session. Using this --setsid (-S) option
578             // will cause debugserver to run in its own sessions and be free
579             // from such issues.
580             //
581             // This is useful when llgs is spawned from a command
582             // line application that uses llgs to do the debugging,
583             // yet that application doesn't want llgs receiving the
584             // signals sent to the session (i.e. dying when anyone hits ^C).
585             {
586                 const ::pid_t new_sid = setsid();
587                 if (new_sid == -1)
588                 {
589                     const char *errno_str = strerror(errno);
590                     fprintf (stderr, "failed to set new session id for %s (%s)\n", LLGS_PROGRAM_NAME, errno_str ? errno_str : "<no error string>");
591                 }
592             }
593             break;
594 #endif
595
596         case 'a': // attach {pid|process_name}
597             if (optarg && optarg[0])
598                 attach_target = optarg;
599                 break;
600
601         case 'h':   /* fall-through is intentional */
602         case '?':
603             show_usage = true;
604             break;
605         }
606     }
607
608     if (show_usage || option_error)
609     {
610         display_usage(progname, subcommand);
611         exit(option_error);
612     }
613
614     if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
615         return -1;
616
617     Log *log(lldb_private::GetLogIfAnyCategoriesSet (GDBR_LOG_VERBOSE));
618     if (log)
619     {
620         log->Printf ("lldb-server launch");
621         for (int i = 0; i < argc; i++)
622         {
623             log->Printf ("argv[%i] = '%s'", i, argv[i]);
624         }
625     }
626
627     // Skip any options we consumed with getopt_long_only.
628     argc -= optind;
629     argv += optind;
630
631     if (argc == 0)
632     {
633         display_usage(progname, subcommand);
634         exit(255);
635     }
636
637     // Setup the platform that GDBRemoteCommunicationServerLLGS will use.
638     lldb::PlatformSP platform_sp = setup_platform (platform_name);
639
640     GDBRemoteCommunicationServerLLGS gdb_server (platform_sp, mainloop);
641
642     const char *const host_and_port = argv[0];
643     argc -= 1;
644     argv += 1;
645
646     // Any arguments left over are for the program that we need to launch. If there
647     // are no arguments, then the GDB server will start up and wait for an 'A' packet
648     // to launch a program, or a vAttach packet to attach to an existing process, unless
649     // explicitly asked to attach with the --attach={pid|program_name} form.
650     if (!attach_target.empty ())
651         handle_attach (gdb_server, attach_target);
652     else if (argc > 0)
653         handle_launch (gdb_server, argc, argv);
654
655     // Print version info.
656     printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
657
658     ConnectToRemote(mainloop, gdb_server, reverse_connect,
659                     host_and_port, progname, subcommand,
660                     named_pipe_path.c_str(), unnamed_pipe_fd);
661
662
663     if (! gdb_server.IsConnected())
664     {
665         fprintf (stderr, "no connection information provided, unable to run\n");
666         display_usage (progname, subcommand);
667         return 1;
668     }
669
670     mainloop.Run();
671     fprintf(stderr, "lldb-server exiting...\n");
672
673     return 0;
674 }