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/Socket.h"
28 #include "lldb/Host/common/NativeProcessProtocol.h"
29 #include "lldb/Target/Process.h"
30 #include "lldb/Utility/Status.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/Option/ArgList.h"
33 #include "llvm/Option/OptTable.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/Errno.h"
36 #include "llvm/Support/WithColor.h"
38 #if defined(__linux__)
39 #include "Plugins/Process/Linux/NativeProcessLinux.h"
40 #elif defined(__FreeBSD__)
41 #include "Plugins/Process/FreeBSD/NativeProcessFreeBSD.h"
42 #elif defined(__NetBSD__)
43 #include "Plugins/Process/NetBSD/NativeProcessNetBSD.h"
45 #include "Plugins/Process/Windows/Common/NativeProcessWindows.h"
48 #ifndef LLGS_PROGRAM_NAME
49 #define LLGS_PROGRAM_NAME "lldb-server"
52 #ifndef LLGS_VERSION_STR
53 #define LLGS_VERSION_STR "local_build"
58 using namespace lldb_private
;
59 using namespace lldb_private::lldb_server
;
60 using namespace lldb_private::process_gdb_remote
;
63 #if defined(__linux__)
64 typedef process_linux::NativeProcessLinux::Factory NativeProcessFactory
;
65 #elif defined(__FreeBSD__)
66 typedef process_freebsd::NativeProcessFreeBSD::Factory NativeProcessFactory
;
67 #elif defined(__NetBSD__)
68 typedef process_netbsd::NativeProcessNetBSD::Factory NativeProcessFactory
;
70 typedef NativeProcessWindows::Factory NativeProcessFactory
;
72 // Dummy implementation to make sure the code compiles
73 class NativeProcessFactory
: public NativeProcessProtocol::Factory
{
75 llvm::Expected
<std::unique_ptr
<NativeProcessProtocol
>>
76 Launch(ProcessLaunchInfo
&launch_info
,
77 NativeProcessProtocol::NativeDelegate
&delegate
,
78 MainLoop
&mainloop
) const override
{
79 llvm_unreachable("Not implemented");
81 llvm::Expected
<std::unique_ptr
<NativeProcessProtocol
>>
82 Attach(lldb::pid_t pid
, NativeProcessProtocol::NativeDelegate
&delegate
,
83 MainLoop
&mainloop
) const override
{
84 llvm_unreachable("Not implemented");
92 static int g_sighup_received_count
= 0;
94 static void sighup_handler(MainLoopBase
&mainloop
) {
95 ++g_sighup_received_count
;
97 Log
*log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS
));
98 LLDB_LOGF(log
, "lldb-server:%s swallowing SIGHUP (receive count=%d)",
99 __FUNCTION__
, g_sighup_received_count
);
101 if (g_sighup_received_count
>= 2)
102 mainloop
.RequestTermination();
104 #endif // #ifndef _WIN32
106 void handle_attach_to_pid(GDBRemoteCommunicationServerLLGS
&gdb_server
,
108 Status error
= gdb_server
.AttachToProcess(pid
);
110 fprintf(stderr
, "error: failed to attach to pid %" PRIu64
": %s\n", pid
,
116 void handle_attach_to_process_name(GDBRemoteCommunicationServerLLGS
&gdb_server
,
117 const std::string
&process_name
) {
121 void handle_attach(GDBRemoteCommunicationServerLLGS
&gdb_server
,
122 const std::string
&attach_target
) {
123 assert(!attach_target
.empty() && "attach_target cannot be empty");
125 // First check if the attach_target is convertible to a long. If so, we'll use
127 char *end_p
= nullptr;
128 const long int pid
= strtol(attach_target
.c_str(), &end_p
, 10);
130 // We'll call it a match if the entire argument is consumed.
132 static_cast<size_t>(end_p
- attach_target
.c_str()) ==
133 attach_target
.size())
134 handle_attach_to_pid(gdb_server
, static_cast<lldb::pid_t
>(pid
));
136 handle_attach_to_process_name(gdb_server
, attach_target
);
139 void handle_launch(GDBRemoteCommunicationServerLLGS
&gdb_server
,
140 llvm::ArrayRef
<llvm::StringRef
> Arguments
) {
141 ProcessLaunchInfo info
;
142 info
.GetFlags().Set(eLaunchFlagStopAtEntry
| eLaunchFlagDebug
|
143 eLaunchFlagDisableASLR
);
144 info
.SetArguments(Args(Arguments
), true);
146 llvm::SmallString
<64> cwd
;
147 if (std::error_code ec
= llvm::sys::fs::current_path(cwd
)) {
148 llvm::errs() << "Error getting current directory: " << ec
.message() << "\n";
151 FileSpec
cwd_spec(cwd
);
152 FileSystem::Instance().Resolve(cwd_spec
);
153 info
.SetWorkingDirectory(cwd_spec
);
154 info
.GetEnvironment() = Host::GetEnvironment();
156 gdb_server
.SetLaunchInfo(info
);
158 Status error
= gdb_server
.LaunchProcess();
160 llvm::errs() << llvm::formatv("error: failed to launch '{0}': {1}\n",
161 Arguments
[0], error
);
166 Status
writeSocketIdToPipe(Pipe
&port_pipe
, llvm::StringRef socket_id
) {
167 size_t bytes_written
= 0;
168 // Write the port number as a C string with the NULL terminator.
169 return port_pipe
.Write(socket_id
.data(), socket_id
.size() + 1, bytes_written
);
172 Status
writeSocketIdToPipe(const char *const named_pipe_path
,
173 llvm::StringRef socket_id
) {
175 // Wait for 10 seconds for pipe to be opened.
176 auto error
= port_name_pipe
.OpenAsWriterWithTimeout(named_pipe_path
, false,
177 std::chrono::seconds
{10});
180 return writeSocketIdToPipe(port_name_pipe
, socket_id
);
183 Status
writeSocketIdToPipe(lldb::pipe_t unnamed_pipe
,
184 llvm::StringRef socket_id
) {
185 Pipe port_pipe
{LLDB_INVALID_PIPE
, unnamed_pipe
};
186 return writeSocketIdToPipe(port_pipe
, socket_id
);
189 void ConnectToRemote(MainLoop
&mainloop
,
190 GDBRemoteCommunicationServerLLGS
&gdb_server
,
191 bool reverse_connect
, llvm::StringRef host_and_port
,
192 const char *const progname
, const char *const subcommand
,
193 const char *const named_pipe_path
, pipe_t unnamed_pipe
,
197 std::unique_ptr
<Connection
> connection_up
;
200 if (connection_fd
!= -1) {
201 url
= llvm::formatv("fd://{0}", connection_fd
).str();
203 // Create the connection.
204 #if LLDB_ENABLE_POSIX && !defined _WIN32
205 ::fcntl(connection_fd
, F_SETFD
, FD_CLOEXEC
);
207 } else if (!host_and_port
.empty()) {
208 llvm::Expected
<std::string
> url_exp
=
209 LLGSArgToURL(host_and_port
, reverse_connect
);
211 llvm::errs() << llvm::formatv("error: invalid host:port or URL '{0}': "
214 llvm::toString(url_exp
.takeError()));
218 url
= std::move(url_exp
.get());
222 // Create the connection or server.
223 std::unique_ptr
<ConnectionFileDescriptor
> conn_fd_up
{
224 new ConnectionFileDescriptor
};
225 auto connection_result
= conn_fd_up
->Connect(
227 [named_pipe_path
, unnamed_pipe
](llvm::StringRef socket_id
) {
228 // If we have a named pipe to write the socket id back to, do that
230 if (named_pipe_path
&& named_pipe_path
[0]) {
231 Status error
= writeSocketIdToPipe(named_pipe_path
, socket_id
);
233 llvm::errs() << llvm::formatv(
234 "failed to write to the named peipe '{0}': {1}\n",
235 named_pipe_path
, error
.AsCString());
237 // If we have an unnamed pipe to write the socket id back to, do
239 else if (unnamed_pipe
!= LLDB_INVALID_PIPE
) {
240 Status error
= writeSocketIdToPipe(unnamed_pipe
, socket_id
);
242 llvm::errs() << llvm::formatv(
243 "failed to write to the unnamed pipe: {0}\n", error
);
249 llvm::errs() << llvm::formatv(
250 "error: failed to connect to client at '{0}': {1}\n", url
, error
);
253 if (connection_result
!= eConnectionStatusSuccess
) {
254 llvm::errs() << llvm::formatv(
255 "error: failed to connect to client at '{0}' "
256 "(connection status: {1})\n",
257 url
, static_cast<int>(connection_result
));
260 connection_up
= std::move(conn_fd_up
);
262 error
= gdb_server
.InitializeConnection(std::move(connection_up
));
264 llvm::errs() << llvm::formatv("failed to initialize connection\n", error
);
267 llvm::outs() << "Connection established.\n";
272 OPT_INVALID
= 0, // This is not an option ID.
273 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
274 HELPTEXT, METAVAR, VALUES) \
276 #include "LLGSOptions.inc"
280 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
281 #include "LLGSOptions.inc"
284 const opt::OptTable::Info InfoTable
[] = {
285 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
286 HELPTEXT, METAVAR, VALUES) \
288 PREFIX, NAME, HELPTEXT, \
289 METAVAR, OPT_##ID, opt::Option::KIND##Class, \
290 PARAM, FLAGS, OPT_##GROUP, \
291 OPT_##ALIAS, ALIASARGS, VALUES},
292 #include "LLGSOptions.inc"
296 class LLGSOptTable
: public opt::OptTable
{
298 LLGSOptTable() : OptTable(InfoTable
) {}
300 void PrintHelp(llvm::StringRef Name
) {
302 (Name
+ " [options] [[host]:port] [[--] program args...]").str();
303 OptTable::printHelp(llvm::outs(), Usage
.c_str(), "lldb-server");
306 lldb-server connects to the LLDB client, which drives the debugging session.
307 If no connection options are given, the [host]:port argument must be present
308 and will denote the address that lldb-server will listen on. [host] defaults
309 to "localhost
" if empty. Port can be zero, in which case the port number will
310 be chosen dynamically and written to destinations given by --named-pipe and
313 If no target is selected at startup, lldb-server can be directed by the LLDB
314 client to launch or attach to a process.
321 int main_gdbserver(int argc
, char *argv
[]) {
325 // Setup signal handlers first thing.
326 signal(SIGPIPE
, SIG_IGN
);
327 MainLoop::SignalHandleUP sighup_handle
=
328 mainloop
.RegisterSignal(SIGHUP
, sighup_handler
, error
);
331 const char *progname
= argv
[0];
332 const char *subcommand
= argv
[1];
333 std::string attach_target
;
334 std::string named_pipe_path
;
335 std::string log_file
;
337 log_channels
; // e.g. "lldb process threads:gdb-remote default:linux all"
338 lldb::pipe_t unnamed_pipe
= LLDB_INVALID_PIPE
;
339 bool reverse_connect
= false;
340 int connection_fd
= -1;
342 // ProcessLaunchInfo launch_info;
343 ProcessAttachInfo attach_info
;
346 llvm::BumpPtrAllocator Alloc
;
347 llvm::StringSaver
Saver(Alloc
);
348 bool HasError
= false;
349 opt::InputArgList Args
= Opts
.parseArgs(argc
- 1, argv
+ 1, OPT_UNKNOWN
,
350 Saver
, [&](llvm::StringRef Msg
) {
351 WithColor::error() << Msg
<< "\n";
355 (llvm::sys::path::filename(argv
[0]) + " g[dbserver]").str();
356 std::string HelpText
=
357 "Use '" + Name
+ " --help' for a complete list of options.\n";
359 llvm::errs() << HelpText
;
363 if (Args
.hasArg(OPT_help
)) {
364 Opts
.PrintHelp(Name
);
369 if (Args
.hasArg(OPT_setsid
)) {
370 // Put llgs into a new session. Terminals group processes
371 // into sessions and when a special terminal key sequences
372 // (like control+c) are typed they can cause signals to go out to
373 // all processes in a session. Using this --setsid (-S) option
374 // will cause debugserver to run in its own sessions and be free
377 // This is useful when llgs is spawned from a command
378 // line application that uses llgs to do the debugging,
379 // yet that application doesn't want llgs receiving the
380 // signals sent to the session (i.e. dying when anyone hits ^C).
382 const ::pid_t new_sid
= setsid();
385 << llvm::formatv("failed to set new session id for {0} ({1})\n",
386 LLGS_PROGRAM_NAME
, llvm::sys::StrError());
392 log_file
= Args
.getLastArgValue(OPT_log_file
).str();
393 log_channels
= Args
.getLastArgValue(OPT_log_channels
);
394 named_pipe_path
= Args
.getLastArgValue(OPT_named_pipe
).str();
395 reverse_connect
= Args
.hasArg(OPT_reverse_connect
);
396 attach_target
= Args
.getLastArgValue(OPT_attach
).str();
397 if (Args
.hasArg(OPT_pipe
)) {
399 if (!llvm::to_integer(Args
.getLastArgValue(OPT_pipe
), Arg
)) {
400 WithColor::error() << "invalid '--pipe' argument\n" << HelpText
;
403 unnamed_pipe
= (pipe_t
)Arg
;
405 if (Args
.hasArg(OPT_fd
)) {
406 if (!llvm::to_integer(Args
.getLastArgValue(OPT_fd
), connection_fd
)) {
407 WithColor::error() << "invalid '--fd' argument\n" << HelpText
;
412 if (!LLDBServerUtilities::SetupLogging(
413 log_file
, log_channels
,
414 LLDB_LOG_OPTION_PREPEND_TIMESTAMP
|
415 LLDB_LOG_OPTION_PREPEND_FILE_FUNCTION
))
418 std::vector
<llvm::StringRef
> Inputs
;
419 for (opt::Arg
*Arg
: Args
.filtered(OPT_INPUT
))
420 Inputs
.push_back(Arg
->getValue());
421 if (opt::Arg
*Arg
= Args
.getLastArg(OPT_REM
)) {
422 for (const char *Val
: Arg
->getValues())
423 Inputs
.push_back(Val
);
425 if (Inputs
.empty() && connection_fd
== -1) {
426 WithColor::error() << "no connection arguments\n" << HelpText
;
430 NativeProcessFactory factory
;
431 GDBRemoteCommunicationServerLLGS
gdb_server(mainloop
, factory
);
433 llvm::StringRef host_and_port
;
434 if (!Inputs
.empty()) {
435 host_and_port
= Inputs
.front();
436 Inputs
.erase(Inputs
.begin());
439 // Any arguments left over are for the program that we need to launch. If
441 // are no arguments, then the GDB server will start up and wait for an 'A'
443 // to launch a program, or a vAttach packet to attach to an existing process,
445 // explicitly asked to attach with the --attach={pid|program_name} form.
446 if (!attach_target
.empty())
447 handle_attach(gdb_server
, attach_target
);
448 else if (!Inputs
.empty())
449 handle_launch(gdb_server
, Inputs
);
451 // Print version info.
452 printf("%s-%s\n", LLGS_PROGRAM_NAME
, LLGS_VERSION_STR
);
454 ConnectToRemote(mainloop
, gdb_server
, reverse_connect
, host_and_port
,
455 progname
, subcommand
, named_pipe_path
.c_str(),
456 unnamed_pipe
, connection_fd
);
458 if (!gdb_server
.IsConnected()) {
459 fprintf(stderr
, "no connection information provided, unable to run\n");
463 Status ret
= mainloop
.Run();
465 fprintf(stderr
, "lldb-server terminating due to error: %s\n",
469 fprintf(stderr
, "lldb-server exiting...\n");