LLDB mainline
GDBRemoteCommunicationServerPlatform.cpp
Go to the documentation of this file.
1//===-- GDBRemoteCommunicationServerPlatform.cpp --------------------------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
10
11#include <cerrno>
12
13#include <chrono>
14#include <csignal>
15#include <cstring>
16#include <mutex>
17#include <optional>
18#include <sstream>
19#include <thread>
20
21#include "llvm/Support/FileSystem.h"
22#include "llvm/Support/JSON.h"
23#include "llvm/Support/Threading.h"
24
25#include "lldb/Host/Config.h"
28#include "lldb/Host/Host.h"
29#include "lldb/Host/HostInfo.h"
35#include "lldb/Utility/Log.h"
40
42
43using namespace lldb;
45using namespace lldb_private;
46
47// GDBRemoteCommunicationServerPlatform constructor
49 FileSpec debugserver_path, const Socket::SocketProtocol socket_protocol,
50 uint16_t gdbserver_port)
51 : m_debugserver_path(std::move(debugserver_path)),
52 m_socket_protocol(socket_protocol), m_gdbserver_port(gdbserver_port) {
53
81
84 bool &interrupt, bool &quit) {
85 error = Status::FromErrorString("interrupt received");
86 interrupt = true;
88 });
89}
90
91// Destructor
93 default;
94
96 const lldb_private::Args &args, lldb::pid_t &pid, std::string &socket_name,
97 shared_fd_t fd) {
99
100 ProcessLaunchInfo debugserver_launch_info;
101 // Do not run in a new session so that it can not linger after the platform
102 // closes.
103 debugserver_launch_info.SetLaunchInSeparateProcessGroup(false);
104 debugserver_launch_info.SetMonitorProcessCallback(
105 [](lldb::pid_t, int, int) {});
107 return Status::FromErrorString("debugserver does not exist");
108 debugserver_launch_info.SetExecutableFile(m_debugserver_path,
109 /*add_exe_file_as_first_arg=*/true);
110
112 if (fd == SharedSocket::kInvalidFD) {
114 // The server will be launched after accepting the connection.
115 return Status();
116 }
117
118 std::ostringstream url;
119 // debugserver does not accept the URL scheme prefix.
120#if !defined(__APPLE__)
122#endif
123 socket_name = GetDomainSocketPath("gdbserver").GetPath();
124 url << socket_name;
125 error = StartDebugserverProcess(url.str(), debugserver_launch_info, &args);
126 } else {
128 return Status::FromErrorString("protocol must be tcp");
129 error = StartDebugserverProcess(fd, debugserver_launch_info, &args);
130 }
131
132 if (error.Success()) {
133 pid = debugserver_launch_info.GetProcessID();
135 LLDB_LOGF(log,
136 "GDBRemoteCommunicationServerPlatform::%s() "
137 "debugserver launched successfully as pid %" PRIu64,
138 __FUNCTION__, pid);
139 } else {
140 LLDB_LOGF(log,
141 "GDBRemoteCommunicationServerPlatform::%s() "
142 "debugserver launch failed: %s",
143 __FUNCTION__, error.AsCString());
144 }
145 return error;
146}
147
150 StringExtractorGDBRemote &packet) {
151 // Spawn a local debugserver as a platform so we can then attach or launch a
152 // process...
153
155 LLDB_LOGF(log, "GDBRemoteCommunicationServerPlatform::%s() called",
156 __FUNCTION__);
157
158 ConnectionFileDescriptor file_conn;
159 packet.SetFilePos(::strlen("qLaunchGDBServer;"));
160 llvm::StringRef name;
161 llvm::StringRef value;
162 std::optional<uint16_t> port;
163 while (packet.GetNameColonValue(name, value)) {
164 if (name == "port") {
165 // Make the Optional valid so we can use its value
166 port = 0;
167 value.getAsInteger(0, *port);
168 }
169 }
170
171 // Ignore client's hostname and the port.
172
173 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
174 std::string socket_name;
175 Status error = LaunchGDBServer(Args(), debugserver_pid, socket_name,
177 if (error.Fail())
178 return SendErrorResponse(9); // EBADF
179
180 StreamGDBRemote response;
181 uint16_t gdbserver_port = socket_name.empty() ? m_gdbserver_port : 0;
182 response.Printf("pid:%" PRIu64 ";port:%u;", debugserver_pid, gdbserver_port);
183 if (!socket_name.empty()) {
184 response.PutCString("socket_name:");
185 response.PutStringAsRawHex8(socket_name);
186 response.PutChar(';');
187 }
188
189 PacketResult packet_result = SendPacketNoLock(response.GetString());
190 if (packet_result != PacketResult::Success) {
191 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
192 Host::Kill(debugserver_pid, SIGINT);
193 }
194 return packet_result;
195}
196
199 StringExtractorGDBRemote &packet) {
200 namespace json = llvm::json;
201
203 return SendErrorResponse(4);
204
205 json::Object server{{"port", m_pending_gdb_server_socket_name->empty()
207 : 0}};
208
210 server.try_emplace("socket_name", *m_pending_gdb_server_socket_name);
211
212 json::Array server_list;
213 server_list.push_back(std::move(server));
214
215 StreamGDBRemote response;
216 response.AsRawOstream() << std::move(server_list);
217
218 StreamGDBRemote escaped_response;
219 escaped_response.PutEscapedBytes(response.GetString().data(),
220 response.GetSize());
221 return SendPacketNoLock(escaped_response.GetString());
222}
223
226 StringExtractorGDBRemote &packet) {
227 packet.SetFilePos(::strlen("qKillSpawnedProcess:"));
228
230
231 // verify that we know anything about this pid.
232 if (!SpawnedProcessIsRunning(pid)) {
233 // not a pid we know about
234 return SendErrorResponse(10);
235 }
236
237 // go ahead and attempt to kill the spawned process
238 if (KillSpawnedProcess(pid))
239 return SendOKResponse();
240 else
241 return SendErrorResponse(11);
242}
243
245 assert(pid != LLDB_INVALID_PROCESS_ID);
246 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
247 m_spawned_pids.insert(pid);
248}
249
251 lldb::pid_t pid) {
252 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
253 return (m_spawned_pids.find(pid) != m_spawned_pids.end());
254}
255
257 // make sure we know about this process
258 if (!SpawnedProcessIsRunning(pid)) {
259 // it seems the process has been finished recently
260 return true;
261 }
262
263 // first try a SIGTERM (standard kill)
264 Host::Kill(pid, SIGTERM);
265
266 // check if that worked
267 for (size_t i = 0; i < 10; ++i) {
268 if (!SpawnedProcessIsRunning(pid)) {
269 // it is now killed
270 return true;
271 }
272 std::this_thread::sleep_for(std::chrono::milliseconds(10));
273 }
274
275 if (!SpawnedProcessIsRunning(pid))
276 return true;
277
278 // the launched process still lives. Now try killing it again, this time
279 // with an unblockable signal.
280 Host::Kill(pid, SIGKILL);
281
282 for (size_t i = 0; i < 10; ++i) {
283 if (!SpawnedProcessIsRunning(pid)) {
284 // it is now killed
285 return true;
286 }
287 std::this_thread::sleep_for(std::chrono::milliseconds(10));
288 }
289
290 // check one more time after the final sleep
291 return !SpawnedProcessIsRunning(pid);
292}
293
296 StringExtractorGDBRemote &packet) {
297 lldb::pid_t pid = m_process_launch_info.GetProcessID();
298 m_process_launch_info.Clear();
299
300 if (pid == LLDB_INVALID_PROCESS_ID)
301 return SendErrorResponse(1);
302
303 ProcessInstanceInfo proc_info;
304 if (!Host::GetProcessInfo(pid, proc_info))
305 return SendErrorResponse(1);
306
307 StreamString response;
309 return SendPacketNoLock(response.GetString());
310}
311
314 StringExtractorGDBRemote &packet) {
315 packet.SetFilePos(::strlen("qPathComplete:"));
316 const bool only_dir = (packet.GetHexMaxU32(false, 0) == 1);
317 if (packet.GetChar() != ',')
318 return SendErrorResponse(85);
319 std::string path;
320 packet.GetHexByteString(path);
321
322 StringList matches;
324 if (only_dir)
325 CommandCompletions::DiskDirectories(path, matches, resolver);
326 else
327 CommandCompletions::DiskFiles(path, matches, resolver);
328
329 StreamString response;
330 response.PutChar('M');
331 llvm::StringRef separator;
332 std::sort(matches.begin(), matches.end());
333 for (const auto &match : matches) {
334 response << separator;
335 separator = ",";
336 // encode result strings into hex bytes to avoid unexpected error caused by
337 // special characters like '$'.
338 response.PutStringAsRawHex8(match.c_str());
339 }
340
341 return SendPacketNoLock(response.GetString());
342}
343
346 StringExtractorGDBRemote &packet) {
347
348 llvm::SmallString<64> cwd;
349 if (std::error_code ec = llvm::sys::fs::current_path(cwd))
350 return SendErrorResponse(ec.value());
351
352 StreamString response;
353 response.PutBytesAsRawHex8(cwd.data(), cwd.size());
354 return SendPacketNoLock(response.GetString());
355}
356
359 StringExtractorGDBRemote &packet) {
360 packet.SetFilePos(::strlen("QSetWorkingDir:"));
361 std::string path;
362 packet.GetHexByteString(path);
363
364 if (std::error_code ec = llvm::sys::fs::set_current_path(path))
365 return SendErrorResponse(ec.value());
366 return SendOKResponse();
367}
368
371 StringExtractorGDBRemote &packet) {
372 // NOTE: lldb should now be using qProcessInfo for process IDs. This path
373 // here
374 // should not be used. It is reporting process id instead of thread id. The
375 // correct answer doesn't seem to make much sense for lldb-platform.
376 // CONSIDER: flip to "unsupported".
377 lldb::pid_t pid = m_process_launch_info.GetProcessID();
378
379 StreamString response;
380 response.Printf("QC%" PRIx64, pid);
381
382 // If we launch a process and this GDB server is acting as a platform, then
383 // we need to clear the process launch state so we can start launching
384 // another process. In order to launch a process a bunch or packets need to
385 // be sent: environment packets, working directory, disable ASLR, and many
386 // more settings. When we launch a process we then need to know when to clear
387 // this information. Currently we are selecting the 'qC' packet as that
388 // packet which seems to make the most sense.
389 if (pid != LLDB_INVALID_PROCESS_ID) {
390 m_process_launch_info.Clear();
391 }
392
393 return SendPacketNoLock(response.GetString());
394}
395
398 StringExtractorGDBRemote &packet) {
399 StructuredData::Array signal_array;
400
402 for (auto signo = signals->GetFirstSignalNumber();
404 signo = signals->GetNextSignalNumber(signo)) {
405 auto dictionary = std::make_shared<StructuredData::Dictionary>();
406
407 dictionary->AddIntegerItem("signo", signo);
408 dictionary->AddStringItem("name", signals->GetSignalAsStringRef(signo));
409
410 bool suppress, stop, notify;
411 signals->GetSignalInfo(signo, suppress, stop, notify);
412 dictionary->AddBooleanItem("suppress", suppress);
413 dictionary->AddBooleanItem("stop", stop);
414 dictionary->AddBooleanItem("notify", notify);
415
416 signal_array.Push(dictionary);
417 }
418
419 StreamString response;
420 signal_array.Dump(response);
421 return SendPacketNoLock(response.GetString());
422}
423
425 lldb::pid_t pid) {
426 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
427 m_spawned_pids.erase(pid);
428}
429
431 if (!m_process_launch_info.GetArguments().GetArgumentCount())
433 "%s: no process command line specified to launch", __FUNCTION__);
434
435 // specify the process monitor if not already set. This should generally be
436 // what happens since we need to reap started processes.
437 if (!m_process_launch_info.GetMonitorProcessCallback())
438 m_process_launch_info.SetMonitorProcessCallback(std::bind(
440 std::placeholders::_1));
441
443 if (!error.Success()) {
444 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
445 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
446 return error;
447 }
448
449 printf("Launched '%s' as process %" PRIu64 "...\n",
450 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
451 m_process_launch_info.GetProcessID());
452
453 // add to list of spawned processes. On an lldb-gdbserver, we would expect
454 // there to be only one.
455 const auto pid = m_process_launch_info.GetProcessID();
457
458 return error;
459}
460
462 static FileSpec g_domainsocket_dir;
463 static llvm::once_flag g_once_flag;
464
465 llvm::call_once(g_once_flag, []() {
466 const char *domainsocket_dir_env =
467 ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR");
468 if (domainsocket_dir_env != nullptr)
469 g_domainsocket_dir = FileSpec(domainsocket_dir_env);
470 else
471 g_domainsocket_dir = HostInfo::GetProcessTempDir();
472 });
473
474 return g_domainsocket_dir;
475}
476
479 llvm::SmallString<128> socket_path;
480 llvm::SmallString<128> socket_name(
481 (llvm::StringRef(prefix) + ".%%%%%%").str());
482
483 FileSpec socket_path_spec(GetDomainSocketDir());
484 socket_path_spec.AppendPathComponent(socket_name.c_str());
485
486 llvm::sys::fs::createUniqueFile(socket_path_spec.GetPath().c_str(),
487 socket_path);
488 return FileSpec(socket_path.c_str());
489}
490
492 const std::string &socket_name) {
494}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOGF(log,...)
Definition Log.h:390
void SetFilePos(uint32_t idx)
uint32_t GetHexMaxU32(bool little_endian, uint32_t fail_value)
bool GetNameColonValue(llvm::StringRef &name, llvm::StringRef &value)
uint64_t GetU64(uint64_t fail_value, int base=0)
size_t GetHexByteString(std::string &str)
char GetChar(char fail_value='\0')
A command line argument class.
Definition Args.h:33
static void DiskDirectories(CommandInterpreter &interpreter, CompletionRequest &request, SearchFilter *searcher)
static void DiskFiles(CommandInterpreter &interpreter, CompletionRequest &request, SearchFilter *searcher)
A file utility class.
Definition FileSpec.h:57
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:452
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:376
static FileSystem & Instance()
static Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch the process specified in launch_info.
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
Definition aix/Host.cpp:211
static void Kill(lldb::pid_t pid, int signo)
void SetExecutableFile(const FileSpec &exe_file, bool add_exe_file_as_first_arg)
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
void SetMonitorProcessCallback(Host::MonitorChildProcessCallback callback)
void SetLaunchInSeparateProcessGroup(bool separate)
static const shared_fd_t kInvalidFD
Definition Socket.h:50
static const char * FindSchemeByProtocol(const SocketProtocol protocol)
Definition Socket.cpp:151
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
int PutEscapedBytes(const void *s, size_t src_len)
Output a block of data to the stream performing GDB-remote escaping.
Definition GDBRemote.cpp:31
llvm::StringRef GetString() const
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t PutStringAsRawHex8(llvm::StringRef s)
Definition Stream.cpp:418
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
size_t PutBytesAsRawHex8(const void *src, size_t src_len, lldb::ByteOrder src_byte_order=lldb::eByteOrderInvalid, lldb::ByteOrder dst_byte_order=lldb::eByteOrderInvalid)
Definition Stream.cpp:391
void Push(const ObjectSP &item)
void Dump(lldb_private::Stream &s, bool pretty_print=true) const
static lldb::UnixSignalsSP CreateForHost()
void RegisterMemberFunctionHandler(StringExtractorGDBRemote::ServerPacketType packet_type, PacketResult(T::*handler)(StringExtractorGDBRemote &packet))
static void CreateProcessInfoResponse_DebugServerStyle(const ProcessInstanceInfo &proc_info, StreamString &response)
Status LaunchGDBServer(const lldb_private::Args &args, lldb::pid_t &pid, std::string &socket_name, shared_fd_t fd)
Status LaunchProcess() override
Launch a process with the current launch settings.
GDBRemoteCommunicationServerPlatform(FileSpec debugserver_path, const Socket::SocketProtocol socket_protocol, uint16_t gdbserver_port)
void RegisterPacketHandler(StringExtractorGDBRemote::ServerPacketType packet_type, PacketHandler handler)
static Status StartDebugserverProcess(std::variant< llvm::StringRef, shared_fd_t > comm, ProcessLaunchInfo &launch_info, const Args *inferior_args)
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_PROCESS_ID
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:339
NativeSocket shared_fd_t
Definition Socket.h:42
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
uint64_t pid_t
Definition lldb-types.h:83
#define SIGKILL