1 //===-- GDBRemoteCommunicationServerPlatform.cpp ----------------*- C++ -*-===//
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 
9 #include "GDBRemoteCommunicationServerPlatform.h"
10 
11 #include <errno.h>
12 
13 #include <chrono>
14 #include <csignal>
15 #include <cstring>
16 #include <mutex>
17 #include <sstream>
18 #include <thread>
19 
20 #include "llvm/Support/FileSystem.h"
21 #include "llvm/Support/Threading.h"
22 
23 #include "lldb/Host/Config.h"
24 #include "lldb/Host/ConnectionFileDescriptor.h"
25 #include "lldb/Host/FileAction.h"
26 #include "lldb/Host/Host.h"
27 #include "lldb/Host/HostInfo.h"
28 #include "lldb/Target/Platform.h"
29 #include "lldb/Target/UnixSignals.h"
30 #include "lldb/Utility/GDBRemote.h"
31 #include "lldb/Utility/JSON.h"
32 #include "lldb/Utility/Log.h"
33 #include "lldb/Utility/StreamString.h"
34 #include "lldb/Utility/StructuredData.h"
35 #include "lldb/Utility/UriParser.h"
36 
37 #include "lldb/Utility/StringExtractorGDBRemote.h"
38 
39 using namespace lldb;
40 using namespace lldb_private;
41 using namespace lldb_private::process_gdb_remote;
42 
43 // GDBRemoteCommunicationServerPlatform constructor
44 GDBRemoteCommunicationServerPlatform::GDBRemoteCommunicationServerPlatform(
45     const Socket::SocketProtocol socket_protocol, const char *socket_scheme)
46     : GDBRemoteCommunicationServerCommon("gdb-remote.server",
47                                          "gdb-remote.server.rx_packet"),
48       m_socket_protocol(socket_protocol), m_socket_scheme(socket_scheme),
49       m_spawned_pids_mutex(), m_port_map(), m_port_offset(0) {
50   m_pending_gdb_server.pid = LLDB_INVALID_PROCESS_ID;
51   m_pending_gdb_server.port = 0;
52 
53   RegisterMemberFunctionHandler(
54       StringExtractorGDBRemote::eServerPacketType_qC,
55       &GDBRemoteCommunicationServerPlatform::Handle_qC);
56   RegisterMemberFunctionHandler(
57       StringExtractorGDBRemote::eServerPacketType_qGetWorkingDir,
58       &GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir);
59   RegisterMemberFunctionHandler(
60       StringExtractorGDBRemote::eServerPacketType_qLaunchGDBServer,
61       &GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer);
62   RegisterMemberFunctionHandler(
63       StringExtractorGDBRemote::eServerPacketType_qQueryGDBServer,
64       &GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer);
65   RegisterMemberFunctionHandler(
66       StringExtractorGDBRemote::eServerPacketType_qKillSpawnedProcess,
67       &GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess);
68   RegisterMemberFunctionHandler(
69       StringExtractorGDBRemote::eServerPacketType_qProcessInfo,
70       &GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo);
71   RegisterMemberFunctionHandler(
72       StringExtractorGDBRemote::eServerPacketType_QSetWorkingDir,
73       &GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir);
74   RegisterMemberFunctionHandler(
75       StringExtractorGDBRemote::eServerPacketType_jSignalsInfo,
76       &GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo);
77 
78   RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
79                         [](StringExtractorGDBRemote packet, Status &error,
80                            bool &interrupt, bool &quit) {
81                           error.SetErrorString("interrupt received");
82                           interrupt = true;
83                           return PacketResult::Success;
84                         });
85 }
86 
87 // Destructor
88 GDBRemoteCommunicationServerPlatform::~GDBRemoteCommunicationServerPlatform() {}
89 
90 Status GDBRemoteCommunicationServerPlatform::LaunchGDBServer(
91     const lldb_private::Args &args, std::string hostname, lldb::pid_t &pid,
92     uint16_t &port, std::string &socket_name) {
93   if (port == UINT16_MAX)
94     port = GetNextAvailablePort();
95 
96   // Spawn a new thread to accept the port that gets bound after binding to
97   // port 0 (zero).
98 
99   // ignore the hostname send from the remote end, just use the ip address that
100   // we're currently communicating with as the hostname
101 
102   // Spawn a debugserver and try to get the port it listens to.
103   ProcessLaunchInfo debugserver_launch_info;
104   if (hostname.empty())
105     hostname = "127.0.0.1";
106 
107   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
108   LLDB_LOGF(log, "Launching debugserver with: %s:%u...", hostname.c_str(),
109             port);
110 
111   // Do not run in a new session so that it can not linger after the platform
112   // closes.
113   debugserver_launch_info.SetLaunchInSeparateProcessGroup(false);
114   debugserver_launch_info.SetMonitorProcessCallback(
115       std::bind(&GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
116                 this, std::placeholders::_1),
117       false);
118 
119   std::ostringstream url;
120 // debugserver does not accept the URL scheme prefix.
121 #if !defined(__APPLE__)
122   url << m_socket_scheme << "://";
123 #endif
124   uint16_t *port_ptr = &port;
125   if (m_socket_protocol == Socket::ProtocolTcp) {
126     llvm::StringRef platform_scheme;
127     llvm::StringRef platform_ip;
128     int platform_port;
129     llvm::StringRef platform_path;
130     std::string platform_uri = GetConnection()->GetURI();
131     bool ok = UriParser::Parse(platform_uri, platform_scheme, platform_ip,
132                                platform_port, platform_path);
133     UNUSED_IF_ASSERT_DISABLED(ok);
134     assert(ok);
135     url << platform_ip.str() << ":" << port;
136   } else {
137     socket_name = GetDomainSocketPath("gdbserver").GetPath();
138     url << socket_name;
139     port_ptr = nullptr;
140   }
141 
142   Status error = StartDebugserverProcess(
143       url.str().c_str(), nullptr, debugserver_launch_info, port_ptr, &args, -1);
144 
145   pid = debugserver_launch_info.GetProcessID();
146   if (pid != LLDB_INVALID_PROCESS_ID) {
147     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
148     m_spawned_pids.insert(pid);
149     if (port > 0)
150       AssociatePortWithProcess(port, pid);
151   } else {
152     if (port > 0)
153       FreePort(port);
154   }
155   return error;
156 }
157 
158 GDBRemoteCommunication::PacketResult
159 GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer(
160     StringExtractorGDBRemote &packet) {
161   // Spawn a local debugserver as a platform so we can then attach or launch a
162   // process...
163 
164   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
165   LLDB_LOGF(log, "GDBRemoteCommunicationServerPlatform::%s() called",
166             __FUNCTION__);
167 
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"))
176       hostname = value;
177     else if (name.equals("port"))
178       value.getAsInteger(0, port);
179   }
180 
181   lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
182   std::string socket_name;
183   Status error =
184       LaunchGDBServer(Args(), hostname, debugserver_pid, port, socket_name);
185   if (error.Fail()) {
186     LLDB_LOGF(log,
187               "GDBRemoteCommunicationServerPlatform::%s() debugserver "
188               "launch failed: %s",
189               __FUNCTION__, error.AsCString());
190     return SendErrorResponse(9);
191   }
192 
193   LLDB_LOGF(log,
194             "GDBRemoteCommunicationServerPlatform::%s() debugserver "
195             "launched successfully as pid %" PRIu64,
196             __FUNCTION__, debugserver_pid);
197 
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(';');
205   }
206 
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);
211   }
212   return packet_result;
213 }
214 
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);
220 
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(
226         "socket_name",
227         std::make_shared<JSONString>(m_pending_gdb_server.socket_name.c_str()));
228 
229   JSONArray server_list;
230   server_list.AppendObject(server_sp);
231 
232   StreamGDBRemote response;
233   server_list.Write(response);
234 
235   StreamGDBRemote escaped_response;
236   escaped_response.PutEscapedBytes(response.GetString().data(),
237                                    response.GetSize());
238   return SendPacketNoLock(escaped_response.GetString());
239 }
240 
241 GDBRemoteCommunication::PacketResult
242 GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess(
243     StringExtractorGDBRemote &packet) {
244   packet.SetFilePos(::strlen("qKillSpawnedProcess:"));
245 
246   lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
247 
248   // verify that we know anything about this pid. Scope for locker
249   {
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);
254     }
255   }
256 
257   // go ahead and attempt to kill the spawned process
258   if (KillSpawnedProcess(pid))
259     return SendOKResponse();
260   else
261     return SendErrorResponse(11);
262 }
263 
264 bool GDBRemoteCommunicationServerPlatform::KillSpawnedProcess(lldb::pid_t pid) {
265   // make sure we know about this process
266   {
267     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
268     if (m_spawned_pids.find(pid) == m_spawned_pids.end())
269       return false;
270   }
271 
272   // first try a SIGTERM (standard kill)
273   Host::Kill(pid, SIGTERM);
274 
275   // check if that worked
276   for (size_t i = 0; i < 10; ++i) {
277     {
278       std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
279       if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
280         // it is now killed
281         return true;
282       }
283     }
284     std::this_thread::sleep_for(std::chrono::milliseconds(10));
285   }
286 
287   {
288     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
289     if (m_spawned_pids.find(pid) == m_spawned_pids.end())
290       return true;
291   }
292 
293   // the launched process still lives.  Now try killing it again, this time
294   // with an unblockable signal.
295   Host::Kill(pid, SIGKILL);
296 
297   for (size_t i = 0; i < 10; ++i) {
298     {
299       std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
300       if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
301         // it is now killed
302         return true;
303       }
304     }
305     std::this_thread::sleep_for(std::chrono::milliseconds(10));
306   }
307 
308   // check one more time after the final sleep
309   {
310     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
311     if (m_spawned_pids.find(pid) == m_spawned_pids.end())
312       return true;
313   }
314 
315   // no luck - the process still lives
316   return false;
317 }
318 
319 GDBRemoteCommunication::PacketResult
320 GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo(
321     StringExtractorGDBRemote &packet) {
322   lldb::pid_t pid = m_process_launch_info.GetProcessID();
323   m_process_launch_info.Clear();
324 
325   if (pid == LLDB_INVALID_PROCESS_ID)
326     return SendErrorResponse(1);
327 
328   ProcessInstanceInfo proc_info;
329   if (!Host::GetProcessInfo(pid, proc_info))
330     return SendErrorResponse(1);
331 
332   StreamString response;
333   CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
334   return SendPacketNoLock(response.GetString());
335 }
336 
337 GDBRemoteCommunication::PacketResult
338 GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir(
339     StringExtractorGDBRemote &packet) {
340 
341   llvm::SmallString<64> cwd;
342   if (std::error_code ec = llvm::sys::fs::current_path(cwd))
343     return SendErrorResponse(ec.value());
344 
345   StreamString response;
346   response.PutBytesAsRawHex8(cwd.data(), cwd.size());
347   return SendPacketNoLock(response.GetString());
348 }
349 
350 GDBRemoteCommunication::PacketResult
351 GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir(
352     StringExtractorGDBRemote &packet) {
353   packet.SetFilePos(::strlen("QSetWorkingDir:"));
354   std::string path;
355   packet.GetHexByteString(path);
356 
357   if (std::error_code ec = llvm::sys::fs::set_current_path(path))
358     return SendErrorResponse(ec.value());
359   return SendOKResponse();
360 }
361 
362 GDBRemoteCommunication::PacketResult
363 GDBRemoteCommunicationServerPlatform::Handle_qC(
364     StringExtractorGDBRemote &packet) {
365   // NOTE: lldb should now be using qProcessInfo for process IDs.  This path
366   // here
367   // should not be used.  It is reporting process id instead of thread id.  The
368   // correct answer doesn't seem to make much sense for lldb-platform.
369   // CONSIDER: flip to "unsupported".
370   lldb::pid_t pid = m_process_launch_info.GetProcessID();
371 
372   StreamString response;
373   response.Printf("QC%" PRIx64, pid);
374 
375   // If we launch a process and this GDB server is acting as a platform, then
376   // we need to clear the process launch state so we can start launching
377   // another process. In order to launch a process a bunch or packets need to
378   // be sent: environment packets, working directory, disable ASLR, and many
379   // more settings. When we launch a process we then need to know when to clear
380   // this information. Currently we are selecting the 'qC' packet as that
381   // packet which seems to make the most sense.
382   if (pid != LLDB_INVALID_PROCESS_ID) {
383     m_process_launch_info.Clear();
384   }
385 
386   return SendPacketNoLock(response.GetString());
387 }
388 
389 GDBRemoteCommunication::PacketResult
390 GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo(
391     StringExtractorGDBRemote &packet) {
392   StructuredData::Array signal_array;
393 
394   lldb::UnixSignalsSP signals = UnixSignals::CreateForHost();
395   for (auto signo = signals->GetFirstSignalNumber();
396        signo != LLDB_INVALID_SIGNAL_NUMBER;
397        signo = signals->GetNextSignalNumber(signo)) {
398     auto dictionary = std::make_shared<StructuredData::Dictionary>();
399 
400     dictionary->AddIntegerItem("signo", signo);
401     dictionary->AddStringItem("name", signals->GetSignalAsCString(signo));
402 
403     bool suppress, stop, notify;
404     signals->GetSignalInfo(signo, suppress, stop, notify);
405     dictionary->AddBooleanItem("suppress", suppress);
406     dictionary->AddBooleanItem("stop", stop);
407     dictionary->AddBooleanItem("notify", notify);
408 
409     signal_array.Push(dictionary);
410   }
411 
412   StreamString response;
413   signal_array.Dump(response);
414   return SendPacketNoLock(response.GetString());
415 }
416 
417 bool GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped(
418     lldb::pid_t pid) {
419   std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
420   FreePortForProcess(pid);
421   m_spawned_pids.erase(pid);
422   return true;
423 }
424 
425 Status GDBRemoteCommunicationServerPlatform::LaunchProcess() {
426   if (!m_process_launch_info.GetArguments().GetArgumentCount())
427     return Status("%s: no process command line specified to launch",
428                   __FUNCTION__);
429 
430   // specify the process monitor if not already set.  This should generally be
431   // what happens since we need to reap started processes.
432   if (!m_process_launch_info.GetMonitorProcessCallback())
433     m_process_launch_info.SetMonitorProcessCallback(
434         std::bind(
435             &GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
436             this, std::placeholders::_1),
437         false);
438 
439   Status error = Host::LaunchProcess(m_process_launch_info);
440   if (!error.Success()) {
441     fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
442             m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
443     return error;
444   }
445 
446   printf("Launched '%s' as process %" PRIu64 "...\n",
447          m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
448          m_process_launch_info.GetProcessID());
449 
450   // add to list of spawned processes.  On an lldb-gdbserver, we would expect
451   // there to be only one.
452   const auto pid = m_process_launch_info.GetProcessID();
453   if (pid != LLDB_INVALID_PROCESS_ID) {
454     // add to spawned pids
455     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
456     m_spawned_pids.insert(pid);
457   }
458 
459   return error;
460 }
461 
462 void GDBRemoteCommunicationServerPlatform::SetPortMap(PortMap &&port_map) {
463   m_port_map = port_map;
464 }
465 
466 uint16_t GDBRemoteCommunicationServerPlatform::GetNextAvailablePort() {
467   if (m_port_map.empty())
468     return 0; // Bind to port zero and get a port, we didn't have any
469               // limitations
470 
471   for (auto &pair : m_port_map) {
472     if (pair.second == LLDB_INVALID_PROCESS_ID) {
473       pair.second = ~(lldb::pid_t)LLDB_INVALID_PROCESS_ID;
474       return pair.first;
475     }
476   }
477   return UINT16_MAX;
478 }
479 
480 bool GDBRemoteCommunicationServerPlatform::AssociatePortWithProcess(
481     uint16_t port, lldb::pid_t pid) {
482   PortMap::iterator pos = m_port_map.find(port);
483   if (pos != m_port_map.end()) {
484     pos->second = pid;
485     return true;
486   }
487   return false;
488 }
489 
490 bool GDBRemoteCommunicationServerPlatform::FreePort(uint16_t port) {
491   PortMap::iterator pos = m_port_map.find(port);
492   if (pos != m_port_map.end()) {
493     pos->second = LLDB_INVALID_PROCESS_ID;
494     return true;
495   }
496   return false;
497 }
498 
499 bool GDBRemoteCommunicationServerPlatform::FreePortForProcess(lldb::pid_t pid) {
500   if (!m_port_map.empty()) {
501     for (auto &pair : m_port_map) {
502       if (pair.second == pid) {
503         pair.second = LLDB_INVALID_PROCESS_ID;
504         return true;
505       }
506     }
507   }
508   return false;
509 }
510 
511 const FileSpec &GDBRemoteCommunicationServerPlatform::GetDomainSocketDir() {
512   static FileSpec g_domainsocket_dir;
513   static llvm::once_flag g_once_flag;
514 
515   llvm::call_once(g_once_flag, []() {
516     const char *domainsocket_dir_env =
517         ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR");
518     if (domainsocket_dir_env != nullptr)
519       g_domainsocket_dir = FileSpec(domainsocket_dir_env);
520     else
521       g_domainsocket_dir = HostInfo::GetProcessTempDir();
522   });
523 
524   return g_domainsocket_dir;
525 }
526 
527 FileSpec
528 GDBRemoteCommunicationServerPlatform::GetDomainSocketPath(const char *prefix) {
529   llvm::SmallString<128> socket_path;
530   llvm::SmallString<128> socket_name(
531       (llvm::StringRef(prefix) + ".%%%%%%").str());
532 
533   FileSpec socket_path_spec(GetDomainSocketDir());
534   socket_path_spec.AppendPathComponent(socket_name.c_str());
535 
536   llvm::sys::fs::createUniqueFile(socket_path_spec.GetCString(), socket_path);
537   return FileSpec(socket_path.c_str());
538 }
539 
540 void GDBRemoteCommunicationServerPlatform::SetPortOffset(uint16_t port_offset) {
541   m_port_offset = port_offset;
542 }
543 
544 void GDBRemoteCommunicationServerPlatform::SetPendingGdbServer(
545     lldb::pid_t pid, uint16_t port, const std::string &socket_name) {
546   m_pending_gdb_server.pid = pid;
547   m_pending_gdb_server.port = port;
548   m_pending_gdb_server.socket_name = socket_name;
549 }
550