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