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