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