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