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