1 //===-- PlatformRemoteGDBServer.cpp ---------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "PlatformRemoteGDBServer.h"
10 #include "lldb/Host/Config.h"
11 
12 #include "lldb/Breakpoint/BreakpointLocation.h"
13 #include "lldb/Core/Debugger.h"
14 #include "lldb/Core/Module.h"
15 #include "lldb/Core/ModuleList.h"
16 #include "lldb/Core/ModuleSpec.h"
17 #include "lldb/Core/PluginManager.h"
18 #include "lldb/Core/StreamFile.h"
19 #include "lldb/Host/ConnectionFileDescriptor.h"
20 #include "lldb/Host/Host.h"
21 #include "lldb/Host/HostInfo.h"
22 #include "lldb/Host/PosixApi.h"
23 #include "lldb/Target/Process.h"
24 #include "lldb/Target/Target.h"
25 #include "lldb/Utility/FileSpec.h"
26 #include "lldb/Utility/Log.h"
27 #include "lldb/Utility/ProcessInfo.h"
28 #include "lldb/Utility/Status.h"
29 #include "lldb/Utility/StreamString.h"
30 #include "lldb/Utility/UriParser.h"
31 
32 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
33 #include "Plugins/Process/gdb-remote/ProcessGDBRemote.h"
34 
35 using namespace lldb;
36 using namespace lldb_private;
37 using namespace lldb_private::platform_gdb_server;
38 
39 LLDB_PLUGIN_DEFINE_ADV(PlatformRemoteGDBServer, PlatformGDB)
40 
41 static bool g_initialized = false;
42 
43 void PlatformRemoteGDBServer::Initialize() {
44   Platform::Initialize();
45 
46   if (!g_initialized) {
47     g_initialized = true;
48     PluginManager::RegisterPlugin(
49         PlatformRemoteGDBServer::GetPluginNameStatic(),
50         PlatformRemoteGDBServer::GetDescriptionStatic(),
51         PlatformRemoteGDBServer::CreateInstance);
52   }
53 }
54 
55 void PlatformRemoteGDBServer::Terminate() {
56   if (g_initialized) {
57     g_initialized = false;
58     PluginManager::UnregisterPlugin(PlatformRemoteGDBServer::CreateInstance);
59   }
60 
61   Platform::Terminate();
62 }
63 
64 PlatformSP PlatformRemoteGDBServer::CreateInstance(bool force,
65                                                    const ArchSpec *arch) {
66   bool create = force;
67   if (!create) {
68     create = !arch->TripleVendorWasSpecified() && !arch->TripleOSWasSpecified();
69   }
70   if (create)
71     return PlatformSP(new PlatformRemoteGDBServer());
72   return PlatformSP();
73 }
74 
75 llvm::StringRef PlatformRemoteGDBServer::GetDescriptionStatic() {
76   return "A platform that uses the GDB remote protocol as the communication "
77          "transport.";
78 }
79 
80 llvm::StringRef PlatformRemoteGDBServer::GetDescription() {
81   if (m_platform_description.empty()) {
82     if (IsConnected()) {
83       // Send the get description packet
84     }
85   }
86 
87   if (!m_platform_description.empty())
88     return m_platform_description.c_str();
89   return GetDescriptionStatic();
90 }
91 
92 bool PlatformRemoteGDBServer::GetModuleSpec(const FileSpec &module_file_spec,
93                                             const ArchSpec &arch,
94                                             ModuleSpec &module_spec) {
95   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
96 
97   const auto module_path = module_file_spec.GetPath(false);
98 
99   if (!m_gdb_client.GetModuleInfo(module_file_spec, arch, module_spec)) {
100     LLDB_LOGF(
101         log,
102         "PlatformRemoteGDBServer::%s - failed to get module info for %s:%s",
103         __FUNCTION__, module_path.c_str(),
104         arch.GetTriple().getTriple().c_str());
105     return false;
106   }
107 
108   if (log) {
109     StreamString stream;
110     module_spec.Dump(stream);
111     LLDB_LOGF(log,
112               "PlatformRemoteGDBServer::%s - got module info for (%s:%s) : %s",
113               __FUNCTION__, module_path.c_str(),
114               arch.GetTriple().getTriple().c_str(), stream.GetData());
115   }
116 
117   return true;
118 }
119 
120 Status PlatformRemoteGDBServer::GetFileWithUUID(const FileSpec &platform_file,
121                                                 const UUID *uuid_ptr,
122                                                 FileSpec &local_file) {
123   // Default to the local case
124   local_file = platform_file;
125   return Status();
126 }
127 
128 /// Default Constructor
129 PlatformRemoteGDBServer::PlatformRemoteGDBServer()
130     : Platform(false), // This is a remote platform
131       m_gdb_client() {
132   m_gdb_client.SetPacketTimeout(
133       process_gdb_remote::ProcessGDBRemote::GetPacketTimeout());
134 }
135 
136 /// Destructor.
137 ///
138 /// The destructor is virtual since this class is designed to be
139 /// inherited from by the plug-in instance.
140 PlatformRemoteGDBServer::~PlatformRemoteGDBServer() = default;
141 
142 size_t PlatformRemoteGDBServer::GetSoftwareBreakpointTrapOpcode(
143     Target &target, BreakpointSite *bp_site) {
144   // This isn't needed if the z/Z packets are supported in the GDB remote
145   // server. But we might need a packet to detect this.
146   return 0;
147 }
148 
149 bool PlatformRemoteGDBServer::GetRemoteOSVersion() {
150   m_os_version = m_gdb_client.GetOSVersion();
151   return !m_os_version.empty();
152 }
153 
154 llvm::Optional<std::string> PlatformRemoteGDBServer::GetRemoteOSBuildString() {
155   return m_gdb_client.GetOSBuildString();
156 }
157 
158 llvm::Optional<std::string>
159 PlatformRemoteGDBServer::GetRemoteOSKernelDescription() {
160   return m_gdb_client.GetOSKernelDescription();
161 }
162 
163 // Remote Platform subclasses need to override this function
164 ArchSpec PlatformRemoteGDBServer::GetRemoteSystemArchitecture() {
165   return m_gdb_client.GetSystemArchitecture();
166 }
167 
168 FileSpec PlatformRemoteGDBServer::GetRemoteWorkingDirectory() {
169   if (IsConnected()) {
170     Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
171     FileSpec working_dir;
172     if (m_gdb_client.GetWorkingDir(working_dir) && log)
173       LLDB_LOGF(log,
174                 "PlatformRemoteGDBServer::GetRemoteWorkingDirectory() -> '%s'",
175                 working_dir.GetCString());
176     return working_dir;
177   } else {
178     return Platform::GetRemoteWorkingDirectory();
179   }
180 }
181 
182 bool PlatformRemoteGDBServer::SetRemoteWorkingDirectory(
183     const FileSpec &working_dir) {
184   if (IsConnected()) {
185     // Clear the working directory it case it doesn't get set correctly. This
186     // will for use to re-read it
187     Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
188     LLDB_LOGF(log, "PlatformRemoteGDBServer::SetRemoteWorkingDirectory('%s')",
189               working_dir.GetCString());
190     return m_gdb_client.SetWorkingDir(working_dir) == 0;
191   } else
192     return Platform::SetRemoteWorkingDirectory(working_dir);
193 }
194 
195 bool PlatformRemoteGDBServer::IsConnected() const {
196   return m_gdb_client.IsConnected();
197 }
198 
199 Status PlatformRemoteGDBServer::ConnectRemote(Args &args) {
200   Status error;
201   if (IsConnected()) {
202     error.SetErrorStringWithFormat("the platform is already connected to '%s', "
203                                    "execute 'platform disconnect' to close the "
204                                    "current connection",
205                                    GetHostname());
206     return error;
207   }
208 
209   if (args.GetArgumentCount() != 1) {
210     error.SetErrorString(
211         "\"platform connect\" takes a single argument: <connect-url>");
212     return error;
213   }
214 
215   const char *url = args.GetArgumentAtIndex(0);
216   if (!url)
217     return Status("URL is null.");
218 
219   llvm::Optional<URI> parsed_url = URI::Parse(url);
220   if (!parsed_url)
221     return Status("Invalid URL: %s", url);
222 
223   // We're going to reuse the hostname when we connect to the debugserver.
224   m_platform_scheme = parsed_url->scheme.str();
225   m_platform_hostname = parsed_url->hostname.str();
226 
227   m_gdb_client.SetConnection(std::make_unique<ConnectionFileDescriptor>());
228   if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
229     repro::GDBRemoteProvider &provider =
230         g->GetOrCreate<repro::GDBRemoteProvider>();
231     m_gdb_client.SetPacketRecorder(provider.GetNewPacketRecorder());
232   }
233   m_gdb_client.Connect(url, &error);
234 
235   if (error.Fail())
236     return error;
237 
238   if (m_gdb_client.HandshakeWithServer(&error)) {
239     m_gdb_client.GetHostInfo();
240     // If a working directory was set prior to connecting, send it down
241     // now.
242     if (m_working_dir)
243       m_gdb_client.SetWorkingDir(m_working_dir);
244 
245     m_supported_architectures.clear();
246     ArchSpec remote_arch = m_gdb_client.GetSystemArchitecture();
247     if (remote_arch) {
248       m_supported_architectures.push_back(remote_arch);
249       if (remote_arch.GetTriple().isArch64Bit())
250         m_supported_architectures.push_back(
251             ArchSpec(remote_arch.GetTriple().get32BitArchVariant()));
252     }
253   } else {
254     m_gdb_client.Disconnect();
255     if (error.Success())
256       error.SetErrorString("handshake failed");
257   }
258   return error;
259 }
260 
261 Status PlatformRemoteGDBServer::DisconnectRemote() {
262   Status error;
263   m_gdb_client.Disconnect(&error);
264   m_remote_signals_sp.reset();
265   return error;
266 }
267 
268 const char *PlatformRemoteGDBServer::GetHostname() {
269   m_gdb_client.GetHostname(m_name);
270   if (m_name.empty())
271     return nullptr;
272   return m_name.c_str();
273 }
274 
275 llvm::Optional<std::string>
276 PlatformRemoteGDBServer::DoGetUserName(UserIDResolver::id_t uid) {
277   std::string name;
278   if (m_gdb_client.GetUserName(uid, name))
279     return std::move(name);
280   return llvm::None;
281 }
282 
283 llvm::Optional<std::string>
284 PlatformRemoteGDBServer::DoGetGroupName(UserIDResolver::id_t gid) {
285   std::string name;
286   if (m_gdb_client.GetGroupName(gid, name))
287     return std::move(name);
288   return llvm::None;
289 }
290 
291 uint32_t PlatformRemoteGDBServer::FindProcesses(
292     const ProcessInstanceInfoMatch &match_info,
293     ProcessInstanceInfoList &process_infos) {
294   return m_gdb_client.FindProcesses(match_info, process_infos);
295 }
296 
297 bool PlatformRemoteGDBServer::GetProcessInfo(
298     lldb::pid_t pid, ProcessInstanceInfo &process_info) {
299   return m_gdb_client.GetProcessInfo(pid, process_info);
300 }
301 
302 Status PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) {
303   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
304   Status error;
305 
306   LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() called", __FUNCTION__);
307 
308   auto num_file_actions = launch_info.GetNumFileActions();
309   for (decltype(num_file_actions) i = 0; i < num_file_actions; ++i) {
310     const auto file_action = launch_info.GetFileActionAtIndex(i);
311     if (file_action->GetAction() != FileAction::eFileActionOpen)
312       continue;
313     switch (file_action->GetFD()) {
314     case STDIN_FILENO:
315       m_gdb_client.SetSTDIN(file_action->GetFileSpec());
316       break;
317     case STDOUT_FILENO:
318       m_gdb_client.SetSTDOUT(file_action->GetFileSpec());
319       break;
320     case STDERR_FILENO:
321       m_gdb_client.SetSTDERR(file_action->GetFileSpec());
322       break;
323     }
324   }
325 
326   m_gdb_client.SetDisableASLR(
327       launch_info.GetFlags().Test(eLaunchFlagDisableASLR));
328   m_gdb_client.SetDetachOnError(
329       launch_info.GetFlags().Test(eLaunchFlagDetachOnError));
330 
331   FileSpec working_dir = launch_info.GetWorkingDirectory();
332   if (working_dir) {
333     m_gdb_client.SetWorkingDir(working_dir);
334   }
335 
336   // Send the environment and the program + arguments after we connect
337   m_gdb_client.SendEnvironment(launch_info.GetEnvironment());
338 
339   ArchSpec arch_spec = launch_info.GetArchitecture();
340   const char *arch_triple = arch_spec.GetTriple().str().c_str();
341 
342   m_gdb_client.SendLaunchArchPacket(arch_triple);
343   LLDB_LOGF(
344       log,
345       "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
346       __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
347 
348   int arg_packet_err;
349   {
350     // Scope for the scoped timeout object
351     process_gdb_remote::GDBRemoteCommunication::ScopedTimeout timeout(
352         m_gdb_client, std::chrono::seconds(5));
353     arg_packet_err = m_gdb_client.SendArgumentsPacket(launch_info);
354   }
355 
356   if (arg_packet_err == 0) {
357     std::string error_str;
358     if (m_gdb_client.GetLaunchSuccess(error_str)) {
359       const auto pid = m_gdb_client.GetCurrentProcessID(false);
360       if (pid != LLDB_INVALID_PROCESS_ID) {
361         launch_info.SetProcessID(pid);
362         LLDB_LOGF(log,
363                   "PlatformRemoteGDBServer::%s() pid %" PRIu64
364                   " launched successfully",
365                   __FUNCTION__, pid);
366       } else {
367         LLDB_LOGF(log,
368                   "PlatformRemoteGDBServer::%s() launch succeeded but we "
369                   "didn't get a valid process id back!",
370                   __FUNCTION__);
371         error.SetErrorString("failed to get PID");
372       }
373     } else {
374       error.SetErrorString(error_str.c_str());
375       LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() launch failed: %s",
376                 __FUNCTION__, error.AsCString());
377     }
378   } else {
379     error.SetErrorStringWithFormat("'A' packet returned an error: %i",
380                                    arg_packet_err);
381   }
382   return error;
383 }
384 
385 Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) {
386   if (!KillSpawnedProcess(pid))
387     return Status("failed to kill remote spawned process");
388   return Status();
389 }
390 
391 lldb::ProcessSP
392 PlatformRemoteGDBServer::DebugProcess(ProcessLaunchInfo &launch_info,
393                                       Debugger &debugger, Target &target,
394                                       Status &error) {
395   lldb::ProcessSP process_sp;
396   if (IsRemote()) {
397     if (IsConnected()) {
398       lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
399       std::string connect_url;
400       if (!LaunchGDBServer(debugserver_pid, connect_url)) {
401         error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
402                                        GetHostname());
403       } else {
404         // The darwin always currently uses the GDB remote debugger plug-in
405         // so even when debugging locally we are debugging remotely!
406         process_sp = target.CreateProcess(launch_info.GetListener(),
407                                           "gdb-remote", nullptr, true);
408 
409         if (process_sp) {
410           error = process_sp->ConnectRemote(connect_url.c_str());
411           // Retry the connect remote one time...
412           if (error.Fail())
413             error = process_sp->ConnectRemote(connect_url.c_str());
414           if (error.Success())
415             error = process_sp->Launch(launch_info);
416           else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) {
417             printf("error: connect remote failed (%s)\n", error.AsCString());
418             KillSpawnedProcess(debugserver_pid);
419           }
420         }
421       }
422     } else {
423       error.SetErrorString("not connected to remote gdb server");
424     }
425   }
426   return process_sp;
427 }
428 
429 bool PlatformRemoteGDBServer::LaunchGDBServer(lldb::pid_t &pid,
430                                               std::string &connect_url) {
431   ArchSpec remote_arch = GetRemoteSystemArchitecture();
432   llvm::Triple &remote_triple = remote_arch.GetTriple();
433 
434   uint16_t port = 0;
435   std::string socket_name;
436   bool launch_result = false;
437   if (remote_triple.getVendor() == llvm::Triple::Apple &&
438       remote_triple.getOS() == llvm::Triple::IOS) {
439     // When remote debugging to iOS, we use a USB mux that always talks to
440     // localhost, so we will need the remote debugserver to accept connections
441     // only from localhost, no matter what our current hostname is
442     launch_result =
443         m_gdb_client.LaunchGDBServer("127.0.0.1", pid, port, socket_name);
444   } else {
445     // All other hosts should use their actual hostname
446     launch_result =
447         m_gdb_client.LaunchGDBServer(nullptr, pid, port, socket_name);
448   }
449 
450   if (!launch_result)
451     return false;
452 
453   connect_url =
454       MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, port,
455                        (socket_name.empty()) ? nullptr : socket_name.c_str());
456   return true;
457 }
458 
459 bool PlatformRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) {
460   return m_gdb_client.KillSpawnedProcess(pid);
461 }
462 
463 lldb::ProcessSP PlatformRemoteGDBServer::Attach(
464     ProcessAttachInfo &attach_info, Debugger &debugger,
465     Target *target, // Can be NULL, if NULL create a new target, else use
466                     // existing one
467     Status &error) {
468   lldb::ProcessSP process_sp;
469   if (IsRemote()) {
470     if (IsConnected()) {
471       lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
472       std::string connect_url;
473       if (!LaunchGDBServer(debugserver_pid, connect_url)) {
474         error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
475                                        GetHostname());
476       } else {
477         if (target == nullptr) {
478           TargetSP new_target_sp;
479 
480           error = debugger.GetTargetList().CreateTarget(
481               debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
482           target = new_target_sp.get();
483         } else
484           error.Clear();
485 
486         if (target && error.Success()) {
487           // The darwin always currently uses the GDB remote debugger plug-in
488           // so even when debugging locally we are debugging remotely!
489           process_sp =
490               target->CreateProcess(attach_info.GetListenerForProcess(debugger),
491                                     "gdb-remote", nullptr, true);
492           if (process_sp) {
493             error = process_sp->ConnectRemote(connect_url.c_str());
494             if (error.Success()) {
495               ListenerSP listener_sp = attach_info.GetHijackListener();
496               if (listener_sp)
497                 process_sp->HijackProcessEvents(listener_sp);
498               error = process_sp->Attach(attach_info);
499             }
500 
501             if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
502               KillSpawnedProcess(debugserver_pid);
503             }
504           }
505         }
506       }
507     } else {
508       error.SetErrorString("not connected to remote gdb server");
509     }
510   }
511   return process_sp;
512 }
513 
514 Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec,
515                                               uint32_t mode) {
516   Status error = m_gdb_client.MakeDirectory(file_spec, mode);
517   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
518   LLDB_LOGF(log,
519             "PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
520             "error = %u (%s)",
521             file_spec.GetCString(), mode, error.GetError(), error.AsCString());
522   return error;
523 }
524 
525 Status PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec,
526                                                    uint32_t &file_permissions) {
527   Status error = m_gdb_client.GetFilePermissions(file_spec, file_permissions);
528   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
529   LLDB_LOGF(log,
530             "PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
531             "file_permissions=%o) error = %u (%s)",
532             file_spec.GetCString(), file_permissions, error.GetError(),
533             error.AsCString());
534   return error;
535 }
536 
537 Status PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec,
538                                                    uint32_t file_permissions) {
539   Status error = m_gdb_client.SetFilePermissions(file_spec, file_permissions);
540   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
541   LLDB_LOGF(log,
542             "PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
543             "file_permissions=%o) error = %u (%s)",
544             file_spec.GetCString(), file_permissions, error.GetError(),
545             error.AsCString());
546   return error;
547 }
548 
549 lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec,
550                                                   File::OpenOptions flags,
551                                                   uint32_t mode,
552                                                   Status &error) {
553   return m_gdb_client.OpenFile(file_spec, flags, mode, error);
554 }
555 
556 bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) {
557   return m_gdb_client.CloseFile(fd, error);
558 }
559 
560 lldb::user_id_t
561 PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) {
562   return m_gdb_client.GetFileSize(file_spec);
563 }
564 
565 void PlatformRemoteGDBServer::AutoCompleteDiskFileOrDirectory(
566     CompletionRequest &request, bool only_dir) {
567   m_gdb_client.AutoCompleteDiskFileOrDirectory(request, only_dir);
568 }
569 
570 uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset,
571                                            void *dst, uint64_t dst_len,
572                                            Status &error) {
573   return m_gdb_client.ReadFile(fd, offset, dst, dst_len, error);
574 }
575 
576 uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset,
577                                             const void *src, uint64_t src_len,
578                                             Status &error) {
579   return m_gdb_client.WriteFile(fd, offset, src, src_len, error);
580 }
581 
582 Status PlatformRemoteGDBServer::PutFile(const FileSpec &source,
583                                         const FileSpec &destination,
584                                         uint32_t uid, uint32_t gid) {
585   return Platform::PutFile(source, destination, uid, gid);
586 }
587 
588 Status PlatformRemoteGDBServer::CreateSymlink(
589     const FileSpec &src, // The name of the link is in src
590     const FileSpec &dst) // The symlink points to dst
591 {
592   Status error = m_gdb_client.CreateSymlink(src, dst);
593   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
594   LLDB_LOGF(log,
595             "PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
596             "error = %u (%s)",
597             src.GetCString(), dst.GetCString(), error.GetError(),
598             error.AsCString());
599   return error;
600 }
601 
602 Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) {
603   Status error = m_gdb_client.Unlink(file_spec);
604   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
605   LLDB_LOGF(log, "PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
606             file_spec.GetCString(), error.GetError(), error.AsCString());
607   return error;
608 }
609 
610 bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) {
611   return m_gdb_client.GetFileExists(file_spec);
612 }
613 
614 Status PlatformRemoteGDBServer::RunShellCommand(
615     llvm::StringRef shell, llvm::StringRef command,
616     const FileSpec &
617         working_dir, // Pass empty FileSpec to use the current working directory
618     int *status_ptr, // Pass NULL if you don't want the process exit status
619     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
620                      // process to exit
621     std::string
622         *command_output, // Pass NULL if you don't want the command output
623     const Timeout<std::micro> &timeout) {
624   return m_gdb_client.RunShellCommand(command, working_dir, status_ptr,
625                                       signo_ptr, command_output, timeout);
626 }
627 
628 void PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames() {
629   m_trap_handlers.push_back(ConstString("_sigtramp"));
630 }
631 
632 const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() {
633   if (!IsConnected())
634     return Platform::GetRemoteUnixSignals();
635 
636   if (m_remote_signals_sp)
637     return m_remote_signals_sp;
638 
639   // If packet not implemented or JSON failed to parse, we'll guess the signal
640   // set based on the remote architecture.
641   m_remote_signals_sp = UnixSignals::Create(GetRemoteSystemArchitecture());
642 
643   StringExtractorGDBRemote response;
644   auto result =
645       m_gdb_client.SendPacketAndWaitForResponse("jSignalsInfo", response);
646 
647   if (result != decltype(result)::Success ||
648       response.GetResponseType() != response.eResponse)
649     return m_remote_signals_sp;
650 
651   auto object_sp =
652       StructuredData::ParseJSON(std::string(response.GetStringRef()));
653   if (!object_sp || !object_sp->IsValid())
654     return m_remote_signals_sp;
655 
656   auto array_sp = object_sp->GetAsArray();
657   if (!array_sp || !array_sp->IsValid())
658     return m_remote_signals_sp;
659 
660   auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
661 
662   bool done = array_sp->ForEach(
663       [&remote_signals_sp](StructuredData::Object *object) -> bool {
664         if (!object || !object->IsValid())
665           return false;
666 
667         auto dict = object->GetAsDictionary();
668         if (!dict || !dict->IsValid())
669           return false;
670 
671         // Signal number and signal name are required.
672         int signo;
673         if (!dict->GetValueForKeyAsInteger("signo", signo))
674           return false;
675 
676         llvm::StringRef name;
677         if (!dict->GetValueForKeyAsString("name", name))
678           return false;
679 
680         // We can live without short_name, description, etc.
681         bool suppress{false};
682         auto object_sp = dict->GetValueForKey("suppress");
683         if (object_sp && object_sp->IsValid())
684           suppress = object_sp->GetBooleanValue();
685 
686         bool stop{false};
687         object_sp = dict->GetValueForKey("stop");
688         if (object_sp && object_sp->IsValid())
689           stop = object_sp->GetBooleanValue();
690 
691         bool notify{false};
692         object_sp = dict->GetValueForKey("notify");
693         if (object_sp && object_sp->IsValid())
694           notify = object_sp->GetBooleanValue();
695 
696         std::string description;
697         object_sp = dict->GetValueForKey("description");
698         if (object_sp && object_sp->IsValid())
699           description = std::string(object_sp->GetStringValue());
700 
701         remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop,
702                                      notify, description.c_str());
703         return true;
704       });
705 
706   if (done)
707     m_remote_signals_sp = std::move(remote_signals_sp);
708 
709   return m_remote_signals_sp;
710 }
711 
712 std::string PlatformRemoteGDBServer::MakeGdbServerUrl(
713     const std::string &platform_scheme, const std::string &platform_hostname,
714     uint16_t port, const char *socket_name) {
715   const char *override_scheme =
716       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME");
717   const char *override_hostname =
718       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
719   const char *port_offset_c_str =
720       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
721   int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
722 
723   return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(),
724                  override_hostname ? override_hostname
725                                    : platform_hostname.c_str(),
726                  port + port_offset, socket_name);
727 }
728 
729 std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
730                                              const char *hostname,
731                                              uint16_t port, const char *path) {
732   StreamString result;
733   result.Printf("%s://[%s]", scheme, hostname);
734   if (port != 0)
735     result.Printf(":%u", port);
736   if (path)
737     result.Write(path, strlen(path));
738   return std::string(result.GetString());
739 }
740 
741 size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger,
742                                                           Status &error) {
743   std::vector<std::string> connection_urls;
744   GetPendingGdbServerList(connection_urls);
745 
746   for (size_t i = 0; i < connection_urls.size(); ++i) {
747     ConnectProcess(connection_urls[i].c_str(), "gdb-remote", debugger, nullptr, error);
748     if (error.Fail())
749       return i; // We already connected to i process succsessfully
750   }
751   return connection_urls.size();
752 }
753 
754 size_t PlatformRemoteGDBServer::GetPendingGdbServerList(
755     std::vector<std::string> &connection_urls) {
756   std::vector<std::pair<uint16_t, std::string>> remote_servers;
757   m_gdb_client.QueryGDBServer(remote_servers);
758   for (const auto &gdbserver : remote_servers) {
759     const char *socket_name_cstr =
760         gdbserver.second.empty() ? nullptr : gdbserver.second.c_str();
761     connection_urls.emplace_back(
762         MakeGdbServerUrl(m_platform_scheme, m_platform_hostname,
763                          gdbserver.first, socket_name_cstr));
764   }
765   return connection_urls.size();
766 }
767