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