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