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 const ConstString& port_file_dir = port_file_spec.GetDirectory(); 106 auto error = FileSystem::MakeDirectory( 107 FileSpec(port_file_dir.AsCString(), false), eFilePermissionsDirectoryDefault); 108 if (error.Fail()) 109 return Error("Failed to create directory %s: %s", port_file_dir.AsCString(), error.AsCString()); 110 111 llvm::SmallString<PATH_MAX> temp_file_path; 112 auto err_code = llvm::sys::fs::createTemporaryFile( 113 port_file_spec.GetPath().c_str(), "", temp_file_path); 114 if (err_code) 115 return Error("Failed to create temp file: %s", err_code.message().c_str()); 116 117 llvm::FileRemover tmp_file_remover(temp_file_path.c_str()); 118 119 { 120 std::ofstream temp_file(temp_file_path.c_str(), std::ios::out); 121 if (!temp_file.is_open()) 122 return Error("Failed to open temp file %s", temp_file_path.c_str()); 123 temp_file << port; 124 } 125 126 err_code = llvm::sys::fs::rename(temp_file_path.c_str(), port_file_spec.GetPath().c_str()); 127 if (err_code) 128 return Error("Failed to rename file %s to %s: %s", 129 temp_file_path.c_str(), port_file_spec.GetPath().c_str(), err_code.message().c_str()); 130 131 tmp_file_remover.releaseFile(); 132 return Error(); 133 } 134 135 //---------------------------------------------------------------------- 136 // main 137 //---------------------------------------------------------------------- 138 int 139 main_platform (int argc, char *argv[]) 140 { 141 const char *progname = argv[0]; 142 const char *subcommand = argv[1]; 143 argc--; 144 argv++; 145 signal (SIGPIPE, SIG_IGN); 146 signal (SIGHUP, signal_handler); 147 int long_option_index = 0; 148 Error error; 149 std::string listen_host_port; 150 int ch; 151 152 std::string log_file; 153 StringRef log_channels; // e.g. "lldb process threads:gdb-remote default:linux all" 154 155 GDBRemoteCommunicationServerPlatform::PortMap gdbserver_portmap; 156 int min_gdbserver_port = 0; 157 int max_gdbserver_port = 0; 158 uint16_t port_offset = 0; 159 160 FileSpec port_file; 161 bool show_usage = false; 162 int option_error = 0; 163 int socket_error = -1; 164 165 std::string short_options(OptionParser::GetShortOptionString(g_long_options)); 166 167 #if __GLIBC__ 168 optind = 0; 169 #else 170 optreset = 1; 171 optind = 1; 172 #endif 173 174 while ((ch = getopt_long_only(argc, argv, short_options.c_str(), g_long_options, &long_option_index)) != -1) 175 { 176 switch (ch) 177 { 178 case 0: // Any optional that auto set themselves will return 0 179 break; 180 181 case 'L': 182 listen_host_port.append (optarg); 183 break; 184 185 case 'l': // Set Log File 186 if (optarg && optarg[0]) 187 log_file.assign(optarg); 188 break; 189 190 case 'c': // Log Channels 191 if (optarg && optarg[0]) 192 log_channels = StringRef(optarg); 193 break; 194 195 case 'f': // Port file 196 if (optarg && optarg[0]) 197 port_file.SetFile(optarg, false); 198 break; 199 200 case 'p': 201 { 202 char *end = NULL; 203 long tmp_port_offset = strtoul(optarg, &end, 0); 204 if (end && *end == '\0') 205 { 206 if (LOW_PORT <= tmp_port_offset && tmp_port_offset <= HIGH_PORT) 207 { 208 port_offset = (uint16_t)tmp_port_offset; 209 } 210 else 211 { 212 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); 213 option_error = 5; 214 } 215 } 216 else 217 { 218 fprintf (stderr, "error: invalid port offset string %s\n", optarg); 219 option_error = 4; 220 } 221 } 222 break; 223 224 case 'P': 225 case 'm': 226 case 'M': 227 { 228 char *end = NULL; 229 long portnum = strtoul(optarg, &end, 0); 230 if (end && *end == '\0') 231 { 232 if (LOW_PORT <= portnum && portnum <= HIGH_PORT) 233 { 234 if (ch == 'P') 235 gdbserver_portmap[(uint16_t)portnum] = LLDB_INVALID_PROCESS_ID; 236 else if (ch == 'm') 237 min_gdbserver_port = portnum; 238 else 239 max_gdbserver_port = portnum; 240 } 241 else 242 { 243 fprintf (stderr, "error: port number %li is not in the valid user port range of %u - %u\n", portnum, LOW_PORT, HIGH_PORT); 244 option_error = 1; 245 } 246 } 247 else 248 { 249 fprintf (stderr, "error: invalid port number string %s\n", optarg); 250 option_error = 2; 251 } 252 } 253 break; 254 255 case 'h': /* fall-through is intentional */ 256 case '?': 257 show_usage = true; 258 break; 259 } 260 } 261 262 if (!LLDBServerUtilities::SetupLogging(log_file, log_channels, 0)) 263 return -1; 264 265 // Make a port map for a port range that was specified. 266 if (min_gdbserver_port < max_gdbserver_port) 267 { 268 for (uint16_t port = min_gdbserver_port; port < max_gdbserver_port; ++port) 269 gdbserver_portmap[port] = LLDB_INVALID_PROCESS_ID; 270 } 271 else if (min_gdbserver_port != max_gdbserver_port) 272 { 273 fprintf (stderr, "error: --min-gdbserver-port (%u) is greater than --max-gdbserver-port (%u)\n", min_gdbserver_port, max_gdbserver_port); 274 option_error = 3; 275 } 276 277 // Print usage and exit if no listening port is specified. 278 if (listen_host_port.empty()) 279 show_usage = true; 280 281 if (show_usage || option_error) 282 { 283 display_usage(progname, subcommand); 284 exit(option_error); 285 } 286 287 std::unique_ptr<Socket> listening_socket_up; 288 Socket *socket = nullptr; 289 const bool children_inherit_listen_socket = false; 290 291 // the test suite makes many connections in parallel, let's not miss any. 292 // The highest this should get reasonably is a function of the number 293 // of target CPUs. For now, let's just use 100 294 const int backlog = 100; 295 error = Socket::TcpListen(listen_host_port.c_str(), children_inherit_listen_socket, socket, NULL, backlog); 296 if (error.Fail()) 297 { 298 printf("error: %s\n", error.AsCString()); 299 exit(socket_error); 300 } 301 listening_socket_up.reset(socket); 302 printf ("Listening for a connection from %u...\n", listening_socket_up->GetLocalPortNumber()); 303 if (port_file) 304 { 305 error = save_port_to_file(listening_socket_up->GetLocalPortNumber(), port_file); 306 if (error.Fail()) 307 { 308 fprintf(stderr, "failed to write port to %s: %s", port_file.GetPath().c_str(), error.AsCString()); 309 return 1; 310 } 311 } 312 313 do { 314 GDBRemoteCommunicationServerPlatform platform; 315 316 if (port_offset > 0) 317 platform.SetPortOffset(port_offset); 318 319 if (!gdbserver_portmap.empty()) 320 { 321 platform.SetPortMap(std::move(gdbserver_portmap)); 322 } 323 324 const bool children_inherit_accept_socket = true; 325 socket = nullptr; 326 error = listening_socket_up->BlockingAccept(listen_host_port.c_str(), children_inherit_accept_socket, socket); 327 if (error.Fail()) 328 { 329 printf ("error: %s\n", error.AsCString()); 330 exit(socket_error); 331 } 332 printf ("Connection established.\n"); 333 if (g_server) 334 { 335 // Collect child zombie processes. 336 while (waitpid(-1, nullptr, WNOHANG) > 0); 337 if (fork()) 338 { 339 // Parent doesn't need a connection to the lldb client 340 delete socket; 341 socket = nullptr; 342 343 // Parent will continue to listen for new connections. 344 continue; 345 } 346 else 347 { 348 // Child process will handle the connection and exit. 349 g_server = 0; 350 // Listening socket is owned by parent process. 351 listening_socket_up.release(); 352 } 353 } 354 else 355 { 356 // If not running as a server, this process will not accept 357 // connections while a connection is active. 358 listening_socket_up.reset(); 359 } 360 platform.SetConnection (new ConnectionFileDescriptor(socket)); 361 362 if (platform.IsConnected()) 363 { 364 // After we connected, we need to get an initial ack from... 365 if (platform.HandshakeWithClient(&error)) 366 { 367 bool interrupt = false; 368 bool done = false; 369 while (!interrupt && !done) 370 { 371 if (platform.GetPacketAndSendResponse (UINT32_MAX, error, interrupt, done) != GDBRemoteCommunication::PacketResult::Success) 372 break; 373 } 374 375 if (error.Fail()) 376 { 377 fprintf(stderr, "error: %s\n", error.AsCString()); 378 } 379 } 380 else 381 { 382 fprintf(stderr, "error: handshake with client failed\n"); 383 } 384 } 385 } while (g_server); 386 387 fprintf(stderr, "lldb-server exiting...\n"); 388 389 return 0; 390 } 391