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