1 //===-- PlatformRemoteGDBServer.cpp -----------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "PlatformRemoteGDBServer.h"
10 #include "lldb/Host/Config.h"
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"
32 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
35 using namespace lldb_private;
36 using namespace lldb_private::platform_gdb_server;
38 static bool g_initialized = false;
40 void PlatformRemoteGDBServer::Initialize() {
41 Platform::Initialize();
45 PluginManager::RegisterPlugin(
46 PlatformRemoteGDBServer::GetPluginNameStatic(),
47 PlatformRemoteGDBServer::GetDescriptionStatic(),
48 PlatformRemoteGDBServer::CreateInstance);
52 void PlatformRemoteGDBServer::Terminate() {
54 g_initialized = false;
55 PluginManager::UnregisterPlugin(PlatformRemoteGDBServer::CreateInstance);
58 Platform::Terminate();
61 PlatformSP PlatformRemoteGDBServer::CreateInstance(bool force,
62 const ArchSpec *arch) {
65 create = !arch->TripleVendorWasSpecified() && !arch->TripleOSWasSpecified();
68 return PlatformSP(new PlatformRemoteGDBServer());
72 ConstString PlatformRemoteGDBServer::GetPluginNameStatic() {
73 static ConstString g_name("remote-gdb-server");
77 const char *PlatformRemoteGDBServer::GetDescriptionStatic() {
78 return "A platform that uses the GDB remote protocol as the communication "
82 const char *PlatformRemoteGDBServer::GetDescription() {
83 if (m_platform_description.empty()) {
85 // Send the get description packet
89 if (!m_platform_description.empty())
90 return m_platform_description.c_str();
91 return GetDescriptionStatic();
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
100 // Nothing special to do here, just use the actual file and architecture
102 ModuleSpec resolved_module_spec(module_spec);
104 // Resolve any executable within an apk on Android?
105 // Host::ResolveExecutableInBundle (resolved_module_spec.GetFileSpec());
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,
115 if (exe_module_sp && exe_module_sp->GetObjectFile())
117 exe_module_sp.reset();
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());
126 error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
127 module_search_paths_ptr, nullptr,
129 // Did we find an executable using one of the
130 if (error.Success()) {
131 if (exe_module_sp && exe_module_sp->GetObjectFile())
134 error.SetErrorToGenericError();
138 arch_names.PutCString(", ");
139 arch_names.PutCString(
140 resolved_module_spec.GetArchitecture().GetArchitectureName());
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());
150 error.SetErrorStringWithFormat(
151 "'%s' is not readable",
152 resolved_module_spec.GetFileSpec().GetPath().c_str());
156 error.SetErrorStringWithFormat(
157 "'%s' does not exist",
158 resolved_module_spec.GetFileSpec().GetPath().c_str());
164 bool PlatformRemoteGDBServer::GetModuleSpec(const FileSpec &module_file_spec,
165 const ArchSpec &arch,
166 ModuleSpec &module_spec) {
167 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
169 const auto module_path = module_file_spec.GetPath(false);
171 if (!m_gdb_client.GetModuleInfo(module_file_spec, arch, module_spec)) {
174 "PlatformRemoteGDBServer::%s - failed to get module info for %s:%s",
175 __FUNCTION__, module_path.c_str(),
176 arch.GetTriple().getTriple().c_str());
182 module_spec.Dump(stream);
184 "PlatformRemoteGDBServer::%s - got module info for (%s:%s) : %s",
185 __FUNCTION__, module_path.c_str(), arch.GetTriple().getTriple().c_str(),
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;
200 /// Default Constructor
201 PlatformRemoteGDBServer::PlatformRemoteGDBServer()
202 : Platform(false), // This is a remote platform
207 /// The destructor is virtual since this class is designed to be
208 /// inherited from by the plug-in instance.
209 PlatformRemoteGDBServer::~PlatformRemoteGDBServer() {}
211 bool PlatformRemoteGDBServer::GetSupportedArchitectureAtIndex(uint32_t idx,
213 ArchSpec remote_arch = m_gdb_client.GetSystemArchitecture();
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();
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.
233 bool PlatformRemoteGDBServer::GetRemoteOSVersion() {
234 m_os_version = m_gdb_client.GetOSVersion();
235 return !m_os_version.empty();
238 bool PlatformRemoteGDBServer::GetRemoteOSBuildString(std::string &s) {
239 return m_gdb_client.GetOSBuildString(s);
242 bool PlatformRemoteGDBServer::GetRemoteOSKernelDescription(std::string &s) {
243 return m_gdb_client.GetOSKernelDescription(s);
246 // Remote Platform subclasses need to override this function
247 ArchSpec PlatformRemoteGDBServer::GetRemoteSystemArchitecture() {
248 return m_gdb_client.GetSystemArchitecture();
251 FileSpec PlatformRemoteGDBServer::GetRemoteWorkingDirectory() {
253 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
254 FileSpec working_dir;
255 if (m_gdb_client.GetWorkingDir(working_dir) && log)
257 "PlatformRemoteGDBServer::GetRemoteWorkingDirectory() -> '%s'",
258 working_dir.GetCString());
261 return Platform::GetRemoteWorkingDirectory();
265 bool PlatformRemoteGDBServer::SetRemoteWorkingDirectory(
266 const FileSpec &working_dir) {
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);
272 log->Printf("PlatformRemoteGDBServer::SetRemoteWorkingDirectory('%s')",
273 working_dir.GetCString());
274 return m_gdb_client.SetWorkingDir(working_dir) == 0;
276 return Platform::SetRemoteWorkingDirectory(working_dir);
279 bool PlatformRemoteGDBServer::IsConnected() const {
280 return m_gdb_client.IsConnected();
283 Status PlatformRemoteGDBServer::ConnectRemote(Args &args) {
286 error.SetErrorStringWithFormat("the platform is already connected to '%s', "
287 "execute 'platform disconnect' to close the "
288 "current connection",
291 if (args.GetArgumentCount() == 1) {
292 m_gdb_client.SetConnection(new ConnectionFileDescriptor());
293 // we're going to reuse the hostname when we connect to the debugserver
296 const char *url = args.GetArgumentAtIndex(0);
298 return Status("URL is null.");
299 llvm::StringRef scheme, hostname, pathname;
300 if (!UriParser::Parse(url, scheme, hostname, port, pathname))
301 return Status("Invalid URL: %s", url);
302 m_platform_scheme = scheme;
303 m_platform_hostname = hostname;
306 const ConnectionStatus status = m_gdb_client.Connect(url, &error);
307 if (status == eConnectionStatusSuccess) {
308 if (m_gdb_client.HandshakeWithServer(&error)) {
309 m_gdb_client.GetHostInfo();
310 // If a working directory was set prior to connecting, send it down
313 m_gdb_client.SetWorkingDir(m_working_dir);
315 m_gdb_client.Disconnect();
317 error.SetErrorString("handshake failed");
321 error.SetErrorString(
322 "\"platform connect\" takes a single argument: <connect-url>");
328 Status PlatformRemoteGDBServer::DisconnectRemote() {
330 m_gdb_client.Disconnect(&error);
331 m_remote_signals_sp.reset();
335 const char *PlatformRemoteGDBServer::GetHostname() {
336 m_gdb_client.GetHostname(m_name);
339 return m_name.c_str();
342 llvm::Optional<std::string>
343 PlatformRemoteGDBServer::DoGetUserName(UserIDResolver::id_t uid) {
345 if (m_gdb_client.GetUserName(uid, name))
346 return std::move(name);
350 llvm::Optional<std::string>
351 PlatformRemoteGDBServer::DoGetGroupName(UserIDResolver::id_t gid) {
353 if (m_gdb_client.GetGroupName(gid, name))
354 return std::move(name);
358 uint32_t PlatformRemoteGDBServer::FindProcesses(
359 const ProcessInstanceInfoMatch &match_info,
360 ProcessInstanceInfoList &process_infos) {
361 return m_gdb_client.FindProcesses(match_info, process_infos);
364 bool PlatformRemoteGDBServer::GetProcessInfo(
365 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
366 return m_gdb_client.GetProcessInfo(pid, process_info);
369 Status PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) {
370 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
374 log->Printf("PlatformRemoteGDBServer::%s() called", __FUNCTION__);
376 auto num_file_actions = launch_info.GetNumFileActions();
377 for (decltype(num_file_actions) i = 0; i < num_file_actions; ++i) {
378 const auto file_action = launch_info.GetFileActionAtIndex(i);
379 if (file_action->GetAction() != FileAction::eFileActionOpen)
381 switch (file_action->GetFD()) {
383 m_gdb_client.SetSTDIN(file_action->GetFileSpec());
386 m_gdb_client.SetSTDOUT(file_action->GetFileSpec());
389 m_gdb_client.SetSTDERR(file_action->GetFileSpec());
394 m_gdb_client.SetDisableASLR(
395 launch_info.GetFlags().Test(eLaunchFlagDisableASLR));
396 m_gdb_client.SetDetachOnError(
397 launch_info.GetFlags().Test(eLaunchFlagDetachOnError));
399 FileSpec working_dir = launch_info.GetWorkingDirectory();
401 m_gdb_client.SetWorkingDir(working_dir);
404 // Send the environment and the program + arguments after we connect
405 m_gdb_client.SendEnvironment(launch_info.GetEnvironment());
407 ArchSpec arch_spec = launch_info.GetArchitecture();
408 const char *arch_triple = arch_spec.GetTriple().str().c_str();
410 m_gdb_client.SendLaunchArchPacket(arch_triple);
413 "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
414 __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
418 // Scope for the scoped timeout object
419 process_gdb_remote::GDBRemoteCommunication::ScopedTimeout timeout(
420 m_gdb_client, std::chrono::seconds(5));
421 arg_packet_err = m_gdb_client.SendArgumentsPacket(launch_info);
424 if (arg_packet_err == 0) {
425 std::string error_str;
426 if (m_gdb_client.GetLaunchSuccess(error_str)) {
427 const auto pid = m_gdb_client.GetCurrentProcessID(false);
428 if (pid != LLDB_INVALID_PROCESS_ID) {
429 launch_info.SetProcessID(pid);
431 log->Printf("PlatformRemoteGDBServer::%s() pid %" PRIu64
432 " launched successfully",
436 log->Printf("PlatformRemoteGDBServer::%s() launch succeeded but we "
437 "didn't get a valid process id back!",
439 error.SetErrorString("failed to get PID");
442 error.SetErrorString(error_str.c_str());
444 log->Printf("PlatformRemoteGDBServer::%s() launch failed: %s",
445 __FUNCTION__, error.AsCString());
448 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
454 Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) {
455 if (!KillSpawnedProcess(pid))
456 return Status("failed to kill remote spawned process");
460 lldb::ProcessSP PlatformRemoteGDBServer::DebugProcess(
461 ProcessLaunchInfo &launch_info, Debugger &debugger,
462 Target *target, // Can be NULL, if NULL create a new target, else use
465 lldb::ProcessSP process_sp;
468 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
469 std::string connect_url;
470 if (!LaunchGDBServer(debugserver_pid, connect_url)) {
471 error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
474 if (target == nullptr) {
475 TargetSP new_target_sp;
477 error = debugger.GetTargetList().CreateTarget(
478 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
479 target = new_target_sp.get();
483 if (target && error.Success()) {
484 debugger.GetTargetList().SetSelectedTarget(target);
486 // The darwin always currently uses the GDB remote debugger plug-in
487 // so even when debugging locally we are debugging remotely!
488 process_sp = target->CreateProcess(launch_info.GetListener(),
489 "gdb-remote", nullptr);
492 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
493 // Retry the connect remote one time...
495 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
497 error = process_sp->Launch(launch_info);
498 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) {
499 printf("error: connect remote failed (%s)\n", error.AsCString());
500 KillSpawnedProcess(debugserver_pid);
506 error.SetErrorString("not connected to remote gdb server");
512 bool PlatformRemoteGDBServer::LaunchGDBServer(lldb::pid_t &pid,
513 std::string &connect_url) {
514 ArchSpec remote_arch = GetRemoteSystemArchitecture();
515 llvm::Triple &remote_triple = remote_arch.GetTriple();
518 std::string socket_name;
519 bool launch_result = false;
520 if (remote_triple.getVendor() == llvm::Triple::Apple &&
521 remote_triple.getOS() == llvm::Triple::IOS) {
522 // When remote debugging to iOS, we use a USB mux that always talks to
523 // localhost, so we will need the remote debugserver to accept connections
524 // only from localhost, no matter what our current hostname is
526 m_gdb_client.LaunchGDBServer("127.0.0.1", pid, port, socket_name);
528 // All other hosts should use their actual hostname
530 m_gdb_client.LaunchGDBServer(nullptr, pid, port, socket_name);
537 MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, port,
538 (socket_name.empty()) ? nullptr : socket_name.c_str());
542 bool PlatformRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) {
543 return m_gdb_client.KillSpawnedProcess(pid);
546 lldb::ProcessSP PlatformRemoteGDBServer::Attach(
547 ProcessAttachInfo &attach_info, Debugger &debugger,
548 Target *target, // Can be NULL, if NULL create a new target, else use
551 lldb::ProcessSP process_sp;
554 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
555 std::string connect_url;
556 if (!LaunchGDBServer(debugserver_pid, connect_url)) {
557 error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
560 if (target == nullptr) {
561 TargetSP new_target_sp;
563 error = debugger.GetTargetList().CreateTarget(
564 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
565 target = new_target_sp.get();
569 if (target && error.Success()) {
570 debugger.GetTargetList().SetSelectedTarget(target);
572 // The darwin always currently uses the GDB remote debugger plug-in
573 // so even when debugging locally we are debugging remotely!
575 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
576 "gdb-remote", nullptr);
578 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
579 if (error.Success()) {
580 ListenerSP listener_sp = attach_info.GetHijackListener();
582 process_sp->HijackProcessEvents(listener_sp);
583 error = process_sp->Attach(attach_info);
586 if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
587 KillSpawnedProcess(debugserver_pid);
593 error.SetErrorString("not connected to remote gdb server");
599 Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec,
601 Status error = m_gdb_client.MakeDirectory(file_spec, mode);
602 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
604 log->Printf("PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
606 file_spec.GetCString(), mode, error.GetError(),
611 Status PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec,
612 uint32_t &file_permissions) {
613 Status error = m_gdb_client.GetFilePermissions(file_spec, file_permissions);
614 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
616 log->Printf("PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
617 "file_permissions=%o) error = %u (%s)",
618 file_spec.GetCString(), file_permissions, error.GetError(),
623 Status PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec,
624 uint32_t file_permissions) {
625 Status error = m_gdb_client.SetFilePermissions(file_spec, file_permissions);
626 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
628 log->Printf("PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
629 "file_permissions=%o) error = %u (%s)",
630 file_spec.GetCString(), file_permissions, error.GetError(),
635 lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec,
636 uint32_t flags, uint32_t mode,
638 return m_gdb_client.OpenFile(file_spec, flags, mode, error);
641 bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) {
642 return m_gdb_client.CloseFile(fd, error);
646 PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) {
647 return m_gdb_client.GetFileSize(file_spec);
650 uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset,
651 void *dst, uint64_t dst_len,
653 return m_gdb_client.ReadFile(fd, offset, dst, dst_len, error);
656 uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset,
657 const void *src, uint64_t src_len,
659 return m_gdb_client.WriteFile(fd, offset, src, src_len, error);
662 Status PlatformRemoteGDBServer::PutFile(const FileSpec &source,
663 const FileSpec &destination,
664 uint32_t uid, uint32_t gid) {
665 return Platform::PutFile(source, destination, uid, gid);
668 Status PlatformRemoteGDBServer::CreateSymlink(
669 const FileSpec &src, // The name of the link is in src
670 const FileSpec &dst) // The symlink points to dst
672 Status error = m_gdb_client.CreateSymlink(src, dst);
673 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
675 log->Printf("PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
677 src.GetCString(), dst.GetCString(), error.GetError(),
682 Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) {
683 Status error = m_gdb_client.Unlink(file_spec);
684 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
686 log->Printf("PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
687 file_spec.GetCString(), error.GetError(), error.AsCString());
691 bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) {
692 return m_gdb_client.GetFileExists(file_spec);
695 Status PlatformRemoteGDBServer::RunShellCommand(
696 const char *command, // Shouldn't be NULL
698 working_dir, // Pass empty FileSpec to use the current working directory
699 int *status_ptr, // Pass NULL if you don't want the process exit status
700 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
703 *command_output, // Pass NULL if you don't want the command output
704 const Timeout<std::micro> &timeout) {
705 return m_gdb_client.RunShellCommand(command, working_dir, status_ptr,
706 signo_ptr, command_output, timeout);
709 void PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames() {
710 m_trap_handlers.push_back(ConstString("_sigtramp"));
713 const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() {
715 return Platform::GetRemoteUnixSignals();
717 if (m_remote_signals_sp)
718 return m_remote_signals_sp;
720 // If packet not implemented or JSON failed to parse, we'll guess the signal
721 // set based on the remote architecture.
722 m_remote_signals_sp = UnixSignals::Create(GetRemoteSystemArchitecture());
724 StringExtractorGDBRemote response;
725 auto result = m_gdb_client.SendPacketAndWaitForResponse("jSignalsInfo",
728 if (result != decltype(result)::Success ||
729 response.GetResponseType() != response.eResponse)
730 return m_remote_signals_sp;
732 auto object_sp = StructuredData::ParseJSON(response.GetStringRef());
733 if (!object_sp || !object_sp->IsValid())
734 return m_remote_signals_sp;
736 auto array_sp = object_sp->GetAsArray();
737 if (!array_sp || !array_sp->IsValid())
738 return m_remote_signals_sp;
740 auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
742 bool done = array_sp->ForEach(
743 [&remote_signals_sp](StructuredData::Object *object) -> bool {
744 if (!object || !object->IsValid())
747 auto dict = object->GetAsDictionary();
748 if (!dict || !dict->IsValid())
751 // Signal number and signal name are required.
753 if (!dict->GetValueForKeyAsInteger("signo", signo))
756 llvm::StringRef name;
757 if (!dict->GetValueForKeyAsString("name", name))
760 // We can live without short_name, description, etc.
761 bool suppress{false};
762 auto object_sp = dict->GetValueForKey("suppress");
763 if (object_sp && object_sp->IsValid())
764 suppress = object_sp->GetBooleanValue();
767 object_sp = dict->GetValueForKey("stop");
768 if (object_sp && object_sp->IsValid())
769 stop = object_sp->GetBooleanValue();
772 object_sp = dict->GetValueForKey("notify");
773 if (object_sp && object_sp->IsValid())
774 notify = object_sp->GetBooleanValue();
776 std::string description{""};
777 object_sp = dict->GetValueForKey("description");
778 if (object_sp && object_sp->IsValid())
779 description = object_sp->GetStringValue();
781 remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop,
782 notify, description.c_str());
787 m_remote_signals_sp = std::move(remote_signals_sp);
789 return m_remote_signals_sp;
792 std::string PlatformRemoteGDBServer::MakeGdbServerUrl(
793 const std::string &platform_scheme, const std::string &platform_hostname,
794 uint16_t port, const char *socket_name) {
795 const char *override_scheme =
796 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME");
797 const char *override_hostname =
798 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
799 const char *port_offset_c_str =
800 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
801 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
803 return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(),
804 override_hostname ? override_hostname
805 : platform_hostname.c_str(),
806 port + port_offset, socket_name);
809 std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
810 const char *hostname,
811 uint16_t port, const char *path) {
813 result.Printf("%s://%s", scheme, hostname);
815 result.Printf(":%u", port);
817 result.Write(path, strlen(path));
818 return result.GetString();
821 lldb::ProcessSP PlatformRemoteGDBServer::ConnectProcess(
822 llvm::StringRef connect_url, llvm::StringRef plugin_name,
823 lldb_private::Debugger &debugger, lldb_private::Target *target,
824 lldb_private::Status &error) {
825 if (!IsRemote() || !IsConnected()) {
826 error.SetErrorString("Not connected to remote gdb server");
829 return Platform::ConnectProcess(connect_url, plugin_name, debugger, target,
833 size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger,
835 std::vector<std::string> connection_urls;
836 GetPendingGdbServerList(connection_urls);
838 for (size_t i = 0; i < connection_urls.size(); ++i) {
839 ConnectProcess(connection_urls[i].c_str(), "", debugger, nullptr, error);
841 return i; // We already connected to i process succsessfully
843 return connection_urls.size();
846 size_t PlatformRemoteGDBServer::GetPendingGdbServerList(
847 std::vector<std::string> &connection_urls) {
848 std::vector<std::pair<uint16_t, std::string>> remote_servers;
849 m_gdb_client.QueryGDBServer(remote_servers);
850 for (const auto &gdbserver : remote_servers) {
851 const char *socket_name_cstr =
852 gdbserver.second.empty() ? nullptr : gdbserver.second.c_str();
853 connection_urls.emplace_back(
854 MakeGdbServerUrl(m_platform_scheme, m_platform_hostname,
855 gdbserver.first, socket_name_cstr));
857 return connection_urls.size();