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 //===----------------------------------------------------------------------===//
20 #include "LLDBServerUtilities.h"
21 #include "Plugins/Process/gdb-remote/GDBRemoteCommunicationServerLLGS.h"
22 #include "Plugins/Process/gdb-remote/ProcessGDBRemoteLog.h"
23 #include "lldb/Host/Config.h"
24 #include "lldb/Host/ConnectionFileDescriptor.h"
25 #include "lldb/Host/FileSystem.h"
26 #include "lldb/Host/Pipe.h"
27 #include "lldb/Host/common/NativeProcessProtocol.h"
28 #include "lldb/Host/common/TCPSocket.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Utility/LLDBLog.h"
31 #include "lldb/Utility/Status.h"
32 #include "llvm/ADT/StringRef.h"
33 #include "llvm/Option/ArgList.h"
34 #include "llvm/Option/OptTable.h"
35 #include "llvm/Option/Option.h"
36 #include "llvm/Support/Errno.h"
37 #include "llvm/Support/Error.h"
38 #include "llvm/Support/WithColor.h"
40 #if defined(__linux__)
41 #include "Plugins/Process/Linux/NativeProcessLinux.h"
42 #elif defined(__FreeBSD__)
43 #include "Plugins/Process/FreeBSD/NativeProcessFreeBSD.h"
44 #elif defined(__NetBSD__)
45 #include "Plugins/Process/NetBSD/NativeProcessNetBSD.h"
47 #include "Plugins/Process/Windows/Common/NativeProcessWindows.h"
50 #ifndef LLGS_PROGRAM_NAME
51 #define LLGS_PROGRAM_NAME "lldb-server"
54 #ifndef LLGS_VERSION_STR
55 #define LLGS_VERSION_STR "local_build"
60 using namespace lldb_private
;
61 using namespace lldb_private::lldb_server
;
62 using namespace lldb_private::process_gdb_remote
;
65 #if defined(__linux__)
66 typedef process_linux::NativeProcessLinux::Manager NativeProcessManager
;
67 #elif defined(__FreeBSD__)
68 typedef process_freebsd::NativeProcessFreeBSD::Manager NativeProcessManager
;
69 #elif defined(__NetBSD__)
70 typedef process_netbsd::NativeProcessNetBSD::Manager NativeProcessManager
;
72 typedef NativeProcessWindows::Manager NativeProcessManager
;
74 // Dummy implementation to make sure the code compiles
75 class NativeProcessManager
: public NativeProcessProtocol::Manager
{
77 NativeProcessManager(MainLoop
&mainloop
)
78 : NativeProcessProtocol::Manager(mainloop
) {}
80 llvm::Expected
<std::unique_ptr
<NativeProcessProtocol
>>
81 Launch(ProcessLaunchInfo
&launch_info
,
82 NativeProcessProtocol::NativeDelegate
&native_delegate
) override
{
83 llvm_unreachable("Not implemented");
85 llvm::Expected
<std::unique_ptr
<NativeProcessProtocol
>>
86 Attach(lldb::pid_t pid
,
87 NativeProcessProtocol::NativeDelegate
&native_delegate
) override
{
88 llvm_unreachable("Not implemented");
96 static int g_sighup_received_count
= 0;
98 static void sighup_handler(MainLoopBase
&mainloop
) {
99 ++g_sighup_received_count
;
101 Log
*log
= GetLog(LLDBLog::Process
);
102 LLDB_LOGF(log
, "lldb-server:%s swallowing SIGHUP (receive count=%d)",
103 __FUNCTION__
, g_sighup_received_count
);
105 if (g_sighup_received_count
>= 2)
106 mainloop
.RequestTermination();
108 #endif // #ifndef _WIN32
110 void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS
&gdb_server
,
112 Status error
= gdb_server
.AttachToProcess(pid
);
114 fprintf(stderr
, "error: failed to attach to pid %" PRIu64
": %s\n", pid
,
120 void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS
&gdb_server
,
121 const std::string
&process_name
) {
125 void handle_attach(GDBRemoteCommunicationServerLLGS
&gdb_server
,
126 const std::string
&attach_target
) {
127 assert(!attach_target
.empty() && "attach_target cannot be empty");
129 // First check if the attach_target is convertible to a long. If so, we'll use
131 char *end_p
= nullptr;
132 const long int pid
= strtol(attach_target
.c_str(), &end_p
, 10);
134 // We'll call it a match if the entire argument is consumed.
136 static_cast<size_t>(end_p
- attach_target
.c_str()) ==
137 attach_target
.size())
138 handle_attach_to_pid(gdb_server
, static_cast<lldb::pid_t
>(pid
));
140 handle_attach_to_process_name(gdb_server
, attach_target
);
143 void handle_launch(GDBRemoteCommunicationServerLLGS
&gdb_server
,
144 llvm::ArrayRef
<llvm::StringRef
> Arguments
) {
145 ProcessLaunchInfo info
;
146 info
.GetFlags().Set(eLaunchFlagStopAtEntry
| eLaunchFlagDebug
|
147 eLaunchFlagDisableASLR
);
148 info
.SetArguments(Args(Arguments
), true);
150 llvm::SmallString
<64> cwd
;
151 if (std::error_code ec
= llvm::sys::fs::current_path(cwd
)) {
152 llvm::errs() << "Error getting current directory: " << ec
.message() << "\n";
155 FileSpec
cwd_spec(cwd
);
156 FileSystem::Instance().Resolve(cwd_spec
);
157 info
.SetWorkingDirectory(cwd_spec
);
158 info
.GetEnvironment() = Host::GetEnvironment();
160 gdb_server
.SetLaunchInfo(info
);
162 Status error
= gdb_server
.LaunchProcess();
164 llvm::errs() << llvm::formatv("error: failed to launch '{0}': {1}\n",
165 Arguments
[0], error
);
170 Status
writeSocketIdToPipe(Pipe
&port_pipe
, llvm::StringRef socket_id
) {
171 size_t bytes_written
= 0;
172 // Write the port number as a C string with the NULL terminator.
173 return port_pipe
.Write(socket_id
.data(), socket_id
.size() + 1, bytes_written
);
176 Status
writeSocketIdToPipe(const char *const named_pipe_path
,
177 llvm::StringRef socket_id
) {
179 // Wait for 10 seconds for pipe to be opened.
180 auto error
= port_name_pipe
.OpenAsWriterWithTimeout(named_pipe_path
, false,
181 std::chrono::seconds
{10});
184 return writeSocketIdToPipe(port_name_pipe
, socket_id
);
187 Status
writeSocketIdToPipe(lldb::pipe_t unnamed_pipe
,
188 llvm::StringRef socket_id
) {
189 Pipe port_pipe
{LLDB_INVALID_PIPE
, unnamed_pipe
};
190 return writeSocketIdToPipe(port_pipe
, socket_id
);
193 void ConnectToRemote(MainLoop
&mainloop
,
194 GDBRemoteCommunicationServerLLGS
&gdb_server
,
195 bool reverse_connect
, llvm::StringRef host_and_port
,
196 const char *const progname
, const char *const subcommand
,
197 const char *const named_pipe_path
, pipe_t unnamed_pipe
,
198 shared_fd_t connection_fd
) {
201 std::unique_ptr
<Connection
> connection_up
;
204 if (connection_fd
!= SharedSocket::kInvalidFD
) {
207 error
= SharedSocket::GetNativeSocket(connection_fd
, sockfd
);
209 llvm::errs() << llvm::formatv("error: GetNativeSocket failed: {0}\n",
213 connection_up
= std::unique_ptr
<Connection
>(new ConnectionFileDescriptor(
214 new TCPSocket(sockfd
, /*should_close=*/true)));
216 url
= llvm::formatv("fd://{0}", connection_fd
).str();
218 // Create the connection.
219 ::fcntl(connection_fd
, F_SETFD
, FD_CLOEXEC
);
221 } else if (!host_and_port
.empty()) {
222 llvm::Expected
<std::string
> url_exp
=
223 LLGSArgToURL(host_and_port
, reverse_connect
);
225 llvm::errs() << llvm::formatv("error: invalid host:port or URL '{0}': "
228 llvm::toString(url_exp
.takeError()));
232 url
= std::move(url_exp
.get());
236 // Create the connection or server.
237 std::unique_ptr
<ConnectionFileDescriptor
> conn_fd_up
{
238 new ConnectionFileDescriptor
};
239 auto connection_result
= conn_fd_up
->Connect(
241 [named_pipe_path
, unnamed_pipe
](llvm::StringRef socket_id
) {
242 // If we have a named pipe to write the socket id back to, do that
244 if (named_pipe_path
&& named_pipe_path
[0]) {
245 Status error
= writeSocketIdToPipe(named_pipe_path
, socket_id
);
247 llvm::errs() << llvm::formatv(
248 "failed to write to the named pipe '{0}': {1}\n",
249 named_pipe_path
, error
.AsCString());
251 // If we have an unnamed pipe to write the socket id back to, do
253 else if (unnamed_pipe
!= LLDB_INVALID_PIPE
) {
254 Status error
= writeSocketIdToPipe(unnamed_pipe
, socket_id
);
256 llvm::errs() << llvm::formatv(
257 "failed to write to the unnamed pipe: {0}\n", error
);
263 llvm::errs() << llvm::formatv(
264 "error: failed to connect to client at '{0}': {1}\n", url
, error
);
267 if (connection_result
!= eConnectionStatusSuccess
) {
268 llvm::errs() << llvm::formatv(
269 "error: failed to connect to client at '{0}' "
270 "(connection status: {1})\n",
271 url
, static_cast<int>(connection_result
));
274 connection_up
= std::move(conn_fd_up
);
276 error
= gdb_server
.InitializeConnection(std::move(connection_up
));
278 llvm::errs() << llvm::formatv("failed to initialize connection\n", error
);
281 llvm::outs() << "Connection established.\n";
285 using namespace llvm::opt
;
288 OPT_INVALID
= 0, // This is not an option ID.
289 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
290 #include "LLGSOptions.inc"
294 #define OPTTABLE_STR_TABLE_CODE
295 #include "LLGSOptions.inc"
296 #undef OPTTABLE_STR_TABLE_CODE
298 #define OPTTABLE_PREFIXES_TABLE_CODE
299 #include "LLGSOptions.inc"
300 #undef OPTTABLE_PREFIXES_TABLE_CODE
302 static constexpr opt::OptTable::Info InfoTable
[] = {
303 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
304 #include "LLGSOptions.inc"
308 class LLGSOptTable
: public opt::GenericOptTable
{
311 : opt::GenericOptTable(OptionStrTable
, OptionPrefixesTable
, InfoTable
) {}
313 void PrintHelp(llvm::StringRef Name
) {
315 (Name
+ " [options] [[host]:port] [[--] program args...]").str();
316 OptTable::printHelp(llvm::outs(), Usage
.c_str(), "lldb-server");
319 lldb-server connects to the LLDB client, which drives the debugging session.
320 If no connection options are given, the [host]:port argument must be present
321 and will denote the address that lldb-server will listen on. [host] defaults
322 to "localhost
" if empty. Port can be zero, in which case the port number will
323 be chosen dynamically and written to destinations given by --named-pipe and
326 If no target is selected at startup, lldb-server can be directed by the LLDB
327 client to launch or attach to a process.
334 int main_gdbserver(int argc
, char *argv
[]) {
338 // Setup signal handlers first thing.
339 signal(SIGPIPE
, SIG_IGN
);
340 MainLoop::SignalHandleUP sighup_handle
=
341 mainloop
.RegisterSignal(SIGHUP
, sighup_handler
, error
);
344 const char *progname
= argv
[0];
345 const char *subcommand
= argv
[1];
346 std::string attach_target
;
347 std::string named_pipe_path
;
348 std::string log_file
;
350 log_channels
; // e.g. "lldb process threads:gdb-remote default:linux all"
351 lldb::pipe_t unnamed_pipe
= LLDB_INVALID_PIPE
;
352 bool reverse_connect
= false;
353 shared_fd_t connection_fd
= SharedSocket::kInvalidFD
;
355 // ProcessLaunchInfo launch_info;
356 ProcessAttachInfo attach_info
;
359 llvm::BumpPtrAllocator Alloc
;
360 llvm::StringSaver
Saver(Alloc
);
361 bool HasError
= false;
362 opt::InputArgList Args
= Opts
.parseArgs(argc
- 1, argv
+ 1, OPT_UNKNOWN
,
363 Saver
, [&](llvm::StringRef Msg
) {
364 WithColor::error() << Msg
<< "\n";
368 (llvm::sys::path::filename(argv
[0]) + " g[dbserver]").str();
369 std::string HelpText
=
370 "Use '" + Name
+ " --help' for a complete list of options.\n";
372 llvm::errs() << HelpText
;
376 if (Args
.hasArg(OPT_help
)) {
377 Opts
.PrintHelp(Name
);
382 if (Args
.hasArg(OPT_setsid
)) {
383 // Put llgs into a new session. Terminals group processes
384 // into sessions and when a special terminal key sequences
385 // (like control+c) are typed they can cause signals to go out to
386 // all processes in a session. Using this --setsid (-S) option
387 // will cause debugserver to run in its own sessions and be free
390 // This is useful when llgs is spawned from a command
391 // line application that uses llgs to do the debugging,
392 // yet that application doesn't want llgs receiving the
393 // signals sent to the session (i.e. dying when anyone hits ^C).
395 const ::pid_t new_sid
= setsid();
398 << llvm::formatv("failed to set new session id for {0} ({1})\n",
399 LLGS_PROGRAM_NAME
, llvm::sys::StrError());
405 log_file
= Args
.getLastArgValue(OPT_log_file
).str();
406 log_channels
= Args
.getLastArgValue(OPT_log_channels
);
407 named_pipe_path
= Args
.getLastArgValue(OPT_named_pipe
).str();
408 reverse_connect
= Args
.hasArg(OPT_reverse_connect
);
409 attach_target
= Args
.getLastArgValue(OPT_attach
).str();
410 if (Args
.hasArg(OPT_pipe
)) {
412 if (!llvm::to_integer(Args
.getLastArgValue(OPT_pipe
), Arg
)) {
413 WithColor::error() << "invalid '--pipe' argument\n" << HelpText
;
416 unnamed_pipe
= (pipe_t
)Arg
;
418 if (Args
.hasArg(OPT_fd
)) {
420 if (!llvm::to_integer(Args
.getLastArgValue(OPT_fd
), fd
)) {
421 WithColor::error() << "invalid '--fd' argument\n" << HelpText
;
424 connection_fd
= (shared_fd_t
)fd
;
427 if (!LLDBServerUtilities::SetupLogging(
428 log_file
, log_channels
,
429 LLDB_LOG_OPTION_PREPEND_TIMESTAMP
|
430 LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION
))
433 std::vector
<llvm::StringRef
> Inputs
;
434 for (opt::Arg
*Arg
: Args
.filtered(OPT_INPUT
))
435 Inputs
.push_back(Arg
->getValue());
436 if (opt::Arg
*Arg
= Args
.getLastArg(OPT_REM
)) {
437 for (const char *Val
: Arg
->getValues())
438 Inputs
.push_back(Val
);
440 if (Inputs
.empty() && connection_fd
== SharedSocket::kInvalidFD
) {
441 WithColor::error() << "no connection arguments\n" << HelpText
;
445 NativeProcessManager
manager(mainloop
);
446 GDBRemoteCommunicationServerLLGS
gdb_server(mainloop
, manager
);
448 llvm::StringRef host_and_port
;
449 if (!Inputs
.empty() && connection_fd
== SharedSocket::kInvalidFD
) {
450 host_and_port
= Inputs
.front();
451 Inputs
.erase(Inputs
.begin());
454 // Any arguments left over are for the program that we need to launch. If
456 // are no arguments, then the GDB server will start up and wait for an 'A'
458 // to launch a program, or a vAttach packet to attach to an existing process,
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 (!Inputs
.empty())
464 handle_launch(gdb_server
, Inputs
);
466 // Print version info.
467 printf("%s-%s\n", LLGS_PROGRAM_NAME
, LLGS_VERSION_STR
);
469 ConnectToRemote(mainloop
, gdb_server
, reverse_connect
, host_and_port
,
470 progname
, subcommand
, named_pipe_path
.c_str(),
471 unnamed_pipe
, connection_fd
);
473 if (!gdb_server
.IsConnected()) {
474 fprintf(stderr
, "no connection information provided, unable to run\n");
478 Status ret
= mainloop
.Run();
480 fprintf(stderr
, "lldb-server terminating due to error: %s\n",
484 fprintf(stderr
, "lldb-server exiting...\n");