1 //===-- GDBRemoteCommunicationServerPlatform.cpp ----------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "GDBRemoteCommunicationServerPlatform.h"
21 // Other libraries and framework includes
22 #include "llvm/Support/FileSystem.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/StreamGDBRemote.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Core/StructuredData.h"
28 #include "lldb/Host/Config.h"
29 #include "lldb/Host/ConnectionFileDescriptor.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/HostInfo.h"
32 #include "lldb/Host/StringConvert.h"
33 #include "lldb/Target/FileAction.h"
34 #include "lldb/Target/Platform.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Target/UnixSignals.h"
37 #include "lldb/Utility/JSON.h"
40 #include "Utility/StringExtractorGDBRemote.h"
41 #include "Utility/UriParser.h"
44 using namespace lldb_private;
45 using namespace lldb_private::process_gdb_remote;
47 //----------------------------------------------------------------------
48 // GDBRemoteCommunicationServerPlatform constructor
49 //----------------------------------------------------------------------
50 GDBRemoteCommunicationServerPlatform::GDBRemoteCommunicationServerPlatform(const Socket::SocketProtocol socket_protocol,
51 const char* socket_scheme) :
52 GDBRemoteCommunicationServerCommon ("gdb-remote.server", "gdb-remote.server.rx_packet"),
53 m_socket_protocol(socket_protocol),
54 m_socket_scheme(socket_scheme),
55 m_spawned_pids_mutex (Mutex::eMutexTypeRecursive),
56 m_platform_sp (Platform::GetHostPlatform ()),
60 m_pending_gdb_server.pid = LLDB_INVALID_PROCESS_ID;
61 m_pending_gdb_server.port = 0;
63 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qC,
64 &GDBRemoteCommunicationServerPlatform::Handle_qC);
65 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
66 &GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir);
67 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer,
68 &GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer);
69 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qQueryGDBServer,
70 &GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer);
71 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess,
72 &GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess);
73 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
74 &GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo);
75 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
76 &GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir);
77 RegisterMemberFunctionHandler(StringExtractorGDBRemote::eServerPacketType_jSignalsInfo,
78 &GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo);
80 RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
81 [this](StringExtractorGDBRemote packet,
86 error.SetErrorString("interrupt received");
88 return PacketResult::Success;
92 //----------------------------------------------------------------------
94 //----------------------------------------------------------------------
95 GDBRemoteCommunicationServerPlatform::~GDBRemoteCommunicationServerPlatform()
100 GDBRemoteCommunicationServerPlatform::LaunchGDBServer(const lldb_private::Args& args,
101 std::string hostname,
104 std::string& socket_name)
106 if (port == UINT16_MAX)
107 port = GetNextAvailablePort();
109 // Spawn a new thread to accept the port that gets bound after
110 // binding to port 0 (zero).
112 // ignore the hostname send from the remote end, just use the ip address
113 // that we're currently communicating with as the hostname
115 // Spawn a debugserver and try to get the port it listens to.
116 ProcessLaunchInfo debugserver_launch_info;
117 if (hostname.empty())
118 hostname = "127.0.0.1";
120 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
122 log->Printf("Launching debugserver with: %s:%u...", hostname.c_str(), port);
124 // Do not run in a new session so that it can not linger after the
126 debugserver_launch_info.SetLaunchInSeparateProcessGroup(false);
127 debugserver_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
129 std::string platform_scheme;
130 std::string platform_ip;
132 std::string platform_path;
133 bool ok = UriParser::Parse(GetConnection()->GetURI().c_str(), platform_scheme, platform_ip, platform_port, platform_path);
134 UNUSED_IF_ASSERT_DISABLED(ok);
137 std::ostringstream url;
138 uint16_t* port_ptr = &port;
139 if (m_socket_protocol == Socket::ProtocolTcp)
140 url << platform_ip << ":" << port;
143 socket_name = GetDomainSocketPath("gdbserver").GetPath();
148 Error error = StartDebugserverProcess (url.str().c_str(),
150 debugserver_launch_info,
154 pid = debugserver_launch_info.GetProcessID();
155 if (pid != LLDB_INVALID_PROCESS_ID)
157 Mutex::Locker locker (m_spawned_pids_mutex);
158 m_spawned_pids.insert(pid);
160 AssociatePortWithProcess(port, pid);
170 GDBRemoteCommunication::PacketResult
171 GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer (StringExtractorGDBRemote &packet)
174 return SendErrorResponse(9);
176 // Spawn a local debugserver as a platform so we can then attach or launch
179 Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
181 log->Printf ("GDBRemoteCommunicationServerPlatform::%s() called", __FUNCTION__);
183 ConnectionFileDescriptor file_conn;
184 std::string hostname;
185 packet.SetFilePos(::strlen ("qLaunchGDBServer;"));
188 uint16_t port = UINT16_MAX;
189 while (packet.GetNameColonValue(name, value))
191 if (name.compare ("host") == 0)
192 hostname.swap(value);
193 else if (name.compare ("port") == 0)
194 port = StringConvert::ToUInt32(value.c_str(), 0, 0);
197 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
198 std::string socket_name;
199 Error error = LaunchGDBServer(Args(), hostname, debugserver_pid, port, socket_name);
203 log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver launch failed: %s", __FUNCTION__, error.AsCString ());
204 return SendErrorResponse(9);
208 log->Printf ("GDBRemoteCommunicationServerPlatform::%s() debugserver launched successfully as pid %" PRIu64, __FUNCTION__, debugserver_pid);
210 StreamGDBRemote response;
211 response.Printf("pid:%" PRIu64 ";port:%u;", debugserver_pid, port + m_port_offset);
212 if (!socket_name.empty())
214 response.PutCString("socket_name:");
215 response.PutCStringAsRawHex8(socket_name.c_str());
216 response.PutChar(';');
219 PacketResult packet_result = SendPacketNoLock(response.GetData(), response.GetSize());
220 if (packet_result != PacketResult::Success)
222 if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
223 ::kill (debugserver_pid, SIGINT);
225 return packet_result;
229 GDBRemoteCommunication::PacketResult
230 GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer (StringExtractorGDBRemote &packet)
232 if (m_pending_gdb_server.pid == LLDB_INVALID_PROCESS_ID)
233 return SendErrorResponse(4);
235 JSONObject::SP server_sp = std::make_shared<JSONObject>();
236 server_sp->SetObject("port", std::make_shared<JSONNumber>(m_pending_gdb_server.port));
237 if (!m_pending_gdb_server.socket_name.empty())
238 server_sp->SetObject("socket_name",
239 std::make_shared<JSONString>(m_pending_gdb_server.socket_name.c_str()));
241 JSONArray server_list;
242 server_list.AppendObject(server_sp);
244 StreamGDBRemote response;
245 server_list.Write(response);
247 StreamGDBRemote escaped_response;
248 escaped_response.PutEscapedBytes(response.GetData(), response.GetSize());
249 return SendPacketNoLock(escaped_response.GetData(), escaped_response.GetSize());
252 GDBRemoteCommunication::PacketResult
253 GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess (StringExtractorGDBRemote &packet)
255 packet.SetFilePos(::strlen ("qKillSpawnedProcess:"));
257 lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
259 // verify that we know anything about this pid.
262 Mutex::Locker locker (m_spawned_pids_mutex);
263 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
265 // not a pid we know about
266 return SendErrorResponse (10);
270 // go ahead and attempt to kill the spawned process
271 if (KillSpawnedProcess (pid))
272 return SendOKResponse ();
274 return SendErrorResponse (11);
278 GDBRemoteCommunicationServerPlatform::KillSpawnedProcess (lldb::pid_t pid)
280 // make sure we know about this process
282 Mutex::Locker locker (m_spawned_pids_mutex);
283 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
287 // first try a SIGTERM (standard kill)
288 Host::Kill (pid, SIGTERM);
290 // check if that worked
291 for (size_t i=0; i<10; ++i)
294 Mutex::Locker locker (m_spawned_pids_mutex);
295 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
304 // check one more time after the final usleep
306 Mutex::Locker locker (m_spawned_pids_mutex);
307 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
311 // the launched process still lives. Now try killing it again,
312 // this time with an unblockable signal.
313 Host::Kill (pid, SIGKILL);
315 for (size_t i=0; i<10; ++i)
318 Mutex::Locker locker (m_spawned_pids_mutex);
319 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
328 // check one more time after the final usleep
331 Mutex::Locker locker (m_spawned_pids_mutex);
332 if (m_spawned_pids.find(pid) == m_spawned_pids.end())
336 // no luck - the process still lives
340 GDBRemoteCommunication::PacketResult
341 GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo (StringExtractorGDBRemote &packet)
343 lldb::pid_t pid = m_process_launch_info.GetProcessID ();
344 m_process_launch_info.Clear ();
346 if (pid == LLDB_INVALID_PROCESS_ID)
347 return SendErrorResponse (1);
349 ProcessInstanceInfo proc_info;
350 if (!Host::GetProcessInfo (pid, proc_info))
351 return SendErrorResponse (1);
353 StreamString response;
354 CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
355 return SendPacketNoLock (response.GetData (), response.GetSize ());
358 GDBRemoteCommunication::PacketResult
359 GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir (StringExtractorGDBRemote &packet)
361 // If this packet is sent to a platform, then change the current working directory
364 if (getcwd(cwd, sizeof(cwd)) == NULL)
365 return SendErrorResponse(errno);
367 StreamString response;
368 response.PutBytesAsRawHex8(cwd, strlen(cwd));
369 return SendPacketNoLock(response.GetData(), response.GetSize());
372 GDBRemoteCommunication::PacketResult
373 GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir (StringExtractorGDBRemote &packet)
375 packet.SetFilePos (::strlen ("QSetWorkingDir:"));
377 packet.GetHexByteString (path);
379 // If this packet is sent to a platform, then change the current working directory
380 if (::chdir(path.c_str()) != 0)
381 return SendErrorResponse (errno);
382 return SendOKResponse ();
385 GDBRemoteCommunication::PacketResult
386 GDBRemoteCommunicationServerPlatform::Handle_qC (StringExtractorGDBRemote &packet)
388 // NOTE: lldb should now be using qProcessInfo for process IDs. This path here
389 // should not be used. It is reporting process id instead of thread id. The
390 // correct answer doesn't seem to make much sense for lldb-platform.
391 // CONSIDER: flip to "unsupported".
392 lldb::pid_t pid = m_process_launch_info.GetProcessID();
394 StreamString response;
395 response.Printf("QC%" PRIx64, pid);
397 // If we launch a process and this GDB server is acting as a platform,
398 // then we need to clear the process launch state so we can start
399 // launching another process. In order to launch a process a bunch or
400 // packets need to be sent: environment packets, working directory,
401 // disable ASLR, and many more settings. When we launch a process we
402 // then need to know when to clear this information. Currently we are
403 // selecting the 'qC' packet as that packet which seems to make the most
405 if (pid != LLDB_INVALID_PROCESS_ID)
407 m_process_launch_info.Clear();
410 return SendPacketNoLock (response.GetData(), response.GetSize());
413 GDBRemoteCommunication::PacketResult
414 GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo(StringExtractorGDBRemote &packet)
416 StructuredData::Array signal_array;
418 const auto &signals = Host::GetUnixSignals();
419 for (auto signo = signals->GetFirstSignalNumber();
420 signo != LLDB_INVALID_SIGNAL_NUMBER;
421 signo = signals->GetNextSignalNumber(signo))
423 auto dictionary = std::make_shared<StructuredData::Dictionary>();
425 dictionary->AddIntegerItem("signo", signo);
426 dictionary->AddStringItem("name", signals->GetSignalAsCString(signo));
428 bool suppress, stop, notify;
429 signals->GetSignalInfo(signo, suppress, stop, notify);
430 dictionary->AddBooleanItem("suppress", suppress);
431 dictionary->AddBooleanItem("stop", stop);
432 dictionary->AddBooleanItem("notify", notify);
434 signal_array.Push(dictionary);
437 StreamString response;
438 signal_array.Dump(response);
439 return SendPacketNoLock(response.GetData(), response.GetSize());
443 GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped (lldb::pid_t pid)
445 Mutex::Locker locker (m_spawned_pids_mutex);
446 FreePortForProcess(pid);
447 return m_spawned_pids.erase(pid) > 0;
451 GDBRemoteCommunicationServerPlatform::ReapDebugserverProcess (void *callback_baton,
454 int signal, // Zero for no signal
455 int status) // Exit value of process if signal is zero
457 GDBRemoteCommunicationServerPlatform *server = (GDBRemoteCommunicationServerPlatform *)callback_baton;
458 server->DebugserverProcessReaped (pid);
463 GDBRemoteCommunicationServerPlatform::LaunchProcess ()
465 if (!m_process_launch_info.GetArguments ().GetArgumentCount ())
466 return Error ("%s: no process command line specified to launch", __FUNCTION__);
468 // specify the process monitor if not already set. This should
469 // generally be what happens since we need to reap started
471 if (!m_process_launch_info.GetMonitorProcessCallback ())
472 m_process_launch_info.SetMonitorProcessCallback(ReapDebugserverProcess, this, false);
474 Error error = m_platform_sp->LaunchProcess (m_process_launch_info);
475 if (!error.Success ())
477 fprintf (stderr, "%s: failed to launch executable %s", __FUNCTION__, m_process_launch_info.GetArguments ().GetArgumentAtIndex (0));
481 printf ("Launched '%s' as process %" PRIu64 "...\n", m_process_launch_info.GetArguments ().GetArgumentAtIndex (0), m_process_launch_info.GetProcessID());
483 // add to list of spawned processes. On an lldb-gdbserver, we
484 // would expect there to be only one.
485 const auto pid = m_process_launch_info.GetProcessID();
486 if (pid != LLDB_INVALID_PROCESS_ID)
488 // add to spawned pids
489 Mutex::Locker locker (m_spawned_pids_mutex);
490 m_spawned_pids.insert(pid);
497 GDBRemoteCommunicationServerPlatform::SetPortMap (PortMap &&port_map)
499 m_port_map = port_map;
503 GDBRemoteCommunicationServerPlatform::GetNextAvailablePort ()
505 if (m_port_map.empty())
506 return 0; // Bind to port zero and get a port, we didn't have any limitations
508 for (auto &pair : m_port_map)
510 if (pair.second == LLDB_INVALID_PROCESS_ID)
512 pair.second = ~(lldb::pid_t)LLDB_INVALID_PROCESS_ID;
520 GDBRemoteCommunicationServerPlatform::AssociatePortWithProcess (uint16_t port, lldb::pid_t pid)
522 PortMap::iterator pos = m_port_map.find(port);
523 if (pos != m_port_map.end())
532 GDBRemoteCommunicationServerPlatform::FreePort (uint16_t port)
534 PortMap::iterator pos = m_port_map.find(port);
535 if (pos != m_port_map.end())
537 pos->second = LLDB_INVALID_PROCESS_ID;
544 GDBRemoteCommunicationServerPlatform::FreePortForProcess (lldb::pid_t pid)
546 if (!m_port_map.empty())
548 for (auto &pair : m_port_map)
550 if (pair.second == pid)
552 pair.second = LLDB_INVALID_PROCESS_ID;
561 GDBRemoteCommunicationServerPlatform::GetDomainSocketDir()
563 static FileSpec g_domainsocket_dir;
564 static std::once_flag g_once_flag;
566 std::call_once(g_once_flag, []() {
567 const char* domainsocket_dir_env = ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR");
568 if (domainsocket_dir_env != nullptr)
569 g_domainsocket_dir = FileSpec(domainsocket_dir_env, false);
571 HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, g_domainsocket_dir);
574 return g_domainsocket_dir;
578 GDBRemoteCommunicationServerPlatform::GetDomainSocketPath(const char* prefix)
580 llvm::SmallString<PATH_MAX> socket_path;
581 llvm::SmallString<PATH_MAX> socket_name((llvm::StringRef(prefix) + ".%%%%%%").str());
583 FileSpec socket_path_spec(GetDomainSocketDir());
584 socket_path_spec.AppendPathComponent(socket_name.c_str());
586 llvm::sys::fs::createUniqueFile(socket_path_spec.GetCString(), socket_path);
587 return FileSpec(socket_path.c_str(), false);
591 GDBRemoteCommunicationServerPlatform::SetPortOffset(uint16_t port_offset)
593 m_port_offset = port_offset;
597 GDBRemoteCommunicationServerPlatform::SetPendingGdbServer(lldb::pid_t pid,
599 const std::string& socket_name)
601 m_pending_gdb_server.pid = pid;
602 m_pending_gdb_server.port = port;
603 m_pending_gdb_server.socket_name = socket_name;