1 //===-- Platform.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 <algorithm> 10 #include <csignal> 11 #include <fstream> 12 #include <memory> 13 #include <vector> 14 15 #include "lldb/Breakpoint/BreakpointIDList.h" 16 #include "lldb/Breakpoint/BreakpointLocation.h" 17 #include "lldb/Core/Debugger.h" 18 #include "lldb/Core/Module.h" 19 #include "lldb/Core/ModuleSpec.h" 20 #include "lldb/Core/PluginManager.h" 21 #include "lldb/Core/StreamFile.h" 22 #include "lldb/Host/FileSystem.h" 23 #include "lldb/Host/Host.h" 24 #include "lldb/Host/HostInfo.h" 25 #include "lldb/Host/OptionParser.h" 26 #include "lldb/Interpreter/OptionValueFileSpec.h" 27 #include "lldb/Interpreter/OptionValueProperties.h" 28 #include "lldb/Interpreter/Property.h" 29 #include "lldb/Symbol/ObjectFile.h" 30 #include "lldb/Target/ModuleCache.h" 31 #include "lldb/Target/Platform.h" 32 #include "lldb/Target/Process.h" 33 #include "lldb/Target/Target.h" 34 #include "lldb/Target/UnixSignals.h" 35 #include "lldb/Utility/DataBufferHeap.h" 36 #include "lldb/Utility/FileSpec.h" 37 #include "lldb/Utility/Log.h" 38 #include "lldb/Utility/Status.h" 39 #include "lldb/Utility/StructuredData.h" 40 #include "llvm/Support/FileSystem.h" 41 #include "llvm/Support/Path.h" 42 43 // Define these constants from POSIX mman.h rather than include the file so 44 // that they will be correct even when compiled on Linux. 45 #define MAP_PRIVATE 2 46 #define MAP_ANON 0x1000 47 48 using namespace lldb; 49 using namespace lldb_private; 50 51 static uint32_t g_initialize_count = 0; 52 53 // Use a singleton function for g_local_platform_sp to avoid init constructors 54 // since LLDB is often part of a shared library 55 static PlatformSP &GetHostPlatformSP() { 56 static PlatformSP g_platform_sp; 57 return g_platform_sp; 58 } 59 60 const char *Platform::GetHostPlatformName() { return "host"; } 61 62 namespace { 63 64 #define LLDB_PROPERTIES_platform 65 #include "TargetProperties.inc" 66 67 enum { 68 #define LLDB_PROPERTIES_platform 69 #include "TargetPropertiesEnum.inc" 70 }; 71 72 } // namespace 73 74 ConstString PlatformProperties::GetSettingName() { 75 static ConstString g_setting_name("platform"); 76 return g_setting_name; 77 } 78 79 PlatformProperties::PlatformProperties() { 80 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); 81 m_collection_sp->Initialize(g_platform_properties); 82 83 auto module_cache_dir = GetModuleCacheDirectory(); 84 if (module_cache_dir) 85 return; 86 87 llvm::SmallString<64> user_home_dir; 88 if (!FileSystem::Instance().GetHomeDirectory(user_home_dir)) 89 return; 90 91 module_cache_dir = FileSpec(user_home_dir.c_str()); 92 module_cache_dir.AppendPathComponent(".lldb"); 93 module_cache_dir.AppendPathComponent("module_cache"); 94 SetDefaultModuleCacheDirectory(module_cache_dir); 95 SetModuleCacheDirectory(module_cache_dir); 96 } 97 98 bool PlatformProperties::GetUseModuleCache() const { 99 const auto idx = ePropertyUseModuleCache; 100 return m_collection_sp->GetPropertyAtIndexAsBoolean( 101 nullptr, idx, g_platform_properties[idx].default_uint_value != 0); 102 } 103 104 bool PlatformProperties::SetUseModuleCache(bool use_module_cache) { 105 return m_collection_sp->SetPropertyAtIndexAsBoolean( 106 nullptr, ePropertyUseModuleCache, use_module_cache); 107 } 108 109 FileSpec PlatformProperties::GetModuleCacheDirectory() const { 110 return m_collection_sp->GetPropertyAtIndexAsFileSpec( 111 nullptr, ePropertyModuleCacheDirectory); 112 } 113 114 bool PlatformProperties::SetModuleCacheDirectory(const FileSpec &dir_spec) { 115 return m_collection_sp->SetPropertyAtIndexAsFileSpec( 116 nullptr, ePropertyModuleCacheDirectory, dir_spec); 117 } 118 119 void PlatformProperties::SetDefaultModuleCacheDirectory( 120 const FileSpec &dir_spec) { 121 auto f_spec_opt = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec( 122 nullptr, false, ePropertyModuleCacheDirectory); 123 assert(f_spec_opt); 124 f_spec_opt->SetDefaultValue(dir_spec); 125 } 126 127 /// Get the native host platform plug-in. 128 /// 129 /// There should only be one of these for each host that LLDB runs 130 /// upon that should be statically compiled in and registered using 131 /// preprocessor macros or other similar build mechanisms. 132 /// 133 /// This platform will be used as the default platform when launching 134 /// or attaching to processes unless another platform is specified. 135 PlatformSP Platform::GetHostPlatform() { return GetHostPlatformSP(); } 136 137 static std::vector<PlatformSP> &GetPlatformList() { 138 static std::vector<PlatformSP> g_platform_list; 139 return g_platform_list; 140 } 141 142 static std::recursive_mutex &GetPlatformListMutex() { 143 static std::recursive_mutex g_mutex; 144 return g_mutex; 145 } 146 147 void Platform::Initialize() { g_initialize_count++; } 148 149 void Platform::Terminate() { 150 if (g_initialize_count > 0) { 151 if (--g_initialize_count == 0) { 152 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex()); 153 GetPlatformList().clear(); 154 } 155 } 156 } 157 158 PlatformProperties &Platform::GetGlobalPlatformProperties() { 159 static PlatformProperties g_settings; 160 return g_settings; 161 } 162 163 void Platform::SetHostPlatform(const lldb::PlatformSP &platform_sp) { 164 // The native platform should use its static void Platform::Initialize() 165 // function to register itself as the native platform. 166 GetHostPlatformSP() = platform_sp; 167 168 if (platform_sp) { 169 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex()); 170 GetPlatformList().push_back(platform_sp); 171 } 172 } 173 174 Status Platform::GetFileWithUUID(const FileSpec &platform_file, 175 const UUID *uuid_ptr, FileSpec &local_file) { 176 // Default to the local case 177 local_file = platform_file; 178 return Status(); 179 } 180 181 FileSpecList 182 Platform::LocateExecutableScriptingResources(Target *target, Module &module, 183 Stream *feedback_stream) { 184 return FileSpecList(); 185 } 186 187 // PlatformSP 188 // Platform::FindPlugin (Process *process, ConstString plugin_name) 189 //{ 190 // PlatformCreateInstance create_callback = nullptr; 191 // if (plugin_name) 192 // { 193 // create_callback = 194 // PluginManager::GetPlatformCreateCallbackForPluginName (plugin_name); 195 // if (create_callback) 196 // { 197 // ArchSpec arch; 198 // if (process) 199 // { 200 // arch = process->GetTarget().GetArchitecture(); 201 // } 202 // PlatformSP platform_sp(create_callback(process, &arch)); 203 // if (platform_sp) 204 // return platform_sp; 205 // } 206 // } 207 // else 208 // { 209 // for (uint32_t idx = 0; (create_callback = 210 // PluginManager::GetPlatformCreateCallbackAtIndex(idx)) != nullptr; 211 // ++idx) 212 // { 213 // PlatformSP platform_sp(create_callback(process, nullptr)); 214 // if (platform_sp) 215 // return platform_sp; 216 // } 217 // } 218 // return PlatformSP(); 219 //} 220 221 Status Platform::GetSharedModule( 222 const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp, 223 const FileSpecList *module_search_paths_ptr, 224 llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules, bool *did_create_ptr) { 225 if (IsHost()) 226 return ModuleList::GetSharedModule(module_spec, module_sp, 227 module_search_paths_ptr, old_modules, 228 did_create_ptr, false); 229 230 // Module resolver lambda. 231 auto resolver = [&](const ModuleSpec &spec) { 232 Status error(eErrorTypeGeneric); 233 ModuleSpec resolved_spec; 234 // Check if we have sysroot set. 235 if (m_sdk_sysroot) { 236 // Prepend sysroot to module spec. 237 resolved_spec = spec; 238 resolved_spec.GetFileSpec().PrependPathComponent( 239 m_sdk_sysroot.GetStringRef()); 240 // Try to get shared module with resolved spec. 241 error = ModuleList::GetSharedModule(resolved_spec, module_sp, 242 module_search_paths_ptr, old_modules, 243 did_create_ptr, false); 244 } 245 // If we don't have sysroot or it didn't work then 246 // try original module spec. 247 if (!error.Success()) { 248 resolved_spec = spec; 249 error = ModuleList::GetSharedModule(resolved_spec, module_sp, 250 module_search_paths_ptr, old_modules, 251 did_create_ptr, false); 252 } 253 if (error.Success() && module_sp) 254 module_sp->SetPlatformFileSpec(resolved_spec.GetFileSpec()); 255 return error; 256 }; 257 258 return GetRemoteSharedModule(module_spec, process, module_sp, resolver, 259 did_create_ptr); 260 } 261 262 bool Platform::GetModuleSpec(const FileSpec &module_file_spec, 263 const ArchSpec &arch, ModuleSpec &module_spec) { 264 ModuleSpecList module_specs; 265 if (ObjectFile::GetModuleSpecifications(module_file_spec, 0, 0, 266 module_specs) == 0) 267 return false; 268 269 ModuleSpec matched_module_spec; 270 return module_specs.FindMatchingModuleSpec(ModuleSpec(module_file_spec, arch), 271 module_spec); 272 } 273 274 PlatformSP Platform::Find(ConstString name) { 275 if (name) { 276 static ConstString g_host_platform_name("host"); 277 if (name == g_host_platform_name) 278 return GetHostPlatform(); 279 280 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex()); 281 for (const auto &platform_sp : GetPlatformList()) { 282 if (platform_sp->GetName() == name) 283 return platform_sp; 284 } 285 } 286 return PlatformSP(); 287 } 288 289 PlatformSP Platform::Create(ConstString name, Status &error) { 290 PlatformCreateInstance create_callback = nullptr; 291 lldb::PlatformSP platform_sp; 292 if (name) { 293 static ConstString g_host_platform_name("host"); 294 if (name == g_host_platform_name) 295 return GetHostPlatform(); 296 297 create_callback = PluginManager::GetPlatformCreateCallbackForPluginName( 298 name.GetStringRef()); 299 if (create_callback) 300 platform_sp = create_callback(true, nullptr); 301 else 302 error.SetErrorStringWithFormat( 303 "unable to find a plug-in for the platform named \"%s\"", 304 name.GetCString()); 305 } else 306 error.SetErrorString("invalid platform name"); 307 308 if (platform_sp) { 309 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex()); 310 GetPlatformList().push_back(platform_sp); 311 } 312 313 return platform_sp; 314 } 315 316 PlatformSP Platform::Create(const ArchSpec &arch, ArchSpec *platform_arch_ptr, 317 Status &error) { 318 lldb::PlatformSP platform_sp; 319 if (arch.IsValid()) { 320 // Scope for locker 321 { 322 // First try exact arch matches across all platforms already created 323 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex()); 324 for (const auto &platform_sp : GetPlatformList()) { 325 if (platform_sp->IsCompatibleArchitecture(arch, true, 326 platform_arch_ptr)) 327 return platform_sp; 328 } 329 330 // Next try compatible arch matches across all platforms already created 331 for (const auto &platform_sp : GetPlatformList()) { 332 if (platform_sp->IsCompatibleArchitecture(arch, false, 333 platform_arch_ptr)) 334 return platform_sp; 335 } 336 } 337 338 PlatformCreateInstance create_callback; 339 // First try exact arch matches across all platform plug-ins 340 uint32_t idx; 341 for (idx = 0; (create_callback = 342 PluginManager::GetPlatformCreateCallbackAtIndex(idx)); 343 ++idx) { 344 if (create_callback) { 345 platform_sp = create_callback(false, &arch); 346 if (platform_sp && 347 platform_sp->IsCompatibleArchitecture(arch, true, 348 platform_arch_ptr)) { 349 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex()); 350 GetPlatformList().push_back(platform_sp); 351 return platform_sp; 352 } 353 } 354 } 355 // Next try compatible arch matches across all platform plug-ins 356 for (idx = 0; (create_callback = 357 PluginManager::GetPlatformCreateCallbackAtIndex(idx)); 358 ++idx) { 359 if (create_callback) { 360 platform_sp = create_callback(false, &arch); 361 if (platform_sp && 362 platform_sp->IsCompatibleArchitecture(arch, false, 363 platform_arch_ptr)) { 364 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex()); 365 GetPlatformList().push_back(platform_sp); 366 return platform_sp; 367 } 368 } 369 } 370 } else 371 error.SetErrorString("invalid platform name"); 372 if (platform_arch_ptr) 373 platform_arch_ptr->Clear(); 374 platform_sp.reset(); 375 return platform_sp; 376 } 377 378 ArchSpec Platform::GetAugmentedArchSpec(Platform *platform, llvm::StringRef triple) { 379 if (platform) 380 return platform->GetAugmentedArchSpec(triple); 381 return HostInfo::GetAugmentedArchSpec(triple); 382 } 383 384 /// Default Constructor 385 Platform::Platform(bool is_host) 386 : m_is_host(is_host), m_os_version_set_while_connected(false), 387 m_system_arch_set_while_connected(false), m_sdk_sysroot(), m_sdk_build(), 388 m_working_dir(), m_remote_url(), m_name(), m_system_arch(), m_mutex(), 389 m_max_uid_name_len(0), m_max_gid_name_len(0), m_supports_rsync(false), 390 m_rsync_opts(), m_rsync_prefix(), m_supports_ssh(false), m_ssh_opts(), 391 m_ignores_remote_hostname(false), m_trap_handlers(), 392 m_calculated_trap_handlers(false), 393 m_module_cache(std::make_unique<ModuleCache>()) { 394 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT)); 395 LLDB_LOGF(log, "%p Platform::Platform()", static_cast<void *>(this)); 396 } 397 398 Platform::~Platform() = default; 399 400 void Platform::GetStatus(Stream &strm) { 401 strm.Format(" Platform: {0}\n", GetPluginName()); 402 403 ArchSpec arch(GetSystemArchitecture()); 404 if (arch.IsValid()) { 405 if (!arch.GetTriple().str().empty()) { 406 strm.Printf(" Triple: "); 407 arch.DumpTriple(strm.AsRawOstream()); 408 strm.EOL(); 409 } 410 } 411 412 llvm::VersionTuple os_version = GetOSVersion(); 413 if (!os_version.empty()) { 414 strm.Format("OS Version: {0}", os_version.getAsString()); 415 416 if (llvm::Optional<std::string> s = GetOSBuildString()) 417 strm.Format(" ({0})", *s); 418 419 strm.EOL(); 420 } 421 422 if (IsHost()) { 423 strm.Printf(" Hostname: %s\n", GetHostname()); 424 } else { 425 const bool is_connected = IsConnected(); 426 if (is_connected) 427 strm.Printf(" Hostname: %s\n", GetHostname()); 428 strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no"); 429 } 430 431 if (GetWorkingDirectory()) { 432 strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString()); 433 } 434 if (!IsConnected()) 435 return; 436 437 std::string specific_info(GetPlatformSpecificConnectionInformation()); 438 439 if (!specific_info.empty()) 440 strm.Printf("Platform-specific connection: %s\n", specific_info.c_str()); 441 442 if (llvm::Optional<std::string> s = GetOSKernelDescription()) 443 strm.Format(" Kernel: {0}\n", *s); 444 } 445 446 llvm::VersionTuple Platform::GetOSVersion(Process *process) { 447 std::lock_guard<std::mutex> guard(m_mutex); 448 449 if (IsHost()) { 450 if (m_os_version.empty()) { 451 // We have a local host platform 452 m_os_version = HostInfo::GetOSVersion(); 453 m_os_version_set_while_connected = !m_os_version.empty(); 454 } 455 } else { 456 // We have a remote platform. We can only fetch the remote 457 // OS version if we are connected, and we don't want to do it 458 // more than once. 459 460 const bool is_connected = IsConnected(); 461 462 bool fetch = false; 463 if (!m_os_version.empty()) { 464 // We have valid OS version info, check to make sure it wasn't manually 465 // set prior to connecting. If it was manually set prior to connecting, 466 // then lets fetch the actual OS version info if we are now connected. 467 if (is_connected && !m_os_version_set_while_connected) 468 fetch = true; 469 } else { 470 // We don't have valid OS version info, fetch it if we are connected 471 fetch = is_connected; 472 } 473 474 if (fetch) 475 m_os_version_set_while_connected = GetRemoteOSVersion(); 476 } 477 478 if (!m_os_version.empty()) 479 return m_os_version; 480 if (process) { 481 // Check with the process in case it can answer the question if a process 482 // was provided 483 return process->GetHostOSVersion(); 484 } 485 return llvm::VersionTuple(); 486 } 487 488 llvm::Optional<std::string> Platform::GetOSBuildString() { 489 if (IsHost()) 490 return HostInfo::GetOSBuildString(); 491 return GetRemoteOSBuildString(); 492 } 493 494 llvm::Optional<std::string> Platform::GetOSKernelDescription() { 495 if (IsHost()) 496 return HostInfo::GetOSKernelDescription(); 497 return GetRemoteOSKernelDescription(); 498 } 499 500 void Platform::AddClangModuleCompilationOptions( 501 Target *target, std::vector<std::string> &options) { 502 std::vector<std::string> default_compilation_options = { 503 "-x", "c++", "-Xclang", "-nostdsysteminc", "-Xclang", "-nostdsysteminc"}; 504 505 options.insert(options.end(), default_compilation_options.begin(), 506 default_compilation_options.end()); 507 } 508 509 FileSpec Platform::GetWorkingDirectory() { 510 if (IsHost()) { 511 llvm::SmallString<64> cwd; 512 if (llvm::sys::fs::current_path(cwd)) 513 return {}; 514 else { 515 FileSpec file_spec(cwd); 516 FileSystem::Instance().Resolve(file_spec); 517 return file_spec; 518 } 519 } else { 520 if (!m_working_dir) 521 m_working_dir = GetRemoteWorkingDirectory(); 522 return m_working_dir; 523 } 524 } 525 526 struct RecurseCopyBaton { 527 const FileSpec &dst; 528 Platform *platform_ptr; 529 Status error; 530 }; 531 532 static FileSystem::EnumerateDirectoryResult 533 RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft, 534 llvm::StringRef path) { 535 RecurseCopyBaton *rc_baton = (RecurseCopyBaton *)baton; 536 FileSpec src(path); 537 namespace fs = llvm::sys::fs; 538 switch (ft) { 539 case fs::file_type::fifo_file: 540 case fs::file_type::socket_file: 541 // we have no way to copy pipes and sockets - ignore them and continue 542 return FileSystem::eEnumerateDirectoryResultNext; 543 break; 544 545 case fs::file_type::directory_file: { 546 // make the new directory and get in there 547 FileSpec dst_dir = rc_baton->dst; 548 if (!dst_dir.GetFilename()) 549 dst_dir.GetFilename() = src.GetLastPathComponent(); 550 Status error = rc_baton->platform_ptr->MakeDirectory( 551 dst_dir, lldb::eFilePermissionsDirectoryDefault); 552 if (error.Fail()) { 553 rc_baton->error.SetErrorStringWithFormat( 554 "unable to setup directory %s on remote end", dst_dir.GetCString()); 555 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out 556 } 557 558 // now recurse 559 std::string src_dir_path(src.GetPath()); 560 561 // Make a filespec that only fills in the directory of a FileSpec so when 562 // we enumerate we can quickly fill in the filename for dst copies 563 FileSpec recurse_dst; 564 recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str()); 565 RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr, 566 Status()}; 567 FileSystem::Instance().EnumerateDirectory(src_dir_path, true, true, true, 568 RecurseCopy_Callback, &rc_baton2); 569 if (rc_baton2.error.Fail()) { 570 rc_baton->error.SetErrorString(rc_baton2.error.AsCString()); 571 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out 572 } 573 return FileSystem::eEnumerateDirectoryResultNext; 574 } break; 575 576 case fs::file_type::symlink_file: { 577 // copy the file and keep going 578 FileSpec dst_file = rc_baton->dst; 579 if (!dst_file.GetFilename()) 580 dst_file.GetFilename() = src.GetFilename(); 581 582 FileSpec src_resolved; 583 584 rc_baton->error = FileSystem::Instance().Readlink(src, src_resolved); 585 586 if (rc_baton->error.Fail()) 587 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out 588 589 rc_baton->error = 590 rc_baton->platform_ptr->CreateSymlink(dst_file, src_resolved); 591 592 if (rc_baton->error.Fail()) 593 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out 594 595 return FileSystem::eEnumerateDirectoryResultNext; 596 } break; 597 598 case fs::file_type::regular_file: { 599 // copy the file and keep going 600 FileSpec dst_file = rc_baton->dst; 601 if (!dst_file.GetFilename()) 602 dst_file.GetFilename() = src.GetFilename(); 603 Status err = rc_baton->platform_ptr->PutFile(src, dst_file); 604 if (err.Fail()) { 605 rc_baton->error.SetErrorString(err.AsCString()); 606 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out 607 } 608 return FileSystem::eEnumerateDirectoryResultNext; 609 } break; 610 611 default: 612 rc_baton->error.SetErrorStringWithFormat( 613 "invalid file detected during copy: %s", src.GetPath().c_str()); 614 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out 615 break; 616 } 617 llvm_unreachable("Unhandled file_type!"); 618 } 619 620 Status Platform::Install(const FileSpec &src, const FileSpec &dst) { 621 Status error; 622 623 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 624 LLDB_LOGF(log, "Platform::Install (src='%s', dst='%s')", 625 src.GetPath().c_str(), dst.GetPath().c_str()); 626 FileSpec fixed_dst(dst); 627 628 if (!fixed_dst.GetFilename()) 629 fixed_dst.GetFilename() = src.GetFilename(); 630 631 FileSpec working_dir = GetWorkingDirectory(); 632 633 if (dst) { 634 if (dst.GetDirectory()) { 635 const char first_dst_dir_char = dst.GetDirectory().GetCString()[0]; 636 if (first_dst_dir_char == '/' || first_dst_dir_char == '\\') { 637 fixed_dst.GetDirectory() = dst.GetDirectory(); 638 } 639 // If the fixed destination file doesn't have a directory yet, then we 640 // must have a relative path. We will resolve this relative path against 641 // the platform's working directory 642 if (!fixed_dst.GetDirectory()) { 643 FileSpec relative_spec; 644 std::string path; 645 if (working_dir) { 646 relative_spec = working_dir; 647 relative_spec.AppendPathComponent(dst.GetPath()); 648 fixed_dst.GetDirectory() = relative_spec.GetDirectory(); 649 } else { 650 error.SetErrorStringWithFormat( 651 "platform working directory must be valid for relative path '%s'", 652 dst.GetPath().c_str()); 653 return error; 654 } 655 } 656 } else { 657 if (working_dir) { 658 fixed_dst.GetDirectory().SetCString(working_dir.GetCString()); 659 } else { 660 error.SetErrorStringWithFormat( 661 "platform working directory must be valid for relative path '%s'", 662 dst.GetPath().c_str()); 663 return error; 664 } 665 } 666 } else { 667 if (working_dir) { 668 fixed_dst.GetDirectory().SetCString(working_dir.GetCString()); 669 } else { 670 error.SetErrorStringWithFormat("platform working directory must be valid " 671 "when destination directory is empty"); 672 return error; 673 } 674 } 675 676 LLDB_LOGF(log, "Platform::Install (src='%s', dst='%s') fixed_dst='%s'", 677 src.GetPath().c_str(), dst.GetPath().c_str(), 678 fixed_dst.GetPath().c_str()); 679 680 if (GetSupportsRSync()) { 681 error = PutFile(src, dst); 682 } else { 683 namespace fs = llvm::sys::fs; 684 switch (fs::get_file_type(src.GetPath(), false)) { 685 case fs::file_type::directory_file: { 686 llvm::sys::fs::remove(fixed_dst.GetPath()); 687 uint32_t permissions = FileSystem::Instance().GetPermissions(src); 688 if (permissions == 0) 689 permissions = eFilePermissionsDirectoryDefault; 690 error = MakeDirectory(fixed_dst, permissions); 691 if (error.Success()) { 692 // Make a filespec that only fills in the directory of a FileSpec so 693 // when we enumerate we can quickly fill in the filename for dst copies 694 FileSpec recurse_dst; 695 recurse_dst.GetDirectory().SetCString(fixed_dst.GetCString()); 696 std::string src_dir_path(src.GetPath()); 697 RecurseCopyBaton baton = {recurse_dst, this, Status()}; 698 FileSystem::Instance().EnumerateDirectory( 699 src_dir_path, true, true, true, RecurseCopy_Callback, &baton); 700 return baton.error; 701 } 702 } break; 703 704 case fs::file_type::regular_file: 705 llvm::sys::fs::remove(fixed_dst.GetPath()); 706 error = PutFile(src, fixed_dst); 707 break; 708 709 case fs::file_type::symlink_file: { 710 llvm::sys::fs::remove(fixed_dst.GetPath()); 711 FileSpec src_resolved; 712 error = FileSystem::Instance().Readlink(src, src_resolved); 713 if (error.Success()) 714 error = CreateSymlink(dst, src_resolved); 715 } break; 716 case fs::file_type::fifo_file: 717 error.SetErrorString("platform install doesn't handle pipes"); 718 break; 719 case fs::file_type::socket_file: 720 error.SetErrorString("platform install doesn't handle sockets"); 721 break; 722 default: 723 error.SetErrorString( 724 "platform install doesn't handle non file or directory items"); 725 break; 726 } 727 } 728 return error; 729 } 730 731 bool Platform::SetWorkingDirectory(const FileSpec &file_spec) { 732 if (IsHost()) { 733 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 734 LLDB_LOG(log, "{0}", file_spec); 735 if (std::error_code ec = llvm::sys::fs::set_current_path(file_spec.GetPath())) { 736 LLDB_LOG(log, "error: {0}", ec.message()); 737 return false; 738 } 739 return true; 740 } else { 741 m_working_dir.Clear(); 742 return SetRemoteWorkingDirectory(file_spec); 743 } 744 } 745 746 Status Platform::MakeDirectory(const FileSpec &file_spec, 747 uint32_t permissions) { 748 if (IsHost()) 749 return llvm::sys::fs::create_directory(file_spec.GetPath(), permissions); 750 else { 751 Status error; 752 error.SetErrorStringWithFormatv("remote platform {0} doesn't support {1}", 753 GetPluginName(), LLVM_PRETTY_FUNCTION); 754 return error; 755 } 756 } 757 758 Status Platform::GetFilePermissions(const FileSpec &file_spec, 759 uint32_t &file_permissions) { 760 if (IsHost()) { 761 auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath()); 762 if (Value) 763 file_permissions = Value.get(); 764 return Status(Value.getError()); 765 } else { 766 Status error; 767 error.SetErrorStringWithFormatv("remote platform {0} doesn't support {1}", 768 GetPluginName(), LLVM_PRETTY_FUNCTION); 769 return error; 770 } 771 } 772 773 Status Platform::SetFilePermissions(const FileSpec &file_spec, 774 uint32_t file_permissions) { 775 if (IsHost()) { 776 auto Perms = static_cast<llvm::sys::fs::perms>(file_permissions); 777 return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms); 778 } else { 779 Status error; 780 error.SetErrorStringWithFormatv("remote platform {0} doesn't support {1}", 781 GetPluginName(), LLVM_PRETTY_FUNCTION); 782 return error; 783 } 784 } 785 786 ConstString Platform::GetName() { return ConstString(GetPluginName()); } 787 788 const char *Platform::GetHostname() { 789 if (IsHost()) 790 return "127.0.0.1"; 791 792 if (m_name.empty()) 793 return nullptr; 794 return m_name.c_str(); 795 } 796 797 ConstString Platform::GetFullNameForDylib(ConstString basename) { 798 return basename; 799 } 800 801 bool Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir) { 802 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 803 LLDB_LOGF(log, "Platform::SetRemoteWorkingDirectory('%s')", 804 working_dir.GetCString()); 805 m_working_dir = working_dir; 806 return true; 807 } 808 809 bool Platform::SetOSVersion(llvm::VersionTuple version) { 810 if (IsHost()) { 811 // We don't need anyone setting the OS version for the host platform, we 812 // should be able to figure it out by calling HostInfo::GetOSVersion(...). 813 return false; 814 } else { 815 // We have a remote platform, allow setting the target OS version if we 816 // aren't connected, since if we are connected, we should be able to 817 // request the remote OS version from the connected platform. 818 if (IsConnected()) 819 return false; 820 else { 821 // We aren't connected and we might want to set the OS version ahead of 822 // time before we connect so we can peruse files and use a local SDK or 823 // PDK cache of support files to disassemble or do other things. 824 m_os_version = version; 825 return true; 826 } 827 } 828 return false; 829 } 830 831 Status 832 Platform::ResolveExecutable(const ModuleSpec &module_spec, 833 lldb::ModuleSP &exe_module_sp, 834 const FileSpecList *module_search_paths_ptr) { 835 Status error; 836 837 if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) { 838 if (module_spec.GetArchitecture().IsValid()) { 839 error = ModuleList::GetSharedModule(module_spec, exe_module_sp, 840 module_search_paths_ptr, nullptr, 841 nullptr); 842 } else { 843 // No valid architecture was specified, ask the platform for the 844 // architectures that we should be using (in the correct order) and see 845 // if we can find a match that way 846 ModuleSpec arch_module_spec(module_spec); 847 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex( 848 idx, arch_module_spec.GetArchitecture()); 849 ++idx) { 850 error = ModuleList::GetSharedModule(arch_module_spec, exe_module_sp, 851 module_search_paths_ptr, nullptr, 852 nullptr); 853 // Did we find an executable using one of the 854 if (error.Success() && exe_module_sp) 855 break; 856 } 857 } 858 } else { 859 error.SetErrorStringWithFormat( 860 "'%s' does not exist", module_spec.GetFileSpec().GetPath().c_str()); 861 } 862 return error; 863 } 864 865 Status 866 Platform::ResolveRemoteExecutable(const ModuleSpec &module_spec, 867 lldb::ModuleSP &exe_module_sp, 868 const FileSpecList *module_search_paths_ptr) { 869 Status error; 870 871 // We may connect to a process and use the provided executable (Don't use 872 // local $PATH). 873 ModuleSpec resolved_module_spec(module_spec); 874 875 // Resolve any executable within a bundle on MacOSX 876 Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec()); 877 878 if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()) || 879 module_spec.GetUUID().IsValid()) { 880 if (resolved_module_spec.GetArchitecture().IsValid() || 881 resolved_module_spec.GetUUID().IsValid()) { 882 error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp, 883 module_search_paths_ptr, nullptr, 884 nullptr); 885 886 if (exe_module_sp && exe_module_sp->GetObjectFile()) 887 return error; 888 exe_module_sp.reset(); 889 } 890 // No valid architecture was specified or the exact arch wasn't found so 891 // ask the platform for the architectures that we should be using (in the 892 // correct order) and see if we can find a match that way 893 StreamString arch_names; 894 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex( 895 idx, resolved_module_spec.GetArchitecture()); 896 ++idx) { 897 error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp, 898 module_search_paths_ptr, nullptr, 899 nullptr); 900 // Did we find an executable using one of the 901 if (error.Success()) { 902 if (exe_module_sp && exe_module_sp->GetObjectFile()) 903 break; 904 else 905 error.SetErrorToGenericError(); 906 } 907 908 if (idx > 0) 909 arch_names.PutCString(", "); 910 arch_names.PutCString( 911 resolved_module_spec.GetArchitecture().GetArchitectureName()); 912 } 913 914 if (error.Fail() || !exe_module_sp) { 915 if (FileSystem::Instance().Readable(resolved_module_spec.GetFileSpec())) { 916 error.SetErrorStringWithFormatv( 917 "'{0}' doesn't contain any '{1}' platform architectures: {2}", 918 resolved_module_spec.GetFileSpec(), GetPluginName(), 919 arch_names.GetData()); 920 } else { 921 error.SetErrorStringWithFormatv("'{0}' is not readable", 922 resolved_module_spec.GetFileSpec()); 923 } 924 } 925 } else { 926 error.SetErrorStringWithFormatv("'{0}' does not exist", 927 resolved_module_spec.GetFileSpec()); 928 } 929 930 return error; 931 } 932 933 Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, 934 FileSpec &sym_file) { 935 Status error; 936 if (FileSystem::Instance().Exists(sym_spec.GetSymbolFileSpec())) 937 sym_file = sym_spec.GetSymbolFileSpec(); 938 else 939 error.SetErrorString("unable to resolve symbol file"); 940 return error; 941 } 942 943 bool Platform::ResolveRemotePath(const FileSpec &platform_path, 944 FileSpec &resolved_platform_path) { 945 resolved_platform_path = platform_path; 946 FileSystem::Instance().Resolve(resolved_platform_path); 947 return true; 948 } 949 950 const ArchSpec &Platform::GetSystemArchitecture() { 951 if (IsHost()) { 952 if (!m_system_arch.IsValid()) { 953 // We have a local host platform 954 m_system_arch = HostInfo::GetArchitecture(); 955 m_system_arch_set_while_connected = m_system_arch.IsValid(); 956 } 957 } else { 958 // We have a remote platform. We can only fetch the remote system 959 // architecture if we are connected, and we don't want to do it more than 960 // once. 961 962 const bool is_connected = IsConnected(); 963 964 bool fetch = false; 965 if (m_system_arch.IsValid()) { 966 // We have valid OS version info, check to make sure it wasn't manually 967 // set prior to connecting. If it was manually set prior to connecting, 968 // then lets fetch the actual OS version info if we are now connected. 969 if (is_connected && !m_system_arch_set_while_connected) 970 fetch = true; 971 } else { 972 // We don't have valid OS version info, fetch it if we are connected 973 fetch = is_connected; 974 } 975 976 if (fetch) { 977 m_system_arch = GetRemoteSystemArchitecture(); 978 m_system_arch_set_while_connected = m_system_arch.IsValid(); 979 } 980 } 981 return m_system_arch; 982 } 983 984 ArchSpec Platform::GetAugmentedArchSpec(llvm::StringRef triple) { 985 if (triple.empty()) 986 return ArchSpec(); 987 llvm::Triple normalized_triple(llvm::Triple::normalize(triple)); 988 if (!ArchSpec::ContainsOnlyArch(normalized_triple)) 989 return ArchSpec(triple); 990 991 if (auto kind = HostInfo::ParseArchitectureKind(triple)) 992 return HostInfo::GetArchitecture(*kind); 993 994 ArchSpec compatible_arch; 995 ArchSpec raw_arch(triple); 996 if (!IsCompatibleArchitecture(raw_arch, false, &compatible_arch)) 997 return raw_arch; 998 999 if (!compatible_arch.IsValid()) 1000 return ArchSpec(normalized_triple); 1001 1002 const llvm::Triple &compatible_triple = compatible_arch.GetTriple(); 1003 if (normalized_triple.getVendorName().empty()) 1004 normalized_triple.setVendor(compatible_triple.getVendor()); 1005 if (normalized_triple.getOSName().empty()) 1006 normalized_triple.setOS(compatible_triple.getOS()); 1007 if (normalized_triple.getEnvironmentName().empty()) 1008 normalized_triple.setEnvironment(compatible_triple.getEnvironment()); 1009 return ArchSpec(normalized_triple); 1010 } 1011 1012 Status Platform::ConnectRemote(Args &args) { 1013 Status error; 1014 if (IsHost()) 1015 error.SetErrorStringWithFormatv( 1016 "The currently selected platform ({0}) is " 1017 "the host platform and is always connected.", 1018 GetPluginName()); 1019 else 1020 error.SetErrorStringWithFormatv( 1021 "Platform::ConnectRemote() is not supported by {0}", GetPluginName()); 1022 return error; 1023 } 1024 1025 Status Platform::DisconnectRemote() { 1026 Status error; 1027 if (IsHost()) 1028 error.SetErrorStringWithFormatv( 1029 "The currently selected platform ({0}) is " 1030 "the host platform and is always connected.", 1031 GetPluginName()); 1032 else 1033 error.SetErrorStringWithFormatv( 1034 "Platform::DisconnectRemote() is not supported by {0}", 1035 GetPluginName()); 1036 return error; 1037 } 1038 1039 bool Platform::GetProcessInfo(lldb::pid_t pid, 1040 ProcessInstanceInfo &process_info) { 1041 // Take care of the host case so that each subclass can just call this 1042 // function to get the host functionality. 1043 if (IsHost()) 1044 return Host::GetProcessInfo(pid, process_info); 1045 return false; 1046 } 1047 1048 uint32_t Platform::FindProcesses(const ProcessInstanceInfoMatch &match_info, 1049 ProcessInstanceInfoList &process_infos) { 1050 // Take care of the host case so that each subclass can just call this 1051 // function to get the host functionality. 1052 uint32_t match_count = 0; 1053 if (IsHost()) 1054 match_count = Host::FindProcesses(match_info, process_infos); 1055 return match_count; 1056 } 1057 1058 Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) { 1059 Status error; 1060 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1061 LLDB_LOGF(log, "Platform::%s()", __FUNCTION__); 1062 1063 // Take care of the host case so that each subclass can just call this 1064 // function to get the host functionality. 1065 if (IsHost()) { 1066 if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY")) 1067 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY); 1068 1069 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInShell)) { 1070 const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug); 1071 const bool first_arg_is_full_shell_command = false; 1072 uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info); 1073 if (log) { 1074 const FileSpec &shell = launch_info.GetShell(); 1075 std::string shell_str = (shell) ? shell.GetPath() : "<null>"; 1076 LLDB_LOGF(log, 1077 "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32 1078 ", shell is '%s'", 1079 __FUNCTION__, num_resumes, shell_str.c_str()); 1080 } 1081 1082 if (!launch_info.ConvertArgumentsForLaunchingInShell( 1083 error, will_debug, first_arg_is_full_shell_command, num_resumes)) 1084 return error; 1085 } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) { 1086 error = ShellExpandArguments(launch_info); 1087 if (error.Fail()) { 1088 error.SetErrorStringWithFormat("shell expansion failed (reason: %s). " 1089 "consider launching with 'process " 1090 "launch'.", 1091 error.AsCString("unknown")); 1092 return error; 1093 } 1094 } 1095 1096 LLDB_LOGF(log, "Platform::%s final launch_info resume count: %" PRIu32, 1097 __FUNCTION__, launch_info.GetResumeCount()); 1098 1099 error = Host::LaunchProcess(launch_info); 1100 } else 1101 error.SetErrorString( 1102 "base lldb_private::Platform class can't launch remote processes"); 1103 return error; 1104 } 1105 1106 Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) { 1107 if (IsHost()) 1108 return Host::ShellExpandArguments(launch_info); 1109 return Status("base lldb_private::Platform class can't expand arguments"); 1110 } 1111 1112 Status Platform::KillProcess(const lldb::pid_t pid) { 1113 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1114 LLDB_LOGF(log, "Platform::%s, pid %" PRIu64, __FUNCTION__, pid); 1115 1116 if (!IsHost()) { 1117 return Status( 1118 "base lldb_private::Platform class can't kill remote processes"); 1119 } 1120 Host::Kill(pid, SIGKILL); 1121 return Status(); 1122 } 1123 1124 lldb::ProcessSP Platform::DebugProcess(ProcessLaunchInfo &launch_info, 1125 Debugger &debugger, Target &target, 1126 Status &error) { 1127 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1128 LLDB_LOG(log, "target = {0})", &target); 1129 1130 ProcessSP process_sp; 1131 // Make sure we stop at the entry point 1132 launch_info.GetFlags().Set(eLaunchFlagDebug); 1133 // We always launch the process we are going to debug in a separate process 1134 // group, since then we can handle ^C interrupts ourselves w/o having to 1135 // worry about the target getting them as well. 1136 launch_info.SetLaunchInSeparateProcessGroup(true); 1137 1138 // Allow any StructuredData process-bound plugins to adjust the launch info 1139 // if needed 1140 size_t i = 0; 1141 bool iteration_complete = false; 1142 // Note iteration can't simply go until a nullptr callback is returned, as it 1143 // is valid for a plugin to not supply a filter. 1144 auto get_filter_func = PluginManager::GetStructuredDataFilterCallbackAtIndex; 1145 for (auto filter_callback = get_filter_func(i, iteration_complete); 1146 !iteration_complete; 1147 filter_callback = get_filter_func(++i, iteration_complete)) { 1148 if (filter_callback) { 1149 // Give this ProcessLaunchInfo filter a chance to adjust the launch info. 1150 error = (*filter_callback)(launch_info, &target); 1151 if (!error.Success()) { 1152 LLDB_LOGF(log, 1153 "Platform::%s() StructuredDataPlugin launch " 1154 "filter failed.", 1155 __FUNCTION__); 1156 return process_sp; 1157 } 1158 } 1159 } 1160 1161 error = LaunchProcess(launch_info); 1162 if (error.Success()) { 1163 LLDB_LOGF(log, 1164 "Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")", 1165 __FUNCTION__, launch_info.GetProcessID()); 1166 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) { 1167 ProcessAttachInfo attach_info(launch_info); 1168 process_sp = Attach(attach_info, debugger, &target, error); 1169 if (process_sp) { 1170 LLDB_LOG(log, "Attach() succeeded, Process plugin: {0}", 1171 process_sp->GetPluginName()); 1172 launch_info.SetHijackListener(attach_info.GetHijackListener()); 1173 1174 // Since we attached to the process, it will think it needs to detach 1175 // if the process object just goes away without an explicit call to 1176 // Process::Kill() or Process::Detach(), so let it know to kill the 1177 // process if this happens. 1178 process_sp->SetShouldDetach(false); 1179 1180 // If we didn't have any file actions, the pseudo terminal might have 1181 // been used where the secondary side was given as the file to open for 1182 // stdin/out/err after we have already opened the primary so we can 1183 // read/write stdin/out/err. 1184 int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor(); 1185 if (pty_fd != PseudoTerminal::invalid_fd) { 1186 process_sp->SetSTDIOFileDescriptor(pty_fd); 1187 } 1188 } else { 1189 LLDB_LOGF(log, "Platform::%s Attach() failed: %s", __FUNCTION__, 1190 error.AsCString()); 1191 } 1192 } else { 1193 LLDB_LOGF(log, 1194 "Platform::%s LaunchProcess() returned launch_info with " 1195 "invalid process id", 1196 __FUNCTION__); 1197 } 1198 } else { 1199 LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__, 1200 error.AsCString()); 1201 } 1202 1203 return process_sp; 1204 } 1205 1206 lldb::PlatformSP 1207 Platform::GetPlatformForArchitecture(const ArchSpec &arch, 1208 ArchSpec *platform_arch_ptr) { 1209 lldb::PlatformSP platform_sp; 1210 Status error; 1211 if (arch.IsValid()) 1212 platform_sp = Platform::Create(arch, platform_arch_ptr, error); 1213 return platform_sp; 1214 } 1215 1216 std::vector<ArchSpec> 1217 Platform::CreateArchList(llvm::ArrayRef<llvm::Triple::ArchType> archs, 1218 llvm::Triple::OSType os) { 1219 std::vector<ArchSpec> list; 1220 for(auto arch : archs) { 1221 llvm::Triple triple; 1222 triple.setArch(arch); 1223 triple.setOS(os); 1224 list.push_back(ArchSpec(triple)); 1225 } 1226 return list; 1227 } 1228 1229 bool Platform::GetSupportedArchitectureAtIndex(uint32_t idx, ArchSpec &arch) { 1230 const auto &archs = GetSupportedArchitectures(); 1231 if (idx >= archs.size()) 1232 return false; 1233 arch = archs[idx]; 1234 return true; 1235 } 1236 1237 std::vector<ArchSpec> Platform::GetSupportedArchitectures() { 1238 std::vector<ArchSpec> result; 1239 ArchSpec arch; 1240 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(idx, arch); ++idx) 1241 result.push_back(arch); 1242 return result; 1243 } 1244 1245 /// Lets a platform answer if it is compatible with a given 1246 /// architecture and the target triple contained within. 1247 bool Platform::IsCompatibleArchitecture(const ArchSpec &arch, 1248 bool exact_arch_match, 1249 ArchSpec *compatible_arch_ptr) { 1250 // If the architecture is invalid, we must answer true... 1251 if (arch.IsValid()) { 1252 ArchSpec platform_arch; 1253 // Try for an exact architecture match first. 1254 if (exact_arch_match) { 1255 for (uint32_t arch_idx = 0; 1256 GetSupportedArchitectureAtIndex(arch_idx, platform_arch); 1257 ++arch_idx) { 1258 if (arch.IsExactMatch(platform_arch)) { 1259 if (compatible_arch_ptr) 1260 *compatible_arch_ptr = platform_arch; 1261 return true; 1262 } 1263 } 1264 } else { 1265 for (uint32_t arch_idx = 0; 1266 GetSupportedArchitectureAtIndex(arch_idx, platform_arch); 1267 ++arch_idx) { 1268 if (arch.IsCompatibleMatch(platform_arch)) { 1269 if (compatible_arch_ptr) 1270 *compatible_arch_ptr = platform_arch; 1271 return true; 1272 } 1273 } 1274 } 1275 } 1276 if (compatible_arch_ptr) 1277 compatible_arch_ptr->Clear(); 1278 return false; 1279 } 1280 1281 Status Platform::PutFile(const FileSpec &source, const FileSpec &destination, 1282 uint32_t uid, uint32_t gid) { 1283 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM)); 1284 LLDB_LOGF(log, "[PutFile] Using block by block transfer....\n"); 1285 1286 auto source_open_options = 1287 File::eOpenOptionReadOnly | File::eOpenOptionCloseOnExec; 1288 namespace fs = llvm::sys::fs; 1289 if (fs::is_symlink_file(source.GetPath())) 1290 source_open_options |= File::eOpenOptionDontFollowSymlinks; 1291 1292 auto source_file = FileSystem::Instance().Open(source, source_open_options, 1293 lldb::eFilePermissionsUserRW); 1294 if (!source_file) 1295 return Status(source_file.takeError()); 1296 Status error; 1297 uint32_t permissions = source_file.get()->GetPermissions(error); 1298 if (permissions == 0) 1299 permissions = lldb::eFilePermissionsFileDefault; 1300 1301 lldb::user_id_t dest_file = OpenFile( 1302 destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly | 1303 File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec, 1304 permissions, error); 1305 LLDB_LOGF(log, "dest_file = %" PRIu64 "\n", dest_file); 1306 1307 if (error.Fail()) 1308 return error; 1309 if (dest_file == UINT64_MAX) 1310 return Status("unable to open target file"); 1311 lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024 * 16, 0)); 1312 uint64_t offset = 0; 1313 for (;;) { 1314 size_t bytes_read = buffer_sp->GetByteSize(); 1315 error = source_file.get()->Read(buffer_sp->GetBytes(), bytes_read); 1316 if (error.Fail() || bytes_read == 0) 1317 break; 1318 1319 const uint64_t bytes_written = 1320 WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error); 1321 if (error.Fail()) 1322 break; 1323 1324 offset += bytes_written; 1325 if (bytes_written != bytes_read) { 1326 // We didn't write the correct number of bytes, so adjust the file 1327 // position in the source file we are reading from... 1328 source_file.get()->SeekFromStart(offset); 1329 } 1330 } 1331 CloseFile(dest_file, error); 1332 1333 if (uid == UINT32_MAX && gid == UINT32_MAX) 1334 return error; 1335 1336 // TODO: ChownFile? 1337 1338 return error; 1339 } 1340 1341 Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) { 1342 Status error("unimplemented"); 1343 return error; 1344 } 1345 1346 Status 1347 Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src 1348 const FileSpec &dst) // The symlink points to dst 1349 { 1350 Status error("unimplemented"); 1351 return error; 1352 } 1353 1354 bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) { 1355 return false; 1356 } 1357 1358 Status Platform::Unlink(const FileSpec &path) { 1359 Status error("unimplemented"); 1360 return error; 1361 } 1362 1363 MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr, 1364 addr_t length, unsigned prot, 1365 unsigned flags, addr_t fd, 1366 addr_t offset) { 1367 uint64_t flags_platform = 0; 1368 if (flags & eMmapFlagsPrivate) 1369 flags_platform |= MAP_PRIVATE; 1370 if (flags & eMmapFlagsAnon) 1371 flags_platform |= MAP_ANON; 1372 1373 MmapArgList args({addr, length, prot, flags_platform, fd, offset}); 1374 return args; 1375 } 1376 1377 lldb_private::Status Platform::RunShellCommand( 1378 llvm::StringRef command, 1379 const FileSpec & 1380 working_dir, // Pass empty FileSpec to use the current working directory 1381 int *status_ptr, // Pass nullptr if you don't want the process exit status 1382 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the 1383 // process to exit 1384 std::string 1385 *command_output, // Pass nullptr if you don't want the command output 1386 const Timeout<std::micro> &timeout) { 1387 return RunShellCommand(llvm::StringRef(), command, working_dir, status_ptr, 1388 signo_ptr, command_output, timeout); 1389 } 1390 1391 lldb_private::Status Platform::RunShellCommand( 1392 llvm::StringRef shell, // Pass empty if you want to use the default 1393 // shell interpreter 1394 llvm::StringRef command, // Shouldn't be empty 1395 const FileSpec & 1396 working_dir, // Pass empty FileSpec to use the current working directory 1397 int *status_ptr, // Pass nullptr if you don't want the process exit status 1398 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the 1399 // process to exit 1400 std::string 1401 *command_output, // Pass nullptr if you don't want the command output 1402 const Timeout<std::micro> &timeout) { 1403 if (IsHost()) 1404 return Host::RunShellCommand(shell, command, working_dir, status_ptr, 1405 signo_ptr, command_output, timeout); 1406 else 1407 return Status("unimplemented"); 1408 } 1409 1410 bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low, 1411 uint64_t &high) { 1412 if (!IsHost()) 1413 return false; 1414 auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath()); 1415 if (!Result) 1416 return false; 1417 std::tie(high, low) = Result->words(); 1418 return true; 1419 } 1420 1421 void Platform::SetLocalCacheDirectory(const char *local) { 1422 m_local_cache_directory.assign(local); 1423 } 1424 1425 const char *Platform::GetLocalCacheDirectory() { 1426 return m_local_cache_directory.c_str(); 1427 } 1428 1429 static constexpr OptionDefinition g_rsync_option_table[] = { 1430 {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr, 1431 {}, 0, eArgTypeNone, "Enable rsync."}, 1432 {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R', 1433 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName, 1434 "Platform-specific options required for rsync to work."}, 1435 {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P', 1436 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName, 1437 "Platform-specific rsync prefix put before the remote path."}, 1438 {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i', 1439 OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone, 1440 "Do not automatically fill in the remote hostname when composing the " 1441 "rsync command."}, 1442 }; 1443 1444 static constexpr OptionDefinition g_ssh_option_table[] = { 1445 {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr, 1446 {}, 0, eArgTypeNone, "Enable SSH."}, 1447 {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument, 1448 nullptr, {}, 0, eArgTypeCommandName, 1449 "Platform-specific options required for SSH to work."}, 1450 }; 1451 1452 static constexpr OptionDefinition g_caching_option_table[] = { 1453 {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c', 1454 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePath, 1455 "Path in which to store local copies of files."}, 1456 }; 1457 1458 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() { 1459 return llvm::makeArrayRef(g_rsync_option_table); 1460 } 1461 1462 void OptionGroupPlatformRSync::OptionParsingStarting( 1463 ExecutionContext *execution_context) { 1464 m_rsync = false; 1465 m_rsync_opts.clear(); 1466 m_rsync_prefix.clear(); 1467 m_ignores_remote_hostname = false; 1468 } 1469 1470 lldb_private::Status 1471 OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx, 1472 llvm::StringRef option_arg, 1473 ExecutionContext *execution_context) { 1474 Status error; 1475 char short_option = (char)GetDefinitions()[option_idx].short_option; 1476 switch (short_option) { 1477 case 'r': 1478 m_rsync = true; 1479 break; 1480 1481 case 'R': 1482 m_rsync_opts.assign(std::string(option_arg)); 1483 break; 1484 1485 case 'P': 1486 m_rsync_prefix.assign(std::string(option_arg)); 1487 break; 1488 1489 case 'i': 1490 m_ignores_remote_hostname = true; 1491 break; 1492 1493 default: 1494 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); 1495 break; 1496 } 1497 1498 return error; 1499 } 1500 1501 lldb::BreakpointSP 1502 Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) { 1503 return lldb::BreakpointSP(); 1504 } 1505 1506 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() { 1507 return llvm::makeArrayRef(g_ssh_option_table); 1508 } 1509 1510 void OptionGroupPlatformSSH::OptionParsingStarting( 1511 ExecutionContext *execution_context) { 1512 m_ssh = false; 1513 m_ssh_opts.clear(); 1514 } 1515 1516 lldb_private::Status 1517 OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx, 1518 llvm::StringRef option_arg, 1519 ExecutionContext *execution_context) { 1520 Status error; 1521 char short_option = (char)GetDefinitions()[option_idx].short_option; 1522 switch (short_option) { 1523 case 's': 1524 m_ssh = true; 1525 break; 1526 1527 case 'S': 1528 m_ssh_opts.assign(std::string(option_arg)); 1529 break; 1530 1531 default: 1532 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); 1533 break; 1534 } 1535 1536 return error; 1537 } 1538 1539 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() { 1540 return llvm::makeArrayRef(g_caching_option_table); 1541 } 1542 1543 void OptionGroupPlatformCaching::OptionParsingStarting( 1544 ExecutionContext *execution_context) { 1545 m_cache_dir.clear(); 1546 } 1547 1548 lldb_private::Status OptionGroupPlatformCaching::SetOptionValue( 1549 uint32_t option_idx, llvm::StringRef option_arg, 1550 ExecutionContext *execution_context) { 1551 Status error; 1552 char short_option = (char)GetDefinitions()[option_idx].short_option; 1553 switch (short_option) { 1554 case 'c': 1555 m_cache_dir.assign(std::string(option_arg)); 1556 break; 1557 1558 default: 1559 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option); 1560 break; 1561 } 1562 1563 return error; 1564 } 1565 1566 Environment Platform::GetEnvironment() { return Environment(); } 1567 1568 const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() { 1569 if (!m_calculated_trap_handlers) { 1570 std::lock_guard<std::mutex> guard(m_mutex); 1571 if (!m_calculated_trap_handlers) { 1572 CalculateTrapHandlerSymbolNames(); 1573 m_calculated_trap_handlers = true; 1574 } 1575 } 1576 return m_trap_handlers; 1577 } 1578 1579 Status 1580 Platform::GetCachedExecutable(ModuleSpec &module_spec, 1581 lldb::ModuleSP &module_sp, 1582 const FileSpecList *module_search_paths_ptr) { 1583 const auto platform_spec = module_spec.GetFileSpec(); 1584 const auto error = 1585 LoadCachedExecutable(module_spec, module_sp, module_search_paths_ptr); 1586 if (error.Success()) { 1587 module_spec.GetFileSpec() = module_sp->GetFileSpec(); 1588 module_spec.GetPlatformFileSpec() = platform_spec; 1589 } 1590 1591 return error; 1592 } 1593 1594 Status 1595 Platform::LoadCachedExecutable(const ModuleSpec &module_spec, 1596 lldb::ModuleSP &module_sp, 1597 const FileSpecList *module_search_paths_ptr) { 1598 return GetRemoteSharedModule( 1599 module_spec, nullptr, module_sp, 1600 [&](const ModuleSpec &spec) { 1601 return ResolveRemoteExecutable(spec, module_sp, 1602 module_search_paths_ptr); 1603 }, 1604 nullptr); 1605 } 1606 1607 Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec, 1608 Process *process, 1609 lldb::ModuleSP &module_sp, 1610 const ModuleResolver &module_resolver, 1611 bool *did_create_ptr) { 1612 // Get module information from a target. 1613 ModuleSpec resolved_module_spec; 1614 bool got_module_spec = false; 1615 if (process) { 1616 // Try to get module information from the process 1617 if (process->GetModuleSpec(module_spec.GetFileSpec(), 1618 module_spec.GetArchitecture(), 1619 resolved_module_spec)) { 1620 if (!module_spec.GetUUID().IsValid() || 1621 module_spec.GetUUID() == resolved_module_spec.GetUUID()) { 1622 got_module_spec = true; 1623 } 1624 } 1625 } 1626 1627 if (!module_spec.GetArchitecture().IsValid()) { 1628 Status error; 1629 // No valid architecture was specified, ask the platform for the 1630 // architectures that we should be using (in the correct order) and see if 1631 // we can find a match that way 1632 ModuleSpec arch_module_spec(module_spec); 1633 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex( 1634 idx, arch_module_spec.GetArchitecture()); 1635 ++idx) { 1636 error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr, 1637 nullptr, nullptr); 1638 // Did we find an executable using one of the 1639 if (error.Success() && module_sp) 1640 break; 1641 } 1642 if (module_sp) { 1643 resolved_module_spec = arch_module_spec; 1644 got_module_spec = true; 1645 } 1646 } 1647 1648 if (!got_module_spec) { 1649 // Get module information from a target. 1650 if (GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(), 1651 resolved_module_spec)) { 1652 if (!module_spec.GetUUID().IsValid() || 1653 module_spec.GetUUID() == resolved_module_spec.GetUUID()) { 1654 got_module_spec = true; 1655 } 1656 } 1657 } 1658 1659 if (!got_module_spec) { 1660 // Fall back to the given module resolver, which may have its own 1661 // search logic. 1662 return module_resolver(module_spec); 1663 } 1664 1665 // If we are looking for a specific UUID, make sure resolved_module_spec has 1666 // the same one before we search. 1667 if (module_spec.GetUUID().IsValid()) { 1668 resolved_module_spec.GetUUID() = module_spec.GetUUID(); 1669 } 1670 1671 // Trying to find a module by UUID on local file system. 1672 const auto error = module_resolver(resolved_module_spec); 1673 if (error.Fail()) { 1674 if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr)) 1675 return Status(); 1676 } 1677 1678 return error; 1679 } 1680 1681 bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec, 1682 lldb::ModuleSP &module_sp, 1683 bool *did_create_ptr) { 1684 if (IsHost() || !GetGlobalPlatformProperties().GetUseModuleCache() || 1685 !GetGlobalPlatformProperties().GetModuleCacheDirectory()) 1686 return false; 1687 1688 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); 1689 1690 // Check local cache for a module. 1691 auto error = m_module_cache->GetAndPut( 1692 GetModuleCacheRoot(), GetCacheHostname(), module_spec, 1693 [this](const ModuleSpec &module_spec, 1694 const FileSpec &tmp_download_file_spec) { 1695 return DownloadModuleSlice( 1696 module_spec.GetFileSpec(), module_spec.GetObjectOffset(), 1697 module_spec.GetObjectSize(), tmp_download_file_spec); 1698 1699 }, 1700 [this](const ModuleSP &module_sp, 1701 const FileSpec &tmp_download_file_spec) { 1702 return DownloadSymbolFile(module_sp, tmp_download_file_spec); 1703 }, 1704 module_sp, did_create_ptr); 1705 if (error.Success()) 1706 return true; 1707 1708 LLDB_LOGF(log, "Platform::%s - module %s not found in local cache: %s", 1709 __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(), 1710 error.AsCString()); 1711 return false; 1712 } 1713 1714 Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec, 1715 const uint64_t src_offset, 1716 const uint64_t src_size, 1717 const FileSpec &dst_file_spec) { 1718 Status error; 1719 1720 std::error_code EC; 1721 llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::OF_None); 1722 if (EC) { 1723 error.SetErrorStringWithFormat("unable to open destination file: %s", 1724 dst_file_spec.GetPath().c_str()); 1725 return error; 1726 } 1727 1728 auto src_fd = OpenFile(src_file_spec, File::eOpenOptionReadOnly, 1729 lldb::eFilePermissionsFileDefault, error); 1730 1731 if (error.Fail()) { 1732 error.SetErrorStringWithFormat("unable to open source file: %s", 1733 error.AsCString()); 1734 return error; 1735 } 1736 1737 std::vector<char> buffer(1024); 1738 auto offset = src_offset; 1739 uint64_t total_bytes_read = 0; 1740 while (total_bytes_read < src_size) { 1741 const auto to_read = std::min(static_cast<uint64_t>(buffer.size()), 1742 src_size - total_bytes_read); 1743 const uint64_t n_read = 1744 ReadFile(src_fd, offset, &buffer[0], to_read, error); 1745 if (error.Fail()) 1746 break; 1747 if (n_read == 0) { 1748 error.SetErrorString("read 0 bytes"); 1749 break; 1750 } 1751 offset += n_read; 1752 total_bytes_read += n_read; 1753 dst.write(&buffer[0], n_read); 1754 } 1755 1756 Status close_error; 1757 CloseFile(src_fd, close_error); // Ignoring close error. 1758 1759 return error; 1760 } 1761 1762 Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp, 1763 const FileSpec &dst_file_spec) { 1764 return Status( 1765 "Symbol file downloading not supported by the default platform."); 1766 } 1767 1768 FileSpec Platform::GetModuleCacheRoot() { 1769 auto dir_spec = GetGlobalPlatformProperties().GetModuleCacheDirectory(); 1770 dir_spec.AppendPathComponent(GetName().AsCString()); 1771 return dir_spec; 1772 } 1773 1774 const char *Platform::GetCacheHostname() { return GetHostname(); } 1775 1776 const UnixSignalsSP &Platform::GetRemoteUnixSignals() { 1777 static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>(); 1778 return s_default_unix_signals_sp; 1779 } 1780 1781 UnixSignalsSP Platform::GetUnixSignals() { 1782 if (IsHost()) 1783 return UnixSignals::CreateForHost(); 1784 return GetRemoteUnixSignals(); 1785 } 1786 1787 uint32_t Platform::LoadImage(lldb_private::Process *process, 1788 const lldb_private::FileSpec &local_file, 1789 const lldb_private::FileSpec &remote_file, 1790 lldb_private::Status &error) { 1791 if (local_file && remote_file) { 1792 // Both local and remote file was specified. Install the local file to the 1793 // given location. 1794 if (IsRemote() || local_file != remote_file) { 1795 error = Install(local_file, remote_file); 1796 if (error.Fail()) 1797 return LLDB_INVALID_IMAGE_TOKEN; 1798 } 1799 return DoLoadImage(process, remote_file, nullptr, error); 1800 } 1801 1802 if (local_file) { 1803 // Only local file was specified. Install it to the current working 1804 // directory. 1805 FileSpec target_file = GetWorkingDirectory(); 1806 target_file.AppendPathComponent(local_file.GetFilename().AsCString()); 1807 if (IsRemote() || local_file != target_file) { 1808 error = Install(local_file, target_file); 1809 if (error.Fail()) 1810 return LLDB_INVALID_IMAGE_TOKEN; 1811 } 1812 return DoLoadImage(process, target_file, nullptr, error); 1813 } 1814 1815 if (remote_file) { 1816 // Only remote file was specified so we don't have to do any copying 1817 return DoLoadImage(process, remote_file, nullptr, error); 1818 } 1819 1820 error.SetErrorString("Neither local nor remote file was specified"); 1821 return LLDB_INVALID_IMAGE_TOKEN; 1822 } 1823 1824 uint32_t Platform::DoLoadImage(lldb_private::Process *process, 1825 const lldb_private::FileSpec &remote_file, 1826 const std::vector<std::string> *paths, 1827 lldb_private::Status &error, 1828 lldb_private::FileSpec *loaded_image) { 1829 error.SetErrorString("LoadImage is not supported on the current platform"); 1830 return LLDB_INVALID_IMAGE_TOKEN; 1831 } 1832 1833 uint32_t Platform::LoadImageUsingPaths(lldb_private::Process *process, 1834 const lldb_private::FileSpec &remote_filename, 1835 const std::vector<std::string> &paths, 1836 lldb_private::Status &error, 1837 lldb_private::FileSpec *loaded_path) 1838 { 1839 FileSpec file_to_use; 1840 if (remote_filename.IsAbsolute()) 1841 file_to_use = FileSpec(remote_filename.GetFilename().GetStringRef(), 1842 1843 remote_filename.GetPathStyle()); 1844 else 1845 file_to_use = remote_filename; 1846 1847 return DoLoadImage(process, file_to_use, &paths, error, loaded_path); 1848 } 1849 1850 Status Platform::UnloadImage(lldb_private::Process *process, 1851 uint32_t image_token) { 1852 return Status("UnloadImage is not supported on the current platform"); 1853 } 1854 1855 lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url, 1856 llvm::StringRef plugin_name, 1857 Debugger &debugger, Target *target, 1858 Status &error) { 1859 return DoConnectProcess(connect_url, plugin_name, debugger, nullptr, target, 1860 error); 1861 } 1862 1863 lldb::ProcessSP Platform::ConnectProcessSynchronous( 1864 llvm::StringRef connect_url, llvm::StringRef plugin_name, 1865 Debugger &debugger, Stream &stream, Target *target, Status &error) { 1866 return DoConnectProcess(connect_url, plugin_name, debugger, &stream, target, 1867 error); 1868 } 1869 1870 lldb::ProcessSP Platform::DoConnectProcess(llvm::StringRef connect_url, 1871 llvm::StringRef plugin_name, 1872 Debugger &debugger, Stream *stream, 1873 Target *target, Status &error) { 1874 error.Clear(); 1875 1876 if (!target) { 1877 ArchSpec arch; 1878 if (target && target->GetArchitecture().IsValid()) 1879 arch = target->GetArchitecture(); 1880 else 1881 arch = Target::GetDefaultArchitecture(); 1882 1883 const char *triple = ""; 1884 if (arch.IsValid()) 1885 triple = arch.GetTriple().getTriple().c_str(); 1886 1887 TargetSP new_target_sp; 1888 error = debugger.GetTargetList().CreateTarget( 1889 debugger, "", triple, eLoadDependentsNo, nullptr, new_target_sp); 1890 target = new_target_sp.get(); 1891 } 1892 1893 if (!target || error.Fail()) 1894 return nullptr; 1895 1896 lldb::ProcessSP process_sp = 1897 target->CreateProcess(debugger.GetListener(), plugin_name, nullptr, true); 1898 1899 if (!process_sp) 1900 return nullptr; 1901 1902 // If this private method is called with a stream we are synchronous. 1903 const bool synchronous = stream != nullptr; 1904 1905 ListenerSP listener_sp( 1906 Listener::MakeListener("lldb.Process.ConnectProcess.hijack")); 1907 if (synchronous) 1908 process_sp->HijackProcessEvents(listener_sp); 1909 1910 error = process_sp->ConnectRemote(connect_url); 1911 if (error.Fail()) { 1912 if (synchronous) 1913 process_sp->RestoreProcessEvents(); 1914 return nullptr; 1915 } 1916 1917 if (synchronous) { 1918 EventSP event_sp; 1919 process_sp->WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp, 1920 nullptr); 1921 process_sp->RestoreProcessEvents(); 1922 bool pop_process_io_handler = false; 1923 Process::HandleProcessStateChangedEvent(event_sp, stream, 1924 pop_process_io_handler); 1925 } 1926 1927 return process_sp; 1928 } 1929 1930 size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger, 1931 lldb_private::Status &error) { 1932 error.Clear(); 1933 return 0; 1934 } 1935 1936 size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target, 1937 BreakpointSite *bp_site) { 1938 ArchSpec arch = target.GetArchitecture(); 1939 assert(arch.IsValid()); 1940 const uint8_t *trap_opcode = nullptr; 1941 size_t trap_opcode_size = 0; 1942 1943 switch (arch.GetMachine()) { 1944 case llvm::Triple::aarch64_32: 1945 case llvm::Triple::aarch64: { 1946 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4}; 1947 trap_opcode = g_aarch64_opcode; 1948 trap_opcode_size = sizeof(g_aarch64_opcode); 1949 } break; 1950 1951 case llvm::Triple::arc: { 1952 static const uint8_t g_hex_opcode[] = { 0xff, 0x7f }; 1953 trap_opcode = g_hex_opcode; 1954 trap_opcode_size = sizeof(g_hex_opcode); 1955 } break; 1956 1957 // TODO: support big-endian arm and thumb trap codes. 1958 case llvm::Triple::arm: { 1959 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the 1960 // linux kernel does otherwise. 1961 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7}; 1962 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde}; 1963 1964 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0)); 1965 AddressClass addr_class = AddressClass::eUnknown; 1966 1967 if (bp_loc_sp) { 1968 addr_class = bp_loc_sp->GetAddress().GetAddressClass(); 1969 if (addr_class == AddressClass::eUnknown && 1970 (bp_loc_sp->GetAddress().GetFileAddress() & 1)) 1971 addr_class = AddressClass::eCodeAlternateISA; 1972 } 1973 1974 if (addr_class == AddressClass::eCodeAlternateISA) { 1975 trap_opcode = g_thumb_breakpoint_opcode; 1976 trap_opcode_size = sizeof(g_thumb_breakpoint_opcode); 1977 } else { 1978 trap_opcode = g_arm_breakpoint_opcode; 1979 trap_opcode_size = sizeof(g_arm_breakpoint_opcode); 1980 } 1981 } break; 1982 1983 case llvm::Triple::avr: { 1984 static const uint8_t g_hex_opcode[] = {0x98, 0x95}; 1985 trap_opcode = g_hex_opcode; 1986 trap_opcode_size = sizeof(g_hex_opcode); 1987 } break; 1988 1989 case llvm::Triple::mips: 1990 case llvm::Triple::mips64: { 1991 static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d}; 1992 trap_opcode = g_hex_opcode; 1993 trap_opcode_size = sizeof(g_hex_opcode); 1994 } break; 1995 1996 case llvm::Triple::mipsel: 1997 case llvm::Triple::mips64el: { 1998 static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00}; 1999 trap_opcode = g_hex_opcode; 2000 trap_opcode_size = sizeof(g_hex_opcode); 2001 } break; 2002 2003 case llvm::Triple::systemz: { 2004 static const uint8_t g_hex_opcode[] = {0x00, 0x01}; 2005 trap_opcode = g_hex_opcode; 2006 trap_opcode_size = sizeof(g_hex_opcode); 2007 } break; 2008 2009 case llvm::Triple::hexagon: { 2010 static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54}; 2011 trap_opcode = g_hex_opcode; 2012 trap_opcode_size = sizeof(g_hex_opcode); 2013 } break; 2014 2015 case llvm::Triple::ppc: 2016 case llvm::Triple::ppc64: { 2017 static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08}; 2018 trap_opcode = g_ppc_opcode; 2019 trap_opcode_size = sizeof(g_ppc_opcode); 2020 } break; 2021 2022 case llvm::Triple::ppc64le: { 2023 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap 2024 trap_opcode = g_ppc64le_opcode; 2025 trap_opcode_size = sizeof(g_ppc64le_opcode); 2026 } break; 2027 2028 case llvm::Triple::x86: 2029 case llvm::Triple::x86_64: { 2030 static const uint8_t g_i386_opcode[] = {0xCC}; 2031 trap_opcode = g_i386_opcode; 2032 trap_opcode_size = sizeof(g_i386_opcode); 2033 } break; 2034 2035 default: 2036 return 0; 2037 } 2038 2039 assert(bp_site); 2040 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size)) 2041 return trap_opcode_size; 2042 2043 return 0; 2044 } 2045