]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lldb/source/Plugins/Platform/gdb-server/PlatformRemoteGDBServer.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r308421, and update
[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 // 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   const char **envp =
427       launch_info.GetEnvironmentEntries().GetConstArgumentVector();
428
429   if (envp) {
430     const char *env_entry;
431     for (int i = 0; (env_entry = envp[i]); ++i) {
432       if (m_gdb_client.SendEnvironmentPacket(env_entry) != 0)
433         break;
434     }
435   }
436
437   ArchSpec arch_spec = launch_info.GetArchitecture();
438   const char *arch_triple = arch_spec.GetTriple().str().c_str();
439
440   m_gdb_client.SendLaunchArchPacket(arch_triple);
441   if (log)
442     log->Printf(
443         "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
444         __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
445
446   int arg_packet_err;
447   {
448     // Scope for the scoped timeout object
449     process_gdb_remote::GDBRemoteCommunication::ScopedTimeout timeout(
450         m_gdb_client, std::chrono::seconds(5));
451     arg_packet_err = m_gdb_client.SendArgumentsPacket(launch_info);
452   }
453
454   if (arg_packet_err == 0) {
455     std::string error_str;
456     if (m_gdb_client.GetLaunchSuccess(error_str)) {
457       const auto pid = m_gdb_client.GetCurrentProcessID(false);
458       if (pid != LLDB_INVALID_PROCESS_ID) {
459         launch_info.SetProcessID(pid);
460         if (log)
461           log->Printf("PlatformRemoteGDBServer::%s() pid %" PRIu64
462                       " launched successfully",
463                       __FUNCTION__, pid);
464       } else {
465         if (log)
466           log->Printf("PlatformRemoteGDBServer::%s() launch succeeded but we "
467                       "didn't get a valid process id back!",
468                       __FUNCTION__);
469         error.SetErrorString("failed to get PID");
470       }
471     } else {
472       error.SetErrorString(error_str.c_str());
473       if (log)
474         log->Printf("PlatformRemoteGDBServer::%s() launch failed: %s",
475                     __FUNCTION__, error.AsCString());
476     }
477   } else {
478     error.SetErrorStringWithFormat("'A' packet returned an error: %i",
479                                    arg_packet_err);
480   }
481   return error;
482 }
483
484 Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) {
485   if (!KillSpawnedProcess(pid))
486     return Status("failed to kill remote spawned process");
487   return Status();
488 }
489
490 lldb::ProcessSP PlatformRemoteGDBServer::DebugProcess(
491     ProcessLaunchInfo &launch_info, Debugger &debugger,
492     Target *target, // Can be NULL, if NULL create a new target, else use
493                     // existing one
494     Status &error) {
495   lldb::ProcessSP process_sp;
496   if (IsRemote()) {
497     if (IsConnected()) {
498       lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
499       std::string connect_url;
500       if (!LaunchGDBServer(debugserver_pid, connect_url)) {
501         error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
502                                        GetHostname());
503       } else {
504         if (target == NULL) {
505           TargetSP new_target_sp;
506
507           error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
508                                                         NULL, new_target_sp);
509           target = new_target_sp.get();
510         } else
511           error.Clear();
512
513         if (target && error.Success()) {
514           debugger.GetTargetList().SetSelectedTarget(target);
515
516           // The darwin always currently uses the GDB remote debugger plug-in
517           // so even when debugging locally we are debugging remotely!
518           process_sp = target->CreateProcess(
519               launch_info.GetListenerForProcess(debugger), "gdb-remote", NULL);
520
521           if (process_sp) {
522             error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
523             // Retry the connect remote one time...
524             if (error.Fail())
525               error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
526             if (error.Success())
527               error = process_sp->Launch(launch_info);
528             else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) {
529               printf("error: connect remote failed (%s)\n", error.AsCString());
530               KillSpawnedProcess(debugserver_pid);
531             }
532           }
533         }
534       }
535     } else {
536       error.SetErrorString("not connected to remote gdb server");
537     }
538   }
539   return process_sp;
540 }
541
542 bool PlatformRemoteGDBServer::LaunchGDBServer(lldb::pid_t &pid,
543                                               std::string &connect_url) {
544   ArchSpec remote_arch = GetRemoteSystemArchitecture();
545   llvm::Triple &remote_triple = remote_arch.GetTriple();
546
547   uint16_t port = 0;
548   std::string socket_name;
549   bool launch_result = false;
550   if (remote_triple.getVendor() == llvm::Triple::Apple &&
551       remote_triple.getOS() == llvm::Triple::IOS) {
552     // When remote debugging to iOS, we use a USB mux that always talks
553     // to localhost, so we will need the remote debugserver to accept
554     // connections
555     // only from localhost, no matter what our current hostname is
556     launch_result =
557         m_gdb_client.LaunchGDBServer("127.0.0.1", pid, port, socket_name);
558   } else {
559     // All other hosts should use their actual hostname
560     launch_result =
561         m_gdb_client.LaunchGDBServer(nullptr, pid, port, socket_name);
562   }
563
564   if (!launch_result)
565     return false;
566
567   connect_url =
568       MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, port,
569                        (socket_name.empty()) ? nullptr : socket_name.c_str());
570   return true;
571 }
572
573 bool PlatformRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) {
574   return m_gdb_client.KillSpawnedProcess(pid);
575 }
576
577 lldb::ProcessSP PlatformRemoteGDBServer::Attach(
578     ProcessAttachInfo &attach_info, Debugger &debugger,
579     Target *target, // Can be NULL, if NULL create a new target, else use
580                     // existing one
581     Status &error) {
582   lldb::ProcessSP process_sp;
583   if (IsRemote()) {
584     if (IsConnected()) {
585       lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
586       std::string connect_url;
587       if (!LaunchGDBServer(debugserver_pid, connect_url)) {
588         error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
589                                        GetHostname());
590       } else {
591         if (target == NULL) {
592           TargetSP new_target_sp;
593
594           error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
595                                                         NULL, new_target_sp);
596           target = new_target_sp.get();
597         } else
598           error.Clear();
599
600         if (target && error.Success()) {
601           debugger.GetTargetList().SetSelectedTarget(target);
602
603           // The darwin always currently uses the GDB remote debugger plug-in
604           // so even when debugging locally we are debugging remotely!
605           process_sp = target->CreateProcess(
606               attach_info.GetListenerForProcess(debugger), "gdb-remote", NULL);
607           if (process_sp) {
608             error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
609             if (error.Success()) {
610               ListenerSP listener_sp = attach_info.GetHijackListener();
611               if (listener_sp)
612                 process_sp->HijackProcessEvents(listener_sp);
613               error = process_sp->Attach(attach_info);
614             }
615
616             if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
617               KillSpawnedProcess(debugserver_pid);
618             }
619           }
620         }
621       }
622     } else {
623       error.SetErrorString("not connected to remote gdb server");
624     }
625   }
626   return process_sp;
627 }
628
629 Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec,
630                                               uint32_t mode) {
631   Status error = m_gdb_client.MakeDirectory(file_spec, mode);
632   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
633   if (log)
634     log->Printf("PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
635                 "error = %u (%s)",
636                 file_spec.GetCString(), mode, error.GetError(),
637                 error.AsCString());
638   return error;
639 }
640
641 Status PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec,
642                                                    uint32_t &file_permissions) {
643   Status error = m_gdb_client.GetFilePermissions(file_spec, file_permissions);
644   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
645   if (log)
646     log->Printf("PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
647                 "file_permissions=%o) error = %u (%s)",
648                 file_spec.GetCString(), file_permissions, error.GetError(),
649                 error.AsCString());
650   return error;
651 }
652
653 Status PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec,
654                                                    uint32_t file_permissions) {
655   Status error = m_gdb_client.SetFilePermissions(file_spec, file_permissions);
656   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
657   if (log)
658     log->Printf("PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
659                 "file_permissions=%o) error = %u (%s)",
660                 file_spec.GetCString(), file_permissions, error.GetError(),
661                 error.AsCString());
662   return error;
663 }
664
665 lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec,
666                                                   uint32_t flags, uint32_t mode,
667                                                   Status &error) {
668   return m_gdb_client.OpenFile(file_spec, flags, mode, error);
669 }
670
671 bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) {
672   return m_gdb_client.CloseFile(fd, error);
673 }
674
675 lldb::user_id_t
676 PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) {
677   return m_gdb_client.GetFileSize(file_spec);
678 }
679
680 uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset,
681                                            void *dst, uint64_t dst_len,
682                                            Status &error) {
683   return m_gdb_client.ReadFile(fd, offset, dst, dst_len, error);
684 }
685
686 uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset,
687                                             const void *src, uint64_t src_len,
688                                             Status &error) {
689   return m_gdb_client.WriteFile(fd, offset, src, src_len, error);
690 }
691
692 Status PlatformRemoteGDBServer::PutFile(const FileSpec &source,
693                                         const FileSpec &destination,
694                                         uint32_t uid, uint32_t gid) {
695   return Platform::PutFile(source, destination, uid, gid);
696 }
697
698 Status PlatformRemoteGDBServer::CreateSymlink(
699     const FileSpec &src, // The name of the link is in src
700     const FileSpec &dst) // The symlink points to dst
701 {
702   Status error = m_gdb_client.CreateSymlink(src, dst);
703   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
704   if (log)
705     log->Printf("PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
706                 "error = %u (%s)",
707                 src.GetCString(), dst.GetCString(), error.GetError(),
708                 error.AsCString());
709   return error;
710 }
711
712 Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) {
713   Status error = m_gdb_client.Unlink(file_spec);
714   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
715   if (log)
716     log->Printf("PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
717                 file_spec.GetCString(), error.GetError(), error.AsCString());
718   return error;
719 }
720
721 bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) {
722   return m_gdb_client.GetFileExists(file_spec);
723 }
724
725 Status PlatformRemoteGDBServer::RunShellCommand(
726     const char *command, // Shouldn't be NULL
727     const FileSpec &
728         working_dir, // Pass empty FileSpec to use the current working directory
729     int *status_ptr, // Pass NULL if you don't want the process exit status
730     int *signo_ptr,  // Pass NULL if you don't want the signal that caused the
731                      // process to exit
732     std::string
733         *command_output, // Pass NULL if you don't want the command output
734     uint32_t
735         timeout_sec) // Timeout in seconds to wait for shell program to finish
736 {
737   return m_gdb_client.RunShellCommand(command, working_dir, status_ptr,
738                                       signo_ptr, command_output, timeout_sec);
739 }
740
741 void PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames() {
742   m_trap_handlers.push_back(ConstString("_sigtramp"));
743 }
744
745 const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() {
746   if (!IsConnected())
747     return Platform::GetRemoteUnixSignals();
748
749   if (m_remote_signals_sp)
750     return m_remote_signals_sp;
751
752   // If packet not implemented or JSON failed to parse,
753   // we'll guess the signal set based on the remote architecture.
754   m_remote_signals_sp = UnixSignals::Create(GetRemoteSystemArchitecture());
755
756   StringExtractorGDBRemote response;
757   auto result = m_gdb_client.SendPacketAndWaitForResponse("jSignalsInfo",
758                                                           response, false);
759
760   if (result != decltype(result)::Success ||
761       response.GetResponseType() != response.eResponse)
762     return m_remote_signals_sp;
763
764   auto object_sp = StructuredData::ParseJSON(response.GetStringRef());
765   if (!object_sp || !object_sp->IsValid())
766     return m_remote_signals_sp;
767
768   auto array_sp = object_sp->GetAsArray();
769   if (!array_sp || !array_sp->IsValid())
770     return m_remote_signals_sp;
771
772   auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
773
774   bool done = array_sp->ForEach(
775       [&remote_signals_sp](StructuredData::Object *object) -> bool {
776         if (!object || !object->IsValid())
777           return false;
778
779         auto dict = object->GetAsDictionary();
780         if (!dict || !dict->IsValid())
781           return false;
782
783         // Signal number and signal name are required.
784         int signo;
785         if (!dict->GetValueForKeyAsInteger("signo", signo))
786           return false;
787
788         llvm::StringRef name;
789         if (!dict->GetValueForKeyAsString("name", name))
790           return false;
791
792         // We can live without short_name, description, etc.
793         bool suppress{false};
794         auto object_sp = dict->GetValueForKey("suppress");
795         if (object_sp && object_sp->IsValid())
796           suppress = object_sp->GetBooleanValue();
797
798         bool stop{false};
799         object_sp = dict->GetValueForKey("stop");
800         if (object_sp && object_sp->IsValid())
801           stop = object_sp->GetBooleanValue();
802
803         bool notify{false};
804         object_sp = dict->GetValueForKey("notify");
805         if (object_sp && object_sp->IsValid())
806           notify = object_sp->GetBooleanValue();
807
808         std::string description{""};
809         object_sp = dict->GetValueForKey("description");
810         if (object_sp && object_sp->IsValid())
811           description = object_sp->GetStringValue();
812
813         remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop,
814                                      notify, description.c_str());
815         return true;
816       });
817
818   if (done)
819     m_remote_signals_sp = std::move(remote_signals_sp);
820
821   return m_remote_signals_sp;
822 }
823
824 std::string PlatformRemoteGDBServer::MakeGdbServerUrl(
825     const std::string &platform_scheme, const std::string &platform_hostname,
826     uint16_t port, const char *socket_name) {
827   const char *override_scheme =
828       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME");
829   const char *override_hostname =
830       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
831   const char *port_offset_c_str =
832       getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
833   int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
834
835   return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(),
836                  override_hostname ? override_hostname
837                                    : platform_hostname.c_str(),
838                  port + port_offset, socket_name);
839 }
840
841 std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
842                                              const char *hostname,
843                                              uint16_t port, const char *path) {
844   StreamString result;
845   result.Printf("%s://%s", scheme, hostname);
846   if (port != 0)
847     result.Printf(":%u", port);
848   if (path)
849     result.Write(path, strlen(path));
850   return result.GetString();
851 }
852
853 lldb::ProcessSP PlatformRemoteGDBServer::ConnectProcess(
854     llvm::StringRef connect_url, llvm::StringRef plugin_name,
855     lldb_private::Debugger &debugger, lldb_private::Target *target,
856     lldb_private::Status &error) {
857   if (!IsRemote() || !IsConnected()) {
858     error.SetErrorString("Not connected to remote gdb server");
859     return nullptr;
860   }
861   return Platform::ConnectProcess(connect_url, plugin_name, debugger, target,
862                                   error);
863 }
864
865 size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger,
866                                                           Status &error) {
867   std::vector<std::string> connection_urls;
868   GetPendingGdbServerList(connection_urls);
869
870   for (size_t i = 0; i < connection_urls.size(); ++i) {
871     ConnectProcess(connection_urls[i].c_str(), "", debugger, nullptr, error);
872     if (error.Fail())
873       return i; // We already connected to i process succsessfully
874   }
875   return connection_urls.size();
876 }
877
878 size_t PlatformRemoteGDBServer::GetPendingGdbServerList(
879     std::vector<std::string> &connection_urls) {
880   std::vector<std::pair<uint16_t, std::string>> remote_servers;
881   m_gdb_client.QueryGDBServer(remote_servers);
882   for (const auto &gdbserver : remote_servers) {
883     const char *socket_name_cstr =
884         gdbserver.second.empty() ? nullptr : gdbserver.second.c_str();
885     connection_urls.emplace_back(
886         MakeGdbServerUrl(m_platform_scheme, m_platform_hostname,
887                          gdbserver.first, socket_name_cstr));
888   }
889   return connection_urls.size();
890 }