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