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