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.SetErrorStringWithFormatv(
149             "'{0}' doesn't contain any '{1}' platform architectures: {2}",
150             resolved_module_spec.GetFileSpec(), GetPluginName(),
151             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 llvm::Optional<std::string> PlatformRemoteGDBServer::GetRemoteOSBuildString() {
245   return m_gdb_client.GetOSBuildString();
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   llvm::Optional<URI> parsed_url = URI::Parse(url);
309   if (!parsed_url)
310     return Status("Invalid URL: %s", url);
311 
312   // We're going to reuse the hostname when we connect to the debugserver.
313   m_platform_scheme = parsed_url->scheme.str();
314   m_platform_hostname = parsed_url->hostname.str();
315 
316   m_gdb_client.SetConnection(std::make_unique<ConnectionFileDescriptor>());
317   if (repro::Reproducer::Instance().IsReplaying()) {
318     error = m_gdb_replay_server.Connect(m_gdb_client);
319     if (error.Success())
320       m_gdb_replay_server.StartAsyncThread();
321   } else {
322     if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) {
323       repro::GDBRemoteProvider &provider =
324           g->GetOrCreate<repro::GDBRemoteProvider>();
325       m_gdb_client.SetPacketRecorder(provider.GetNewPacketRecorder());
326     }
327     m_gdb_client.Connect(url, &error);
328   }
329 
330   if (error.Fail())
331     return error;
332 
333   if (m_gdb_client.HandshakeWithServer(&error)) {
334     m_gdb_client.GetHostInfo();
335     // If a working directory was set prior to connecting, send it down
336     // now.
337     if (m_working_dir)
338       m_gdb_client.SetWorkingDir(m_working_dir);
339   } else {
340     m_gdb_client.Disconnect();
341     if (error.Success())
342       error.SetErrorString("handshake failed");
343   }
344   return error;
345 }
346 
347 Status PlatformRemoteGDBServer::DisconnectRemote() {
348   Status error;
349   m_gdb_client.Disconnect(&error);
350   m_remote_signals_sp.reset();
351   return error;
352 }
353 
354 const char *PlatformRemoteGDBServer::GetHostname() {
355   m_gdb_client.GetHostname(m_name);
356   if (m_name.empty())
357     return nullptr;
358   return m_name.c_str();
359 }
360 
361 llvm::Optional<std::string>
362 PlatformRemoteGDBServer::DoGetUserName(UserIDResolver::id_t uid) {
363   std::string name;
364   if (m_gdb_client.GetUserName(uid, name))
365     return std::move(name);
366   return llvm::None;
367 }
368 
369 llvm::Optional<std::string>
370 PlatformRemoteGDBServer::DoGetGroupName(UserIDResolver::id_t gid) {
371   std::string name;
372   if (m_gdb_client.GetGroupName(gid, name))
373     return std::move(name);
374   return llvm::None;
375 }
376 
377 uint32_t PlatformRemoteGDBServer::FindProcesses(
378     const ProcessInstanceInfoMatch &match_info,
379     ProcessInstanceInfoList &process_infos) {
380   return m_gdb_client.FindProcesses(match_info, process_infos);
381 }
382 
383 bool PlatformRemoteGDBServer::GetProcessInfo(
384     lldb::pid_t pid, ProcessInstanceInfo &process_info) {
385   return m_gdb_client.GetProcessInfo(pid, process_info);
386 }
387 
388 Status PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) {
389   Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
390   Status error;
391 
392   LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() called", __FUNCTION__);
393 
394   auto num_file_actions = launch_info.GetNumFileActions();
395   for (decltype(num_file_actions) i = 0; i < num_file_actions; ++i) {
396     const auto file_action = launch_info.GetFileActionAtIndex(i);
397     if (file_action->GetAction() != FileAction::eFileActionOpen)
398       continue;
399     switch (file_action->GetFD()) {
400     case STDIN_FILENO:
401       m_gdb_client.SetSTDIN(file_action->GetFileSpec());
402       break;
403     case STDOUT_FILENO:
404       m_gdb_client.SetSTDOUT(file_action->GetFileSpec());
405       break;
406     case STDERR_FILENO:
407       m_gdb_client.SetSTDERR(file_action->GetFileSpec());
408       break;
409     }
410   }
411 
412   m_gdb_client.SetDisableASLR(
413       launch_info.GetFlags().Test(eLaunchFlagDisableASLR));
414   m_gdb_client.SetDetachOnError(
415       launch_info.GetFlags().Test(eLaunchFlagDetachOnError));
416 
417   FileSpec working_dir = launch_info.GetWorkingDirectory();
418   if (working_dir) {
419     m_gdb_client.SetWorkingDir(working_dir);
420   }
421 
422   // Send the environment and the program + arguments after we connect
423   m_gdb_client.SendEnvironment(launch_info.GetEnvironment());
424 
425   ArchSpec arch_spec = launch_info.GetArchitecture();
426   const char *arch_triple = arch_spec.GetTriple().str().c_str();
427 
428   m_gdb_client.SendLaunchArchPacket(arch_triple);
429   LLDB_LOGF(
430       log,
431       "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
432       __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
433 
434   int arg_packet_err;
435   {
436     // Scope for the scoped timeout object
437     process_gdb_remote::GDBRemoteCommunication::ScopedTimeout timeout(
438         m_gdb_client, std::chrono::seconds(5));
439     arg_packet_err = m_gdb_client.SendArgumentsPacket(launch_info);
440   }
441 
442   if (arg_packet_err == 0) {
443     std::string error_str;
444     if (m_gdb_client.GetLaunchSuccess(error_str)) {
445       const auto pid = m_gdb_client.GetCurrentProcessID(false);
446       if (pid != LLDB_INVALID_PROCESS_ID) {
447         launch_info.SetProcessID(pid);
448         LLDB_LOGF(log,
449                   "PlatformRemoteGDBServer::%s() pid %" PRIu64
450                   " launched successfully",
451                   __FUNCTION__, pid);
452       } else {
453         LLDB_LOGF(log,
454                   "PlatformRemoteGDBServer::%s() launch succeeded but we "
455                   "didn't get a valid process id back!",
456                   __FUNCTION__);
457         error.SetErrorString("failed to get PID");
458       }
459     } else {
460       error.SetErrorString(error_str.c_str());
461       LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() launch failed: %s",
462                 __FUNCTION__, error.AsCString());
463     }
464   } else {
465     error.SetErrorStringWithFormat("'A' packet returned an error: %i",
466                                    arg_packet_err);
467   }
468   return error;
469 }
470 
471 Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) {
472   if (!KillSpawnedProcess(pid))
473     return Status("failed to kill remote spawned process");
474   return Status();
475 }
476 
477 lldb::ProcessSP
478 PlatformRemoteGDBServer::DebugProcess(ProcessLaunchInfo &launch_info,
479                                       Debugger &debugger, Target &target,
480                                       Status &error) {
481   lldb::ProcessSP process_sp;
482   if (IsRemote()) {
483     if (IsConnected()) {
484       lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
485       std::string connect_url;
486       if (!LaunchGDBServer(debugserver_pid, connect_url)) {
487         error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
488                                        GetHostname());
489       } else {
490         // The darwin always currently uses the GDB remote debugger plug-in
491         // so even when debugging locally we are debugging remotely!
492         process_sp = target.CreateProcess(launch_info.GetListener(),
493                                           "gdb-remote", nullptr, true);
494 
495         if (process_sp) {
496           error = process_sp->ConnectRemote(connect_url.c_str());
497           // Retry the connect remote one time...
498           if (error.Fail())
499             error = process_sp->ConnectRemote(connect_url.c_str());
500           if (error.Success())
501             error = process_sp->Launch(launch_info);
502           else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) {
503             printf("error: connect remote failed (%s)\n", error.AsCString());
504             KillSpawnedProcess(debugserver_pid);
505           }
506         }
507       }
508     } else {
509       error.SetErrorString("not connected to remote gdb server");
510     }
511   }
512   return process_sp;
513 }
514 
515 bool PlatformRemoteGDBServer::LaunchGDBServer(lldb::pid_t &pid,
516                                               std::string &connect_url) {
517   ArchSpec remote_arch = GetRemoteSystemArchitecture();
518   llvm::Triple &remote_triple = remote_arch.GetTriple();
519 
520   uint16_t port = 0;
521   std::string socket_name;
522   bool launch_result = false;
523   if (remote_triple.getVendor() == llvm::Triple::Apple &&
524       remote_triple.getOS() == llvm::Triple::IOS) {
525     // When remote debugging to iOS, we use a USB mux that always talks to
526     // localhost, so we will need the remote debugserver to accept connections
527     // only from localhost, no matter what our current hostname is
528     launch_result =
529         m_gdb_client.LaunchGDBServer("127.0.0.1", pid, port, socket_name);
530   } else {
531     // All other hosts should use their actual hostname
532     launch_result =
533         m_gdb_client.LaunchGDBServer(nullptr, pid, port, socket_name);
534   }
535 
536   if (!launch_result)
537     return false;
538 
539   connect_url =
540       MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, port,
541                        (socket_name.empty()) ? nullptr : socket_name.c_str());
542   return true;
543 }
544 
545 bool PlatformRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) {
546   return m_gdb_client.KillSpawnedProcess(pid);
547 }
548 
549 lldb::ProcessSP PlatformRemoteGDBServer::Attach(
550     ProcessAttachInfo &attach_info, Debugger &debugger,
551     Target *target, // Can be NULL, if NULL create a new target, else use
552                     // existing one
553     Status &error) {
554   lldb::ProcessSP process_sp;
555   if (IsRemote()) {
556     if (IsConnected()) {
557       lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
558       std::string connect_url;
559       if (!LaunchGDBServer(debugserver_pid, connect_url)) {
560         error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
561                                        GetHostname());
562       } else {
563         if (target == nullptr) {
564           TargetSP new_target_sp;
565 
566           error = debugger.GetTargetList().CreateTarget(
567               debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
568           target = new_target_sp.get();
569         } else
570           error.Clear();
571 
572         if (target && error.Success()) {
573           // The darwin always currently uses the GDB remote debugger plug-in
574           // so even when debugging locally we are debugging remotely!
575           process_sp =
576               target->CreateProcess(attach_info.GetListenerForProcess(debugger),
577                                     "gdb-remote", nullptr, true);
578           if (process_sp) {
579             error = process_sp->ConnectRemote(connect_url.c_str());
580             if (error.Success()) {
581               ListenerSP listener_sp = attach_info.GetHijackListener();
582               if (listener_sp)
583                 process_sp->HijackProcessEvents(listener_sp);
584               error = process_sp->Attach(attach_info);
585             }
586 
587             if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
588               KillSpawnedProcess(debugserver_pid);
589             }
590           }
591         }
592       }
593     } else {
594       error.SetErrorString("not connected to remote gdb server");
595     }
596   }
597   return process_sp;
598 }
599 
600 Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec,
601                                               uint32_t mode) {
602   Status error = m_gdb_client.MakeDirectory(file_spec, mode);
603   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
604   LLDB_LOGF(log,
605             "PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
606             "error = %u (%s)",
607             file_spec.GetCString(), mode, error.GetError(), error.AsCString());
608   return error;
609 }
610 
611 Status PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec,
612                                                    uint32_t &file_permissions) {
613   Status error = m_gdb_client.GetFilePermissions(file_spec, file_permissions);
614   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
615   LLDB_LOGF(log,
616             "PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
617             "file_permissions=%o) error = %u (%s)",
618             file_spec.GetCString(), file_permissions, error.GetError(),
619             error.AsCString());
620   return error;
621 }
622 
623 Status PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec,
624                                                    uint32_t file_permissions) {
625   Status error = m_gdb_client.SetFilePermissions(file_spec, file_permissions);
626   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
627   LLDB_LOGF(log,
628             "PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
629             "file_permissions=%o) error = %u (%s)",
630             file_spec.GetCString(), file_permissions, error.GetError(),
631             error.AsCString());
632   return error;
633 }
634 
635 lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec,
636                                                   File::OpenOptions flags,
637                                                   uint32_t mode,
638                                                   Status &error) {
639   return m_gdb_client.OpenFile(file_spec, flags, mode, error);
640 }
641 
642 bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) {
643   return m_gdb_client.CloseFile(fd, error);
644 }
645 
646 lldb::user_id_t
647 PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) {
648   return m_gdb_client.GetFileSize(file_spec);
649 }
650 
651 void PlatformRemoteGDBServer::AutoCompleteDiskFileOrDirectory(
652     CompletionRequest &request, bool only_dir) {
653   m_gdb_client.AutoCompleteDiskFileOrDirectory(request, only_dir);
654 }
655 
656 uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset,
657                                            void *dst, uint64_t dst_len,
658                                            Status &error) {
659   return m_gdb_client.ReadFile(fd, offset, dst, dst_len, error);
660 }
661 
662 uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset,
663                                             const void *src, uint64_t src_len,
664                                             Status &error) {
665   return m_gdb_client.WriteFile(fd, offset, src, src_len, error);
666 }
667 
668 Status PlatformRemoteGDBServer::PutFile(const FileSpec &source,
669                                         const FileSpec &destination,
670                                         uint32_t uid, uint32_t gid) {
671   return Platform::PutFile(source, destination, uid, gid);
672 }
673 
674 Status PlatformRemoteGDBServer::CreateSymlink(
675     const FileSpec &src, // The name of the link is in src
676     const FileSpec &dst) // The symlink points to dst
677 {
678   Status error = m_gdb_client.CreateSymlink(src, dst);
679   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
680   LLDB_LOGF(log,
681             "PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
682             "error = %u (%s)",
683             src.GetCString(), dst.GetCString(), error.GetError(),
684             error.AsCString());
685   return error;
686 }
687 
688 Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) {
689   Status error = m_gdb_client.Unlink(file_spec);
690   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
691   LLDB_LOGF(log, "PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
692             file_spec.GetCString(), error.GetError(), error.AsCString());
693   return error;
694 }
695 
696 bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) {
697   return m_gdb_client.GetFileExists(file_spec);
698 }
699 
700 Status PlatformRemoteGDBServer::RunShellCommand(
701     llvm::StringRef shell, llvm::StringRef command,
702     const FileSpec &
703         working_dir, // Pass empty FileSpec to use the current working directory
704     int *status_ptr, // Pass NULL if you don't want the process exit status
705     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
706                      // process to exit
707     std::string
708         *command_output, // Pass NULL if you don't want the command output
709     const Timeout<std::micro> &timeout) {
710   return m_gdb_client.RunShellCommand(command, working_dir, status_ptr,
711                                       signo_ptr, command_output, timeout);
712 }
713 
714 void PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames() {
715   m_trap_handlers.push_back(ConstString("_sigtramp"));
716 }
717 
718 const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() {
719   if (!IsConnected())
720     return Platform::GetRemoteUnixSignals();
721 
722   if (m_remote_signals_sp)
723     return m_remote_signals_sp;
724 
725   // If packet not implemented or JSON failed to parse, we'll guess the signal
726   // set based on the remote architecture.
727   m_remote_signals_sp = UnixSignals::Create(GetRemoteSystemArchitecture());
728 
729   StringExtractorGDBRemote response;
730   auto result =
731       m_gdb_client.SendPacketAndWaitForResponse("jSignalsInfo", response);
732 
733   if (result != decltype(result)::Success ||
734       response.GetResponseType() != response.eResponse)
735     return m_remote_signals_sp;
736 
737   auto object_sp =
738       StructuredData::ParseJSON(std::string(response.GetStringRef()));
739   if (!object_sp || !object_sp->IsValid())
740     return m_remote_signals_sp;
741 
742   auto array_sp = object_sp->GetAsArray();
743   if (!array_sp || !array_sp->IsValid())
744     return m_remote_signals_sp;
745 
746   auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
747 
748   bool done = array_sp->ForEach(
749       [&remote_signals_sp](StructuredData::Object *object) -> bool {
750         if (!object || !object->IsValid())
751           return false;
752 
753         auto dict = object->GetAsDictionary();
754         if (!dict || !dict->IsValid())
755           return false;
756 
757         // Signal number and signal name are required.
758         int signo;
759         if (!dict->GetValueForKeyAsInteger("signo", signo))
760           return false;
761 
762         llvm::StringRef name;
763         if (!dict->GetValueForKeyAsString("name", name))
764           return false;
765 
766         // We can live without short_name, description, etc.
767         bool suppress{false};
768         auto object_sp = dict->GetValueForKey("suppress");
769         if (object_sp && object_sp->IsValid())
770           suppress = object_sp->GetBooleanValue();
771 
772         bool stop{false};
773         object_sp = dict->GetValueForKey("stop");
774         if (object_sp && object_sp->IsValid())
775           stop = object_sp->GetBooleanValue();
776 
777         bool notify{false};
778         object_sp = dict->GetValueForKey("notify");
779         if (object_sp && object_sp->IsValid())
780           notify = object_sp->GetBooleanValue();
781 
782         std::string description{""};
783         object_sp = dict->GetValueForKey("description");
784         if (object_sp && object_sp->IsValid())
785           description = std::string(object_sp->GetStringValue());
786 
787         remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop,
788                                      notify, description.c_str());
789         return true;
790       });
791 
792   if (done)
793     m_remote_signals_sp = std::move(remote_signals_sp);
794 
795   return m_remote_signals_sp;
796 }
797 
798 std::string PlatformRemoteGDBServer::MakeGdbServerUrl(
799     const std::string &platform_scheme, const std::string &platform_hostname,
800     uint16_t port, const char *socket_name) {
801   const char *override_scheme =
802       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME");
803   const char *override_hostname =
804       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
805   const char *port_offset_c_str =
806       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
807   int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
808 
809   return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(),
810                  override_hostname ? override_hostname
811                                    : platform_hostname.c_str(),
812                  port + port_offset, socket_name);
813 }
814 
815 std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
816                                              const char *hostname,
817                                              uint16_t port, const char *path) {
818   StreamString result;
819   result.Printf("%s://[%s]", scheme, hostname);
820   if (port != 0)
821     result.Printf(":%u", port);
822   if (path)
823     result.Write(path, strlen(path));
824   return std::string(result.GetString());
825 }
826 
827 size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger,
828                                                           Status &error) {
829   std::vector<std::string> connection_urls;
830   GetPendingGdbServerList(connection_urls);
831 
832   for (size_t i = 0; i < connection_urls.size(); ++i) {
833     ConnectProcess(connection_urls[i].c_str(), "gdb-remote", debugger, nullptr, error);
834     if (error.Fail())
835       return i; // We already connected to i process succsessfully
836   }
837   return connection_urls.size();
838 }
839 
840 size_t PlatformRemoteGDBServer::GetPendingGdbServerList(
841     std::vector<std::string> &connection_urls) {
842   std::vector<std::pair<uint16_t, std::string>> remote_servers;
843   m_gdb_client.QueryGDBServer(remote_servers);
844   for (const auto &gdbserver : remote_servers) {
845     const char *socket_name_cstr =
846         gdbserver.second.empty() ? nullptr : gdbserver.second.c_str();
847     connection_urls.emplace_back(
848         MakeGdbServerUrl(m_platform_scheme, m_platform_hostname,
849                          gdbserver.first, socket_name_cstr));
850   }
851   return connection_urls.size();
852 }
853