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