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/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"
35 
36 #include "lldb/Utility/StringExtractorGDBRemote.h"
37 
38 using namespace lldb;
39 using namespace lldb_private;
40 using namespace lldb_private::process_gdb_remote;
41 
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;
51 
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);
76 
77   RegisterPacketHandler(StringExtractorGDBRemote::eServerPacketType_interrupt,
78                         [](StringExtractorGDBRemote packet, Status &error,
79                            bool &interrupt, bool &quit) {
80                           error.SetErrorString("interrupt received");
81                           interrupt = true;
82                           return PacketResult::Success;
83                         });
84 }
85 
86 // Destructor
87 GDBRemoteCommunicationServerPlatform::~GDBRemoteCommunicationServerPlatform() {}
88 
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();
94 
95   // Spawn a new thread to accept the port that gets bound after binding to
96   // port 0 (zero).
97 
98   // ignore the hostname send from the remote end, just use the ip address that
99   // we're currently communicating with as the hostname
100 
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";
105 
106   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
107   LLDB_LOGF(log, "Launching debugserver with: %s:%u...", hostname.c_str(),
108             port);
109 
110   // Do not run in a new session so that it can not linger after the platform
111   // closes.
112   debugserver_launch_info.SetLaunchInSeparateProcessGroup(false);
113   debugserver_launch_info.SetMonitorProcessCallback(
114       std::bind(&GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
115                 this, std::placeholders::_1),
116       false);
117 
118   std::ostringstream url;
119 // debugserver does not accept the URL scheme prefix.
120 #if !defined(__APPLE__)
121   url << m_socket_scheme << "://";
122 #endif
123   uint16_t *port_ptr = &port;
124   if (m_socket_protocol == Socket::ProtocolTcp) {
125     llvm::StringRef platform_scheme;
126     llvm::StringRef platform_ip;
127     int platform_port;
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);
133     assert(ok);
134     url << platform_ip.str() << ":" << port;
135   } else {
136     socket_name = GetDomainSocketPath("gdbserver").GetPath();
137     url << socket_name;
138     port_ptr = nullptr;
139   }
140 
141   Status error = StartDebugserverProcess(
142       url.str().c_str(), nullptr, debugserver_launch_info, port_ptr, &args, -1);
143 
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);
148     if (port > 0)
149       AssociatePortWithProcess(port, pid);
150   } else {
151     if (port > 0)
152       FreePort(port);
153   }
154   return error;
155 }
156 
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
161   // process...
162 
163   Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM));
164   LLDB_LOGF(log, "GDBRemoteCommunicationServerPlatform::%s() called",
165             __FUNCTION__);
166 
167   ConnectionFileDescriptor file_conn;
168   std::string hostname;
169   packet.SetFilePos(::strlen("qLaunchGDBServer;"));
170   llvm::StringRef name;
171   llvm::StringRef value;
172   uint16_t port = UINT16_MAX;
173   while (packet.GetNameColonValue(name, value)) {
174     if (name.equals("host"))
175       hostname = value;
176     else if (name.equals("port"))
177       value.getAsInteger(0, port);
178   }
179 
180   lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
181   std::string socket_name;
182   Status error =
183       LaunchGDBServer(Args(), hostname, debugserver_pid, port, socket_name);
184   if (error.Fail()) {
185     LLDB_LOGF(log,
186               "GDBRemoteCommunicationServerPlatform::%s() debugserver "
187               "launch failed: %s",
188               __FUNCTION__, error.AsCString());
189     return SendErrorResponse(9);
190   }
191 
192   LLDB_LOGF(log,
193             "GDBRemoteCommunicationServerPlatform::%s() debugserver "
194             "launched successfully as pid %" PRIu64,
195             __FUNCTION__, debugserver_pid);
196 
197   StreamGDBRemote response;
198   response.Printf("pid:%" PRIu64 ";port:%u;", debugserver_pid,
199                   port + m_port_offset);
200   if (!socket_name.empty()) {
201     response.PutCString("socket_name:");
202     response.PutStringAsRawHex8(socket_name);
203     response.PutChar(';');
204   }
205 
206   PacketResult packet_result = SendPacketNoLock(response.GetString());
207   if (packet_result != PacketResult::Success) {
208     if (debugserver_pid != LLDB_INVALID_PROCESS_ID)
209       Host::Kill(debugserver_pid, SIGINT);
210   }
211   return packet_result;
212 }
213 
214 GDBRemoteCommunication::PacketResult
215 GDBRemoteCommunicationServerPlatform::Handle_qQueryGDBServer(
216     StringExtractorGDBRemote &packet) {
217   if (m_pending_gdb_server.pid == LLDB_INVALID_PROCESS_ID)
218     return SendErrorResponse(4);
219 
220   JSONObject::SP server_sp = std::make_shared<JSONObject>();
221   server_sp->SetObject("port",
222                        std::make_shared<JSONNumber>(m_pending_gdb_server.port));
223   if (!m_pending_gdb_server.socket_name.empty())
224     server_sp->SetObject(
225         "socket_name",
226         std::make_shared<JSONString>(m_pending_gdb_server.socket_name.c_str()));
227 
228   JSONArray server_list;
229   server_list.AppendObject(server_sp);
230 
231   StreamGDBRemote response;
232   server_list.Write(response);
233 
234   StreamGDBRemote escaped_response;
235   escaped_response.PutEscapedBytes(response.GetString().data(),
236                                    response.GetSize());
237   return SendPacketNoLock(escaped_response.GetString());
238 }
239 
240 GDBRemoteCommunication::PacketResult
241 GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess(
242     StringExtractorGDBRemote &packet) {
243   packet.SetFilePos(::strlen("qKillSpawnedProcess:"));
244 
245   lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
246 
247   // verify that we know anything about this pid. Scope for locker
248   {
249     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
250     if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
251       // not a pid we know about
252       return SendErrorResponse(10);
253     }
254   }
255 
256   // go ahead and attempt to kill the spawned process
257   if (KillSpawnedProcess(pid))
258     return SendOKResponse();
259   else
260     return SendErrorResponse(11);
261 }
262 
263 bool GDBRemoteCommunicationServerPlatform::KillSpawnedProcess(lldb::pid_t pid) {
264   // make sure we know about this process
265   {
266     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
267     if (m_spawned_pids.find(pid) == m_spawned_pids.end())
268       return false;
269   }
270 
271   // first try a SIGTERM (standard kill)
272   Host::Kill(pid, SIGTERM);
273 
274   // check if that worked
275   for (size_t i = 0; i < 10; ++i) {
276     {
277       std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
278       if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
279         // it is now killed
280         return true;
281       }
282     }
283     usleep(10000);
284   }
285 
286   // check one more time after the final usleep
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     usleep(10000);
306   }
307 
308   // check one more time after the final usleep Scope for locker
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