blob: 3da3c09a90df3b70eeddf05768c55511599d49a0 [file] [log] [blame]
Greg Claytonb43767a2011-03-22 01:34:44 +00001//===-- 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
Greg Claytond314e812011-03-23 00:09:55 +000010// C Includes
Greg Claytonb43767a2011-03-22 01:34:44 +000011#include <errno.h>
Zachary Turner98688922014-08-06 18:16:26 +000012#if defined(__APPLE__)
13#include <netinet/in.h>
14#endif
Greg Claytonb43767a2011-03-22 01:34:44 +000015#include <signal.h>
16#include <stdint.h>
17#include <stdio.h>
18#include <stdlib.h>
19#include <string.h>
Robert Flacka0e70cd2015-03-25 12:51:31 +000020#include <sys/wait.h>
Greg Claytonb43767a2011-03-22 01:34:44 +000021
Greg Claytond314e812011-03-23 00:09:55 +000022// C++ Includes
Oleksiy Vyalov298be462015-07-06 18:05:19 +000023#include <fstream>
Greg Claytond314e812011-03-23 00:09:55 +000024
25// Other libraries and framework includes
Oleksiy Vyalov9fe526c2015-10-21 19:34:26 +000026#include "llvm/Support/FileSystem.h"
27#include "llvm/Support/FileUtilities.h"
28
Kate Stoneb9c1b512016-09-06 20:57:50 +000029#include "Acceptor.h"
30#include "LLDBServerUtilities.h"
31#include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerPlatform.h"
32#include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
Zachary Turner93a66fc2014-10-06 21:22:36 +000033#include "lldb/Host/ConnectionFileDescriptor.h"
Oleksiy Vyalov298be462015-07-06 18:05:19 +000034#include "lldb/Host/FileSpec.h"
Zachary Turner98688922014-08-06 18:16:26 +000035#include "lldb/Host/HostGetOpt.h"
Greg Claytonfb909312013-11-23 01:58:15 +000036#include "lldb/Host/OptionParser.h"
Oleksiy Vyalove98628c2015-10-15 23:54:09 +000037#include "lldb/Host/common/TCPSocket.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000038#include "lldb/Utility/Error.h"
Tamas Berghammere13c2732015-02-11 10:29:30 +000039
Greg Claytond314e812011-03-23 00:09:55 +000040using namespace lldb;
41using namespace lldb_private;
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +000042using namespace lldb_private::lldb_server;
Tamas Berghammerdb264a62015-03-31 09:52:22 +000043using namespace lldb_private::process_gdb_remote;
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +000044using namespace llvm;
Greg Claytond314e812011-03-23 00:09:55 +000045
Greg Claytonb43767a2011-03-22 01:34:44 +000046//----------------------------------------------------------------------
Greg Claytonb7ad58a2013-04-04 20:35:24 +000047// option descriptors for getopt_long_only()
Greg Claytonb43767a2011-03-22 01:34:44 +000048//----------------------------------------------------------------------
49
Tamas Berghammerc2c3d712015-02-18 15:39:41 +000050static int g_debug = 0;
51static int g_verbose = 0;
Robert Flacka0e70cd2015-03-25 12:51:31 +000052static int g_server = 0;
Greg Claytonb43767a2011-03-22 01:34:44 +000053
Kate Stoneb9c1b512016-09-06 20:57:50 +000054static struct option g_long_options[] = {
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 {"socket-file", required_argument, NULL, 'f'},
65 {"server", no_argument, &g_server, 1},
66 {NULL, 0, NULL, 0}};
Greg Claytonb43767a2011-03-22 01:34:44 +000067
Kate Stoneb9c1b512016-09-06 20:57:50 +000068#if defined(__APPLE__)
69#define LOW_PORT (IPPORT_RESERVED)
70#define HIGH_PORT (IPPORT_HIFIRSTAUTO)
Greg Clayton29b8fc42013-11-21 01:44:58 +000071#else
Kate Stoneb9c1b512016-09-06 20:57:50 +000072#define LOW_PORT (1024u)
73#define HIGH_PORT (49151u)
Greg Clayton29b8fc42013-11-21 01:44:58 +000074#endif
75
Greg Claytonb43767a2011-03-22 01:34:44 +000076//----------------------------------------------------------------------
77// Watch for signals
78//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +000079static void signal_handler(int signo) {
80 switch (signo) {
81 case SIGHUP:
82 // Use SIGINT first, if that does not work, use SIGHUP as a last resort.
83 // And we should not call exit() here because it results in the global
84 // destructors
85 // to be invoked and wreaking havoc on the threads still running.
86 Host::SystemLog(Host::eSystemLogWarning,
87 "SIGHUP received, exiting lldb-server...\n");
88 abort();
89 break;
90 }
Greg Claytonb43767a2011-03-22 01:34:44 +000091}
92
Kate Stoneb9c1b512016-09-06 20:57:50 +000093static void display_usage(const char *progname, const char *subcommand) {
94 fprintf(stderr, "Usage:\n %s %s [--log-file log-file-name] [--log-channels "
95 "log-channel-list] [--port-file port-file-path] --server "
96 "--listen port\n",
97 progname, subcommand);
98 exit(0);
Daniel Maleae0f8f572013-08-26 23:57:52 +000099}
100
Kate Stoneb9c1b512016-09-06 20:57:50 +0000101static Error save_socket_id_to_file(const std::string &socket_id,
102 const FileSpec &file_spec) {
103 FileSpec temp_file_spec(file_spec.GetDirectory().AsCString(), false);
Zachary Turnerd3d95fd2017-03-19 05:48:47 +0000104 Error error(llvm::sys::fs::create_directory(temp_file_spec.GetPath()));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000105 if (error.Fail())
106 return Error("Failed to create directory %s: %s",
107 temp_file_spec.GetCString(), error.AsCString());
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000108
Kate Stoneb9c1b512016-09-06 20:57:50 +0000109 llvm::SmallString<PATH_MAX> temp_file_path;
110 temp_file_spec.AppendPathComponent("port-file.%%%%%%");
111 auto err_code = llvm::sys::fs::createUniqueFile(temp_file_spec.GetCString(),
112 temp_file_path);
113 if (err_code)
114 return Error("Failed to create temp file: %s", err_code.message().c_str());
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000115
Kate Stoneb9c1b512016-09-06 20:57:50 +0000116 llvm::FileRemover tmp_file_remover(temp_file_path.c_str());
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000117
Kate Stoneb9c1b512016-09-06 20:57:50 +0000118 {
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 << socket_id;
123 }
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000124
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000125 err_code = llvm::sys::fs::rename(temp_file_path.c_str(), file_spec.GetPath());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000126 if (err_code)
127 return Error("Failed to rename file %s to %s: %s", temp_file_path.c_str(),
128 file_spec.GetPath().c_str(), err_code.message().c_str());
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000129
Kate Stoneb9c1b512016-09-06 20:57:50 +0000130 tmp_file_remover.releaseFile();
Mehdi Aminic1edf562016-11-11 04:29:25 +0000131 return Error();
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000132}
133
Greg Claytonb43767a2011-03-22 01:34:44 +0000134//----------------------------------------------------------------------
135// main
136//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137int main_platform(int argc, char *argv[]) {
138 const char *progname = argv[0];
139 const char *subcommand = argv[1];
140 argc--;
141 argv++;
142 signal(SIGPIPE, SIG_IGN);
143 signal(SIGHUP, signal_handler);
144 int long_option_index = 0;
145 Error error;
146 std::string listen_host_port;
147 int ch;
Greg Clayton5fb8f792013-12-02 19:35:49 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 std::string log_file;
150 StringRef
151 log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000152
Kate Stoneb9c1b512016-09-06 20:57:50 +0000153 GDBRemoteCommunicationServerPlatform::PortMap gdbserver_portmap;
154 int min_gdbserver_port = 0;
155 int max_gdbserver_port = 0;
156 uint16_t port_offset = 0;
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000157
Kate Stoneb9c1b512016-09-06 20:57:50 +0000158 FileSpec socket_file;
159 bool show_usage = false;
160 int option_error = 0;
161 int socket_error = -1;
162
163 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
164
Greg Claytond4724cf2013-11-22 18:55:04 +0000165#if __GLIBC__
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166 optind = 0;
Greg Claytond4724cf2013-11-22 18:55:04 +0000167#else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000168 optreset = 1;
169 optind = 1;
Greg Claytond4724cf2013-11-22 18:55:04 +0000170#endif
171
Kate Stoneb9c1b512016-09-06 20:57:50 +0000172 while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
173 g_long_options, &long_option_index)) != -1) {
174 switch (ch) {
175 case 0: // Any optional that auto set themselves will return 0
176 break;
Greg Claytonb43767a2011-03-22 01:34:44 +0000177
Kate Stoneb9c1b512016-09-06 20:57:50 +0000178 case 'L':
179 listen_host_port.append(optarg);
180 break;
Daniel Maleae0f8f572013-08-26 23:57:52 +0000181
Kate Stoneb9c1b512016-09-06 20:57:50 +0000182 case 'l': // Set Log File
183 if (optarg && optarg[0])
184 log_file.assign(optarg);
185 break;
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +0000186
Kate Stoneb9c1b512016-09-06 20:57:50 +0000187 case 'c': // Log Channels
188 if (optarg && optarg[0])
189 log_channels = StringRef(optarg);
190 break;
Tamas Berghammer9c9ecce2015-05-27 13:34:04 +0000191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192 case 'f': // Socket file
193 if (optarg && optarg[0])
194 socket_file.SetFile(optarg, false);
195 break;
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000196
Kate Stoneb9c1b512016-09-06 20:57:50 +0000197 case 'p': {
198 char *end = NULL;
199 long tmp_port_offset = strtoul(optarg, &end, 0);
200 if (end && *end == '\0') {
201 if (LOW_PORT <= tmp_port_offset && tmp_port_offset <= HIGH_PORT) {
202 port_offset = (uint16_t)tmp_port_offset;
203 } else {
204 fprintf(stderr, "error: port offset %li is not in the valid user "
205 "port range of %u - %u\n",
206 tmp_port_offset, LOW_PORT, HIGH_PORT);
207 option_error = 5;
Greg Claytonb43767a2011-03-22 01:34:44 +0000208 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209 } else {
210 fprintf(stderr, "error: invalid port offset string %s\n", optarg);
211 option_error = 4;
212 }
213 } break;
Greg Clayton5fb8f792013-12-02 19:35:49 +0000214
Kate Stoneb9c1b512016-09-06 20:57:50 +0000215 case 'P':
216 case 'm':
217 case 'M': {
218 char *end = NULL;
219 long portnum = strtoul(optarg, &end, 0);
220 if (end && *end == '\0') {
221 if (LOW_PORT <= portnum && portnum <= HIGH_PORT) {
222 if (ch == 'P')
223 gdbserver_portmap[(uint16_t)portnum] = LLDB_INVALID_PROCESS_ID;
224 else if (ch == 'm')
225 min_gdbserver_port = portnum;
226 else
227 max_gdbserver_port = portnum;
228 } else {
229 fprintf(stderr, "error: port number %li is not in the valid user "
230 "port range of %u - %u\n",
231 portnum, LOW_PORT, HIGH_PORT);
232 option_error = 1;
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000233 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234 } else {
235 fprintf(stderr, "error: invalid port number string %s\n", optarg);
236 option_error = 2;
237 }
238 } break;
239
240 case 'h': /* fall-through is intentional */
241 case '?':
242 show_usage = true;
243 break;
244 }
245 }
246
247 if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0))
248 return -1;
249
250 // Make a port map for a port range that was specified.
251 if (min_gdbserver_port < max_gdbserver_port) {
252 for (uint16_t port = min_gdbserver_port; port < max_gdbserver_port; ++port)
253 gdbserver_portmap[port] = LLDB_INVALID_PROCESS_ID;
254 } else if (min_gdbserver_port != max_gdbserver_port) {
255 fprintf(stderr, "error: --min-gdbserver-port (%u) is greater than "
256 "--max-gdbserver-port (%u)\n",
257 min_gdbserver_port, max_gdbserver_port);
258 option_error = 3;
259 }
260
261 // Print usage and exit if no listening port is specified.
262 if (listen_host_port.empty())
263 show_usage = true;
264
265 if (show_usage || option_error) {
266 display_usage(progname, subcommand);
267 exit(option_error);
268 }
269
270 // Skip any options we consumed with getopt_long_only.
271 argc -= optind;
272 argv += optind;
273 lldb_private::Args inferior_arguments;
274 inferior_arguments.SetArguments(argc, const_cast<const char **>(argv));
275
276 const bool children_inherit_listen_socket = false;
277 // the test suite makes many connections in parallel, let's not miss any.
278 // The highest this should get reasonably is a function of the number
279 // of target CPUs. For now, let's just use 100.
280 const int backlog = 100;
281
282 std::unique_ptr<Acceptor> acceptor_up(Acceptor::Create(
283 listen_host_port, children_inherit_listen_socket, error));
284 if (error.Fail()) {
285 fprintf(stderr, "failed to create acceptor: %s", error.AsCString());
286 exit(socket_error);
287 }
288
289 error = acceptor_up->Listen(backlog);
290 if (error.Fail()) {
291 printf("failed to listen: %s\n", error.AsCString());
292 exit(socket_error);
293 }
294 if (socket_file) {
295 error =
296 save_socket_id_to_file(acceptor_up->GetLocalSocketId(), socket_file);
297 if (error.Fail()) {
298 fprintf(stderr, "failed to write socket id to %s: %s\n",
299 socket_file.GetPath().c_str(), error.AsCString());
300 return 1;
301 }
302 }
303
304 do {
305 GDBRemoteCommunicationServerPlatform platform(
306 acceptor_up->GetSocketProtocol(), acceptor_up->GetSocketScheme());
307
308 if (port_offset > 0)
309 platform.SetPortOffset(port_offset);
310
311 if (!gdbserver_portmap.empty()) {
312 platform.SetPortMap(std::move(gdbserver_portmap));
Oleksiy Vyalov298be462015-07-06 18:05:19 +0000313 }
Greg Claytonb43767a2011-03-22 01:34:44 +0000314
Kate Stoneb9c1b512016-09-06 20:57:50 +0000315 const bool children_inherit_accept_socket = true;
316 Connection *conn = nullptr;
317 error = acceptor_up->Accept(children_inherit_accept_socket, conn);
318 if (error.Fail()) {
319 printf("error: %s\n", error.AsCString());
320 exit(socket_error);
321 }
322 printf("Connection established.\n");
323 if (g_server) {
324 // Collect child zombie processes.
325 while (waitpid(-1, nullptr, WNOHANG) > 0)
326 ;
327 if (fork()) {
328 // Parent doesn't need a connection to the lldb client
329 delete conn;
Tamas Berghammerccd6cff2015-12-08 14:08:19 +0000330
Kate Stoneb9c1b512016-09-06 20:57:50 +0000331 // Parent will continue to listen for new connections.
332 continue;
333 } else {
334 // Child process will handle the connection and exit.
335 g_server = 0;
336 // Listening socket is owned by parent process.
337 acceptor_up.release();
338 }
339 } else {
340 // If not running as a server, this process will not accept
341 // connections while a connection is active.
342 acceptor_up.reset();
343 }
344 platform.SetConnection(conn);
Greg Claytond4724cf2013-11-22 18:55:04 +0000345
Kate Stoneb9c1b512016-09-06 20:57:50 +0000346 if (platform.IsConnected()) {
347 if (inferior_arguments.GetArgumentCount() > 0) {
348 lldb::pid_t pid = LLDB_INVALID_PROCESS_ID;
349 uint16_t port = 0;
350 std::string socket_name;
351 Error error = platform.LaunchGDBServer(inferior_arguments,
352 "", // hostname
353 pid, port, socket_name);
354 if (error.Success())
355 platform.SetPendingGdbServer(pid, port, socket_name);
Robert Flacka0e70cd2015-03-25 12:51:31 +0000356 else
Kate Stoneb9c1b512016-09-06 20:57:50 +0000357 fprintf(stderr, "failed to start gdbserver: %s\n", error.AsCString());
358 }
359
360 // After we connected, we need to get an initial ack from...
361 if (platform.HandshakeWithClient()) {
362 bool interrupt = false;
363 bool done = false;
364 while (!interrupt && !done) {
Pavel Labath1eff73c2016-11-24 10:54:49 +0000365 if (platform.GetPacketAndSendResponse(llvm::None, error, interrupt,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000366 done) !=
367 GDBRemoteCommunication::PacketResult::Success)
368 break;
Robert Flacka0e70cd2015-03-25 12:51:31 +0000369 }
Robert Flacka0e70cd2015-03-25 12:51:31 +0000370
Kate Stoneb9c1b512016-09-06 20:57:50 +0000371 if (error.Fail()) {
372 fprintf(stderr, "error: %s\n", error.AsCString());
Robert Flacka0e70cd2015-03-25 12:51:31 +0000373 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000374 } else {
375 fprintf(stderr, "error: handshake with client failed\n");
376 }
377 }
378 } while (g_server);
Greg Claytonb43767a2011-03-22 01:34:44 +0000379
Kate Stoneb9c1b512016-09-06 20:57:50 +0000380 fprintf(stderr, "lldb-server exiting...\n");
Daniel Maleae0f8f572013-08-26 23:57:52 +0000381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382 return 0;
Greg Claytonb43767a2011-03-22 01:34:44 +0000383}