1 //===-- PlatformRemoteGDBServer.cpp ---------------------------------------===// 2 // 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 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "PlatformRemoteGDBServer.h" 10 #include "lldb/Host/Config.h" 11 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" 31 32 #include "Plugins/Process/Utility/GDBRemoteSignals.h" 33 #include "Plugins/Process/gdb-remote/ProcessGDBRemote.h" 34 35 using namespace lldb; 36 using namespace lldb_private; 37 using namespace lldb_private::platform_gdb_server; 38 39 LLDB_PLUGIN_DEFINE_ADV(PlatformRemoteGDBServer, PlatformGDB) 40 41 static bool g_initialized = false; 42 43 void PlatformRemoteGDBServer::Initialize() { 44 Platform::Initialize(); 45 46 if (!g_initialized) { 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 llvm::StringRef PlatformRemoteGDBServer::GetDescriptionStatic() { 76 return "A platform that uses the GDB remote protocol as the communication " 77 "transport."; 78 } 79 80 llvm::StringRef PlatformRemoteGDBServer::GetDescription() { 81 if (m_platform_description.empty()) { 82 if (IsConnected()) { 83 // Send the get description packet 84 } 85 } 86 87 if (!m_platform_description.empty()) 88 return m_platform_description.c_str(); 89 return GetDescriptionStatic(); 90 } 91 92 bool PlatformRemoteGDBServer::GetModuleSpec(const FileSpec &module_file_spec, 93 const ArchSpec &arch, 94 ModuleSpec &module_spec) { 95 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 96 97 const auto module_path = module_file_spec.GetPath(false); 98 99 if (!m_gdb_client.GetModuleInfo(module_file_spec, arch, module_spec)) { 100 LLDB_LOGF( 101 log, 102 "PlatformRemoteGDBServer::%s - failed to get module info for %s:%s", 103 __FUNCTION__, module_path.c_str(), 104 arch.GetTriple().getTriple().c_str()); 105 return false; 106 } 107 108 if (log) { 109 StreamString stream; 110 module_spec.Dump(stream); 111 LLDB_LOGF(log, 112 "PlatformRemoteGDBServer::%s - got module info for (%s:%s) : %s", 113 __FUNCTION__, module_path.c_str(), 114 arch.GetTriple().getTriple().c_str(), stream.GetData()); 115 } 116 117 return true; 118 } 119 120 Status PlatformRemoteGDBServer::GetFileWithUUID(const FileSpec &platform_file, 121 const UUID *uuid_ptr, 122 FileSpec &local_file) { 123 // Default to the local case 124 local_file = platform_file; 125 return Status(); 126 } 127 128 /// Default Constructor 129 PlatformRemoteGDBServer::PlatformRemoteGDBServer() 130 : Platform(false), // This is a remote platform 131 m_gdb_client() { 132 m_gdb_client.SetPacketTimeout( 133 process_gdb_remote::ProcessGDBRemote::GetPacketTimeout()); 134 } 135 136 /// Destructor. 137 /// 138 /// The destructor is virtual since this class is designed to be 139 /// inherited from by the plug-in instance. 140 PlatformRemoteGDBServer::~PlatformRemoteGDBServer() = default; 141 142 size_t PlatformRemoteGDBServer::GetSoftwareBreakpointTrapOpcode( 143 Target &target, BreakpointSite *bp_site) { 144 // This isn't needed if the z/Z packets are supported in the GDB remote 145 // server. But we might need a packet to detect this. 146 return 0; 147 } 148 149 bool PlatformRemoteGDBServer::GetRemoteOSVersion() { 150 m_os_version = m_gdb_client.GetOSVersion(); 151 return !m_os_version.empty(); 152 } 153 154 llvm::Optional<std::string> PlatformRemoteGDBServer::GetRemoteOSBuildString() { 155 return m_gdb_client.GetOSBuildString(); 156 } 157 158 llvm::Optional<std::string> 159 PlatformRemoteGDBServer::GetRemoteOSKernelDescription() { 160 return m_gdb_client.GetOSKernelDescription(); 161 } 162 163 // Remote Platform subclasses need to override this function 164 ArchSpec PlatformRemoteGDBServer::GetRemoteSystemArchitecture() { 165 return m_gdb_client.GetSystemArchitecture(); 166 } 167 168 FileSpec PlatformRemoteGDBServer::GetRemoteWorkingDirectory() { 169 if (IsConnected()) { 170 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 171 FileSpec working_dir; 172 if (m_gdb_client.GetWorkingDir(working_dir) && log) 173 LLDB_LOGF(log, 174 "PlatformRemoteGDBServer::GetRemoteWorkingDirectory() -> '%s'", 175 working_dir.GetCString()); 176 return working_dir; 177 } else { 178 return Platform::GetRemoteWorkingDirectory(); 179 } 180 } 181 182 bool PlatformRemoteGDBServer::SetRemoteWorkingDirectory( 183 const FileSpec &working_dir) { 184 if (IsConnected()) { 185 // Clear the working directory it case it doesn't get set correctly. This 186 // will for use to re-read it 187 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 188 LLDB_LOGF(log, "PlatformRemoteGDBServer::SetRemoteWorkingDirectory('%s')", 189 working_dir.GetCString()); 190 return m_gdb_client.SetWorkingDir(working_dir) == 0; 191 } else 192 return Platform::SetRemoteWorkingDirectory(working_dir); 193 } 194 195 bool PlatformRemoteGDBServer::IsConnected() const { 196 return m_gdb_client.IsConnected(); 197 } 198 199 Status PlatformRemoteGDBServer::ConnectRemote(Args &args) { 200 Status error; 201 if (IsConnected()) { 202 error.SetErrorStringWithFormat("the platform is already connected to '%s', " 203 "execute 'platform disconnect' to close the " 204 "current connection", 205 GetHostname()); 206 return error; 207 } 208 209 if (args.GetArgumentCount() != 1) { 210 error.SetErrorString( 211 "\"platform connect\" takes a single argument: <connect-url>"); 212 return error; 213 } 214 215 const char *url = args.GetArgumentAtIndex(0); 216 if (!url) 217 return Status("URL is null."); 218 219 llvm::Optional<URI> parsed_url = URI::Parse(url); 220 if (!parsed_url) 221 return Status("Invalid URL: %s", url); 222 223 // We're going to reuse the hostname when we connect to the debugserver. 224 m_platform_scheme = parsed_url->scheme.str(); 225 m_platform_hostname = parsed_url->hostname.str(); 226 227 m_gdb_client.SetConnection(std::make_unique<ConnectionFileDescriptor>()); 228 if (repro::Reproducer::Instance().IsReplaying()) { 229 error = m_gdb_replay_server.Connect(m_gdb_client); 230 if (error.Success()) 231 m_gdb_replay_server.StartAsyncThread(); 232 } else { 233 if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { 234 repro::GDBRemoteProvider &provider = 235 g->GetOrCreate<repro::GDBRemoteProvider>(); 236 m_gdb_client.SetPacketRecorder(provider.GetNewPacketRecorder()); 237 } 238 m_gdb_client.Connect(url, &error); 239 } 240 241 if (error.Fail()) 242 return error; 243 244 if (m_gdb_client.HandshakeWithServer(&error)) { 245 m_gdb_client.GetHostInfo(); 246 // If a working directory was set prior to connecting, send it down 247 // now. 248 if (m_working_dir) 249 m_gdb_client.SetWorkingDir(m_working_dir); 250 251 m_supported_architectures.clear(); 252 ArchSpec remote_arch = m_gdb_client.GetSystemArchitecture(); 253 if (remote_arch) { 254 m_supported_architectures.push_back(remote_arch); 255 if (remote_arch.GetTriple().isArch64Bit()) 256 m_supported_architectures.push_back( 257 ArchSpec(remote_arch.GetTriple().get32BitArchVariant())); 258 } 259 } else { 260 m_gdb_client.Disconnect(); 261 if (error.Success()) 262 error.SetErrorString("handshake failed"); 263 } 264 return error; 265 } 266 267 Status PlatformRemoteGDBServer::DisconnectRemote() { 268 Status error; 269 m_gdb_client.Disconnect(&error); 270 m_remote_signals_sp.reset(); 271 return error; 272 } 273 274 const char *PlatformRemoteGDBServer::GetHostname() { 275 m_gdb_client.GetHostname(m_name); 276 if (m_name.empty()) 277 return nullptr; 278 return m_name.c_str(); 279 } 280 281 llvm::Optional<std::string> 282 PlatformRemoteGDBServer::DoGetUserName(UserIDResolver::id_t uid) { 283 std::string name; 284 if (m_gdb_client.GetUserName(uid, name)) 285 return std::move(name); 286 return llvm::None; 287 } 288 289 llvm::Optional<std::string> 290 PlatformRemoteGDBServer::DoGetGroupName(UserIDResolver::id_t gid) { 291 std::string name; 292 if (m_gdb_client.GetGroupName(gid, name)) 293 return std::move(name); 294 return llvm::None; 295 } 296 297 uint32_t PlatformRemoteGDBServer::FindProcesses( 298 const ProcessInstanceInfoMatch &match_info, 299 ProcessInstanceInfoList &process_infos) { 300 return m_gdb_client.FindProcesses(match_info, process_infos); 301 } 302 303 bool PlatformRemoteGDBServer::GetProcessInfo( 304 lldb::pid_t pid, ProcessInstanceInfo &process_info) { 305 return m_gdb_client.GetProcessInfo(pid, process_info); 306 } 307 308 Status PlatformRemoteGDBServer::LaunchProcess(ProcessLaunchInfo &launch_info) { 309 Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); 310 Status error; 311 312 LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() called", __FUNCTION__); 313 314 auto num_file_actions = launch_info.GetNumFileActions(); 315 for (decltype(num_file_actions) i = 0; i < num_file_actions; ++i) { 316 const auto file_action = launch_info.GetFileActionAtIndex(i); 317 if (file_action->GetAction() != FileAction::eFileActionOpen) 318 continue; 319 switch (file_action->GetFD()) { 320 case STDIN_FILENO: 321 m_gdb_client.SetSTDIN(file_action->GetFileSpec()); 322 break; 323 case STDOUT_FILENO: 324 m_gdb_client.SetSTDOUT(file_action->GetFileSpec()); 325 break; 326 case STDERR_FILENO: 327 m_gdb_client.SetSTDERR(file_action->GetFileSpec()); 328 break; 329 } 330 } 331 332 m_gdb_client.SetDisableASLR( 333 launch_info.GetFlags().Test(eLaunchFlagDisableASLR)); 334 m_gdb_client.SetDetachOnError( 335 launch_info.GetFlags().Test(eLaunchFlagDetachOnError)); 336 337 FileSpec working_dir = launch_info.GetWorkingDirectory(); 338 if (working_dir) { 339 m_gdb_client.SetWorkingDir(working_dir); 340 } 341 342 // Send the environment and the program + arguments after we connect 343 m_gdb_client.SendEnvironment(launch_info.GetEnvironment()); 344 345 ArchSpec arch_spec = launch_info.GetArchitecture(); 346 const char *arch_triple = arch_spec.GetTriple().str().c_str(); 347 348 m_gdb_client.SendLaunchArchPacket(arch_triple); 349 LLDB_LOGF( 350 log, 351 "PlatformRemoteGDBServer::%s() set launch architecture triple to '%s'", 352 __FUNCTION__, arch_triple ? arch_triple : "<NULL>"); 353 354 int arg_packet_err; 355 { 356 // Scope for the scoped timeout object 357 process_gdb_remote::GDBRemoteCommunication::ScopedTimeout timeout( 358 m_gdb_client, std::chrono::seconds(5)); 359 arg_packet_err = m_gdb_client.SendArgumentsPacket(launch_info); 360 } 361 362 if (arg_packet_err == 0) { 363 std::string error_str; 364 if (m_gdb_client.GetLaunchSuccess(error_str)) { 365 const auto pid = m_gdb_client.GetCurrentProcessID(false); 366 if (pid != LLDB_INVALID_PROCESS_ID) { 367 launch_info.SetProcessID(pid); 368 LLDB_LOGF(log, 369 "PlatformRemoteGDBServer::%s() pid %" PRIu64 370 " launched successfully", 371 __FUNCTION__, pid); 372 } else { 373 LLDB_LOGF(log, 374 "PlatformRemoteGDBServer::%s() launch succeeded but we " 375 "didn't get a valid process id back!", 376 __FUNCTION__); 377 error.SetErrorString("failed to get PID"); 378 } 379 } else { 380 error.SetErrorString(error_str.c_str()); 381 LLDB_LOGF(log, "PlatformRemoteGDBServer::%s() launch failed: %s", 382 __FUNCTION__, error.AsCString()); 383 } 384 } else { 385 error.SetErrorStringWithFormat("'A' packet returned an error: %i", 386 arg_packet_err); 387 } 388 return error; 389 } 390 391 Status PlatformRemoteGDBServer::KillProcess(const lldb::pid_t pid) { 392 if (!KillSpawnedProcess(pid)) 393 return Status("failed to kill remote spawned process"); 394 return Status(); 395 } 396 397 lldb::ProcessSP 398 PlatformRemoteGDBServer::DebugProcess(ProcessLaunchInfo &launch_info, 399 Debugger &debugger, Target &target, 400 Status &error) { 401 lldb::ProcessSP process_sp; 402 if (IsRemote()) { 403 if (IsConnected()) { 404 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID; 405 std::string connect_url; 406 if (!LaunchGDBServer(debugserver_pid, connect_url)) { 407 error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'", 408 GetHostname()); 409 } else { 410 // The darwin always currently uses the GDB remote debugger plug-in 411 // so even when debugging locally we are debugging remotely! 412 process_sp = target.CreateProcess(launch_info.GetListener(), 413 "gdb-remote", nullptr, true); 414 415 if (process_sp) { 416 error = process_sp->ConnectRemote(connect_url.c_str()); 417 // Retry the connect remote one time... 418 if (error.Fail()) 419 error = process_sp->ConnectRemote(connect_url.c_str()); 420 if (error.Success()) 421 error = process_sp->Launch(launch_info); 422 else if (debugserver_pid != LLDB_INVALID_PROCESS_ID) { 423 printf("error: connect remote failed (%s)\n", error.AsCString()); 424 KillSpawnedProcess(debugserver_pid); 425 } 426 } 427 } 428 } else { 429 error.SetErrorString("not connected to remote gdb server"); 430 } 431 } 432 return process_sp; 433 } 434 435 bool PlatformRemoteGDBServer::LaunchGDBServer(lldb::pid_t &pid, 436 std::string &connect_url) { 437 ArchSpec remote_arch = GetRemoteSystemArchitecture(); 438 llvm::Triple &remote_triple = remote_arch.GetTriple(); 439 440 uint16_t port = 0; 441 std::string socket_name; 442 bool launch_result = false; 443 if (remote_triple.getVendor() == llvm::Triple::Apple && 444 remote_triple.getOS() == llvm::Triple::IOS) { 445 // When remote debugging to iOS, we use a USB mux that always talks to 446 // localhost, so we will need the remote debugserver to accept connections 447 // only from localhost, no matter what our current hostname is 448 launch_result = 449 m_gdb_client.LaunchGDBServer("127.0.0.1", pid, port, socket_name); 450 } else { 451 // All other hosts should use their actual hostname 452 launch_result = 453 m_gdb_client.LaunchGDBServer(nullptr, pid, port, socket_name); 454 } 455 456 if (!launch_result) 457 return false; 458 459 connect_url = 460 MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, port, 461 (socket_name.empty()) ? nullptr : socket_name.c_str()); 462 return true; 463 } 464 465 bool PlatformRemoteGDBServer::KillSpawnedProcess(lldb::pid_t pid) { 466 return m_gdb_client.KillSpawnedProcess(pid); 467 } 468 469 lldb::ProcessSP PlatformRemoteGDBServer::Attach( 470 ProcessAttachInfo &attach_info, Debugger &debugger, 471 Target *target, // Can be NULL, if NULL create a new target, else use 472 // existing one 473 Status &error) { 474 lldb::ProcessSP process_sp; 475 if (IsRemote()) { 476 if (IsConnected()) { 477 lldb::pid_t debugserver_pid = LLDB_INVALID_PROCESS_ID; 478 std::string connect_url; 479 if (!LaunchGDBServer(debugserver_pid, connect_url)) { 480 error.SetErrorStringWithFormat("unable to launch a GDB server on '%s'", 481 GetHostname()); 482 } else { 483 if (target == nullptr) { 484 TargetSP new_target_sp; 485 486 error = debugger.GetTargetList().CreateTarget( 487 debugger, "", "", eLoadDependentsNo, nullptr, new_target_sp); 488 target = new_target_sp.get(); 489 } else 490 error.Clear(); 491 492 if (target && error.Success()) { 493 // The darwin always currently uses the GDB remote debugger plug-in 494 // so even when debugging locally we are debugging remotely! 495 process_sp = 496 target->CreateProcess(attach_info.GetListenerForProcess(debugger), 497 "gdb-remote", nullptr, true); 498 if (process_sp) { 499 error = process_sp->ConnectRemote(connect_url.c_str()); 500 if (error.Success()) { 501 ListenerSP listener_sp = attach_info.GetHijackListener(); 502 if (listener_sp) 503 process_sp->HijackProcessEvents(listener_sp); 504 error = process_sp->Attach(attach_info); 505 } 506 507 if (error.Fail() && debugserver_pid != LLDB_INVALID_PROCESS_ID) { 508 KillSpawnedProcess(debugserver_pid); 509 } 510 } 511 } 512 } 513 } else { 514 error.SetErrorString("not connected to remote gdb server"); 515 } 516 } 517 return process_sp; 518 } 519 520 Status PlatformRemoteGDBServer::MakeDirectory(const FileSpec &file_spec, 521 uint32_t mode) { 522 Status error = m_gdb_client.MakeDirectory(file_spec, mode); 523 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 524 LLDB_LOGF(log, 525 "PlatformRemoteGDBServer::MakeDirectory(path='%s', mode=%o) " 526 "error = %u (%s)", 527 file_spec.GetCString(), mode, error.GetError(), error.AsCString()); 528 return error; 529 } 530 531 Status PlatformRemoteGDBServer::GetFilePermissions(const FileSpec &file_spec, 532 uint32_t &file_permissions) { 533 Status error = m_gdb_client.GetFilePermissions(file_spec, file_permissions); 534 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 535 LLDB_LOGF(log, 536 "PlatformRemoteGDBServer::GetFilePermissions(path='%s', " 537 "file_permissions=%o) error = %u (%s)", 538 file_spec.GetCString(), file_permissions, error.GetError(), 539 error.AsCString()); 540 return error; 541 } 542 543 Status PlatformRemoteGDBServer::SetFilePermissions(const FileSpec &file_spec, 544 uint32_t file_permissions) { 545 Status error = m_gdb_client.SetFilePermissions(file_spec, file_permissions); 546 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 547 LLDB_LOGF(log, 548 "PlatformRemoteGDBServer::SetFilePermissions(path='%s', " 549 "file_permissions=%o) error = %u (%s)", 550 file_spec.GetCString(), file_permissions, error.GetError(), 551 error.AsCString()); 552 return error; 553 } 554 555 lldb::user_id_t PlatformRemoteGDBServer::OpenFile(const FileSpec &file_spec, 556 File::OpenOptions flags, 557 uint32_t mode, 558 Status &error) { 559 return m_gdb_client.OpenFile(file_spec, flags, mode, error); 560 } 561 562 bool PlatformRemoteGDBServer::CloseFile(lldb::user_id_t fd, Status &error) { 563 return m_gdb_client.CloseFile(fd, error); 564 } 565 566 lldb::user_id_t 567 PlatformRemoteGDBServer::GetFileSize(const FileSpec &file_spec) { 568 return m_gdb_client.GetFileSize(file_spec); 569 } 570 571 void PlatformRemoteGDBServer::AutoCompleteDiskFileOrDirectory( 572 CompletionRequest &request, bool only_dir) { 573 m_gdb_client.AutoCompleteDiskFileOrDirectory(request, only_dir); 574 } 575 576 uint64_t PlatformRemoteGDBServer::ReadFile(lldb::user_id_t fd, uint64_t offset, 577 void *dst, uint64_t dst_len, 578 Status &error) { 579 return m_gdb_client.ReadFile(fd, offset, dst, dst_len, error); 580 } 581 582 uint64_t PlatformRemoteGDBServer::WriteFile(lldb::user_id_t fd, uint64_t offset, 583 const void *src, uint64_t src_len, 584 Status &error) { 585 return m_gdb_client.WriteFile(fd, offset, src, src_len, error); 586 } 587 588 Status PlatformRemoteGDBServer::PutFile(const FileSpec &source, 589 const FileSpec &destination, 590 uint32_t uid, uint32_t gid) { 591 return Platform::PutFile(source, destination, uid, gid); 592 } 593 594 Status PlatformRemoteGDBServer::CreateSymlink( 595 const FileSpec &src, // The name of the link is in src 596 const FileSpec &dst) // The symlink points to dst 597 { 598 Status error = m_gdb_client.CreateSymlink(src, dst); 599 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 600 LLDB_LOGF(log, 601 "PlatformRemoteGDBServer::CreateSymlink(src='%s', dst='%s') " 602 "error = %u (%s)", 603 src.GetCString(), dst.GetCString(), error.GetError(), 604 error.AsCString()); 605 return error; 606 } 607 608 Status PlatformRemoteGDBServer::Unlink(const FileSpec &file_spec) { 609 Status error = m_gdb_client.Unlink(file_spec); 610 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 611 LLDB_LOGF(log, "PlatformRemoteGDBServer::Unlink(path='%s') error = %u (%s)", 612 file_spec.GetCString(), error.GetError(), error.AsCString()); 613 return error; 614 } 615 616 bool PlatformRemoteGDBServer::GetFileExists(const FileSpec &file_spec) { 617 return m_gdb_client.GetFileExists(file_spec); 618 } 619 620 Status PlatformRemoteGDBServer::RunShellCommand( 621 llvm::StringRef shell, llvm::StringRef command, 622 const FileSpec & 623 working_dir, // Pass empty FileSpec to use the current working directory 624 int *status_ptr, // Pass NULL if you don't want the process exit status 625 int *signo_ptr, // Pass NULL if you don't want the signal that caused the 626 // process to exit 627 std::string 628 *command_output, // Pass NULL if you don't want the command output 629 const Timeout<std::micro> &timeout) { 630 return m_gdb_client.RunShellCommand(command, working_dir, status_ptr, 631 signo_ptr, command_output, timeout); 632 } 633 634 void PlatformRemoteGDBServer::CalculateTrapHandlerSymbolNames() { 635 m_trap_handlers.push_back(ConstString("_sigtramp")); 636 } 637 638 const UnixSignalsSP &PlatformRemoteGDBServer::GetRemoteUnixSignals() { 639 if (!IsConnected()) 640 return Platform::GetRemoteUnixSignals(); 641 642 if (m_remote_signals_sp) 643 return m_remote_signals_sp; 644 645 // If packet not implemented or JSON failed to parse, we'll guess the signal 646 // set based on the remote architecture. 647 m_remote_signals_sp = UnixSignals::Create(GetRemoteSystemArchitecture()); 648 649 StringExtractorGDBRemote response; 650 auto result = 651 m_gdb_client.SendPacketAndWaitForResponse("jSignalsInfo", response); 652 653 if (result != decltype(result)::Success || 654 response.GetResponseType() != response.eResponse) 655 return m_remote_signals_sp; 656 657 auto object_sp = 658 StructuredData::ParseJSON(std::string(response.GetStringRef())); 659 if (!object_sp || !object_sp->IsValid()) 660 return m_remote_signals_sp; 661 662 auto array_sp = object_sp->GetAsArray(); 663 if (!array_sp || !array_sp->IsValid()) 664 return m_remote_signals_sp; 665 666 auto remote_signals_sp = std::make_shared<lldb_private::GDBRemoteSignals>(); 667 668 bool done = array_sp->ForEach( 669 [&remote_signals_sp](StructuredData::Object *object) -> bool { 670 if (!object || !object->IsValid()) 671 return false; 672 673 auto dict = object->GetAsDictionary(); 674 if (!dict || !dict->IsValid()) 675 return false; 676 677 // Signal number and signal name are required. 678 int signo; 679 if (!dict->GetValueForKeyAsInteger("signo", signo)) 680 return false; 681 682 llvm::StringRef name; 683 if (!dict->GetValueForKeyAsString("name", name)) 684 return false; 685 686 // We can live without short_name, description, etc. 687 bool suppress{false}; 688 auto object_sp = dict->GetValueForKey("suppress"); 689 if (object_sp && object_sp->IsValid()) 690 suppress = object_sp->GetBooleanValue(); 691 692 bool stop{false}; 693 object_sp = dict->GetValueForKey("stop"); 694 if (object_sp && object_sp->IsValid()) 695 stop = object_sp->GetBooleanValue(); 696 697 bool notify{false}; 698 object_sp = dict->GetValueForKey("notify"); 699 if (object_sp && object_sp->IsValid()) 700 notify = object_sp->GetBooleanValue(); 701 702 std::string description{""}; 703 object_sp = dict->GetValueForKey("description"); 704 if (object_sp && object_sp->IsValid()) 705 description = std::string(object_sp->GetStringValue()); 706 707 remote_signals_sp->AddSignal(signo, name.str().c_str(), suppress, stop, 708 notify, description.c_str()); 709 return true; 710 }); 711 712 if (done) 713 m_remote_signals_sp = std::move(remote_signals_sp); 714 715 return m_remote_signals_sp; 716 } 717 718 std::string PlatformRemoteGDBServer::MakeGdbServerUrl( 719 const std::string &platform_scheme, const std::string &platform_hostname, 720 uint16_t port, const char *socket_name) { 721 const char *override_scheme = 722 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_SCHEME"); 723 const char *override_hostname = 724 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_HOSTNAME"); 725 const char *port_offset_c_str = 726 getenv("LLDB_PLATFORM_REMOTE_GDB_SERVER_PORT_OFFSET"); 727 int port_offset = port_offset_c_str ? ::atoi(port_offset_c_str) : 0; 728 729 return MakeUrl(override_scheme ? override_scheme : platform_scheme.c_str(), 730 override_hostname ? override_hostname 731 : platform_hostname.c_str(), 732 port + port_offset, socket_name); 733 } 734 735 std::string PlatformRemoteGDBServer::MakeUrl(const char *scheme, 736 const char *hostname, 737 uint16_t port, const char *path) { 738 StreamString result; 739 result.Printf("%s://[%s]", scheme, hostname); 740 if (port != 0) 741 result.Printf(":%u", port); 742 if (path) 743 result.Write(path, strlen(path)); 744 return std::string(result.GetString()); 745 } 746 747 size_t PlatformRemoteGDBServer::ConnectToWaitingProcesses(Debugger &debugger, 748 Status &error) { 749 std::vector<std::string> connection_urls; 750 GetPendingGdbServerList(connection_urls); 751 752 for (size_t i = 0; i < connection_urls.size(); ++i) { 753 ConnectProcess(connection_urls[i].c_str(), "gdb-remote", debugger, nullptr, error); 754 if (error.Fail()) 755 return i; // We already connected to i process succsessfully 756 } 757 return connection_urls.size(); 758 } 759 760 size_t PlatformRemoteGDBServer::GetPendingGdbServerList( 761 std::vector<std::string> &connection_urls) { 762 std::vector<std::pair<uint16_t, std::string>> remote_servers; 763 m_gdb_client.QueryGDBServer(remote_servers); 764 for (const auto &gdbserver : remote_servers) { 765 const char *socket_name_cstr = 766 gdbserver.second.empty() ? nullptr : gdbserver.second.c_str(); 767 connection_urls.emplace_back( 768 MakeGdbServerUrl(m_platform_scheme, m_platform_hostname, 769 gdbserver.first, socket_name_cstr)); 770 } 771 return connection_urls.size(); 772 } 773