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