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