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