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