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