1 //===-- lldb-gdbserver.cpp --------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
22 #include "LLDBServerUtilities.h"
23 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
24 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
25 #include "lldb/Host/ConnectionFileDescriptor.h"
26 #include "lldb/Host/FileSystem.h"
27 #include "lldb/Host/HostGetOpt.h"
28 #include "lldb/Host/OptionParser.h"
29 #include "lldb/Host/Pipe.h"
30 #include "lldb/Host/Socket.h"
31 #include "lldb/Host/StringConvert.h"
32 #include "lldb/Host/common/NativeProcessProtocol.h"
33 #include "lldb/Target/Process.h"
34 #include "lldb/Utility/Status.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/Support/Errno.h"
38 #if defined(__linux__)
39 #include "Plugins/Process/Linux/NativeProcessLinux.h"
40 #elif defined(__NetBSD__)
41 #include "Plugins/Process/NetBSD/NativeProcessNetBSD.h"
44 #ifndef LLGS_PROGRAM_NAME
45 #define LLGS_PROGRAM_NAME "lldb-server"
48 #ifndef LLGS_VERSION_STR
49 #define LLGS_VERSION_STR "local_build"
54 using namespace lldb_private;
55 using namespace lldb_private::lldb_server;
56 using namespace lldb_private::process_gdb_remote;
59 #if defined(__linux__)
60 typedef process_linux::NativeProcessLinux::Factory NativeProcessFactory;
61 #elif defined(__NetBSD__)
62 typedef process_netbsd::NativeProcessNetBSD::Factory NativeProcessFactory;
64 // Dummy implementation to make sure the code compiles
65 class NativeProcessFactory : public NativeProcessProtocol::Factory {
67 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
68 Launch(ProcessLaunchInfo &launch_info,
69 NativeProcessProtocol::NativeDelegate &delegate,
70 MainLoop &mainloop) const override {
71 llvm_unreachable("Not implemented");
73 llvm::Expected<std::unique_ptr<NativeProcessProtocol>>
74 Attach(lldb::pid_t pid, NativeProcessProtocol::NativeDelegate &delegate,
75 MainLoop &mainloop) const override {
76 llvm_unreachable("Not implemented");
82 // option descriptors for getopt_long_only()
84 static int g_debug = 0;
85 static int g_verbose = 0;
87 static struct option g_long_options[] = {
88 {"debug", no_argument, &g_debug, 1},
89 {"verbose", no_argument, &g_verbose, 1},
90 {"log-file", required_argument, nullptr, 'l'},
91 {"log-channels", required_argument, nullptr, 'c'},
92 {"attach", required_argument, nullptr, 'a'},
93 {"named-pipe", required_argument, nullptr, 'N'},
94 {"pipe", required_argument, nullptr, 'U'},
95 {"native-regs", no_argument, nullptr,
96 'r'}, // Specify to use the native registers instead of the gdb defaults
97 // for the architecture. NOTE: this is a do-nothing arg as it's
98 // behavior is default now. FIXME remove call from lldb-platform.
99 {"reverse-connect", no_argument, nullptr,
100 'R'}, // Specifies that llgs attaches to the client address:port rather
101 // than llgs listening for a connection from address on port.
102 {"setsid", no_argument, nullptr,
103 'S'}, // Call setsid() to make llgs run in its own session.
104 {"fd", required_argument, nullptr, 'F'},
105 {nullptr, 0, nullptr, 0}};
108 static int g_sighup_received_count = 0;
111 static void sighup_handler(MainLoopBase &mainloop) {
112 ++g_sighup_received_count;
114 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS));
116 log->Printf("lldb-server:%s swallowing SIGHUP (receive count=%d)",
117 __FUNCTION__, g_sighup_received_count);
119 if (g_sighup_received_count >= 2)
120 mainloop.RequestTermination();
122 #endif // #ifndef _WIN32
124 static void display_usage(const char *progname, const char *subcommand) {
125 fprintf(stderr, "Usage:\n %s %s "
126 "[--log-file log-file-name] "
127 "[--log-channels log-channel-list] "
129 "[--fd file-descriptor]"
130 "[--named-pipe named-pipe-path] "
134 "[-- PROGRAM ARG1 ARG2 ...]\n",
135 progname, subcommand);
138 void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS &gdb_server,
140 Status error = gdb_server.AttachToProcess(pid);
142 fprintf(stderr, "error: failed to attach to pid %" PRIu64 ": %s\n", pid,
148 void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS &gdb_server,
149 const std::string &process_name) {
153 void handle_attach(GDBRemoteCommunicationServerLLGS &gdb_server,
154 const std::string &attach_target) {
155 assert(!attach_target.empty() && "attach_target cannot be empty");
157 // First check if the attach_target is convertible to a long. If so, we'll use
159 char *end_p = nullptr;
160 const long int pid = strtol(attach_target.c_str(), &end_p, 10);
162 // We'll call it a match if the entire argument is consumed.
164 static_cast<size_t>(end_p - attach_target.c_str()) ==
165 attach_target.size())
166 handle_attach_to_pid(gdb_server, static_cast<lldb::pid_t>(pid));
168 handle_attach_to_process_name(gdb_server, attach_target);
171 void handle_launch(GDBRemoteCommunicationServerLLGS &gdb_server, int argc,
172 const char *const argv[]) {
173 ProcessLaunchInfo info;
174 info.GetFlags().Set(eLaunchFlagStopAtEntry | eLaunchFlagDebug |
175 eLaunchFlagDisableASLR);
176 info.SetArguments(const_cast<const char **>(argv), true);
178 llvm::SmallString<64> cwd;
179 if (std::error_code ec = llvm::sys::fs::current_path(cwd)) {
180 llvm::errs() << "Error getting current directory: " << ec.message() << "\n";
183 FileSpec cwd_spec(cwd);
184 FileSystem::Instance().Resolve(cwd_spec);
185 info.SetWorkingDirectory(cwd_spec);
186 info.GetEnvironment() = Host::GetEnvironment();
188 gdb_server.SetLaunchInfo(info);
190 Status error = gdb_server.LaunchProcess();
192 llvm::errs() << llvm::formatv("error: failed to launch '{0}': {1}\n",
198 Status writeSocketIdToPipe(Pipe &port_pipe, const std::string &socket_id) {
199 size_t bytes_written = 0;
200 // Write the port number as a C string with the NULL terminator.
201 return port_pipe.Write(socket_id.c_str(), socket_id.size() + 1,
205 Status writeSocketIdToPipe(const char *const named_pipe_path,
206 const std::string &socket_id) {
208 // Wait for 10 seconds for pipe to be opened.
209 auto error = port_name_pipe.OpenAsWriterWithTimeout(named_pipe_path, false,
210 std::chrono::seconds{10});
213 return writeSocketIdToPipe(port_name_pipe, socket_id);
216 Status writeSocketIdToPipe(lldb::pipe_t unnamed_pipe,
217 const std::string &socket_id) {
218 Pipe port_pipe{LLDB_INVALID_PIPE, unnamed_pipe};
219 return writeSocketIdToPipe(port_pipe, socket_id);
222 void ConnectToRemote(MainLoop &mainloop,
223 GDBRemoteCommunicationServerLLGS &gdb_server,
224 bool reverse_connect, const char *const host_and_port,
225 const char *const progname, const char *const subcommand,
226 const char *const named_pipe_path, pipe_t unnamed_pipe,
230 std::unique_ptr<Connection> connection_up;
231 if (connection_fd != -1) {
232 // Build the connection string.
233 char connection_url[512];
234 snprintf(connection_url, sizeof(connection_url), "fd://%d", connection_fd);
236 // Create the connection.
237 #if !defined LLDB_DISABLE_POSIX && !defined _WIN32
238 ::fcntl(connection_fd, F_SETFD, FD_CLOEXEC);
240 connection_up.reset(new ConnectionFileDescriptor);
241 auto connection_result = connection_up->Connect(connection_url, &error);
242 if (connection_result != eConnectionStatusSuccess) {
243 fprintf(stderr, "error: failed to connect to client at '%s' "
244 "(connection status: %d)\n",
245 connection_url, static_cast<int>(connection_result));
249 fprintf(stderr, "error: failed to connect to client at '%s': %s\n",
250 connection_url, error.AsCString());
253 } else if (host_and_port && host_and_port[0]) {
254 // Parse out host and port.
255 std::string final_host_and_port;
256 std::string connection_host;
257 std::string connection_port;
258 uint32_t connection_portno = 0;
260 // If host_and_port starts with ':', default the host to be "localhost" and
261 // expect the remainder to be the port.
262 if (host_and_port[0] == ':')
263 final_host_and_port.append("localhost");
264 final_host_and_port.append(host_and_port);
266 const std::string::size_type colon_pos = final_host_and_port.find(':');
267 if (colon_pos != std::string::npos) {
268 connection_host = final_host_and_port.substr(0, colon_pos);
269 connection_port = final_host_and_port.substr(colon_pos + 1);
270 connection_portno = StringConvert::ToUInt32(connection_port.c_str(), 0);
274 if (reverse_connect) {
275 // llgs will connect to the gdb-remote client.
277 // Ensure we have a port number for the connection.
278 if (connection_portno == 0) {
279 fprintf(stderr, "error: port number must be specified on when using "
280 "reverse connect\n");
284 // Build the connection string.
285 char connection_url[512];
286 snprintf(connection_url, sizeof(connection_url), "connect://%s",
287 final_host_and_port.c_str());
289 // Create the connection.
290 connection_up.reset(new ConnectionFileDescriptor);
291 auto connection_result = connection_up->Connect(connection_url, &error);
292 if (connection_result != eConnectionStatusSuccess) {
293 fprintf(stderr, "error: failed to connect to client at '%s' "
294 "(connection status: %d)\n",
295 connection_url, static_cast<int>(connection_result));
299 fprintf(stderr, "error: failed to connect to client at '%s': %s\n",
300 connection_url, error.AsCString());
304 std::unique_ptr<Acceptor> acceptor_up(
305 Acceptor::Create(final_host_and_port, false, error));
307 fprintf(stderr, "failed to create acceptor: %s\n", error.AsCString());
310 error = acceptor_up->Listen(1);
312 fprintf(stderr, "failed to listen: %s\n", error.AsCString());
315 const std::string socket_id = acceptor_up->GetLocalSocketId();
316 if (!socket_id.empty()) {
317 // If we have a named pipe to write the socket id back to, do that now.
318 if (named_pipe_path && named_pipe_path[0]) {
319 error = writeSocketIdToPipe(named_pipe_path, socket_id);
321 fprintf(stderr, "failed to write to the named pipe \'%s\': %s\n",
322 named_pipe_path, error.AsCString());
324 // If we have an unnamed pipe to write the socket id back to, do that
326 else if (unnamed_pipe != LLDB_INVALID_PIPE) {
327 error = writeSocketIdToPipe(unnamed_pipe, socket_id);
329 fprintf(stderr, "failed to write to the unnamed pipe: %s\n",
334 "unable to get the socket id for the listening connection\n");
337 Connection *conn = nullptr;
338 error = acceptor_up->Accept(false, conn);
340 printf("failed to accept new connection: %s\n", error.AsCString());
343 connection_up.reset(conn);
346 error = gdb_server.InitializeConnection(std::move(connection_up));
348 fprintf(stderr, "Failed to initialize connection: %s\n",
352 printf("Connection established.\n");
356 int main_gdbserver(int argc, char *argv[]) {
360 // Setup signal handlers first thing.
361 signal(SIGPIPE, SIG_IGN);
362 MainLoop::SignalHandleUP sighup_handle =
363 mainloop.RegisterSignal(SIGHUP, sighup_handler, error);
366 const char *progname = argv[0];
367 const char *subcommand = argv[1];
370 int long_option_index = 0;
372 std::string attach_target;
373 std::string named_pipe_path;
374 std::string log_file;
376 log_channels; // e.g. "lldb process threads:gdb-remote default:linux all"
377 lldb::pipe_t unnamed_pipe = LLDB_INVALID_PIPE;
378 bool reverse_connect = false;
379 int connection_fd = -1;
381 // ProcessLaunchInfo launch_info;
382 ProcessAttachInfo attach_info;
384 bool show_usage = false;
385 int option_error = 0;
393 std::string short_options(OptionParser::GetShortOptionString(g_long_options));
395 while ((ch = getopt_long_only(argc, argv, short_options.c_str(),
396 g_long_options, &long_option_index)) != -1) {
398 case 0: // Any optional that auto set themselves will return 0
401 case 'l': // Set Log File
402 if (optarg && optarg[0])
403 log_file.assign(optarg);
406 case 'c': // Log Channels
407 if (optarg && optarg[0])
408 log_channels = StringRef(optarg);
411 case 'N': // named pipe
412 if (optarg && optarg[0])
413 named_pipe_path = optarg;
416 case 'U': // unnamed pipe
417 if (optarg && optarg[0])
418 unnamed_pipe = (pipe_t)StringConvert::ToUInt64(optarg, -1);
422 // Do nothing, native regs is the default these days
426 reverse_connect = true;
430 connection_fd = StringConvert::ToUInt32(optarg, -1);
435 // Put llgs into a new session. Terminals group processes
436 // into sessions and when a special terminal key sequences
437 // (like control+c) are typed they can cause signals to go out to
438 // all processes in a session. Using this --setsid (-S) option
439 // will cause debugserver to run in its own sessions and be free
442 // This is useful when llgs is spawned from a command
443 // line application that uses llgs to do the debugging,
444 // yet that application doesn't want llgs receiving the
445 // signals sent to the session (i.e. dying when anyone hits ^C).
447 const ::pid_t new_sid = setsid();
449 llvm::errs() << llvm::formatv(
450 "failed to set new session id for {0} ({1})\n", LLGS_PROGRAM_NAME,
451 llvm::sys::StrError());
457 case 'a': // attach {pid|process_name}
458 if (optarg && optarg[0])
459 attach_target = optarg;
462 case 'h': /* fall-through is intentional */
469 if (show_usage || option_error) {
470 display_usage(progname, subcommand);
474 if (!LLDBServerUtilities::SetupLogging(
475 log_file, log_channels,
476 LLDB_LOG_OPTION_PREPEND_TIMESTAMP |
477 LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION))
480 Log *log(lldb_private::GetLogIfAnyCategoriesSet(GDBR_LOG_PROCESS));
482 log->Printf("lldb-server launch");
483 for (int i = 0; i < argc; i++) {
484 log->Printf("argv[%i] = '%s'", i, argv[i]);
488 // Skip any options we consumed with getopt_long_only.
492 if (argc == 0 && connection_fd == -1) {
493 fputs("No arguments\n", stderr);
494 display_usage(progname, subcommand);
498 NativeProcessFactory factory;
499 GDBRemoteCommunicationServerLLGS gdb_server(mainloop, factory);
501 const char *const host_and_port = argv[0];
505 // Any arguments left over are for the program that we need to launch. If
507 // are no arguments, then the GDB server will start up and wait for an 'A'
509 // to launch a program, or a vAttach packet to attach to an existing process,
511 // explicitly asked to attach with the --attach={pid|program_name} form.
512 if (!attach_target.empty())
513 handle_attach(gdb_server, attach_target);
515 handle_launch(gdb_server, argc, argv);
517 // Print version info.
518 printf("%s-%s", LLGS_PROGRAM_NAME, LLGS_VERSION_STR);
520 ConnectToRemote(mainloop, gdb_server, reverse_connect, host_and_port,
521 progname, subcommand, named_pipe_path.c_str(),
522 unnamed_pipe, connection_fd);
524 if (!gdb_server.IsConnected()) {
525 fprintf(stderr, "no connection information provided, unable to run\n");
526 display_usage(progname, subcommand);
530 Status ret = mainloop.Run();
532 fprintf(stderr, "lldb-server terminating due to error: %s\n",
536 fprintf(stderr, "lldb-server exiting...\n");