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