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