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