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