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