1 //===-- GDBRemoteCommunicationServerPlatform.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 //===----------------------------------------------------------------------===//
9 #include "GDBRemoteCommunicationServerPlatform.h"
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Threading.h"
22 #include "lldb/Host/Config.h"
23 #include "lldb/Host/ConnectionFileDescriptor.h"
24 #include "lldb/Host/FileAction.h"
25 #include "lldb/Host/Host.h"
26 #include "lldb/Host/HostInfo.h"
27 #include "lldb/Target/Platform.h"
28 #include "lldb/Target/UnixSignals.h"
29 #include "lldb/Utility/JSON.h"
30 #include "lldb/Utility/Log.h"
31 #include "lldb/Utility/StreamGDBRemote.h"
32 #include "lldb/Utility/StreamString.h"
33 #include "lldb/Utility/StructuredData.h"
34 #include "lldb/Utility/UriParser.h"
36 #include "lldb/Utility/StringExtractorGDBRemote.h"
39 using namespace lldb_private;
40 using namespace lldb_private::process_gdb_remote;
42 // GDBRemoteCommunicationServerPlatform constructor
43 GDBRemoteCommunicationServerPlatform::GDBRemoteCommunicationServerPlatform(
44 const Socket::SocketProtocol socket_protocol, const char *socket_scheme)
45 : GDBRemoteCommunicationServerCommon("gdb-remote.server",
46 "gdb-remote.server.rx_packet"),
47 m_socket_protocol(socket_protocol), m_socket_scheme(socket_scheme),
48 m_spawned_pids_mutex(), m_port_map(), m_port_offset(0) {
49 m_pending_gdb_server.pid = LLDB_INVALID_PROCESS_ID;
50 m_pending_gdb_server.port = 0;
52 RegisterMemberFunctionHandler(
53 StringExtractorGDBRemote::eServerPacketType_qC,
54 &GDBRemoteCommunicationServerPlatform::Handle_qC);
55 RegisterMemberFunctionHandler(
56 StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
57 &GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir);
58 RegisterMemberFunctionHandler(
59 StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer,
60 &GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer);
61 RegisterMemberFunctionHandler(
62 StringExtractorGDBRemote::eServerPacketType_qQueryGDBServer,
63 &GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer);
64 RegisterMemberFunctionHandler(
65 StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess,
66 &GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess);
67 RegisterMemberFunctionHandler(
68 StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
69 &GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo);
70 RegisterMemberFunctionHandler(
71 StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
72 &GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir);
73 RegisterMemberFunctionHandler(
74 StringExtractorGDBRemote::eServerPacketType_jSignalsInfo,
75 &GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo);
77 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
78 [](StringExtractorGDBRemote packet, Status &error,
79 bool &interrupt, bool &quit) {
80 error.SetErrorString("interrupt received");
82 return PacketResult::Success;
87 GDBRemoteCommunicationServerPlatform::~GDBRemoteCommunicationServerPlatform() {}
89 Status GDBRemoteCommunicationServerPlatform::LaunchGDBServer(
90 const lldb_private::Args &args, std::string hostname, lldb::pid_t &pid,
91 uint16_t &port, std::string &socket_name) {
92 if (port == UINT16_MAX)
93 port = GetNextAvailablePort();
95 // Spawn a new thread to accept the port that gets bound after binding to
98 // ignore the hostname send from the remote end, just use the ip address that
99 // we're currently communicating with as the hostname
101 // Spawn a debugserver and try to get the port it listens to.
102 ProcessLaunchInfo debugserver_launch_info;
103 if (hostname.empty())
104 hostname = "127.0.0.1";
106 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
108 log->Printf("Launching debugserver with: %s:%u...", hostname.c_str(), port);
110 // Do not run in a new session so that it can not linger after the platform
112 debugserver_launch_info.SetLaunchInSeparateProcessGroup(false);
113 debugserver_launch_info.SetMonitorProcessCallback(
114 std::bind(&GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
115 this, std::placeholders::_1),
118 std::ostringstream url;
119 // debugserver does not accept the URL scheme prefix.
120 #if !defined(__APPLE__)
121 url << m_socket_scheme << "://";
123 uint16_t *port_ptr = &port;
124 if (m_socket_protocol == Socket::ProtocolTcp) {
125 llvm::StringRef platform_scheme;
126 llvm::StringRef platform_ip;
128 llvm::StringRef platform_path;
129 std::string platform_uri = GetConnection()->GetURI();
130 bool ok = UriParser::Parse(platform_uri, platform_scheme, platform_ip,
131 platform_port, platform_path);
132 UNUSED_IF_ASSERT_DISABLED(ok);
134 url << platform_ip.str() << ":" << port;
136 socket_name = GetDomainSocketPath("gdbserver").GetPath();
141 Status error = StartDebugserverProcess(
142 url.str().c_str(), nullptr, debugserver_launch_info, port_ptr, &args, -1);
144 pid = debugserver_launch_info.GetProcessID();
145 if (pid != LLDB_INVALID_PROCESS_ID) {
146 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
147 m_spawned_pids.insert(pid);
149 AssociatePortWithProcess(port, pid);
157 GDBRemoteCommunication::PacketResult
158 GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer(
159 StringExtractorGDBRemote &packet) {
160 // Spawn a local debugserver as a platform so we can then attach or launch a
163 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
165 log->Printf("GDBRemoteCommunicationServerPlatform::%s() called",
168 ConnectionFileDescriptor file_conn;
169 std::string hostname;
170 packet.SetFilePos(::strlen("qLaunchGDBServer;"));
171 llvm::StringRef name;
172 llvm::StringRef value;
173 uint16_t port = UINT16_MAX;
174 while (packet.GetNameColonValue(name, value)) {
175 if (name.equals("host"))
177 else if (name.equals("port"))
178 value.getAsInteger(0, port);
181 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
182 std::string socket_name;
184 LaunchGDBServer(Args(), hostname, debugserver_pid, port, socket_name);
187 log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver "
189 __FUNCTION__, error.AsCString());
190 return SendErrorResponse(9);
194 log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver "
195 "launched successfully as pid %" PRIu64,
196 __FUNCTION__, debugserver_pid);
198 StreamGDBRemote response;
199 response.Printf("pid:%" PRIu64 ";port:%u;", debugserver_pid,
200 port + m_port_offset);
201 if (!socket_name.empty()) {
202 response.PutCString("socket_name:");
203 response.PutStringAsRawHex8(socket_name);
204 response.PutChar(';');
207 PacketResult packet_result = SendPacketNoLock(response.GetString());
208 if (packet_result != PacketResult::Success) {
209 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
210 Host::Kill(debugserver_pid, SIGINT);
212 return packet_result;
215 GDBRemoteCommunication::PacketResult
216 GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer(
217 StringExtractorGDBRemote &packet) {
218 if (m_pending_gdb_server.pid == LLDB_INVALID_PROCESS_ID)
219 return SendErrorResponse(4);
221 JSONObject::SP server_sp = std::make_shared<JSONObject>();
222 server_sp->SetObject("port",
223 std::make_shared<JSONNumber>(m_pending_gdb_server.port));
224 if (!m_pending_gdb_server.socket_name.empty())
225 server_sp->SetObject(
227 std::make_shared<JSONString>(m_pending_gdb_server.socket_name.c_str()));
229 JSONArray server_list;
230 server_list.AppendObject(server_sp);
232 StreamGDBRemote response;
233 server_list.Write(response);
235 StreamGDBRemote escaped_response;
236 escaped_response.PutEscapedBytes(response.GetString().data(),
238 return SendPacketNoLock(escaped_response.GetString());
241 GDBRemoteCommunication::PacketResult
242 GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess(
243 StringExtractorGDBRemote &packet) {
244 packet.SetFilePos(::strlen("qKillSpawnedProcess:"));
246 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
248 // verify that we know anything about this pid. Scope for locker
250 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
251 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
252 // not a pid we know about
253 return SendErrorResponse(10);
257 // go ahead and attempt to kill the spawned process
258 if (KillSpawnedProcess(pid))
259 return SendOKResponse();
261 return SendErrorResponse(11);
264 bool GDBRemoteCommunicationServerPlatform::KillSpawnedProcess(lldb::pid_t pid) {
265 // make sure we know about this process
267 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
268 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
272 // first try a SIGTERM (standard kill)
273 Host::Kill(pid, SIGTERM);
275 // check if that worked
276 for (size_t i = 0; i < 10; ++i) {
278 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
279 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
287 // check one more time after the final usleep
289 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
290 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
294 // the launched process still lives. Now try killing it again, this time
295 // with an unblockable signal.
296 Host::Kill(pid, SIGKILL);
298 for (size_t i = 0; i < 10; ++i) {
300 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
301 if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
309 // check one more time after the final usleep Scope for locker
311 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
312 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
316 // no luck - the process still lives
320 GDBRemoteCommunication::PacketResult
321 GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo(
322 StringExtractorGDBRemote &packet) {
323 lldb::pid_t pid = m_process_launch_info.GetProcessID();
324 m_process_launch_info.Clear();
326 if (pid == LLDB_INVALID_PROCESS_ID)
327 return SendErrorResponse(1);
329 ProcessInstanceInfo proc_info;
330 if (!Host::GetProcessInfo(pid, proc_info))
331 return SendErrorResponse(1);
333 StreamString response;
334 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
335 return SendPacketNoLock(response.GetString());
338 GDBRemoteCommunication::PacketResult
339 GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir(
340 StringExtractorGDBRemote &packet) {
342 llvm::SmallString<64> cwd;
343 if (std::error_code ec = llvm::sys::fs::current_path(cwd))
344 return SendErrorResponse(ec.value());
346 StreamString response;
347 response.PutBytesAsRawHex8(cwd.data(), cwd.size());
348 return SendPacketNoLock(response.GetString());
351 GDBRemoteCommunication::PacketResult
352 GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir(
353 StringExtractorGDBRemote &packet) {
354 packet.SetFilePos(::strlen("QSetWorkingDir:"));
356 packet.GetHexByteString(path);
358 if (std::error_code ec = llvm::sys::fs::set_current_path(path))
359 return SendErrorResponse(ec.value());
360 return SendOKResponse();
363 GDBRemoteCommunication::PacketResult
364 GDBRemoteCommunicationServerPlatform::Handle_qC(
365 StringExtractorGDBRemote &packet) {
366 // NOTE: lldb should now be using qProcessInfo for process IDs. This path
368 // should not be used. It is reporting process id instead of thread id. The
369 // correct answer doesn't seem to make much sense for lldb-platform.
370 // CONSIDER: flip to "unsupported".
371 lldb::pid_t pid = m_process_launch_info.GetProcessID();
373 StreamString response;
374 response.Printf("QC%" PRIx64, pid);
376 // If we launch a process and this GDB server is acting as a platform, then
377 // we need to clear the process launch state so we can start launching
378 // another process. In order to launch a process a bunch or packets need to
379 // be sent: environment packets, working directory, disable ASLR, and many
380 // more settings. When we launch a process we then need to know when to clear
381 // this information. Currently we are selecting the 'qC' packet as that
382 // packet which seems to make the most sense.
383 if (pid != LLDB_INVALID_PROCESS_ID) {
384 m_process_launch_info.Clear();
387 return SendPacketNoLock(response.GetString());
390 GDBRemoteCommunication::PacketResult
391 GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo(
392 StringExtractorGDBRemote &packet) {
393 StructuredData::Array signal_array;
395 lldb::UnixSignalsSP signals = UnixSignals::CreateForHost();
396 for (auto signo = signals->GetFirstSignalNumber();
397 signo != LLDB_INVALID_SIGNAL_NUMBER;
398 signo = signals->GetNextSignalNumber(signo)) {
399 auto dictionary = std::make_shared<StructuredData::Dictionary>();
401 dictionary->AddIntegerItem("signo", signo);
402 dictionary->AddStringItem("name", signals->GetSignalAsCString(signo));
404 bool suppress, stop, notify;
405 signals->GetSignalInfo(signo, suppress, stop, notify);
406 dictionary->AddBooleanItem("suppress", suppress);
407 dictionary->AddBooleanItem("stop", stop);
408 dictionary->AddBooleanItem("notify", notify);
410 signal_array.Push(dictionary);
413 StreamString response;
414 signal_array.Dump(response);
415 return SendPacketNoLock(response.GetString());
418 bool GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped(
420 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
421 FreePortForProcess(pid);
422 m_spawned_pids.erase(pid);
426 Status GDBRemoteCommunicationServerPlatform::LaunchProcess() {
427 if (!m_process_launch_info.GetArguments().GetArgumentCount())
428 return Status("%s: no process command line specified to launch",
431 // specify the process monitor if not already set. This should generally be
432 // what happens since we need to reap started processes.
433 if (!m_process_launch_info.GetMonitorProcessCallback())
434 m_process_launch_info.SetMonitorProcessCallback(
436 &GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
437 this, std::placeholders::_1),
440 Status error = Host::LaunchProcess(m_process_launch_info);
441 if (!error.Success()) {
442 fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
443 m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
447 printf("Launched '%s' as process %" PRIu64 "...\n",
448 m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
449 m_process_launch_info.GetProcessID());
451 // add to list of spawned processes. On an lldb-gdbserver, we would expect
452 // there to be only one.
453 const auto pid = m_process_launch_info.GetProcessID();
454 if (pid != LLDB_INVALID_PROCESS_ID) {
455 // add to spawned pids
456 std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
457 m_spawned_pids.insert(pid);
463 void GDBRemoteCommunicationServerPlatform::SetPortMap(PortMap &&port_map) {
464 m_port_map = port_map;
467 uint16_t GDBRemoteCommunicationServerPlatform::GetNextAvailablePort() {
468 if (m_port_map.empty())
469 return 0; // Bind to port zero and get a port, we didn't have any
472 for (auto &pair : m_port_map) {
473 if (pair.second == LLDB_INVALID_PROCESS_ID) {
474 pair.second = ~(lldb::pid_t)LLDB_INVALID_PROCESS_ID;
481 bool GDBRemoteCommunicationServerPlatform::AssociatePortWithProcess(
482 uint16_t port, lldb::pid_t pid) {
483 PortMap::iterator pos = m_port_map.find(port);
484 if (pos != m_port_map.end()) {
491 bool GDBRemoteCommunicationServerPlatform::FreePort(uint16_t port) {
492 PortMap::iterator pos = m_port_map.find(port);
493 if (pos != m_port_map.end()) {
494 pos->second = LLDB_INVALID_PROCESS_ID;
500 bool GDBRemoteCommunicationServerPlatform::FreePortForProcess(lldb::pid_t pid) {
501 if (!m_port_map.empty()) {
502 for (auto &pair : m_port_map) {
503 if (pair.second == pid) {
504 pair.second = LLDB_INVALID_PROCESS_ID;
512 const FileSpec &GDBRemoteCommunicationServerPlatform::GetDomainSocketDir() {
513 static FileSpec g_domainsocket_dir;
514 static llvm::once_flag g_once_flag;
516 llvm::call_once(g_once_flag, []() {
517 const char *domainsocket_dir_env =
518 ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR");
519 if (domainsocket_dir_env != nullptr)
520 g_domainsocket_dir = FileSpec(domainsocket_dir_env);
522 g_domainsocket_dir = HostInfo::GetProcessTempDir();
525 return g_domainsocket_dir;
529 GDBRemoteCommunicationServerPlatform::GetDomainSocketPath(const char *prefix) {
530 llvm::SmallString<128> socket_path;
531 llvm::SmallString<128> socket_name(
532 (llvm::StringRef(prefix) + ".%%%%%%").str());
534 FileSpec socket_path_spec(GetDomainSocketDir());
535 socket_path_spec.AppendPathComponent(socket_name.c_str());
537 llvm::sys::fs::createUniqueFile(socket_path_spec.GetCString(), socket_path);
538 return FileSpec(socket_path.c_str());
541 void GDBRemoteCommunicationServerPlatform::SetPortOffset(uint16_t port_offset) {
542 m_port_offset = port_offset;
545 void GDBRemoteCommunicationServerPlatform::SetPendingGdbServer(
546 lldb::pid_t pid, uint16_t port, const std::string &socket_name) {
547 m_pending_gdb_server.pid = pid;
548 m_pending_gdb_server.port = port;
549 m_pending_gdb_server.socket_name = socket_name;