1 //===-- PlatformRemoteGDBServer.cpp -----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "PlatformRemoteGDBServer.h"
11 #include "lldb/Host/Config.h"
14 // Other libraries and framework 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"
35 #include "Plugins/Process/Utility/GDBRemoteSignals.h"
38 using namespace lldb_private;
39 using namespace lldb_private::platform_gdb_server;
41 static bool g_initialized = false;
43 void PlatformRemoteGDBServer::Initialize() {
44 Platform::Initialize();
46 if (g_initialized == false) {
48 PluginManager::RegisterPlugin(
49 PlatformRemoteGDBServer::GetPluginNameStatic(),
50 PlatformRemoteGDBServer::GetDescriptionStatic(),
51 PlatformRemoteGDBServer::CreateInstance);
55 void PlatformRemoteGDBServer::Terminate() {
57 g_initialized = false;
58 PluginManager::UnregisterPlugin(PlatformRemoteGDBServer::CreateInstance);
61 Platform::Terminate();
64 PlatformSP PlatformRemoteGDBServer::CreateInstance(bool force,
65 const ArchSpec *arch) {
68 create = !arch->TripleVendorWasSpecified() && !arch->TripleOSWasSpecified();
71 return PlatformSP(new PlatformRemoteGDBServer());
75 ConstString PlatformRemoteGDBServer::GetPluginNameStatic() {
76 static ConstString g_name("remote-gdb-server");
80 const char *PlatformRemoteGDBServer::GetDescriptionStatic() {
81 return "A platform that uses the GDB remote protocol as the communication "
85 const char *PlatformRemoteGDBServer::GetDescription() {
86 if (m_platform_description.empty()) {
88 // Send the get description packet
92 if (!m_platform_description.empty())
93 return m_platform_description.c_str();
94 return GetDescriptionStatic();
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
103 // Nothing special to do here, just use the actual file and architecture
105 ModuleSpec resolved_module_spec(module_spec);
107 // Resolve any executable within an apk on Android?
108 // Host::ResolveExecutableInBundle (resolved_module_spec.GetFileSpec());
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);
117 if (exe_module_sp && exe_module_sp->GetObjectFile())
119 exe_module_sp.reset();
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());
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())
135 error.SetErrorToGenericError();
139 arch_names.PutCString(", ");
140 arch_names.PutCString(
141 resolved_module_spec.GetArchitecture().GetArchitectureName());
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());
151 error.SetErrorStringWithFormat(
152 "'%s' is not readable",
153 resolved_module_spec.GetFileSpec().GetPath().c_str());
157 error.SetErrorStringWithFormat(
158 "'%s' does not exist",
159 resolved_module_spec.GetFileSpec().GetPath().c_str());
165 bool PlatformRemoteGDBServer::GetModuleSpec(const FileSpec &module_file_spec,
166 const ArchSpec &arch,
167 ModuleSpec &module_spec) {
168 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
170 const auto module_path = module_file_spec.GetPath(false);
172 if (!m_gdb_client.GetModuleInfo(module_file_spec, arch, module_spec)) {
175 "PlatformRemoteGDBServer::%s - failed to get module info for %s:%s",
176 __FUNCTION__, module_path.c_str(),
177 arch.GetTriple().getTriple().c_str());
183 module_spec.Dump(stream);
185 "PlatformRemoteGDBServer::%s - got module info for (%s:%s) : %s",
186 __FUNCTION__, module_path.c_str(), arch.GetTriple().getTriple().c_str(),
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;
201 //------------------------------------------------------------------
202 /// Default Constructor
203 //------------------------------------------------------------------
204 PlatformRemoteGDBServer::PlatformRemoteGDBServer()
205 : Platform(false), // This is a remote platform
208 //------------------------------------------------------------------
211 /// The destructor is virtual since this class is designed to be
212 /// inherited from by the plug-in instance.
213 //------------------------------------------------------------------
214 PlatformRemoteGDBServer::~PlatformRemoteGDBServer() {}
216 bool PlatformRemoteGDBServer::GetSupportedArchitectureAtIndex(uint32_t idx,
218 ArchSpec remote_arch = m_gdb_client.GetSystemArchitecture();
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();
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.
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;
249 bool PlatformRemoteGDBServer::GetRemoteOSBuildString(std::string &s) {
250 return m_gdb_client.GetOSBuildString(s);
253 bool PlatformRemoteGDBServer::GetRemoteOSKernelDescription(std::string &s) {
254 return m_gdb_client.GetOSKernelDescription(s);
257 // Remote Platform subclasses need to override this function
258 ArchSpec PlatformRemoteGDBServer::GetRemoteSystemArchitecture() {
259 return m_gdb_client.GetSystemArchitecture();
262 FileSpec PlatformRemoteGDBServer::GetRemoteWorkingDirectory() {
264 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
265 FileSpec working_dir;
266 if (m_gdb_client.GetWorkingDir(working_dir) && log)
268 "PlatformRemoteGDBServer::GetRemoteWorkingDirectory() -> '%s'",
269 working_dir.GetCString());
272 return Platform::GetRemoteWorkingDirectory();
276 bool PlatformRemoteGDBServer::SetRemoteWorkingDirectory(
277 const FileSpec &working_dir) {
279 // Clear the working directory it case it doesn't get set correctly. This
281 // for use to re-read it
282 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
284 log->Printf("PlatformRemoteGDBServer::SetRemoteWorkingDirectory('%s')",
285 working_dir.GetCString());
286 return m_gdb_client.SetWorkingDir(working_dir) == 0;
288 return Platform::SetRemoteWorkingDirectory(working_dir);
291 bool PlatformRemoteGDBServer::IsConnected() const {
292 return m_gdb_client.IsConnected();
295 Status PlatformRemoteGDBServer::ConnectRemote(Args &args) {
298 error.SetErrorStringWithFormat("the platform is already connected to '%s', "
299 "execute 'platform disconnect' to close the "
300 "current connection",
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
308 const char *url = args.GetArgumentAtIndex(0);
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;
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
325 m_gdb_client.SetWorkingDir(m_working_dir);
327 m_gdb_client.Disconnect();
329 error.SetErrorString("handshake failed");
333 error.SetErrorString(
334 "\"platform connect\" takes a single argument: <connect-url>");
340 Status PlatformRemoteGDBServer::DisconnectRemote() {
342 m_gdb_client.Disconnect(&error);
343 m_remote_signals_sp.reset();
347 const char *PlatformRemoteGDBServer::GetHostname() {
348 m_gdb_client.GetHostname(m_name);
351 return m_name.c_str();
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;
360 if (m_gdb_client.GetUserName(uid, name))
361 return SetCachedUserName(uid, name.c_str(), name.size());
363 SetUserNameNotFound(uid); // Negative cache so we don't keep sending packets
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;
372 if (m_gdb_client.GetGroupName(gid, name))
373 return SetCachedGroupName(gid, name.c_str(), name.size());
375 SetGroupNameNotFound(gid); // Negative cache so we don't keep sending packets
379 uint32_t PlatformRemoteGDBServer::FindProcesses(
380 const ProcessInstanceInfoMatch &match_info,
381 ProcessInstanceInfoList &process_infos) {
382 return m_gdb_client.FindProcesses(match_info, process_infos);
385 bool PlatformRemoteGDBServer::GetProcessInfo(
386 lldb::pid_t pid, ProcessInstanceInfo &process_info) {
387 return m_gdb_client.GetProcessInfo(pid, process_info);
390 Status PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) {
391 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
395 log->Printf("PlatformRemoteGDBServer::%s() called", __FUNCTION__);
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)
402 switch (file_action->GetFD()) {
404 m_gdb_client.SetSTDIN(file_action->GetFileSpec());
407 m_gdb_client.SetSTDOUT(file_action->GetFileSpec());
410 m_gdb_client.SetSTDERR(file_action->GetFileSpec());
415 m_gdb_client.SetDisableASLR(
416 launch_info.GetFlags().Test(eLaunchFlagDisableASLR));
417 m_gdb_client.SetDetachOnError(
418 launch_info.GetFlags().Test(eLaunchFlagDetachOnError));
420 FileSpec working_dir = launch_info.GetWorkingDirectory();
422 m_gdb_client.SetWorkingDir(working_dir);
425 // Send the environment and the program + arguments after we connect
427 launch_info.GetEnvironmentEntries().GetConstArgumentVector();
430 const char *env_entry;
431 for (int i = 0; (env_entry = envp[i]); ++i) {
432 if (m_gdb_client.SendEnvironmentPacket(env_entry) != 0)
437 ArchSpec arch_spec = launch_info.GetArchitecture();
438 const char *arch_triple = arch_spec.GetTriple().str().c_str();
440 m_gdb_client.SendLaunchArchPacket(arch_triple);
443 "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'",
444 __FUNCTION__, arch_triple ? arch_triple : "<NULL>");
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);
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);
461 log->Printf("PlatformRemoteGDBServer::%s() pid %" PRIu64
462 " launched successfully",
466 log->Printf("PlatformRemoteGDBServer::%s() launch succeeded but we "
467 "didn't get a valid process id back!",
469 error.SetErrorString("failed to get PID");
472 error.SetErrorString(error_str.c_str());
474 log->Printf("PlatformRemoteGDBServer::%s() launch failed: %s",
475 __FUNCTION__, error.AsCString());
478 error.SetErrorStringWithFormat("'A' packet returned an error: %i",
484 Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) {
485 if (!KillSpawnedProcess(pid))
486 return Status("failed to kill remote spawned process");
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
495 lldb::ProcessSP process_sp;
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'",
504 if (target == NULL) {
505 TargetSP new_target_sp;
507 error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
508 NULL, new_target_sp);
509 target = new_target_sp.get();
513 if (target && error.Success()) {
514 debugger.GetTargetList().SetSelectedTarget(target);
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);
522 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
523 // Retry the connect remote one time...
525 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
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);
536 error.SetErrorString("not connected to remote gdb server");
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();
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
555 // only from localhost, no matter what our current hostname is
557 m_gdb_client.LaunchGDBServer("127.0.0.1", pid, port, socket_name);
559 // All other hosts should use their actual hostname
561 m_gdb_client.LaunchGDBServer(nullptr, pid, port, socket_name);
568 MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, port,
569 (socket_name.empty()) ? nullptr : socket_name.c_str());
573 bool PlatformRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) {
574 return m_gdb_client.KillSpawnedProcess(pid);
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
582 lldb::ProcessSP process_sp;
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'",
591 if (target == NULL) {
592 TargetSP new_target_sp;
594 error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
595 NULL, new_target_sp);
596 target = new_target_sp.get();
600 if (target && error.Success()) {
601 debugger.GetTargetList().SetSelectedTarget(target);
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);
608 error = process_sp->ConnectRemote(nullptr, connect_url.c_str());
609 if (error.Success()) {
610 ListenerSP listener_sp = attach_info.GetHijackListener();
612 process_sp->HijackProcessEvents(listener_sp);
613 error = process_sp->Attach(attach_info);
616 if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) {
617 KillSpawnedProcess(debugserver_pid);
623 error.SetErrorString("not connected to remote gdb server");
629 Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec,
631 Status error = m_gdb_client.MakeDirectory(file_spec, mode);
632 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
634 log->Printf("PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) "
636 file_spec.GetCString(), mode, error.GetError(),
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);
646 log->Printf("PlatformRemoteGDBServer::GetFilePermissions(path='%s', "
647 "file_permissions=%o) error = %u (%s)",
648 file_spec.GetCString(), file_permissions, error.GetError(),
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);
658 log->Printf("PlatformRemoteGDBServer::SetFilePermissions(path='%s', "
659 "file_permissions=%o) error = %u (%s)",
660 file_spec.GetCString(), file_permissions, error.GetError(),
665 lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec,
666 uint32_t flags, uint32_t mode,
668 return m_gdb_client.OpenFile(file_spec, flags, mode, error);
671 bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) {
672 return m_gdb_client.CloseFile(fd, error);
676 PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) {
677 return m_gdb_client.GetFileSize(file_spec);
680 uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset,
681 void *dst, uint64_t dst_len,
683 return m_gdb_client.ReadFile(fd, offset, dst, dst_len, error);
686 uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset,
687 const void *src, uint64_t src_len,
689 return m_gdb_client.WriteFile(fd, offset, src, src_len, error);
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);
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
702 Status error = m_gdb_client.CreateSymlink(src, dst);
703 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
705 log->Printf("PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') "
707 src.GetCString(), dst.GetCString(), error.GetError(),
712 Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) {
713 Status error = m_gdb_client.Unlink(file_spec);
714 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
716 log->Printf("PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)",
717 file_spec.GetCString(), error.GetError(), error.AsCString());
721 bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) {
722 return m_gdb_client.GetFileExists(file_spec);
725 Status PlatformRemoteGDBServer::RunShellCommand(
726 const char *command, // Shouldn't be NULL
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
733 *command_output, // Pass NULL if you don't want the command output
735 timeout_sec) // Timeout in seconds to wait for shell program to finish
737 return m_gdb_client.RunShellCommand(command, working_dir, status_ptr,
738 signo_ptr, command_output, timeout_sec);
741 void PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames() {
742 m_trap_handlers.push_back(ConstString("_sigtramp"));
745 const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() {
747 return Platform::GetRemoteUnixSignals();
749 if (m_remote_signals_sp)
750 return m_remote_signals_sp;
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());
756 StringExtractorGDBRemote response;
757 auto result = m_gdb_client.SendPacketAndWaitForResponse("jSignalsInfo",
760 if (result != decltype(result)::Success ||
761 response.GetResponseType() != response.eResponse)
762 return m_remote_signals_sp;
764 auto object_sp = StructuredData::ParseJSON(response.GetStringRef());
765 if (!object_sp || !object_sp->IsValid())
766 return m_remote_signals_sp;
768 auto array_sp = object_sp->GetAsArray();
769 if (!array_sp || !array_sp->IsValid())
770 return m_remote_signals_sp;
772 auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>();
774 bool done = array_sp->ForEach(
775 [&remote_signals_sp](StructuredData::Object *object) -> bool {
776 if (!object || !object->IsValid())
779 auto dict = object->GetAsDictionary();
780 if (!dict || !dict->IsValid())
783 // Signal number and signal name are required.
785 if (!dict->GetValueForKeyAsInteger("signo", signo))
788 llvm::StringRef name;
789 if (!dict->GetValueForKeyAsString("name", name))
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();
799 object_sp = dict->GetValueForKey("stop");
800 if (object_sp && object_sp->IsValid())
801 stop = object_sp->GetBooleanValue();
804 object_sp = dict->GetValueForKey("notify");
805 if (object_sp && object_sp->IsValid())
806 notify = object_sp->GetBooleanValue();
808 std::string description{""};
809 object_sp = dict->GetValueForKey("description");
810 if (object_sp && object_sp->IsValid())
811 description = object_sp->GetStringValue();
813 remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop,
814 notify, description.c_str());
819 m_remote_signals_sp = std::move(remote_signals_sp);
821 return m_remote_signals_sp;
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;
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);
841 std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme,
842 const char *hostname,
843 uint16_t port, const char *path) {
845 result.Printf("%s://%s", scheme, hostname);
847 result.Printf(":%u", port);
849 result.Write(path, strlen(path));
850 return result.GetString();
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");
861 return Platform::ConnectProcess(connect_url, plugin_name, debugger, target,
865 size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger,
867 std::vector<std::string> connection_urls;
868 GetPendingGdbServerList(connection_urls);
870 for (size_t i = 0; i < connection_urls.size(); ++i) {
871 ConnectProcess(connection_urls[i].c_str(), "", debugger, nullptr, error);
873 return i; // We already connected to i process succsessfully
875 return connection_urls.size();
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));
889 return connection_urls.size();