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