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 
19 #include "llvm/Support/FileSystem.h"
20 #include "llvm/Support/Threading.h"
21 
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/Process.h"
29 #include "lldb/Target/UnixSignals.h"
30 #include "lldb/Utility/JSON.h"
31 #include "lldb/Utility/Log.h"
32 #include "lldb/Utility/StreamGDBRemote.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   if (log)
109     log->Printf("Launching debugserver with: %s:%u...", hostname.c_str(), 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   llvm::StringRef platform_scheme;
120   llvm::StringRef platform_ip;
121   int platform_port;
122   llvm::StringRef platform_path;
123   std::string platform_uri = GetConnection()->GetURI();
124   bool ok = UriParser::Parse(platform_uri, platform_scheme, platform_ip,
125                              platform_port, platform_path);
126   UNUSED_IF_ASSERT_DISABLED(ok);
127   assert(ok);
128 
129   std::ostringstream url;
130 // debugserver does not accept the URL scheme prefix.
131 #if !defined(__APPLE__)
132   url << m_socket_scheme << "://";
133 #endif
134   uint16_t *port_ptr = &port;
135   if (m_socket_protocol == Socket::ProtocolTcp)
136     url << platform_ip.str() << ":" << port;
137   else {
138     socket_name = GetDomainSocketPath("gdbserver").GetPath();
139     url << socket_name;
140     port_ptr = nullptr;
141   }
142 
143   Status error = StartDebugserverProcess(
144       url.str().c_str(), nullptr, debugserver_launch_info, port_ptr, &args, -1);
145 
146   pid = debugserver_launch_info.GetProcessID();
147   if (pid != LLDB_INVALID_PROCESS_ID) {
148     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
149     m_spawned_pids.insert(pid);
150     if (port > 0)
151       AssociatePortWithProcess(port, pid);
152   } else {
153     if (port > 0)
154       FreePort(port);
155   }
156   return error;
157 }
158 
159 GDBRemoteCommunication::PacketResult
160 GDBRemoteCommunicationServerPlatform::Handle_qLaunchGDBServer(
161     StringExtractorGDBRemote &packet) {
162   // Spawn a local debugserver as a platform so we can then attach or launch a
163   // process...
164 
165   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
166   if (log)
167     log->Printf("GDBRemoteCommunicationServerPlatform::%s() called",
168                 __FUNCTION__);
169 
170   ConnectionFileDescriptor file_conn;
171   std::string hostname;
172   packet.SetFilePos(::strlen("qLaunchGDBServer;"));
173   llvm::StringRef name;
174   llvm::StringRef value;
175   uint16_t port = UINT16_MAX;
176   while (packet.GetNameColonValue(name, value)) {
177     if (name.equals("host"))
178       hostname = value;
179     else if (name.equals("port"))
180       value.getAsInteger(0, port);
181   }
182 
183   lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
184   std::string socket_name;
185   Status error =
186       LaunchGDBServer(Args(), hostname, debugserver_pid, port, socket_name);
187   if (error.Fail()) {
188     if (log)
189       log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver "
190                   "launch failed: %s",
191                   __FUNCTION__, error.AsCString());
192     return SendErrorResponse(9);
193   }
194 
195   if (log)
196     log->Printf("GDBRemoteCommunicationServerPlatform::%s() debugserver "
197                 "launched successfully as pid %" PRIu64,
198                 __FUNCTION__, debugserver_pid);
199 
200   StreamGDBRemote response;
201   response.Printf("pid:%" PRIu64 ";port:%u;", debugserver_pid,
202                   port + m_port_offset);
203   if (!socket_name.empty()) {
204     response.PutCString("socket_name:");
205     response.PutStringAsRawHex8(socket_name);
206     response.PutChar(';');
207   }
208 
209   PacketResult packet_result = SendPacketNoLock(response.GetString());
210   if (packet_result != PacketResult::Success) {
211     if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
212       Host::Kill(debugserver_pid, SIGINT);
213   }
214   return packet_result;
215 }
216 
217 GDBRemoteCommunication::PacketResult
218 GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer(
219     StringExtractorGDBRemote &packet) {
220   if (m_pending_gdb_server.pid == LLDB_INVALID_PROCESS_ID)
221     return SendErrorResponse(4);
222 
223   JSONObject::SP server_sp = std::make_shared<JSONObject>();
224   server_sp->SetObject("port",
225                        std::make_shared<JSONNumber>(m_pending_gdb_server.port));
226   if (!m_pending_gdb_server.socket_name.empty())
227     server_sp->SetObject(
228         "socket_name",
229         std::make_shared<JSONString>(m_pending_gdb_server.socket_name.c_str()));
230 
231   JSONArray server_list;
232   server_list.AppendObject(server_sp);
233 
234   StreamGDBRemote response;
235   server_list.Write(response);
236 
237   StreamGDBRemote escaped_response;
238   escaped_response.PutEscapedBytes(response.GetString().data(),
239                                    response.GetSize());
240   return SendPacketNoLock(escaped_response.GetString());
241 }
242 
243 GDBRemoteCommunication::PacketResult
244 GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess(
245     StringExtractorGDBRemote &packet) {
246   packet.SetFilePos(::strlen("qKillSpawnedProcess:"));
247 
248   lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
249 
250   // verify that we know anything about this pid. Scope for locker
251   {
252     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
253     if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
254       // not a pid we know about
255       return SendErrorResponse(10);
256     }
257   }
258 
259   // go ahead and attempt to kill the spawned process
260   if (KillSpawnedProcess(pid))
261     return SendOKResponse();
262   else
263     return SendErrorResponse(11);
264 }
265 
266 bool GDBRemoteCommunicationServerPlatform::KillSpawnedProcess(lldb::pid_t pid) {
267   // make sure we know about this process
268   {
269     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
270     if (m_spawned_pids.find(pid) == m_spawned_pids.end())
271       return false;
272   }
273 
274   // first try a SIGTERM (standard kill)
275   Host::Kill(pid, SIGTERM);
276 
277   // check if that worked
278   for (size_t i = 0; i < 10; ++i) {
279     {
280       std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
281       if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
282         // it is now killed
283         return true;
284       }
285     }
286     usleep(10000);
287   }
288 
289   // check one more time after the final usleep
290   {
291     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
292     if (m_spawned_pids.find(pid) == m_spawned_pids.end())
293       return true;
294   }
295 
296   // the launched process still lives.  Now try killing it again, this time
297   // with an unblockable signal.
298   Host::Kill(pid, SIGKILL);
299 
300   for (size_t i = 0; i < 10; ++i) {
301     {
302       std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
303       if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
304         // it is now killed
305         return true;
306       }
307     }
308     usleep(10000);
309   }
310 
311   // check one more time after the final usleep Scope for locker
312   {
313     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
314     if (m_spawned_pids.find(pid) == m_spawned_pids.end())
315       return true;
316   }
317 
318   // no luck - the process still lives
319   return false;
320 }
321 
322 GDBRemoteCommunication::PacketResult
323 GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo(
324     StringExtractorGDBRemote &packet) {
325   lldb::pid_t pid = m_process_launch_info.GetProcessID();
326   m_process_launch_info.Clear();
327 
328   if (pid == LLDB_INVALID_PROCESS_ID)
329     return SendErrorResponse(1);
330 
331   ProcessInstanceInfo proc_info;
332   if (!Host::GetProcessInfo(pid, proc_info))
333     return SendErrorResponse(1);
334 
335   StreamString response;
336   CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
337   return SendPacketNoLock(response.GetString());
338 }
339 
340 GDBRemoteCommunication::PacketResult
341 GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir(
342     StringExtractorGDBRemote &packet) {
343 
344   llvm::SmallString<64> cwd;
345   if (std::error_code ec = llvm::sys::fs::current_path(cwd))
346     return SendErrorResponse(ec.value());
347 
348   StreamString response;
349   response.PutBytesAsRawHex8(cwd.data(), cwd.size());
350   return SendPacketNoLock(response.GetString());
351 }
352 
353 GDBRemoteCommunication::PacketResult
354 GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir(
355     StringExtractorGDBRemote &packet) {
356   packet.SetFilePos(::strlen("QSetWorkingDir:"));
357   std::string path;
358   packet.GetHexByteString(path);
359 
360   if (std::error_code ec = llvm::sys::fs::set_current_path(path))
361     return SendErrorResponse(ec.value());
362   return SendOKResponse();
363 }
364 
365 GDBRemoteCommunication::PacketResult
366 GDBRemoteCommunicationServerPlatform::Handle_qC(
367     StringExtractorGDBRemote &packet) {
368   // NOTE: lldb should now be using qProcessInfo for process IDs.  This path
369   // here
370   // should not be used.  It is reporting process id instead of thread id.  The
371   // correct answer doesn't seem to make much sense for lldb-platform.
372   // CONSIDER: flip to "unsupported".
373   lldb::pid_t pid = m_process_launch_info.GetProcessID();
374 
375   StreamString response;
376   response.Printf("QC%" PRIx64, pid);
377 
378   // If we launch a process and this GDB server is acting as a platform, then
379   // we need to clear the process launch state so we can start launching
380   // another process. In order to launch a process a bunch or packets need to
381   // be sent: environment packets, working directory, disable ASLR, and many
382   // more settings. When we launch a process we then need to know when to clear
383   // this information. Currently we are selecting the 'qC' packet as that
384   // packet which seems to make the most sense.
385   if (pid != LLDB_INVALID_PROCESS_ID) {
386     m_process_launch_info.Clear();
387   }
388 
389   return SendPacketNoLock(response.GetString());
390 }
391 
392 GDBRemoteCommunication::PacketResult
393 GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo(
394     StringExtractorGDBRemote &packet) {
395   StructuredData::Array signal_array;
396 
397   lldb::UnixSignalsSP signals = UnixSignals::CreateForHost();
398   for (auto signo = signals->GetFirstSignalNumber();
399        signo != LLDB_INVALID_SIGNAL_NUMBER;
400        signo = signals->GetNextSignalNumber(signo)) {
401     auto dictionary = std::make_shared<StructuredData::Dictionary>();
402 
403     dictionary->AddIntegerItem("signo", signo);
404     dictionary->AddStringItem("name", signals->GetSignalAsCString(signo));
405 
406     bool suppress, stop, notify;
407     signals->GetSignalInfo(signo, suppress, stop, notify);
408     dictionary->AddBooleanItem("suppress", suppress);
409     dictionary->AddBooleanItem("stop", stop);
410     dictionary->AddBooleanItem("notify", notify);
411 
412     signal_array.Push(dictionary);
413   }
414 
415   StreamString response;
416   signal_array.Dump(response);
417   return SendPacketNoLock(response.GetString());
418 }
419 
420 bool GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped(
421     lldb::pid_t pid) {
422   std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
423   FreePortForProcess(pid);
424   m_spawned_pids.erase(pid);
425   return true;
426 }
427 
428 Status GDBRemoteCommunicationServerPlatform::LaunchProcess() {
429   if (!m_process_launch_info.GetArguments().GetArgumentCount())
430     return Status("%s: no process command line specified to launch",
431                   __FUNCTION__);
432 
433   // specify the process monitor if not already set.  This should generally be
434   // what happens since we need to reap started processes.
435   if (!m_process_launch_info.GetMonitorProcessCallback())
436     m_process_launch_info.SetMonitorProcessCallback(
437         std::bind(
438             &GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
439             this, std::placeholders::_1),
440         false);
441 
442   Status error = Host::LaunchProcess(m_process_launch_info);
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();
456   if (pid != LLDB_INVALID_PROCESS_ID) {
457     // add to spawned pids
458     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
459     m_spawned_pids.insert(pid);
460   }
461 
462   return error;
463 }
464 
465 void GDBRemoteCommunicationServerPlatform::SetPortMap(PortMap &&port_map) {
466   m_port_map = port_map;
467 }
468 
469 uint16_t GDBRemoteCommunicationServerPlatform::GetNextAvailablePort() {
470   if (m_port_map.empty())
471     return 0; // Bind to port zero and get a port, we didn't have any
472               // limitations
473 
474   for (auto &pair : m_port_map) {
475     if (pair.second == LLDB_INVALID_PROCESS_ID) {
476       pair.second = ~(lldb::pid_t)LLDB_INVALID_PROCESS_ID;
477       return pair.first;
478     }
479   }
480   return UINT16_MAX;
481 }
482 
483 bool GDBRemoteCommunicationServerPlatform::AssociatePortWithProcess(
484     uint16_t port, lldb::pid_t pid) {
485   PortMap::iterator pos = m_port_map.find(port);
486   if (pos != m_port_map.end()) {
487     pos->second = pid;
488     return true;
489   }
490   return false;
491 }
492 
493 bool GDBRemoteCommunicationServerPlatform::FreePort(uint16_t port) {
494   PortMap::iterator pos = m_port_map.find(port);
495   if (pos != m_port_map.end()) {
496     pos->second = LLDB_INVALID_PROCESS_ID;
497     return true;
498   }
499   return false;
500 }
501 
502 bool GDBRemoteCommunicationServerPlatform::FreePortForProcess(lldb::pid_t pid) {
503   if (!m_port_map.empty()) {
504     for (auto &pair : m_port_map) {
505       if (pair.second == pid) {
506         pair.second = LLDB_INVALID_PROCESS_ID;
507         return true;
508       }
509     }
510   }
511   return false;
512 }
513 
514 const FileSpec &GDBRemoteCommunicationServerPlatform::GetDomainSocketDir() {
515   static FileSpec g_domainsocket_dir;
516   static llvm::once_flag g_once_flag;
517 
518   llvm::call_once(g_once_flag, []() {
519     const char *domainsocket_dir_env =
520         ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR");
521     if (domainsocket_dir_env != nullptr)
522       g_domainsocket_dir = FileSpec(domainsocket_dir_env);
523     else
524       g_domainsocket_dir = HostInfo::GetProcessTempDir();
525   });
526 
527   return g_domainsocket_dir;
528 }
529 
530 FileSpec
531 GDBRemoteCommunicationServerPlatform::GetDomainSocketPath(const char *prefix) {
532   llvm::SmallString<128> socket_path;
533   llvm::SmallString<128> socket_name(
534       (llvm::StringRef(prefix) + ".%%%%%%").str());
535 
536   FileSpec socket_path_spec(GetDomainSocketDir());
537   socket_path_spec.AppendPathComponent(socket_name.c_str());
538 
539   llvm::sys::fs::createUniqueFile(socket_path_spec.GetCString(), socket_path);
540   return FileSpec(socket_path.c_str());
541 }
542 
543 void GDBRemoteCommunicationServerPlatform::SetPortOffset(uint16_t port_offset) {
544   m_port_offset = port_offset;
545 }
546 
547 void GDBRemoteCommunicationServerPlatform::SetPendingGdbServer(
548     lldb::pid_t pid, uint16_t port, const std::string &socket_name) {
549   m_pending_gdb_server.pid = pid;
550   m_pending_gdb_server.port = port;
551   m_pending_gdb_server.socket_name = socket_name;
552 }
553