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