1 //===-- lldb-platform.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 #if defined(__APPLE__)
13 #include <netinet/in.h>
14 #endif
15 #include <signal.h>
16 #include <stdint.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <sys/wait.h>
21 
22 // C++ Includes
23 #include <fstream>
24 
25 // Other libraries and framework includes
26 #include "lldb/Core/Error.h"
27 #include "lldb/Host/ConnectionFileDescriptor.h"
28 #include "lldb/Host/FileSpec.h"
29 #include "lldb/Host/FileSystem.h"
30 #include "lldb/Host/HostGetOpt.h"
31 #include "lldb/Host/OptionParser.h"
32 #include "lldb/Host/Socket.h"
33 #include "llvm/Support/FileSystem.h"
34 #include "llvm/Support/FileUtilities.h"
35 #include "LLDBServerUtilities.h"
36 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h"
37 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 using namespace lldb_private::lldb_server;
42 using namespace lldb_private::process_gdb_remote;
43 using namespace llvm;
44 
45 //----------------------------------------------------------------------
46 // option descriptors for getopt_long_only()
47 //----------------------------------------------------------------------
48 
49 static int g_debug = 0;
50 static int g_verbose = 0;
51 static int g_server = 0;
52 
53 static struct option g_long_options[] =
54 {
55     { "debug",              no_argument,        &g_debug,           1   },
56     { "verbose",            no_argument,        &g_verbose,         1   },
57     { "log-file",           required_argument,  NULL,               'l' },
58     { "log-channels",       required_argument,  NULL,               'c' },
59     { "listen",             required_argument,  NULL,               'L' },
60     { "port-offset",        required_argument,  NULL,               'p' },
61     { "gdbserver-port",     required_argument,  NULL,               'P' },
62     { "min-gdbserver-port", required_argument,  NULL,               'm' },
63     { "max-gdbserver-port", required_argument,  NULL,               'M' },
64     { "port-file",          required_argument,  NULL,               'f' },
65     { "server",             no_argument,        &g_server,          1   },
66     { NULL,                 0,                  NULL,               0   }
67 };
68 
69 #if defined (__APPLE__)
70 #define LOW_PORT    (IPPORT_RESERVED)
71 #define HIGH_PORT   (IPPORT_HIFIRSTAUTO)
72 #else
73 #define LOW_PORT    (1024u)
74 #define HIGH_PORT   (49151u)
75 #endif
76 
77 //----------------------------------------------------------------------
78 // Watch for signals
79 //----------------------------------------------------------------------
80 static void
81 signal_handler(int signo)
82 {
83     switch (signo)
84     {
85     case SIGHUP:
86         // Use SIGINT first, if that does not work, use SIGHUP as a last resort.
87         // And we should not call exit() here because it results in the global destructors
88         // to be invoked and wreaking havoc on the threads still running.
89         Host::SystemLog(Host::eSystemLogWarning, "SIGHUP received, exiting lldb-server...\n");
90         abort();
91         break;
92     }
93 }
94 
95 static void
96 display_usage (const char *progname, const char *subcommand)
97 {
98     fprintf(stderr, "Usage:\n  %s %s [--log-file log-file-name] [--log-channels log-channel-list] [--port-file port-file-path] --server --listen port\n", progname, subcommand);
99     exit(0);
100 }
101 
102 static Error
103 save_port_to_file(const uint16_t port, const FileSpec &port_file_spec)
104 {
105     FileSpec temp_file_spec(port_file_spec.GetDirectory().AsCString(), false);
106     auto error = FileSystem::MakeDirectory(temp_file_spec, eFilePermissionsDirectoryDefault);
107     if (error.Fail())
108        return Error("Failed to create directory %s: %s", temp_file_spec.GetCString(), error.AsCString());
109 
110     llvm::SmallString<PATH_MAX> temp_file_path;
111     temp_file_spec.AppendPathComponent("port-file.%%%%%%");
112     auto err_code = llvm::sys::fs::createUniqueFile(temp_file_spec.GetCString(), temp_file_path);
113     if (err_code)
114         return Error("Failed to create temp file: %s", err_code.message().c_str());
115 
116     llvm::FileRemover tmp_file_remover(temp_file_path.c_str());
117 
118     {
119         std::ofstream temp_file(temp_file_path.c_str(), std::ios::out);
120         if (!temp_file.is_open())
121             return Error("Failed to open temp file %s", temp_file_path.c_str());
122         temp_file << port;
123     }
124 
125     err_code = llvm::sys::fs::rename(temp_file_path.c_str(), port_file_spec.GetPath().c_str());
126     if (err_code)
127         return Error("Failed to rename file %s to %s: %s",
128                      temp_file_path.c_str(), port_file_spec.GetPath().c_str(), err_code.message().c_str());
129 
130     tmp_file_remover.releaseFile();
131     return Error();
132 }
133 
134 //----------------------------------------------------------------------
135 // main
136 //----------------------------------------------------------------------
137 int
138 main_platform (int argc, char *argv[])
139 {
140     const char *progname = argv[0];
141     const char *subcommand = argv[1];
142     argc--;
143     argv++;
144     signal (SIGPIPE, SIG_IGN);
145     signal (SIGHUP, signal_handler);
146     int long_option_index = 0;
147     Error error;
148     std::string listen_host_port;
149     int ch;
150 
151     std::string log_file;
152     StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
153 
154     GDBRemoteCommunicationServerPlatform::PortMap gdbserver_portmap;
155     int min_gdbserver_port = 0;
156     int max_gdbserver_port = 0;
157     uint16_t port_offset = 0;
158 
159     FileSpec port_file;
160     bool show_usage = false;
161     int option_error = 0;
162     int socket_error = -1;
163 
164     std::string short_options(OptionParser::GetShortOptionString(g_long_options));
165 
166 #if __GLIBC__
167     optind = 0;
168 #else
169     optreset = 1;
170     optind = 1;
171 #endif
172 
173     while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1)
174     {
175         switch (ch)
176         {
177         case 0:   // Any optional that auto set themselves will return 0
178             break;
179 
180         case 'L':
181             listen_host_port.append (optarg);
182             break;
183 
184         case 'l': // Set Log File
185             if (optarg && optarg[0])
186                 log_file.assign(optarg);
187             break;
188 
189         case 'c': // Log Channels
190             if (optarg && optarg[0])
191                 log_channels = StringRef(optarg);
192             break;
193 
194         case 'f': // Port file
195             if (optarg && optarg[0])
196                 port_file.SetFile(optarg, false);
197             break;
198 
199         case 'p':
200             {
201                 char *end = NULL;
202                 long tmp_port_offset = strtoul(optarg, &end, 0);
203                 if (end && *end == '\0')
204                 {
205                     if (LOW_PORT <= tmp_port_offset && tmp_port_offset <= HIGH_PORT)
206                     {
207                         port_offset = (uint16_t)tmp_port_offset;
208                     }
209                     else
210                     {
211                         fprintf (stderr, "error: port offset %li is not in the valid user port range of %u - %u\n", tmp_port_offset, LOW_PORT, HIGH_PORT);
212                         option_error = 5;
213                     }
214                 }
215                 else
216                 {
217                     fprintf (stderr, "error: invalid port offset string %s\n", optarg);
218                     option_error = 4;
219                 }
220             }
221             break;
222 
223         case 'P':
224         case 'm':
225         case 'M':
226             {
227                 char *end = NULL;
228                 long portnum = strtoul(optarg, &end, 0);
229                 if (end && *end == '\0')
230                 {
231                     if (LOW_PORT <= portnum && portnum <= HIGH_PORT)
232                     {
233                         if (ch  == 'P')
234                             gdbserver_portmap[(uint16_t)portnum] = LLDB_INVALID_PROCESS_ID;
235                         else if (ch == 'm')
236                             min_gdbserver_port = portnum;
237                         else
238                             max_gdbserver_port = portnum;
239                     }
240                     else
241                     {
242                         fprintf (stderr, "error: port number %li is not in the valid user port range of %u - %u\n", portnum, LOW_PORT, HIGH_PORT);
243                         option_error = 1;
244                     }
245                 }
246                 else
247                 {
248                     fprintf (stderr, "error: invalid port number string %s\n", optarg);
249                     option_error = 2;
250                 }
251             }
252             break;
253 
254         case 'h':   /* fall-through is intentional */
255         case '?':
256             show_usage = true;
257             break;
258         }
259     }
260 
261     if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
262         return -1;
263 
264     // Make a port map for a port range that was specified.
265     if (min_gdbserver_port < max_gdbserver_port)
266     {
267         for (uint16_t port = min_gdbserver_port; port < max_gdbserver_port; ++port)
268             gdbserver_portmap[port] = LLDB_INVALID_PROCESS_ID;
269     }
270     else if (min_gdbserver_port != max_gdbserver_port)
271     {
272         fprintf (stderr, "error: --min-gdbserver-port (%u) is greater than --max-gdbserver-port (%u)\n", min_gdbserver_port, max_gdbserver_port);
273         option_error = 3;
274     }
275 
276     // Print usage and exit if no listening port is specified.
277     if (listen_host_port.empty())
278         show_usage = true;
279 
280     if (show_usage || option_error)
281     {
282         display_usage(progname, subcommand);
283         exit(option_error);
284     }
285 
286     std::unique_ptr<Socket> listening_socket_up;
287     Socket *socket = nullptr;
288     const bool children_inherit_listen_socket = false;
289 
290     // the test suite makes many connections in parallel, let's not miss any.
291     // The highest this should get reasonably is a function of the number
292     // of target CPUs.  For now, let's just use 100
293     const int backlog = 100;
294     error = Socket::TcpListen(listen_host_port.c_str(), children_inherit_listen_socket, socket, NULL, backlog);
295     if (error.Fail())
296     {
297         printf("error: %s\n", error.AsCString());
298         exit(socket_error);
299     }
300     listening_socket_up.reset(socket);
301     printf ("Listening for a connection from %u...\n", listening_socket_up->GetLocalPortNumber());
302     if (port_file)
303     {
304         error = save_port_to_file(listening_socket_up->GetLocalPortNumber(), port_file);
305         if (error.Fail())
306         {
307             fprintf(stderr, "failed to write port to %s: %s", port_file.GetPath().c_str(), error.AsCString());
308             return 1;
309         }
310     }
311 
312     do {
313         GDBRemoteCommunicationServerPlatform platform;
314 
315         if (port_offset > 0)
316             platform.SetPortOffset(port_offset);
317 
318         if (!gdbserver_portmap.empty())
319         {
320             platform.SetPortMap(std::move(gdbserver_portmap));
321         }
322 
323         const bool children_inherit_accept_socket = true;
324         socket = nullptr;
325         error = listening_socket_up->BlockingAccept(listen_host_port.c_str(), children_inherit_accept_socket, socket);
326         if (error.Fail())
327         {
328             printf ("error: %s\n", error.AsCString());
329             exit(socket_error);
330         }
331         printf ("Connection established.\n");
332         if (g_server)
333         {
334             // Collect child zombie processes.
335             while (waitpid(-1, nullptr, WNOHANG) > 0);
336             if (fork())
337             {
338                 // Parent doesn't need a connection to the lldb client
339                 delete socket;
340                 socket = nullptr;
341 
342                 // Parent will continue to listen for new connections.
343                 continue;
344             }
345             else
346             {
347                 // Child process will handle the connection and exit.
348                 g_server = 0;
349                 // Listening socket is owned by parent process.
350                 listening_socket_up.release();
351             }
352         }
353         else
354         {
355             // If not running as a server, this process will not accept
356             // connections while a connection is active.
357             listening_socket_up.reset();
358         }
359         platform.SetConnection (new ConnectionFileDescriptor(socket));
360 
361         if (platform.IsConnected())
362         {
363             // After we connected, we need to get an initial ack from...
364             if (platform.HandshakeWithClient())
365             {
366                 bool interrupt = false;
367                 bool done = false;
368                 while (!interrupt && !done)
369                 {
370                     if (platform.GetPacketAndSendResponse (UINT32_MAX, error, interrupt, done) != GDBRemoteCommunication::PacketResult::Success)
371                         break;
372                 }
373 
374                 if (error.Fail())
375                 {
376                     fprintf(stderr, "error: %s\n", error.AsCString());
377                 }
378             }
379             else
380             {
381                 fprintf(stderr, "error: handshake with client failed\n");
382             }
383         }
384     } while (g_server);
385 
386     fprintf(stderr, "lldb-server exiting...\n");
387 
388     return 0;
389 }
390