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