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