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   std::string platform_scheme;
128   std::string platform_ip;
129   int platform_port;
130   std::string platform_path;
131   bool ok = UriParser::Parse(GetConnection()->GetURI().c_str(), 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 << ":" << 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.GetData(), response.GetSize());
250   return SendPacketNoLock(escaped_response.GetString());
251 }
252 
253 GDBRemoteCommunication::PacketResult
254 GDBRemoteCommunicationServerPlatform::Handle_qKillSpawnedProcess(
255     StringExtractorGDBRemote &packet) {
256   packet.SetFilePos(::strlen("qKillSpawnedProcess:"));
257 
258   lldb::pid_t pid = packet.GetU64(LLDB_INVALID_PROCESS_ID);
259 
260   // verify that we know anything about this pid.
261   // Scope for locker
262   {
263     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
264     if (m_spawned_pids.find(pid) == m_spawned_pids.end()) {
265       // not a pid we know about
266       return SendErrorResponse(10);
267     }
268   }
269 
270   // go ahead and attempt to kill the spawned process
271   if (KillSpawnedProcess(pid))
272     return SendOKResponse();
273   else
274     return SendErrorResponse(11);
275 }
276 
277 bool GDBRemoteCommunicationServerPlatform::KillSpawnedProcess(lldb::pid_t pid) {
278   // make sure we know about this process
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       return false;
283   }
284 
285   // first try a SIGTERM (standard kill)
286   Host::Kill(pid, SIGTERM);
287 
288   // check if that worked
289   for (size_t i = 0; i < 10; ++i) {
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         // it is now killed
294         return true;
295       }
296     }
297     usleep(10000);
298   }
299 
300   // check one more time after the final usleep
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       return true;
305   }
306 
307   // the launched process still lives.  Now try killing it again,
308   // this time with an unblockable signal.
309   Host::Kill(pid, SIGKILL);
310 
311   for (size_t i = 0; i < 10; ++i) {
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         // it is now killed
316         return true;
317       }
318     }
319     usleep(10000);
320   }
321 
322   // check one more time after the final usleep
323   // Scope for locker
324   {
325     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
326     if (m_spawned_pids.find(pid) == m_spawned_pids.end())
327       return true;
328   }
329 
330   // no luck - the process still lives
331   return false;
332 }
333 
334 GDBRemoteCommunication::PacketResult
335 GDBRemoteCommunicationServerPlatform::Handle_qProcessInfo(
336     StringExtractorGDBRemote &packet) {
337   lldb::pid_t pid = m_process_launch_info.GetProcessID();
338   m_process_launch_info.Clear();
339 
340   if (pid == LLDB_INVALID_PROCESS_ID)
341     return SendErrorResponse(1);
342 
343   ProcessInstanceInfo proc_info;
344   if (!Host::GetProcessInfo(pid, proc_info))
345     return SendErrorResponse(1);
346 
347   StreamString response;
348   CreateProcessInfoResponse_DebugServerStyle(proc_info, response);
349   return SendPacketNoLock(response.GetString());
350 }
351 
352 GDBRemoteCommunication::PacketResult
353 GDBRemoteCommunicationServerPlatform::Handle_qGetWorkingDir(
354     StringExtractorGDBRemote &packet) {
355   // If this packet is sent to a platform, then change the current working
356   // directory
357 
358   char cwd[PATH_MAX];
359   if (getcwd(cwd, sizeof(cwd)) == NULL)
360     return SendErrorResponse(errno);
361 
362   StreamString response;
363   response.PutBytesAsRawHex8(cwd, strlen(cwd));
364   return SendPacketNoLock(response.GetString());
365 }
366 
367 GDBRemoteCommunication::PacketResult
368 GDBRemoteCommunicationServerPlatform::Handle_QSetWorkingDir(
369     StringExtractorGDBRemote &packet) {
370   packet.SetFilePos(::strlen("QSetWorkingDir:"));
371   std::string path;
372   packet.GetHexByteString(path);
373 
374   // If this packet is sent to a platform, then change the current working
375   // directory
376   if (::chdir(path.c_str()) != 0)
377     return SendErrorResponse(errno);
378   return SendOKResponse();
379 }
380 
381 GDBRemoteCommunication::PacketResult
382 GDBRemoteCommunicationServerPlatform::Handle_qC(
383     StringExtractorGDBRemote &packet) {
384   // NOTE: lldb should now be using qProcessInfo for process IDs.  This path
385   // here
386   // should not be used.  It is reporting process id instead of thread id.  The
387   // correct answer doesn't seem to make much sense for lldb-platform.
388   // CONSIDER: flip to "unsupported".
389   lldb::pid_t pid = m_process_launch_info.GetProcessID();
390 
391   StreamString response;
392   response.Printf("QC%" PRIx64, pid);
393 
394   // If we launch a process and this GDB server is acting as a platform,
395   // then we need to clear the process launch state so we can start
396   // launching another process. In order to launch a process a bunch or
397   // packets need to be sent: environment packets, working directory,
398   // disable ASLR, and many more settings. When we launch a process we
399   // then need to know when to clear this information. Currently we are
400   // selecting the 'qC' packet as that packet which seems to make the most
401   // sense.
402   if (pid != LLDB_INVALID_PROCESS_ID) {
403     m_process_launch_info.Clear();
404   }
405 
406   return SendPacketNoLock(response.GetString());
407 }
408 
409 GDBRemoteCommunication::PacketResult
410 GDBRemoteCommunicationServerPlatform::Handle_jSignalsInfo(
411     StringExtractorGDBRemote &packet) {
412   StructuredData::Array signal_array;
413 
414   const auto &signals = Host::GetUnixSignals();
415   for (auto signo = signals->GetFirstSignalNumber();
416        signo != LLDB_INVALID_SIGNAL_NUMBER;
417        signo = signals->GetNextSignalNumber(signo)) {
418     auto dictionary = std::make_shared<StructuredData::Dictionary>();
419 
420     dictionary->AddIntegerItem("signo", signo);
421     dictionary->AddStringItem("name", signals->GetSignalAsCString(signo));
422 
423     bool suppress, stop, notify;
424     signals->GetSignalInfo(signo, suppress, stop, notify);
425     dictionary->AddBooleanItem("suppress", suppress);
426     dictionary->AddBooleanItem("stop", stop);
427     dictionary->AddBooleanItem("notify", notify);
428 
429     signal_array.Push(dictionary);
430   }
431 
432   StreamString response;
433   signal_array.Dump(response);
434   return SendPacketNoLock(response.GetString());
435 }
436 
437 bool GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped(
438     lldb::pid_t pid) {
439   std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
440   FreePortForProcess(pid);
441   m_spawned_pids.erase(pid);
442   return true;
443 }
444 
445 Error GDBRemoteCommunicationServerPlatform::LaunchProcess() {
446   if (!m_process_launch_info.GetArguments().GetArgumentCount())
447     return Error("%s: no process command line specified to launch",
448                  __FUNCTION__);
449 
450   // specify the process monitor if not already set.  This should
451   // generally be what happens since we need to reap started
452   // processes.
453   if (!m_process_launch_info.GetMonitorProcessCallback())
454     m_process_launch_info.SetMonitorProcessCallback(
455         std::bind(
456             &GDBRemoteCommunicationServerPlatform::DebugserverProcessReaped,
457             this, std::placeholders::_1),
458         false);
459 
460   Error error = Host::LaunchProcess(m_process_launch_info);
461   if (!error.Success()) {
462     fprintf(stderr, "%s: failed to launch executable %s", __FUNCTION__,
463             m_process_launch_info.GetArguments().GetArgumentAtIndex(0));
464     return error;
465   }
466 
467   printf("Launched '%s' as process %" PRIu64 "...\n",
468          m_process_launch_info.GetArguments().GetArgumentAtIndex(0),
469          m_process_launch_info.GetProcessID());
470 
471   // add to list of spawned processes.  On an lldb-gdbserver, we
472   // would expect there to be only one.
473   const auto pid = m_process_launch_info.GetProcessID();
474   if (pid != LLDB_INVALID_PROCESS_ID) {
475     // add to spawned pids
476     std::lock_guard<std::recursive_mutex> guard(m_spawned_pids_mutex);
477     m_spawned_pids.insert(pid);
478   }
479 
480   return error;
481 }
482 
483 void GDBRemoteCommunicationServerPlatform::SetPortMap(PortMap &&port_map) {
484   m_port_map = port_map;
485 }
486 
487 uint16_t GDBRemoteCommunicationServerPlatform::GetNextAvailablePort() {
488   if (m_port_map.empty())
489     return 0; // Bind to port zero and get a port, we didn't have any
490               // limitations
491 
492   for (auto &pair : m_port_map) {
493     if (pair.second == LLDB_INVALID_PROCESS_ID) {
494       pair.second = ~(lldb::pid_t)LLDB_INVALID_PROCESS_ID;
495       return pair.first;
496     }
497   }
498   return UINT16_MAX;
499 }
500 
501 bool GDBRemoteCommunicationServerPlatform::AssociatePortWithProcess(
502     uint16_t port, lldb::pid_t pid) {
503   PortMap::iterator pos = m_port_map.find(port);
504   if (pos != m_port_map.end()) {
505     pos->second = pid;
506     return true;
507   }
508   return false;
509 }
510 
511 bool GDBRemoteCommunicationServerPlatform::FreePort(uint16_t port) {
512   PortMap::iterator pos = m_port_map.find(port);
513   if (pos != m_port_map.end()) {
514     pos->second = LLDB_INVALID_PROCESS_ID;
515     return true;
516   }
517   return false;
518 }
519 
520 bool GDBRemoteCommunicationServerPlatform::FreePortForProcess(lldb::pid_t pid) {
521   if (!m_port_map.empty()) {
522     for (auto &pair : m_port_map) {
523       if (pair.second == pid) {
524         pair.second = LLDB_INVALID_PROCESS_ID;
525         return true;
526       }
527     }
528   }
529   return false;
530 }
531 
532 const FileSpec &GDBRemoteCommunicationServerPlatform::GetDomainSocketDir() {
533   static FileSpec g_domainsocket_dir;
534   static std::once_flag g_once_flag;
535 
536   std::call_once(g_once_flag, []() {
537     const char *domainsocket_dir_env =
538         ::getenv("LLDB_DEBUGSERVER_DOMAINSOCKET_DIR");
539     if (domainsocket_dir_env != nullptr)
540       g_domainsocket_dir = FileSpec(domainsocket_dir_env, false);
541     else
542       HostInfo::GetLLDBPath(ePathTypeLLDBTempSystemDir, g_domainsocket_dir);
543   });
544 
545   return g_domainsocket_dir;
546 }
547 
548 FileSpec
549 GDBRemoteCommunicationServerPlatform::GetDomainSocketPath(const char *prefix) {
550   llvm::SmallString<PATH_MAX> socket_path;
551   llvm::SmallString<PATH_MAX> socket_name(
552       (llvm::StringRef(prefix) + ".%%%%%%").str());
553 
554   FileSpec socket_path_spec(GetDomainSocketDir());
555   socket_path_spec.AppendPathComponent(socket_name.c_str());
556 
557   llvm::sys::fs::createUniqueFile(socket_path_spec.GetCString(), socket_path);
558   return FileSpec(socket_path.c_str(), false);
559 }
560 
561 void GDBRemoteCommunicationServerPlatform::SetPortOffset(uint16_t port_offset) {
562   m_port_offset = port_offset;
563 }
564 
565 void GDBRemoteCommunicationServerPlatform::SetPendingGdbServer(
566     lldb::pid_t pid, uint16_t port, const std::string &socket_name) {
567   m_pending_gdb_server.pid = pid;
568   m_pending_gdb_server.port = port;
569   m_pending_gdb_server.socket_name = socket_name;
570 }
571