1 //===-- Platform.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
16 // Other libraries and framework includes
17 #include "llvm/Support/FileSystem.h"
18 #include "llvm/Support/Path.h"
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"
46 #include "llvm/Support/FileSystem.h"
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.
51 #define MAP_ANON 0x1000
54 using namespace lldb_private;
56 static uint32_t g_initialize_count = 0;
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;
65 const char *Platform::GetHostPlatformName() { return "host"; }
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}};
76 enum { ePropertyUseModuleCache, ePropertyModuleCacheDirectory };
80 ConstString PlatformProperties::GetSettingName() {
81 static ConstString g_setting_name("platform");
82 return g_setting_name;
85 PlatformProperties::PlatformProperties() {
86 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
87 m_collection_sp->Initialize(g_properties);
89 auto module_cache_dir = GetModuleCacheDirectory();
93 llvm::SmallString<64> user_home_dir;
94 if (!llvm::sys::path::home_directory(user_home_dir))
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);
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);
109 bool PlatformProperties::SetUseModuleCache(bool use_module_cache) {
110 return m_collection_sp->SetPropertyAtIndexAsBoolean(
111 nullptr, ePropertyUseModuleCache, use_module_cache);
114 FileSpec PlatformProperties::GetModuleCacheDirectory() const {
115 return m_collection_sp->GetPropertyAtIndexAsFileSpec(
116 nullptr, ePropertyModuleCacheDirectory);
119 bool PlatformProperties::SetModuleCacheDirectory(const FileSpec &dir_spec) {
120 return m_collection_sp->SetPropertyAtIndexAsFileSpec(
121 nullptr, ePropertyModuleCacheDirectory, dir_spec);
124 //------------------------------------------------------------------
125 /// Get the native host platform plug-in.
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.
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(); }
136 static std::vector<PlatformSP> &GetPlatformList() {
137 static std::vector<PlatformSP> g_platform_list;
138 return g_platform_list;
141 static std::recursive_mutex &GetPlatformListMutex() {
142 static std::recursive_mutex g_mutex;
146 void Platform::Initialize() { g_initialize_count++; }
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();
157 const PlatformPropertiesSP &Platform::GetGlobalPlatformProperties() {
158 static const auto g_settings_sp(std::make_shared<PlatformProperties>());
159 return g_settings_sp;
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;
168 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
169 GetPlatformList().push_back(platform_sp);
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;
181 Platform::LocateExecutableScriptingResources(Target *target, Module &module,
182 Stream *feedback_stream) {
183 return FileSpecList();
187 // Platform::FindPlugin (Process *process, const ConstString &plugin_name)
189 // PlatformCreateInstance create_callback = nullptr;
193 // PluginManager::GetPlatformCreateCallbackForPluginName (plugin_name);
194 // if (create_callback)
199 // arch = process->GetTarget().GetArchitecture();
201 // PlatformSP platform_sp(create_callback(process, &arch));
203 // return platform_sp;
208 // for (uint32_t idx = 0; (create_callback =
209 // PluginManager::GetPlatformCreateCallbackAtIndex(idx)) != nullptr;
212 // PlatformSP platform_sp(create_callback(process, nullptr));
214 // return platform_sp;
217 // return PlatformSP();
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) {
226 return ModuleList::GetSharedModule(
227 module_spec, module_sp, module_search_paths_ptr, old_module_sp_ptr,
228 did_create_ptr, false);
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(
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,
250 ModuleSpec matched_module_spec;
251 return module_specs.FindMatchingModuleSpec(ModuleSpec(module_file_spec, arch),
255 PlatformSP Platform::Find(const ConstString &name) {
257 static ConstString g_host_platform_name("host");
258 if (name == g_host_platform_name)
259 return GetHostPlatform();
261 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
262 for (const auto &platform_sp : GetPlatformList()) {
263 if (platform_sp->GetName() == name)
270 PlatformSP Platform::Create(const ConstString &name, Status &error) {
271 PlatformCreateInstance create_callback = nullptr;
272 lldb::PlatformSP platform_sp;
274 static ConstString g_host_platform_name("host");
275 if (name == g_host_platform_name)
276 return GetHostPlatform();
279 PluginManager::GetPlatformCreateCallbackForPluginName(name);
281 platform_sp = create_callback(true, nullptr);
283 error.SetErrorStringWithFormat(
284 "unable to find a plug-in for the platform named \"%s\"",
287 error.SetErrorString("invalid platform name");
290 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
291 GetPlatformList().push_back(platform_sp);
297 PlatformSP Platform::Create(const ArchSpec &arch, ArchSpec *platform_arch_ptr,
299 lldb::PlatformSP platform_sp;
300 if (arch.IsValid()) {
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,
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,
319 PlatformCreateInstance create_callback;
320 // First try exact arch matches across all platform plug-ins
322 for (idx = 0; (create_callback =
323 PluginManager::GetPlatformCreateCallbackAtIndex(idx));
325 if (create_callback) {
326 platform_sp = create_callback(false, &arch);
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);
336 // Next try compatible arch matches across all platform plug-ins
337 for (idx = 0; (create_callback =
338 PluginManager::GetPlatformCreateCallbackAtIndex(idx));
340 if (create_callback) {
341 platform_sp = create_callback(false, &arch);
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);
352 error.SetErrorString("invalid platform name");
353 if (platform_arch_ptr)
354 platform_arch_ptr->Clear();
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));
375 log->Printf("%p Platform::Platform()", static_cast<void *>(this));
378 //------------------------------------------------------------------
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));
387 log->Printf("%p Platform::~Platform()", static_cast<void *>(this));
390 void Platform::GetStatus(Stream &strm) {
391 uint32_t major = UINT32_MAX;
392 uint32_t minor = UINT32_MAX;
393 uint32_t update = UINT32_MAX;
395 strm.Printf(" Platform: %s\n", GetPluginName().GetCString());
397 ArchSpec arch(GetSystemArchitecture());
398 if (arch.IsValid()) {
399 if (!arch.GetTriple().str().empty()) {
400 strm.Printf(" Triple: ");
401 arch.DumpTriple(strm);
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);
413 if (GetOSBuildString(s))
414 strm.Printf(" (%s)", s.c_str());
419 if (GetOSKernelDescription(s))
420 strm.Printf(" Kernel: %s\n", s.c_str());
423 strm.Printf(" Hostname: %s\n", GetHostname());
425 const bool is_connected = IsConnected();
427 strm.Printf(" Hostname: %s\n", GetHostname());
428 strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no");
431 if (GetWorkingDirectory()) {
432 strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString());
437 std::string specific_info(GetPlatformSpecificConnectionInformation());
439 if (!specific_info.empty())
440 strm.Printf("Platform-specific connection: %s\n", specific_info.c_str());
443 bool Platform::GetOSVersion(uint32_t &major, uint32_t &minor, uint32_t &update,
445 std::lock_guard<std::mutex> guard(m_mutex);
447 bool success = m_major_os_version != UINT32_MAX;
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;
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
460 const bool is_connected = IsConnected();
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)
471 // We don't have valid OS version info, fetch it if we are connected
472 fetch = is_connected;
476 success = GetRemoteOSVersion();
477 m_os_version_set_while_connected = 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);
493 bool Platform::GetOSBuildString(std::string &s) {
497 #if !defined(__linux__)
498 return HostInfo::GetOSBuildString(s);
503 return GetRemoteOSBuildString(s);
506 bool Platform::GetOSKernelDescription(std::string &s) {
508 #if !defined(__linux__)
509 return HostInfo::GetOSKernelDescription(s);
514 return GetRemoteOSKernelDescription(s);
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"};
522 options.insert(options.end(), default_compilation_options.begin(),
523 default_compilation_options.end());
526 FileSpec Platform::GetWorkingDirectory() {
528 llvm::SmallString<64> cwd;
529 if (llvm::sys::fs::current_path(cwd))
532 return FileSpec(cwd, true);
535 m_working_dir = GetRemoteWorkingDirectory();
536 return m_working_dir;
540 struct RecurseCopyBaton {
542 Platform *platform_ptr;
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;
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;
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);
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
572 std::string src_dir_path(src.GetPath());
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,
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
586 return FileSpec::eEnumerateDirectoryResultNext;
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();
595 FileSpec src_resolved;
597 rc_baton->error = FileSystem::Readlink(src, src_resolved);
599 if (rc_baton->error.Fail())
600 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
603 rc_baton->platform_ptr->CreateSymlink(dst_file, src_resolved);
605 if (rc_baton->error.Fail())
606 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
608 return FileSpec::eEnumerateDirectoryResultNext;
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);
618 rc_baton->error.SetErrorString(err.AsCString());
619 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
621 return FileSpec::eEnumerateDirectoryResultNext;
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
630 llvm_unreachable("Unhandled file_type!");
633 Status Platform::Install(const FileSpec &src, const FileSpec &dst) {
636 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
638 log->Printf("Platform::Install (src='%s', dst='%s')", src.GetPath().c_str(),
639 dst.GetPath().c_str());
640 FileSpec fixed_dst(dst);
642 if (!fixed_dst.GetFilename())
643 fixed_dst.GetFilename() = src.GetFilename();
645 FileSpec working_dir = GetWorkingDirectory();
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();
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;
660 relative_spec = working_dir;
661 relative_spec.AppendPathComponent(dst.GetPath());
662 fixed_dst.GetDirectory() = relative_spec.GetDirectory();
664 error.SetErrorStringWithFormat(
665 "platform working directory must be valid for relative path '%s'",
666 dst.GetPath().c_str());
672 fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
674 error.SetErrorStringWithFormat(
675 "platform working directory must be valid for relative path '%s'",
676 dst.GetPath().c_str());
682 fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
684 error.SetErrorStringWithFormat("platform working directory must be valid "
685 "when destination directory is empty");
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());
695 if (GetSupportsRSync()) {
696 error = PutFile(src, dst);
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);
719 case fs::file_type::regular_file:
720 llvm::sys::fs::remove(fixed_dst.GetPath());
721 error = PutFile(src, fixed_dst);
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);
729 error = CreateSymlink(dst, src_resolved);
731 case fs::file_type::fifo_file:
732 error.SetErrorString("platform install doesn't handle pipes");
734 case fs::file_type::socket_file:
735 error.SetErrorString("platform install doesn't handle sockets");
738 error.SetErrorString(
739 "platform install doesn't handle non file or directory items");
746 bool Platform::SetWorkingDirectory(const FileSpec &file_spec) {
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());
756 m_working_dir.Clear();
757 return SetRemoteWorkingDirectory(file_spec);
761 Status Platform::MakeDirectory(const FileSpec &file_spec,
762 uint32_t permissions) {
764 return llvm::sys::fs::create_directory(file_spec.GetPath(), permissions);
767 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
768 GetPluginName().GetCString(),
769 LLVM_PRETTY_FUNCTION);
774 Status Platform::GetFilePermissions(const FileSpec &file_spec,
775 uint32_t &file_permissions) {
777 auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath());
779 file_permissions = Value.get();
780 return Status(Value.getError());
783 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
784 GetPluginName().GetCString(),
785 LLVM_PRETTY_FUNCTION);
790 Status Platform::SetFilePermissions(const FileSpec &file_spec,
791 uint32_t file_permissions) {
793 auto Perms = static_cast<llvm::sys::fs::perms>(file_permissions);
794 return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms);
797 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
798 GetPluginName().GetCString(),
799 LLVM_PRETTY_FUNCTION);
804 ConstString Platform::GetName() { return GetPluginName(); }
806 const char *Platform::GetHostname() {
812 return m_name.c_str();
815 ConstString Platform::GetFullNameForDylib(ConstString basename) {
819 bool Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
820 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
822 log->Printf("Platform::SetRemoteWorkingDirectory('%s')",
823 working_dir.GetCString());
824 m_working_dir = working_dir;
828 const char *Platform::GetUserName(uint32_t uid) {
829 #if !defined(LLDB_DISABLE_POSIX)
830 const char *user_name = GetCachedUserName(uid);
835 if (HostInfo::LookupUserName(uid, name))
836 return SetCachedUserName(uid, name.c_str(), name.size());
842 const char *Platform::GetGroupName(uint32_t gid) {
843 #if !defined(LLDB_DISABLE_POSIX)
844 const char *group_name = GetCachedGroupName(gid);
849 if (HostInfo::LookupGroupName(gid, name))
850 return SetCachedGroupName(gid, name.c_str(), name.size());
856 bool Platform::SetOSVersion(uint32_t major, uint32_t minor, uint32_t update) {
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(...).
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.
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;
883 Platform::ResolveExecutable(const ModuleSpec &module_spec,
884 lldb::ModuleSP &exe_module_sp,
885 const FileSpecList *module_search_paths_ptr) {
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,
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());
900 error = ModuleList::GetSharedModule(arch_module_spec, exe_module_sp,
901 module_search_paths_ptr, nullptr,
903 // Did we find an executable using one of the
904 if (error.Success() && exe_module_sp)
909 error.SetErrorStringWithFormat("'%s' does not exist",
910 module_spec.GetFileSpec().GetPath().c_str());
915 Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec,
916 FileSpec &sym_file) {
918 if (sym_spec.GetSymbolFileSpec().Exists())
919 sym_file = sym_spec.GetSymbolFileSpec();
921 error.SetErrorString("unable to resolve symbol file");
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();
931 const ArchSpec &Platform::GetSystemArchitecture() {
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();
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
943 const bool is_connected = IsConnected();
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)
954 // We don't have valid OS version info, fetch it if we are connected
955 fetch = is_connected;
959 m_system_arch = GetRemoteSystemArchitecture();
960 m_system_arch_set_while_connected = m_system_arch.IsValid();
963 return m_system_arch;
966 Status Platform::ConnectRemote(Args &args) {
969 error.SetErrorStringWithFormat("The currently selected platform (%s) is "
970 "the host platform and is always connected.",
971 GetPluginName().GetCString());
973 error.SetErrorStringWithFormat(
974 "Platform::ConnectRemote() is not supported by %s",
975 GetPluginName().GetCString());
979 Status Platform::DisconnectRemote() {
982 error.SetErrorStringWithFormat("The currently selected platform (%s) is "
983 "the host platform and is always connected.",
984 GetPluginName().GetCString());
986 error.SetErrorStringWithFormat(
987 "Platform::DisconnectRemote() is not supported by %s",
988 GetPluginName().GetCString());
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.
997 return Host::GetProcessInfo(pid, process_info);
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;
1007 match_count = Host::FindProcesses(match_info, process_infos);
1011 Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) {
1013 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1015 log->Printf("Platform::%s()", __FUNCTION__);
1017 // Take care of the host case so that each subclass can just
1018 // call this function to get the host functionality.
1020 if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
1021 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
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);
1029 const FileSpec &shell = launch_info.GetShell();
1030 const char *shell_str = (shell) ? shell.GetPath().c_str() : "<null>";
1032 "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32
1034 __FUNCTION__, num_resumes, shell_str);
1037 if (!launch_info.ConvertArgumentsForLaunchingInShell(
1038 error, is_localhost, will_debug, first_arg_is_full_shell_command,
1041 } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1042 error = ShellExpandArguments(launch_info);
1044 error.SetErrorStringWithFormat("shell expansion failed (reason: %s). "
1045 "consider launching with 'process "
1047 error.AsCString("unknown"));
1053 log->Printf("Platform::%s final launch_info resume count: %" PRIu32,
1054 __FUNCTION__, launch_info.GetResumeCount());
1056 error = Host::LaunchProcess(launch_info);
1058 error.SetErrorString(
1059 "base lldb_private::Platform class can't launch remote processes");
1063 Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
1065 return Host::ShellExpandArguments(launch_info);
1066 return Status("base lldb_private::Platform class can't expand arguments");
1069 Status Platform::KillProcess(const lldb::pid_t pid) {
1070 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1072 log->Printf("Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
1074 // Try to find a process plugin to handle this Kill request. If we can't,
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);
1090 "base lldb_private::Platform class can't kill remote processes unless "
1091 "they are controlled by a process plugin");
1093 Host::Kill(pid, SIGTERM);
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
1102 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1104 log->Printf("Platform::%s entered (target %p)", __FUNCTION__,
1105 static_cast<void *>(target));
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);
1115 // Allow any StructuredData process-bound plugins to adjust the launch info
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
1128 error = (*filter_callback)(launch_info, target);
1129 if (!error.Success()) {
1131 log->Printf("Platform::%s() StructuredDataPlugin launch "
1139 error = LaunchProcess(launch_info);
1140 if (error.Success()) {
1142 log->Printf("Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64
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);
1150 log->Printf("Platform::%s Attach() succeeded, Process plugin: %s",
1151 __FUNCTION__, process_sp->GetPluginName().AsCString());
1152 launch_info.SetHijackListener(attach_info.GetHijackListener());
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);
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);
1170 log->Printf("Platform::%s Attach() failed: %s", __FUNCTION__,
1175 log->Printf("Platform::%s LaunchProcess() returned launch_info with "
1176 "invalid process id",
1181 log->Printf("Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
1189 Platform::GetPlatformForArchitecture(const ArchSpec &arch,
1190 ArchSpec *platform_arch_ptr) {
1191 lldb::PlatformSP platform_sp;
1194 platform_sp = Platform::Create(arch, platform_arch_ptr, error);
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);
1213 if (arch.IsExactMatch(platform_arch)) {
1214 if (compatible_arch_ptr)
1215 *compatible_arch_ptr = platform_arch;
1220 for (uint32_t arch_idx = 0;
1221 GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1223 if (arch.IsCompatibleMatch(platform_arch)) {
1224 if (compatible_arch_ptr)
1225 *compatible_arch_ptr = platform_arch;
1231 if (compatible_arch_ptr)
1232 compatible_arch_ptr->Clear();
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));
1240 log->Printf("[PutFile] Using block by block transfer....\n");
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;
1248 File source_file(source, source_open_options, lldb::eFilePermissionsUserRW);
1250 uint32_t permissions = source_file.GetPermissions(error);
1251 if (permissions == 0)
1252 permissions = lldb::eFilePermissionsFileDefault;
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);
1261 log->Printf("dest_file = %" PRIu64 "\n", dest_file);
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;
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)
1275 const uint64_t bytes_written =
1276 WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error);
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);
1287 CloseFile(dest_file, error);
1289 if (uid == UINT32_MAX && gid == UINT32_MAX)
1297 Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) {
1298 Status error("unimplemented");
1303 Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1304 const FileSpec &dst) // The symlink points to dst
1306 Status error("unimplemented");
1310 bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) {
1314 Status Platform::Unlink(const FileSpec &path) {
1315 Status error("unimplemented");
1319 MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr,
1320 addr_t length, unsigned prot,
1321 unsigned flags, addr_t fd,
1323 uint64_t flags_platform = 0;
1324 if (flags & eMmapFlagsPrivate)
1325 flags_platform |= MAP_PRIVATE;
1326 if (flags & eMmapFlagsAnon)
1327 flags_platform |= MAP_ANON;
1329 MmapArgList args({addr, length, prot, flags_platform, fd, offset});
1333 lldb_private::Status Platform::RunShellCommand(
1334 const char *command, // Shouldn't be nullptr
1336 working_dir, // Pass empty FileSpec to use the current working directory
1337 int *status_ptr, // Pass nullptr if you don't want the process exit status
1338 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1341 *command_output, // Pass nullptr if you don't want the command output
1343 timeout_sec) // Timeout in seconds to wait for shell program to finish
1346 return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr,
1347 command_output, timeout_sec);
1349 return Status("unimplemented");
1352 bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
1356 auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath());
1359 std::tie(high, low) = Result->words();
1363 void Platform::SetLocalCacheDirectory(const char *local) {
1364 m_local_cache_directory.assign(local);
1367 const char *Platform::GetLocalCacheDirectory() {
1368 return m_local_cache_directory.c_str();
1371 static OptionDefinition g_rsync_option_table[] = {
1372 {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
1373 nullptr, 0, eArgTypeNone, "Enable rsync."},
1374 {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
1375 OptionParser::eRequiredArgument, nullptr, 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, 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, nullptr, 0, eArgTypeNone,
1382 "Do not automatically fill in the remote hostname when composing the "
1386 static OptionDefinition g_ssh_option_table[] = {
1387 {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
1388 nullptr, 0, eArgTypeNone, "Enable SSH."},
1389 {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
1390 nullptr, nullptr, 0, eArgTypeCommandName,
1391 "Platform-specific options required for SSH to work."},
1394 static OptionDefinition g_caching_option_table[] = {
1395 {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
1396 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePath,
1397 "Path in which to store local copies of files."},
1400 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
1401 return llvm::makeArrayRef(g_rsync_option_table);
1404 void OptionGroupPlatformRSync::OptionParsingStarting(
1405 ExecutionContext *execution_context) {
1407 m_rsync_opts.clear();
1408 m_rsync_prefix.clear();
1409 m_ignores_remote_hostname = false;
1412 lldb_private::Status
1413 OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx,
1414 llvm::StringRef option_arg,
1415 ExecutionContext *execution_context) {
1417 char short_option = (char)GetDefinitions()[option_idx].short_option;
1418 switch (short_option) {
1424 m_rsync_opts.assign(option_arg);
1428 m_rsync_prefix.assign(option_arg);
1432 m_ignores_remote_hostname = true;
1436 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1444 Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) {
1445 return lldb::BreakpointSP();
1448 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
1449 return llvm::makeArrayRef(g_ssh_option_table);
1452 void OptionGroupPlatformSSH::OptionParsingStarting(
1453 ExecutionContext *execution_context) {
1458 lldb_private::Status
1459 OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx,
1460 llvm::StringRef option_arg,
1461 ExecutionContext *execution_context) {
1463 char short_option = (char)GetDefinitions()[option_idx].short_option;
1464 switch (short_option) {
1470 m_ssh_opts.assign(option_arg);
1474 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1481 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
1482 return llvm::makeArrayRef(g_caching_option_table);
1485 void OptionGroupPlatformCaching::OptionParsingStarting(
1486 ExecutionContext *execution_context) {
1487 m_cache_dir.clear();
1490 lldb_private::Status OptionGroupPlatformCaching::SetOptionValue(
1491 uint32_t option_idx, llvm::StringRef option_arg,
1492 ExecutionContext *execution_context) {
1494 char short_option = (char)GetDefinitions()[option_idx].short_option;
1495 switch (short_option) {
1497 m_cache_dir.assign(option_arg);
1501 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1508 size_t Platform::GetEnvironment(StringList &environment) {
1509 environment.Clear();
1513 const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1514 if (!m_calculated_trap_handlers) {
1515 std::lock_guard<std::mutex> guard(m_mutex);
1516 if (!m_calculated_trap_handlers) {
1517 CalculateTrapHandlerSymbolNames();
1518 m_calculated_trap_handlers = true;
1521 return m_trap_handlers;
1524 Status Platform::GetCachedExecutable(
1525 ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1526 const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1527 const auto platform_spec = module_spec.GetFileSpec();
1528 const auto error = LoadCachedExecutable(
1529 module_spec, module_sp, module_search_paths_ptr, remote_platform);
1530 if (error.Success()) {
1531 module_spec.GetFileSpec() = module_sp->GetFileSpec();
1532 module_spec.GetPlatformFileSpec() = platform_spec;
1538 Status Platform::LoadCachedExecutable(
1539 const ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1540 const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1541 return GetRemoteSharedModule(module_spec, nullptr, module_sp,
1542 [&](const ModuleSpec &spec) {
1543 return remote_platform.ResolveExecutable(
1544 spec, module_sp, module_search_paths_ptr);
1549 Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec,
1551 lldb::ModuleSP &module_sp,
1552 const ModuleResolver &module_resolver,
1553 bool *did_create_ptr) {
1554 // Get module information from a target.
1555 ModuleSpec resolved_module_spec;
1556 bool got_module_spec = false;
1558 // Try to get module information from the process
1559 if (process->GetModuleSpec(module_spec.GetFileSpec(),
1560 module_spec.GetArchitecture(),
1561 resolved_module_spec)) {
1562 if (module_spec.GetUUID().IsValid() == false ||
1563 module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1564 got_module_spec = true;
1569 if (module_spec.GetArchitecture().IsValid() == false) {
1571 // No valid architecture was specified, ask the platform for
1572 // the architectures that we should be using (in the correct order)
1573 // and see if we can find a match that way
1574 ModuleSpec arch_module_spec(module_spec);
1575 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
1576 idx, arch_module_spec.GetArchitecture());
1578 error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
1580 // Did we find an executable using one of the
1581 if (error.Success() && module_sp)
1585 got_module_spec = true;
1588 if (!got_module_spec) {
1589 // Get module information from a target.
1590 if (!GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1591 resolved_module_spec)) {
1592 if (module_spec.GetUUID().IsValid() == false ||
1593 module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1594 return module_resolver(module_spec);
1599 // If we are looking for a specific UUID, make sure resolved_module_spec has
1600 // the same one before we search.
1601 if (module_spec.GetUUID().IsValid()) {
1602 resolved_module_spec.GetUUID() = module_spec.GetUUID();
1605 // Trying to find a module by UUID on local file system.
1606 const auto error = module_resolver(resolved_module_spec);
1608 if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr))
1615 bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec,
1616 lldb::ModuleSP &module_sp,
1617 bool *did_create_ptr) {
1618 if (IsHost() || !GetGlobalPlatformProperties()->GetUseModuleCache() ||
1619 !GetGlobalPlatformProperties()->GetModuleCacheDirectory())
1622 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
1624 // Check local cache for a module.
1625 auto error = m_module_cache->GetAndPut(
1626 GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1627 [this](const ModuleSpec &module_spec,
1628 const FileSpec &tmp_download_file_spec) {
1629 return DownloadModuleSlice(
1630 module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1631 module_spec.GetObjectSize(), tmp_download_file_spec);
1634 [this](const ModuleSP &module_sp,
1635 const FileSpec &tmp_download_file_spec) {
1636 return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1638 module_sp, did_create_ptr);
1639 if (error.Success())
1643 log->Printf("Platform::%s - module %s not found in local cache: %s",
1644 __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1649 Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec,
1650 const uint64_t src_offset,
1651 const uint64_t src_size,
1652 const FileSpec &dst_file_spec) {
1656 llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::F_None);
1658 error.SetErrorStringWithFormat("unable to open destination file: %s",
1659 dst_file_spec.GetPath().c_str());
1663 auto src_fd = OpenFile(src_file_spec, File::eOpenOptionRead,
1664 lldb::eFilePermissionsFileDefault, error);
1667 error.SetErrorStringWithFormat("unable to open source file: %s",
1672 std::vector<char> buffer(1024);
1673 auto offset = src_offset;
1674 uint64_t total_bytes_read = 0;
1675 while (total_bytes_read < src_size) {
1676 const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1677 src_size - total_bytes_read);
1678 const uint64_t n_read =
1679 ReadFile(src_fd, offset, &buffer[0], to_read, error);
1683 error.SetErrorString("read 0 bytes");
1687 total_bytes_read += n_read;
1688 dst.write(&buffer[0], n_read);
1692 CloseFile(src_fd, close_error); // Ignoring close error.
1697 Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
1698 const FileSpec &dst_file_spec) {
1700 "Symbol file downloading not supported by the default platform.");
1703 FileSpec Platform::GetModuleCacheRoot() {
1704 auto dir_spec = GetGlobalPlatformProperties()->GetModuleCacheDirectory();
1705 dir_spec.AppendPathComponent(GetName().AsCString());
1709 const char *Platform::GetCacheHostname() { return GetHostname(); }
1711 const UnixSignalsSP &Platform::GetRemoteUnixSignals() {
1712 static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1713 return s_default_unix_signals_sp;
1716 const UnixSignalsSP &Platform::GetUnixSignals() {
1718 return Host::GetUnixSignals();
1719 return GetRemoteUnixSignals();
1722 uint32_t Platform::LoadImage(lldb_private::Process *process,
1723 const lldb_private::FileSpec &local_file,
1724 const lldb_private::FileSpec &remote_file,
1725 lldb_private::Status &error) {
1726 if (local_file && remote_file) {
1727 // Both local and remote file was specified. Install the local file to the
1729 if (IsRemote() || local_file != remote_file) {
1730 error = Install(local_file, remote_file);
1732 return LLDB_INVALID_IMAGE_TOKEN;
1734 return DoLoadImage(process, remote_file, error);
1738 // Only local file was specified. Install it to the current working
1740 FileSpec target_file = GetWorkingDirectory();
1741 target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1742 if (IsRemote() || local_file != target_file) {
1743 error = Install(local_file, target_file);
1745 return LLDB_INVALID_IMAGE_TOKEN;
1747 return DoLoadImage(process, target_file, error);
1751 // Only remote file was specified so we don't have to do any copying
1752 return DoLoadImage(process, remote_file, error);
1755 error.SetErrorString("Neither local nor remote file was specified");
1756 return LLDB_INVALID_IMAGE_TOKEN;
1759 uint32_t Platform::DoLoadImage(lldb_private::Process *process,
1760 const lldb_private::FileSpec &remote_file,
1761 lldb_private::Status &error) {
1762 error.SetErrorString("LoadImage is not supported on the current platform");
1763 return LLDB_INVALID_IMAGE_TOKEN;
1766 Status Platform::UnloadImage(lldb_private::Process *process,
1767 uint32_t image_token) {
1768 return Status("UnloadImage is not supported on the current platform");
1771 lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
1772 llvm::StringRef plugin_name,
1773 lldb_private::Debugger &debugger,
1774 lldb_private::Target *target,
1775 lldb_private::Status &error) {
1779 TargetSP new_target_sp;
1780 error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
1781 nullptr, new_target_sp);
1782 target = new_target_sp.get();
1785 if (!target || error.Fail())
1788 debugger.GetTargetList().SetSelectedTarget(target);
1790 lldb::ProcessSP process_sp =
1791 target->CreateProcess(debugger.GetListener(), plugin_name, nullptr);
1796 process_sp->ConnectRemote(debugger.GetOutputFile().get(), connect_url);
1803 size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
1804 lldb_private::Status &error) {
1809 size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target,
1810 BreakpointSite *bp_site) {
1811 ArchSpec arch = target.GetArchitecture();
1812 const uint8_t *trap_opcode = nullptr;
1813 size_t trap_opcode_size = 0;
1815 switch (arch.GetMachine()) {
1816 case llvm::Triple::aarch64: {
1817 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1818 trap_opcode = g_aarch64_opcode;
1819 trap_opcode_size = sizeof(g_aarch64_opcode);
1822 // TODO: support big-endian arm and thumb trap codes.
1823 case llvm::Triple::arm: {
1824 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
1825 // but the linux kernel does otherwise.
1826 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1827 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1829 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
1830 AddressClass addr_class = eAddressClassUnknown;
1833 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
1834 if (addr_class == eAddressClassUnknown &&
1835 (bp_loc_sp->GetAddress().GetFileAddress() & 1))
1836 addr_class = eAddressClassCodeAlternateISA;
1839 if (addr_class == eAddressClassCodeAlternateISA) {
1840 trap_opcode = g_thumb_breakpoint_opcode;
1841 trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1843 trap_opcode = g_arm_breakpoint_opcode;
1844 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1848 case llvm::Triple::mips:
1849 case llvm::Triple::mips64: {
1850 static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1851 trap_opcode = g_hex_opcode;
1852 trap_opcode_size = sizeof(g_hex_opcode);
1855 case llvm::Triple::mipsel:
1856 case llvm::Triple::mips64el: {
1857 static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1858 trap_opcode = g_hex_opcode;
1859 trap_opcode_size = sizeof(g_hex_opcode);
1862 case llvm::Triple::systemz: {
1863 static const uint8_t g_hex_opcode[] = {0x00, 0x01};
1864 trap_opcode = g_hex_opcode;
1865 trap_opcode_size = sizeof(g_hex_opcode);
1868 case llvm::Triple::hexagon: {
1869 static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
1870 trap_opcode = g_hex_opcode;
1871 trap_opcode_size = sizeof(g_hex_opcode);
1874 case llvm::Triple::ppc:
1875 case llvm::Triple::ppc64: {
1876 static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
1877 trap_opcode = g_ppc_opcode;
1878 trap_opcode_size = sizeof(g_ppc_opcode);
1881 case llvm::Triple::x86:
1882 case llvm::Triple::x86_64: {
1883 static const uint8_t g_i386_opcode[] = {0xCC};
1884 trap_opcode = g_i386_opcode;
1885 trap_opcode_size = sizeof(g_i386_opcode);
1890 "Unhandled architecture in Platform::GetSoftwareBreakpointTrapOpcode");
1894 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1895 return trap_opcode_size;