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