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