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(),
186 arch.GetTriple().getTriple().c_str(), stream.GetData());
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);
271 LLDB_LOGF(log, "PlatformRemoteGDBServer::SetRemoteWorkingDirectory('%s')",
272 working_dir.GetCString());
273 return m_gdb_client.SetWorkingDir(working_dir) == 0;
275 return Platform::SetRemoteWorkingDirectory(working_dir);
278 bool PlatformRemoteGDBServer::IsConnected() const {
279 return m_gdb_client.IsConnected();
282 Status PlatformRemoteGDBServer::ConnectRemote(Args &args) {
285 error.SetErrorStringWithFormat("the platform is already connected to '%s', "
286 "execute 'platform disconnect' to close the "
287 "current connection",
290 if (args.GetArgumentCount() == 1) {
291 m_gdb_client.SetConnection(new ConnectionFileDescriptor());
292 // we're going to reuse the hostname when we connect to the debugserver
295 const char *url = args.GetArgumentAtIndex(0);
297 return Status("URL is null.");
298 llvm::StringRef scheme, hostname, pathname;
299 if (!UriParser::Parse(url, scheme, hostname, port, pathname))
300 return Status("Invalid URL: %s", url);
301 m_platform_scheme = scheme;
302 m_platform_hostname = hostname;
305 const ConnectionStatus status = m_gdb_client.Connect(url, &error);
306 if (status == eConnectionStatusSuccess) {
307 if (m_gdb_client.HandshakeWithServer(&error)) {
308 m_gdb_client.GetHostInfo();
309 // If a working directory was set prior to connecting, send it down
312 m_gdb_client.SetWorkingDir(m_working_dir);
314 m_gdb_client.Disconnect();
316 error.SetErrorString("handshake failed");
320 error.SetErrorString(
321 "\"platform connect\" takes a single argument: <connect-url>");
327 Status PlatformRemoteGDBServer::DisconnectRemote() {
329 m_gdb_client.Disconnect(&error);
330 m_remote_signals_sp.reset();
334 const char *PlatformRemoteGDBServer::GetHostname() {
335 m_gdb_client.GetHostname(m_name);
338 return m_name.c_str();
341 llvm::Optional<std::string>
342 PlatformRemoteGDBServer::DoGetUserName(UserIDResolver::id_t uid) {
344 if (m_gdb_client.GetUserName(uid, name))
345 return std::move(name);
349 llvm::Optional<std::string>
350 PlatformRemoteGDBServer::DoGetGroupName(UserIDResolver::id_t gid) {
352 if (m_gdb_client.GetGroupName(gid, name))
353 return std::move(name);
357 uint32_t PlatformRemoteGDBServer::FindProcesses(
358 const ProcessInstanceInfoMatch &match_info,
359 ProcessInstanceInfoList &process_infos) {
360 return m_gdb_client.FindProcesses(match_info, process_infos);
363 bool PlatformRemoteGDBServer::GetProcessInfo(
364 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
365 return m_gdb_client.GetProcessInfo(pid, process_info);
368 Status PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) {
369 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
372 LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() called", __FUNCTION__);
374 auto num_file_actions = launch_info.GetNumFileActions();
375 for (decltype(num_file_actions) i = 0; i < num_file_actions; ++i) {
376 const auto file_action = launch_info.GetFileActionAtIndex(i);
377 if (file_action->GetAction() != FileAction::eFileActionOpen)
379 switch (file_action->GetFD()) {
381 m_gdb_client.SetSTDIN(file_action->GetFileSpec());
384 m_gdb_client.SetSTDOUT(file_action->GetFileSpec());
387 m_gdb_client.SetSTDERR(file_action->GetFileSpec());
392 m_gdb_client.SetDisableASLR(
393 launch_info.GetFlags().Test(eLaunchFlagDisableASLR));
394 m_gdb_client.SetDetachOnError(
395 launch_info.GetFlags().Test(eLaunchFlagDetachOnError));
397 FileSpec working_dir = launch_info.GetWorkingDirectory();
399 m_gdb_client.SetWorkingDir(working_dir);
402 // Send the environment and the program + arguments after we connect
403 m_gdb_client.SendEnvironment(launch_info.GetEnvironment());
405 ArchSpec arch_spec = launch_info.GetArchitecture();
406 const char *arch_triple = arch_spec.GetTriple().str().c_str();
408 m_gdb_client.SendLaunchArchPacket(arch_triple);
411 "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
412 __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
416 // Scope for the scoped timeout object
417 process_gdb_remote::GDBRemoteCommunication::ScopedTimeout timeout(
418 m_gdb_client, std::chrono::seconds(5));
419 arg_packet_err = m_gdb_client.SendArgumentsPacket(launch_info);
422 if (arg_packet_err == 0) {
423 std::string error_str;
424 if (m_gdb_client.GetLaunchSuccess(error_str)) {
425 const auto pid = m_gdb_client.GetCurrentProcessID(false);
426 if (pid != LLDB_INVALID_PROCESS_ID) {
427 launch_info.SetProcessID(pid);
429 "PlatformRemoteGDBServer::%s() pid %" PRIu64
430 " launched successfully",
434 "PlatformRemoteGDBServer::%s() launch succeeded but we "
435 "didn't get a valid process id back!",
437 error.SetErrorString("failed to get PID");
440 error.SetErrorString(error_str.c_str());
441 LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() launch failed: %s",
442 __FUNCTION__, error.AsCString());
445 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
451 Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) {
452 if (!KillSpawnedProcess(pid))
453 return Status("failed to kill remote spawned process");
457 lldb::ProcessSP PlatformRemoteGDBServer::DebugProcess(
458 ProcessLaunchInfo &launch_info, Debugger &debugger,
459 Target *target, // Can be NULL, if NULL create a new target, else use
462 lldb::ProcessSP process_sp;
465 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
466 std::string connect_url;
467 if (!LaunchGDBServer(debugserver_pid, connect_url)) {
468 error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
471 if (target == nullptr) {
472 TargetSP new_target_sp;
474 error = debugger.GetTargetList().CreateTarget(
475 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
476 target = new_target_sp.get();
480 if (target && error.Success()) {
481 debugger.GetTargetList().SetSelectedTarget(target);
483 // The darwin always currently uses the GDB remote debugger plug-in
484 // so even when debugging locally we are debugging remotely!
485 process_sp = target->CreateProcess(launch_info.GetListener(),
486 "gdb-remote", nullptr);
489 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
490 // Retry the connect remote one time...
492 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
494 error = process_sp->Launch(launch_info);
495 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) {
496 printf("error: connect remote failed (%s)\n", error.AsCString());
497 KillSpawnedProcess(debugserver_pid);
503 error.SetErrorString("not connected to remote gdb server");
509 bool PlatformRemoteGDBServer::LaunchGDBServer(lldb::pid_t &pid,
510 std::string &connect_url) {
511 ArchSpec remote_arch = GetRemoteSystemArchitecture();
512 llvm::Triple &remote_triple = remote_arch.GetTriple();
515 std::string socket_name;
516 bool launch_result = false;
517 if (remote_triple.getVendor() == llvm::Triple::Apple &&
518 remote_triple.getOS() == llvm::Triple::IOS) {
519 // When remote debugging to iOS, we use a USB mux that always talks to
520 // localhost, so we will need the remote debugserver to accept connections
521 // only from localhost, no matter what our current hostname is
523 m_gdb_client.LaunchGDBServer("127.0.0.1", pid, port, socket_name);
525 // All other hosts should use their actual hostname
527 m_gdb_client.LaunchGDBServer(nullptr, pid, port, socket_name);
534 MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, port,
535 (socket_name.empty()) ? nullptr : socket_name.c_str());
539 bool PlatformRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) {
540 return m_gdb_client.KillSpawnedProcess(pid);
543 lldb::ProcessSP PlatformRemoteGDBServer::Attach(
544 ProcessAttachInfo &attach_info, Debugger &debugger,
545 Target *target, // Can be NULL, if NULL create a new target, else use
548 lldb::ProcessSP process_sp;
551 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID;
552 std::string connect_url;
553 if (!LaunchGDBServer(debugserver_pid, connect_url)) {
554 error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'",
557 if (target == nullptr) {
558 TargetSP new_target_sp;
560 error = debugger.GetTargetList().CreateTarget(
561 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp);
562 target = new_target_sp.get();
566 if (target && error.Success()) {
567 debugger.GetTargetList().SetSelectedTarget(target);
569 // The darwin always currently uses the GDB remote debugger plug-in
570 // so even when debugging locally we are debugging remotely!
572 target->CreateProcess(attach_info.GetListenerForProcess(debugger),
573 "gdb-remote", nullptr);
575 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
576 if (error.Success()) {
577 ListenerSP listener_sp = attach_info.GetHijackListener();
579 process_sp->HijackProcessEvents(listener_sp);
580 error = process_sp->Attach(attach_info);
583 if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
584 KillSpawnedProcess(debugserver_pid);
590 error.SetErrorString("not connected to remote gdb server");
596 Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec,
598 Status error = m_gdb_client.MakeDirectory(file_spec, mode);
599 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
601 "PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
603 file_spec.GetCString(), mode, error.GetError(), error.AsCString());
607 Status PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec,
608 uint32_t &file_permissions) {
609 Status error = m_gdb_client.GetFilePermissions(file_spec, file_permissions);
610 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
612 "PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
613 "file_permissions=%o) error = %u (%s)",
614 file_spec.GetCString(), file_permissions, error.GetError(),
619 Status PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec,
620 uint32_t file_permissions) {
621 Status error = m_gdb_client.SetFilePermissions(file_spec, file_permissions);
622 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
624 "PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
625 "file_permissions=%o) error = %u (%s)",
626 file_spec.GetCString(), file_permissions, error.GetError(),
631 lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec,
632 File::OpenOptions flags,
635 return m_gdb_client.OpenFile(file_spec, flags, mode, error);
638 bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) {
639 return m_gdb_client.CloseFile(fd, error);
643 PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) {
644 return m_gdb_client.GetFileSize(file_spec);
647 uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset,
648 void *dst, uint64_t dst_len,
650 return m_gdb_client.ReadFile(fd, offset, dst, dst_len, error);
653 uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset,
654 const void *src, uint64_t src_len,
656 return m_gdb_client.WriteFile(fd, offset, src, src_len, error);
659 Status PlatformRemoteGDBServer::PutFile(const FileSpec &source,
660 const FileSpec &destination,
661 uint32_t uid, uint32_t gid) {
662 return Platform::PutFile(source, destination, uid, gid);
665 Status PlatformRemoteGDBServer::CreateSymlink(
666 const FileSpec &src, // The name of the link is in src
667 const FileSpec &dst) // The symlink points to dst
669 Status error = m_gdb_client.CreateSymlink(src, dst);
670 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
672 "PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
674 src.GetCString(), dst.GetCString(), error.GetError(),
679 Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) {
680 Status error = m_gdb_client.Unlink(file_spec);
681 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
682 LLDB_LOGF(log, "PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
683 file_spec.GetCString(), error.GetError(), error.AsCString());
687 bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) {
688 return m_gdb_client.GetFileExists(file_spec);
691 Status PlatformRemoteGDBServer::RunShellCommand(
692 const char *command, // Shouldn't be NULL
694 working_dir, // Pass empty FileSpec to use the current working directory
695 int *status_ptr, // Pass NULL if you don't want the process exit status
696 int *signo_ptr, // Pass NULL if you don't want the signal that caused the
699 *command_output, // Pass NULL if you don't want the command output
700 const Timeout<std::micro> &timeout) {
701 return m_gdb_client.RunShellCommand(command, working_dir, status_ptr,
702 signo_ptr, command_output, timeout);
705 void PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames() {
706 m_trap_handlers.push_back(ConstString("_sigtramp"));
709 const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() {
711 return Platform::GetRemoteUnixSignals();
713 if (m_remote_signals_sp)
714 return m_remote_signals_sp;
716 // If packet not implemented or JSON failed to parse, we'll guess the signal
717 // set based on the remote architecture.
718 m_remote_signals_sp = UnixSignals::Create(GetRemoteSystemArchitecture());
720 StringExtractorGDBRemote response;
721 auto result = m_gdb_client.SendPacketAndWaitForResponse("jSignalsInfo",
724 if (result != decltype(result)::Success ||
725 response.GetResponseType() != response.eResponse)
726 return m_remote_signals_sp;
728 auto object_sp = StructuredData::ParseJSON(response.GetStringRef());
729 if (!object_sp || !object_sp->IsValid())
730 return m_remote_signals_sp;
732 auto array_sp = object_sp->GetAsArray();
733 if (!array_sp || !array_sp->IsValid())
734 return m_remote_signals_sp;
736 auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
738 bool done = array_sp->ForEach(
739 [&remote_signals_sp](StructuredData::Object *object) -> bool {
740 if (!object || !object->IsValid())
743 auto dict = object->GetAsDictionary();
744 if (!dict || !dict->IsValid())
747 // Signal number and signal name are required.
749 if (!dict->GetValueForKeyAsInteger("signo", signo))
752 llvm::StringRef name;
753 if (!dict->GetValueForKeyAsString("name", name))
756 // We can live without short_name, description, etc.
757 bool suppress{false};
758 auto object_sp = dict->GetValueForKey("suppress");
759 if (object_sp && object_sp->IsValid())
760 suppress = object_sp->GetBooleanValue();
763 object_sp = dict->GetValueForKey("stop");
764 if (object_sp && object_sp->IsValid())
765 stop = object_sp->GetBooleanValue();
768 object_sp = dict->GetValueForKey("notify");
769 if (object_sp && object_sp->IsValid())
770 notify = object_sp->GetBooleanValue();
772 std::string description{""};
773 object_sp = dict->GetValueForKey("description");
774 if (object_sp && object_sp->IsValid())
775 description = object_sp->GetStringValue();
777 remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop,
778 notify, description.c_str());
783 m_remote_signals_sp = std::move(remote_signals_sp);
785 return m_remote_signals_sp;
788 std::string PlatformRemoteGDBServer::MakeGdbServerUrl(
789 const std::string &platform_scheme, const std::string &platform_hostname,
790 uint16_t port, const char *socket_name) {
791 const char *override_scheme =
792 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME");
793 const char *override_hostname =
794 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME");
795 const char *port_offset_c_str =
796 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET");
797 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0;
799 return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(),
800 override_hostname ? override_hostname
801 : platform_hostname.c_str(),
802 port + port_offset, socket_name);
805 std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
806 const char *hostname,
807 uint16_t port, const char *path) {
809 result.Printf("%s://%s", scheme, hostname);
811 result.Printf(":%u", port);
813 result.Write(path, strlen(path));
814 return result.GetString();
817 lldb::ProcessSP PlatformRemoteGDBServer::ConnectProcess(
818 llvm::StringRef connect_url, llvm::StringRef plugin_name,
819 lldb_private::Debugger &debugger, lldb_private::Target *target,
820 lldb_private::Status &error) {
821 if (!IsRemote() || !IsConnected()) {
822 error.SetErrorString("Not connected to remote gdb server");
825 return Platform::ConnectProcess(connect_url, plugin_name, debugger, target,
829 size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger,
831 std::vector<std::string> connection_urls;
832 GetPendingGdbServerList(connection_urls);
834 for (size_t i = 0; i < connection_urls.size(); ++i) {
835 ConnectProcess(connection_urls[i].c_str(), "", debugger, nullptr, error);
837 return i; // We already connected to i process succsessfully
839 return connection_urls.size();
842 size_t PlatformRemoteGDBServer::GetPendingGdbServerList(
843 std::vector<std::string> &connection_urls) {
844 std::vector<std::pair<uint16_t, std::string>> remote_servers;
845 m_gdb_client.QueryGDBServer(remote_servers);
846 for (const auto &gdbserver : remote_servers) {
847 const char *socket_name_cstr =
848 gdbserver.second.empty() ? nullptr : gdbserver.second.c_str();
849 connection_urls.emplace_back(
850 MakeGdbServerUrl(m_platform_scheme, m_platform_hostname,
851 gdbserver.first, socket_name_cstr));
853 return connection_urls.size();