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 //===----------------------------------------------------------------------===//
17 // Other libraries and framework includes
18 #include "llvm/Support/FileSystem.h"
19 #include "llvm/Support/Path.h"
22 #include "lldb/Breakpoint/BreakpointIDList.h"
23 #include "lldb/Breakpoint/BreakpointLocation.h"
24 #include "lldb/Core/Debugger.h"
25 #include "lldb/Core/Module.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/PluginManager.h"
28 #include "lldb/Core/StreamFile.h"
29 #include "lldb/Host/FileSystem.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Host/HostInfo.h"
32 #include "lldb/Host/OptionParser.h"
33 #include "lldb/Interpreter/OptionValueProperties.h"
34 #include "lldb/Interpreter/Property.h"
35 #include "lldb/Symbol/ObjectFile.h"
36 #include "lldb/Target/ModuleCache.h"
37 #include "lldb/Target/Platform.h"
38 #include "lldb/Target/Process.h"
39 #include "lldb/Target/Target.h"
40 #include "lldb/Target/UnixSignals.h"
41 #include "lldb/Utility/DataBufferHeap.h"
42 #include "lldb/Utility/FileSpec.h"
43 #include "lldb/Utility/Log.h"
44 #include "lldb/Utility/Status.h"
45 #include "lldb/Utility/StructuredData.h"
47 #include "llvm/Support/FileSystem.h"
49 // Define these constants from POSIX mman.h rather than include the file so
50 // that they will be correct even when compiled on Linux.
52 #define MAP_ANON 0x1000
55 using namespace lldb_private;
57 static uint32_t g_initialize_count = 0;
59 // Use a singleton function for g_local_platform_sp to avoid init constructors
60 // since LLDB is often part of a shared library
61 static PlatformSP &GetHostPlatformSP() {
62 static PlatformSP g_platform_sp;
66 const char *Platform::GetHostPlatformName() { return "host"; }
70 PropertyDefinition g_properties[] = {
71 {"use-module-cache", OptionValue::eTypeBoolean, true, true, nullptr,
72 nullptr, "Use module cache."},
73 {"module-cache-directory", OptionValue::eTypeFileSpec, true, 0, nullptr,
74 nullptr, "Root directory for cached modules."},
75 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
77 enum { ePropertyUseModuleCache, ePropertyModuleCacheDirectory };
81 ConstString PlatformProperties::GetSettingName() {
82 static ConstString g_setting_name("platform");
83 return g_setting_name;
86 PlatformProperties::PlatformProperties() {
87 m_collection_sp.reset(new OptionValueProperties(GetSettingName()));
88 m_collection_sp->Initialize(g_properties);
90 auto module_cache_dir = GetModuleCacheDirectory();
94 llvm::SmallString<64> user_home_dir;
95 if (!llvm::sys::path::home_directory(user_home_dir))
98 module_cache_dir = FileSpec(user_home_dir.c_str(), false);
99 module_cache_dir.AppendPathComponent(".lldb");
100 module_cache_dir.AppendPathComponent("module_cache");
101 SetModuleCacheDirectory(module_cache_dir);
104 bool PlatformProperties::GetUseModuleCache() const {
105 const auto idx = ePropertyUseModuleCache;
106 return m_collection_sp->GetPropertyAtIndexAsBoolean(
107 nullptr, idx, g_properties[idx].default_uint_value != 0);
110 bool PlatformProperties::SetUseModuleCache(bool use_module_cache) {
111 return m_collection_sp->SetPropertyAtIndexAsBoolean(
112 nullptr, ePropertyUseModuleCache, use_module_cache);
115 FileSpec PlatformProperties::GetModuleCacheDirectory() const {
116 return m_collection_sp->GetPropertyAtIndexAsFileSpec(
117 nullptr, ePropertyModuleCacheDirectory);
120 bool PlatformProperties::SetModuleCacheDirectory(const FileSpec &dir_spec) {
121 return m_collection_sp->SetPropertyAtIndexAsFileSpec(
122 nullptr, ePropertyModuleCacheDirectory, dir_spec);
125 //------------------------------------------------------------------
126 /// Get the native host platform plug-in.
128 /// There should only be one of these for each host that LLDB runs
129 /// upon that should be statically compiled in and registered using
130 /// preprocessor macros or other similar build mechanisms.
132 /// This platform will be used as the default platform when launching
133 /// or attaching to processes unless another platform is specified.
134 //------------------------------------------------------------------
135 PlatformSP Platform::GetHostPlatform() { return GetHostPlatformSP(); }
137 static std::vector<PlatformSP> &GetPlatformList() {
138 static std::vector<PlatformSP> g_platform_list;
139 return g_platform_list;
142 static std::recursive_mutex &GetPlatformListMutex() {
143 static std::recursive_mutex g_mutex;
147 void Platform::Initialize() { g_initialize_count++; }
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();
158 const PlatformPropertiesSP &Platform::GetGlobalPlatformProperties() {
159 static const auto g_settings_sp(std::make_shared<PlatformProperties>());
160 return g_settings_sp;
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;
169 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
170 GetPlatformList().push_back(platform_sp);
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;
182 Platform::LocateExecutableScriptingResources(Target *target, Module &module,
183 Stream *feedback_stream) {
184 return FileSpecList();
188 // Platform::FindPlugin (Process *process, const ConstString &plugin_name)
190 // PlatformCreateInstance create_callback = nullptr;
194 // PluginManager::GetPlatformCreateCallbackForPluginName (plugin_name);
195 // if (create_callback)
200 // arch = process->GetTarget().GetArchitecture();
202 // PlatformSP platform_sp(create_callback(process, &arch));
204 // return platform_sp;
209 // for (uint32_t idx = 0; (create_callback =
210 // PluginManager::GetPlatformCreateCallbackAtIndex(idx)) != nullptr;
213 // PlatformSP platform_sp(create_callback(process, nullptr));
215 // return platform_sp;
218 // return PlatformSP();
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) {
227 return ModuleList::GetSharedModule(
228 module_spec, module_sp, module_search_paths_ptr, old_module_sp_ptr,
229 did_create_ptr, false);
231 return GetRemoteSharedModule(module_spec, process, module_sp,
232 [&](const ModuleSpec &spec) {
233 Status error = ModuleList::GetSharedModule(
234 spec, module_sp, module_search_paths_ptr,
235 old_module_sp_ptr, did_create_ptr, false);
236 if (error.Success() && module_sp)
237 module_sp->SetPlatformFileSpec(
244 bool Platform::GetModuleSpec(const FileSpec &module_file_spec,
245 const ArchSpec &arch, ModuleSpec &module_spec) {
246 ModuleSpecList module_specs;
247 if (ObjectFile::GetModuleSpecifications(module_file_spec, 0, 0,
251 ModuleSpec matched_module_spec;
252 return module_specs.FindMatchingModuleSpec(ModuleSpec(module_file_spec, arch),
256 PlatformSP Platform::Find(const ConstString &name) {
258 static ConstString g_host_platform_name("host");
259 if (name == g_host_platform_name)
260 return GetHostPlatform();
262 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
263 for (const auto &platform_sp : GetPlatformList()) {
264 if (platform_sp->GetName() == name)
271 PlatformSP Platform::Create(const ConstString &name, Status &error) {
272 PlatformCreateInstance create_callback = nullptr;
273 lldb::PlatformSP platform_sp;
275 static ConstString g_host_platform_name("host");
276 if (name == g_host_platform_name)
277 return GetHostPlatform();
280 PluginManager::GetPlatformCreateCallbackForPluginName(name);
282 platform_sp = create_callback(true, nullptr);
284 error.SetErrorStringWithFormat(
285 "unable to find a plug-in for the platform named \"%s\"",
288 error.SetErrorString("invalid platform name");
291 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
292 GetPlatformList().push_back(platform_sp);
298 PlatformSP Platform::Create(const ArchSpec &arch, ArchSpec *platform_arch_ptr,
300 lldb::PlatformSP platform_sp;
301 if (arch.IsValid()) {
304 // First try exact arch matches across all platforms already created
305 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
306 for (const auto &platform_sp : GetPlatformList()) {
307 if (platform_sp->IsCompatibleArchitecture(arch, true,
312 // Next try compatible arch matches across all platforms already created
313 for (const auto &platform_sp : GetPlatformList()) {
314 if (platform_sp->IsCompatibleArchitecture(arch, false,
320 PlatformCreateInstance create_callback;
321 // First try exact arch matches across all platform plug-ins
323 for (idx = 0; (create_callback =
324 PluginManager::GetPlatformCreateCallbackAtIndex(idx));
326 if (create_callback) {
327 platform_sp = create_callback(false, &arch);
329 platform_sp->IsCompatibleArchitecture(arch, true,
330 platform_arch_ptr)) {
331 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
332 GetPlatformList().push_back(platform_sp);
337 // Next try compatible arch matches across all platform plug-ins
338 for (idx = 0; (create_callback =
339 PluginManager::GetPlatformCreateCallbackAtIndex(idx));
341 if (create_callback) {
342 platform_sp = create_callback(false, &arch);
344 platform_sp->IsCompatibleArchitecture(arch, false,
345 platform_arch_ptr)) {
346 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
347 GetPlatformList().push_back(platform_sp);
353 error.SetErrorString("invalid platform name");
354 if (platform_arch_ptr)
355 platform_arch_ptr->Clear();
360 ArchSpec Platform::GetAugmentedArchSpec(Platform *platform, llvm::StringRef triple) {
362 return platform->GetAugmentedArchSpec(triple);
363 return HostInfo::GetAugmentedArchSpec(triple);
366 //------------------------------------------------------------------
367 /// Default Constructor
368 //------------------------------------------------------------------
369 Platform::Platform(bool is_host)
370 : m_is_host(is_host), m_os_version_set_while_connected(false),
371 m_system_arch_set_while_connected(false), m_sdk_sysroot(), m_sdk_build(),
372 m_working_dir(), m_remote_url(), m_name(), m_system_arch(), m_mutex(),
373 m_uid_map(), m_gid_map(), m_max_uid_name_len(0), m_max_gid_name_len(0),
374 m_supports_rsync(false), m_rsync_opts(), m_rsync_prefix(),
375 m_supports_ssh(false), m_ssh_opts(), m_ignores_remote_hostname(false),
376 m_trap_handlers(), m_calculated_trap_handlers(false),
377 m_module_cache(llvm::make_unique<ModuleCache>()) {
378 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
380 log->Printf("%p Platform::Platform()", static_cast<void *>(this));
383 //------------------------------------------------------------------
386 /// The destructor is virtual since this class is designed to be
387 /// inherited from by the plug-in instance.
388 //------------------------------------------------------------------
389 Platform::~Platform() {
390 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
392 log->Printf("%p Platform::~Platform()", static_cast<void *>(this));
395 void Platform::GetStatus(Stream &strm) {
397 strm.Printf(" Platform: %s\n", GetPluginName().GetCString());
399 ArchSpec arch(GetSystemArchitecture());
400 if (arch.IsValid()) {
401 if (!arch.GetTriple().str().empty()) {
402 strm.Printf(" Triple: ");
403 arch.DumpTriple(strm);
408 llvm::VersionTuple os_version = GetOSVersion();
409 if (!os_version.empty()) {
410 strm.Format("OS Version: {0}", os_version.getAsString());
412 if (GetOSBuildString(s))
413 strm.Printf(" (%s)", s.c_str());
418 if (GetOSKernelDescription(s))
419 strm.Printf(" Kernel: %s\n", s.c_str());
422 strm.Printf(" Hostname: %s\n", GetHostname());
424 const bool is_connected = IsConnected();
426 strm.Printf(" Hostname: %s\n", GetHostname());
427 strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no");
430 if (GetWorkingDirectory()) {
431 strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString());
436 std::string specific_info(GetPlatformSpecificConnectionInformation());
438 if (!specific_info.empty())
439 strm.Printf("Platform-specific connection: %s\n", specific_info.c_str());
442 llvm::VersionTuple Platform::GetOSVersion(Process *process) {
443 std::lock_guard<std::mutex> guard(m_mutex);
446 if (m_os_version.empty()) {
447 // We have a local host platform
448 m_os_version = HostInfo::GetOSVersion();
449 m_os_version_set_while_connected = !m_os_version.empty();
452 // We have a remote platform. We can only fetch the remote
453 // OS version if we are connected, and we don't want to do it
456 const bool is_connected = IsConnected();
459 if (!m_os_version.empty()) {
460 // We have valid OS version info, check to make sure it wasn't manually
461 // set prior to connecting. If it was manually set prior to connecting,
462 // then lets fetch the actual OS version info if we are now connected.
463 if (is_connected && !m_os_version_set_while_connected)
466 // We don't have valid OS version info, fetch it if we are connected
467 fetch = is_connected;
471 m_os_version_set_while_connected = GetRemoteOSVersion();
474 if (!m_os_version.empty())
477 // Check with the process in case it can answer the question if a process
479 return process->GetHostOSVersion();
481 return llvm::VersionTuple();
484 bool Platform::GetOSBuildString(std::string &s) {
488 #if !defined(__linux__)
489 return HostInfo::GetOSBuildString(s);
494 return GetRemoteOSBuildString(s);
497 bool Platform::GetOSKernelDescription(std::string &s) {
499 #if !defined(__linux__)
500 return HostInfo::GetOSKernelDescription(s);
505 return GetRemoteOSKernelDescription(s);
508 void Platform::AddClangModuleCompilationOptions(
509 Target *target, std::vector<std::string> &options) {
510 std::vector<std::string> default_compilation_options = {
511 "-x", "c++", "-Xclang", "-nostdsysteminc", "-Xclang", "-nostdsysteminc"};
513 options.insert(options.end(), default_compilation_options.begin(),
514 default_compilation_options.end());
517 FileSpec Platform::GetWorkingDirectory() {
519 llvm::SmallString<64> cwd;
520 if (llvm::sys::fs::current_path(cwd))
523 return FileSpec(cwd, true);
526 m_working_dir = GetRemoteWorkingDirectory();
527 return m_working_dir;
531 struct RecurseCopyBaton {
533 Platform *platform_ptr;
537 static FileSpec::EnumerateDirectoryResult
538 RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft,
539 const FileSpec &src) {
540 RecurseCopyBaton *rc_baton = (RecurseCopyBaton *)baton;
541 namespace fs = llvm::sys::fs;
543 case fs::file_type::fifo_file:
544 case fs::file_type::socket_file:
545 // we have no way to copy pipes and sockets - ignore them and continue
546 return FileSpec::eEnumerateDirectoryResultNext;
549 case fs::file_type::directory_file: {
550 // make the new directory and get in there
551 FileSpec dst_dir = rc_baton->dst;
552 if (!dst_dir.GetFilename())
553 dst_dir.GetFilename() = src.GetLastPathComponent();
554 Status error = rc_baton->platform_ptr->MakeDirectory(
555 dst_dir, lldb::eFilePermissionsDirectoryDefault);
557 rc_baton->error.SetErrorStringWithFormat(
558 "unable to setup directory %s on remote end", dst_dir.GetCString());
559 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
563 std::string src_dir_path(src.GetPath());
565 // Make a filespec that only fills in the directory of a FileSpec so when
566 // we enumerate we can quickly fill in the filename for dst copies
567 FileSpec recurse_dst;
568 recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str());
569 RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr,
571 FileSpec::EnumerateDirectory(src_dir_path, true, true, true,
572 RecurseCopy_Callback, &rc_baton2);
573 if (rc_baton2.error.Fail()) {
574 rc_baton->error.SetErrorString(rc_baton2.error.AsCString());
575 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
577 return FileSpec::eEnumerateDirectoryResultNext;
580 case fs::file_type::symlink_file: {
581 // copy the file and keep going
582 FileSpec dst_file = rc_baton->dst;
583 if (!dst_file.GetFilename())
584 dst_file.GetFilename() = src.GetFilename();
586 FileSpec src_resolved;
588 rc_baton->error = FileSystem::Readlink(src, src_resolved);
590 if (rc_baton->error.Fail())
591 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
594 rc_baton->platform_ptr->CreateSymlink(dst_file, src_resolved);
596 if (rc_baton->error.Fail())
597 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
599 return FileSpec::eEnumerateDirectoryResultNext;
602 case fs::file_type::regular_file: {
603 // copy the file and keep going
604 FileSpec dst_file = rc_baton->dst;
605 if (!dst_file.GetFilename())
606 dst_file.GetFilename() = src.GetFilename();
607 Status err = rc_baton->platform_ptr->PutFile(src, dst_file);
609 rc_baton->error.SetErrorString(err.AsCString());
610 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
612 return FileSpec::eEnumerateDirectoryResultNext;
616 rc_baton->error.SetErrorStringWithFormat(
617 "invalid file detected during copy: %s", src.GetPath().c_str());
618 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
621 llvm_unreachable("Unhandled file_type!");
624 Status Platform::Install(const FileSpec &src, const FileSpec &dst) {
627 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
629 log->Printf("Platform::Install (src='%s', dst='%s')", src.GetPath().c_str(),
630 dst.GetPath().c_str());
631 FileSpec fixed_dst(dst);
633 if (!fixed_dst.GetFilename())
634 fixed_dst.GetFilename() = src.GetFilename();
636 FileSpec working_dir = GetWorkingDirectory();
639 if (dst.GetDirectory()) {
640 const char first_dst_dir_char = dst.GetDirectory().GetCString()[0];
641 if (first_dst_dir_char == '/' || first_dst_dir_char == '\\') {
642 fixed_dst.GetDirectory() = dst.GetDirectory();
644 // If the fixed destination file doesn't have a directory yet, then we
645 // must have a relative path. We will resolve this relative path against
646 // the platform's working directory
647 if (!fixed_dst.GetDirectory()) {
648 FileSpec relative_spec;
651 relative_spec = working_dir;
652 relative_spec.AppendPathComponent(dst.GetPath());
653 fixed_dst.GetDirectory() = relative_spec.GetDirectory();
655 error.SetErrorStringWithFormat(
656 "platform working directory must be valid for relative path '%s'",
657 dst.GetPath().c_str());
663 fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
665 error.SetErrorStringWithFormat(
666 "platform working directory must be valid for relative path '%s'",
667 dst.GetPath().c_str());
673 fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
675 error.SetErrorStringWithFormat("platform working directory must be valid "
676 "when destination directory is empty");
682 log->Printf("Platform::Install (src='%s', dst='%s') fixed_dst='%s'",
683 src.GetPath().c_str(), dst.GetPath().c_str(),
684 fixed_dst.GetPath().c_str());
686 if (GetSupportsRSync()) {
687 error = PutFile(src, dst);
689 namespace fs = llvm::sys::fs;
690 switch (fs::get_file_type(src.GetPath(), false)) {
691 case fs::file_type::directory_file: {
692 llvm::sys::fs::remove(fixed_dst.GetPath());
693 uint32_t permissions = src.GetPermissions();
694 if (permissions == 0)
695 permissions = eFilePermissionsDirectoryDefault;
696 error = MakeDirectory(fixed_dst, permissions);
697 if (error.Success()) {
698 // Make a filespec that only fills in the directory of a FileSpec so
699 // when we enumerate we can quickly fill in the filename for dst copies
700 FileSpec recurse_dst;
701 recurse_dst.GetDirectory().SetCString(fixed_dst.GetCString());
702 std::string src_dir_path(src.GetPath());
703 RecurseCopyBaton baton = {recurse_dst, this, Status()};
704 FileSpec::EnumerateDirectory(src_dir_path, true, true, true,
705 RecurseCopy_Callback, &baton);
710 case fs::file_type::regular_file:
711 llvm::sys::fs::remove(fixed_dst.GetPath());
712 error = PutFile(src, fixed_dst);
715 case fs::file_type::symlink_file: {
716 llvm::sys::fs::remove(fixed_dst.GetPath());
717 FileSpec src_resolved;
718 error = FileSystem::Readlink(src, src_resolved);
720 error = CreateSymlink(dst, src_resolved);
722 case fs::file_type::fifo_file:
723 error.SetErrorString("platform install doesn't handle pipes");
725 case fs::file_type::socket_file:
726 error.SetErrorString("platform install doesn't handle sockets");
729 error.SetErrorString(
730 "platform install doesn't handle non file or directory items");
737 bool Platform::SetWorkingDirectory(const FileSpec &file_spec) {
739 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
740 LLDB_LOG(log, "{0}", file_spec);
741 if (std::error_code ec = llvm::sys::fs::set_current_path(file_spec.GetPath())) {
742 LLDB_LOG(log, "error: {0}", ec.message());
747 m_working_dir.Clear();
748 return SetRemoteWorkingDirectory(file_spec);
752 Status Platform::MakeDirectory(const FileSpec &file_spec,
753 uint32_t permissions) {
755 return llvm::sys::fs::create_directory(file_spec.GetPath(), permissions);
758 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
759 GetPluginName().GetCString(),
760 LLVM_PRETTY_FUNCTION);
765 Status Platform::GetFilePermissions(const FileSpec &file_spec,
766 uint32_t &file_permissions) {
768 auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath());
770 file_permissions = Value.get();
771 return Status(Value.getError());
774 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
775 GetPluginName().GetCString(),
776 LLVM_PRETTY_FUNCTION);
781 Status Platform::SetFilePermissions(const FileSpec &file_spec,
782 uint32_t file_permissions) {
784 auto Perms = static_cast<llvm::sys::fs::perms>(file_permissions);
785 return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms);
788 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
789 GetPluginName().GetCString(),
790 LLVM_PRETTY_FUNCTION);
795 ConstString Platform::GetName() { return GetPluginName(); }
797 const char *Platform::GetHostname() {
803 return m_name.c_str();
806 ConstString Platform::GetFullNameForDylib(ConstString basename) {
810 bool Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
811 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
813 log->Printf("Platform::SetRemoteWorkingDirectory('%s')",
814 working_dir.GetCString());
815 m_working_dir = working_dir;
819 const char *Platform::GetUserName(uint32_t uid) {
820 #if !defined(LLDB_DISABLE_POSIX)
821 const char *user_name = GetCachedUserName(uid);
826 if (HostInfo::LookupUserName(uid, name))
827 return SetCachedUserName(uid, name.c_str(), name.size());
833 const char *Platform::GetGroupName(uint32_t gid) {
834 #if !defined(LLDB_DISABLE_POSIX)
835 const char *group_name = GetCachedGroupName(gid);
840 if (HostInfo::LookupGroupName(gid, name))
841 return SetCachedGroupName(gid, name.c_str(), name.size());
847 bool Platform::SetOSVersion(llvm::VersionTuple version) {
849 // We don't need anyone setting the OS version for the host platform, we
850 // should be able to figure it out by calling HostInfo::GetOSVersion(...).
853 // We have a remote platform, allow setting the target OS version if we
854 // aren't connected, since if we are connected, we should be able to
855 // request the remote OS version from the connected platform.
859 // We aren't connected and we might want to set the OS version ahead of
860 // time before we connect so we can peruse files and use a local SDK or
861 // PDK cache of support files to disassemble or do other things.
862 m_os_version = version;
870 Platform::ResolveExecutable(const ModuleSpec &module_spec,
871 lldb::ModuleSP &exe_module_sp,
872 const FileSpecList *module_search_paths_ptr) {
874 if (module_spec.GetFileSpec().Exists()) {
875 if (module_spec.GetArchitecture().IsValid()) {
876 error = ModuleList::GetSharedModule(module_spec, exe_module_sp,
877 module_search_paths_ptr, nullptr,
880 // No valid architecture was specified, ask the platform for the
881 // architectures that we should be using (in the correct order) and see
882 // if we can find a match that way
883 ModuleSpec arch_module_spec(module_spec);
884 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
885 idx, arch_module_spec.GetArchitecture());
887 error = ModuleList::GetSharedModule(arch_module_spec, exe_module_sp,
888 module_search_paths_ptr, nullptr,
890 // Did we find an executable using one of the
891 if (error.Success() && exe_module_sp)
896 error.SetErrorStringWithFormat("'%s' does not exist",
897 module_spec.GetFileSpec().GetPath().c_str());
902 Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec,
903 FileSpec &sym_file) {
905 if (sym_spec.GetSymbolFileSpec().Exists())
906 sym_file = sym_spec.GetSymbolFileSpec();
908 error.SetErrorString("unable to resolve symbol file");
912 bool Platform::ResolveRemotePath(const FileSpec &platform_path,
913 FileSpec &resolved_platform_path) {
914 resolved_platform_path = platform_path;
915 return resolved_platform_path.ResolvePath();
918 const ArchSpec &Platform::GetSystemArchitecture() {
920 if (!m_system_arch.IsValid()) {
921 // We have a local host platform
922 m_system_arch = HostInfo::GetArchitecture();
923 m_system_arch_set_while_connected = m_system_arch.IsValid();
926 // We have a remote platform. We can only fetch the remote system
927 // architecture if we are connected, and we don't want to do it more than
930 const bool is_connected = IsConnected();
933 if (m_system_arch.IsValid()) {
934 // We have valid OS version info, check to make sure it wasn't manually
935 // set prior to connecting. If it was manually set prior to connecting,
936 // then lets fetch the actual OS version info if we are now connected.
937 if (is_connected && !m_system_arch_set_while_connected)
940 // We don't have valid OS version info, fetch it if we are connected
941 fetch = is_connected;
945 m_system_arch = GetRemoteSystemArchitecture();
946 m_system_arch_set_while_connected = m_system_arch.IsValid();
949 return m_system_arch;
952 ArchSpec Platform::GetAugmentedArchSpec(llvm::StringRef triple) {
955 llvm::Triple normalized_triple(llvm::Triple::normalize(triple));
956 if (!ArchSpec::ContainsOnlyArch(normalized_triple))
957 return ArchSpec(triple);
959 if (auto kind = HostInfo::ParseArchitectureKind(triple))
960 return HostInfo::GetArchitecture(*kind);
962 ArchSpec compatible_arch;
963 ArchSpec raw_arch(triple);
964 if (!IsCompatibleArchitecture(raw_arch, false, &compatible_arch))
967 if (!compatible_arch.IsValid())
968 return ArchSpec(normalized_triple);
970 const llvm::Triple &compatible_triple = compatible_arch.GetTriple();
971 if (normalized_triple.getVendorName().empty())
972 normalized_triple.setVendor(compatible_triple.getVendor());
973 if (normalized_triple.getOSName().empty())
974 normalized_triple.setOS(compatible_triple.getOS());
975 if (normalized_triple.getEnvironmentName().empty())
976 normalized_triple.setEnvironment(compatible_triple.getEnvironment());
977 return ArchSpec(normalized_triple);
980 Status Platform::ConnectRemote(Args &args) {
983 error.SetErrorStringWithFormat("The currently selected platform (%s) is "
984 "the host platform and is always connected.",
985 GetPluginName().GetCString());
987 error.SetErrorStringWithFormat(
988 "Platform::ConnectRemote() is not supported by %s",
989 GetPluginName().GetCString());
993 Status Platform::DisconnectRemote() {
996 error.SetErrorStringWithFormat("The currently selected platform (%s) is "
997 "the host platform and is always connected.",
998 GetPluginName().GetCString());
1000 error.SetErrorStringWithFormat(
1001 "Platform::DisconnectRemote() is not supported by %s",
1002 GetPluginName().GetCString());
1006 bool Platform::GetProcessInfo(lldb::pid_t pid,
1007 ProcessInstanceInfo &process_info) {
1008 // Take care of the host case so that each subclass can just call this
1009 // function to get the host functionality.
1011 return Host::GetProcessInfo(pid, process_info);
1015 uint32_t Platform::FindProcesses(const ProcessInstanceInfoMatch &match_info,
1016 ProcessInstanceInfoList &process_infos) {
1017 // Take care of the host case so that each subclass can just call this
1018 // function to get the host functionality.
1019 uint32_t match_count = 0;
1021 match_count = Host::FindProcesses(match_info, process_infos);
1025 Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) {
1027 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1029 log->Printf("Platform::%s()", __FUNCTION__);
1031 // Take care of the host case so that each subclass can just call this
1032 // function to get the host functionality.
1034 if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
1035 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
1037 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInShell)) {
1038 const bool is_localhost = true;
1039 const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1040 const bool first_arg_is_full_shell_command = false;
1041 uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info);
1043 const FileSpec &shell = launch_info.GetShell();
1044 const char *shell_str = (shell) ? shell.GetPath().c_str() : "<null>";
1046 "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32
1048 __FUNCTION__, num_resumes, shell_str);
1051 if (!launch_info.ConvertArgumentsForLaunchingInShell(
1052 error, is_localhost, will_debug, first_arg_is_full_shell_command,
1055 } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1056 error = ShellExpandArguments(launch_info);
1058 error.SetErrorStringWithFormat("shell expansion failed (reason: %s). "
1059 "consider launching with 'process "
1061 error.AsCString("unknown"));
1067 log->Printf("Platform::%s final launch_info resume count: %" PRIu32,
1068 __FUNCTION__, launch_info.GetResumeCount());
1070 error = Host::LaunchProcess(launch_info);
1072 error.SetErrorString(
1073 "base lldb_private::Platform class can't launch remote processes");
1077 Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
1079 return Host::ShellExpandArguments(launch_info);
1080 return Status("base lldb_private::Platform class can't expand arguments");
1083 Status Platform::KillProcess(const lldb::pid_t pid) {
1084 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1086 log->Printf("Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
1088 // Try to find a process plugin to handle this Kill request. If we can't,
1089 // fall back to the default OS implementation.
1090 size_t num_debuggers = Debugger::GetNumDebuggers();
1091 for (size_t didx = 0; didx < num_debuggers; ++didx) {
1092 DebuggerSP debugger = Debugger::GetDebuggerAtIndex(didx);
1093 lldb_private::TargetList &targets = debugger->GetTargetList();
1094 for (int tidx = 0; tidx < targets.GetNumTargets(); ++tidx) {
1095 ProcessSP process = targets.GetTargetAtIndex(tidx)->GetProcessSP();
1096 if (process->GetID() == pid)
1097 return process->Destroy(true);
1103 "base lldb_private::Platform class can't kill remote processes unless "
1104 "they are controlled by a process plugin");
1106 Host::Kill(pid, SIGTERM);
1111 Platform::DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger,
1112 Target *target, // Can be nullptr, if nullptr create a
1113 // new target, else use existing one
1115 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1117 log->Printf("Platform::%s entered (target %p)", __FUNCTION__,
1118 static_cast<void *>(target));
1120 ProcessSP process_sp;
1121 // Make sure we stop at the entry point
1122 launch_info.GetFlags().Set(eLaunchFlagDebug);
1123 // We always launch the process we are going to debug in a separate process
1124 // group, since then we can handle ^C interrupts ourselves w/o having to
1125 // worry about the target getting them as well.
1126 launch_info.SetLaunchInSeparateProcessGroup(true);
1128 // Allow any StructuredData process-bound plugins to adjust the launch info
1131 bool iteration_complete = false;
1132 // Note iteration can't simply go until a nullptr callback is returned, as it
1133 // is valid for a plugin to not supply a filter.
1134 auto get_filter_func = PluginManager::GetStructuredDataFilterCallbackAtIndex;
1135 for (auto filter_callback = get_filter_func(i, iteration_complete);
1136 !iteration_complete;
1137 filter_callback = get_filter_func(++i, iteration_complete)) {
1138 if (filter_callback) {
1139 // Give this ProcessLaunchInfo filter a chance to adjust the launch info.
1140 error = (*filter_callback)(launch_info, target);
1141 if (!error.Success()) {
1143 log->Printf("Platform::%s() StructuredDataPlugin launch "
1151 error = LaunchProcess(launch_info);
1152 if (error.Success()) {
1154 log->Printf("Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64
1156 __FUNCTION__, launch_info.GetProcessID());
1157 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1158 ProcessAttachInfo attach_info(launch_info);
1159 process_sp = Attach(attach_info, debugger, target, error);
1162 log->Printf("Platform::%s Attach() succeeded, Process plugin: %s",
1163 __FUNCTION__, process_sp->GetPluginName().AsCString());
1164 launch_info.SetHijackListener(attach_info.GetHijackListener());
1166 // Since we attached to the process, it will think it needs to detach
1167 // if the process object just goes away without an explicit call to
1168 // Process::Kill() or Process::Detach(), so let it know to kill the
1169 // process if this happens.
1170 process_sp->SetShouldDetach(false);
1172 // If we didn't have any file actions, the pseudo terminal might have
1173 // been used where the slave side was given as the file to open for
1174 // stdin/out/err after we have already opened the master so we can
1175 // read/write stdin/out/err.
1176 int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
1177 if (pty_fd != PseudoTerminal::invalid_fd) {
1178 process_sp->SetSTDIOFileDescriptor(pty_fd);
1182 log->Printf("Platform::%s Attach() failed: %s", __FUNCTION__,
1187 log->Printf("Platform::%s LaunchProcess() returned launch_info with "
1188 "invalid process id",
1193 log->Printf("Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
1201 Platform::GetPlatformForArchitecture(const ArchSpec &arch,
1202 ArchSpec *platform_arch_ptr) {
1203 lldb::PlatformSP platform_sp;
1206 platform_sp = Platform::Create(arch, platform_arch_ptr, error);
1210 //------------------------------------------------------------------
1211 /// Lets a platform answer if it is compatible with a given
1212 /// architecture and the target triple contained within.
1213 //------------------------------------------------------------------
1214 bool Platform::IsCompatibleArchitecture(const ArchSpec &arch,
1215 bool exact_arch_match,
1216 ArchSpec *compatible_arch_ptr) {
1217 // If the architecture is invalid, we must answer true...
1218 if (arch.IsValid()) {
1219 ArchSpec platform_arch;
1220 // Try for an exact architecture match first.
1221 if (exact_arch_match) {
1222 for (uint32_t arch_idx = 0;
1223 GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1225 if (arch.IsExactMatch(platform_arch)) {
1226 if (compatible_arch_ptr)
1227 *compatible_arch_ptr = platform_arch;
1232 for (uint32_t arch_idx = 0;
1233 GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1235 if (arch.IsCompatibleMatch(platform_arch)) {
1236 if (compatible_arch_ptr)
1237 *compatible_arch_ptr = platform_arch;
1243 if (compatible_arch_ptr)
1244 compatible_arch_ptr->Clear();
1248 Status Platform::PutFile(const FileSpec &source, const FileSpec &destination,
1249 uint32_t uid, uint32_t gid) {
1250 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1252 log->Printf("[PutFile] Using block by block transfer....\n");
1254 uint32_t source_open_options =
1255 File::eOpenOptionRead | File::eOpenOptionCloseOnExec;
1256 namespace fs = llvm::sys::fs;
1257 if (fs::is_symlink_file(source.GetPath()))
1258 source_open_options |= File::eOpenOptionDontFollowSymlinks;
1260 File source_file(source, source_open_options, lldb::eFilePermissionsUserRW);
1262 uint32_t permissions = source_file.GetPermissions(error);
1263 if (permissions == 0)
1264 permissions = lldb::eFilePermissionsFileDefault;
1266 if (!source_file.IsValid())
1267 return Status("PutFile: unable to open source file");
1268 lldb::user_id_t dest_file = OpenFile(
1269 destination, File::eOpenOptionCanCreate | File::eOpenOptionWrite |
1270 File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec,
1271 permissions, error);
1273 log->Printf("dest_file = %" PRIu64 "\n", dest_file);
1277 if (dest_file == UINT64_MAX)
1278 return Status("unable to open target file");
1279 lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
1280 uint64_t offset = 0;
1282 size_t bytes_read = buffer_sp->GetByteSize();
1283 error = source_file.Read(buffer_sp->GetBytes(), bytes_read);
1284 if (error.Fail() || bytes_read == 0)
1287 const uint64_t bytes_written =
1288 WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error);
1292 offset += bytes_written;
1293 if (bytes_written != bytes_read) {
1294 // We didn't write the correct number of bytes, so adjust the file
1295 // position in the source file we are reading from...
1296 source_file.SeekFromStart(offset);
1299 CloseFile(dest_file, error);
1301 if (uid == UINT32_MAX && gid == UINT32_MAX)
1309 Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) {
1310 Status error("unimplemented");
1315 Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1316 const FileSpec &dst) // The symlink points to dst
1318 Status error("unimplemented");
1322 bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) {
1326 Status Platform::Unlink(const FileSpec &path) {
1327 Status error("unimplemented");
1331 MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr,
1332 addr_t length, unsigned prot,
1333 unsigned flags, addr_t fd,
1335 uint64_t flags_platform = 0;
1336 if (flags & eMmapFlagsPrivate)
1337 flags_platform |= MAP_PRIVATE;
1338 if (flags & eMmapFlagsAnon)
1339 flags_platform |= MAP_ANON;
1341 MmapArgList args({addr, length, prot, flags_platform, fd, offset});
1345 lldb_private::Status Platform::RunShellCommand(
1346 const char *command, // Shouldn't be nullptr
1348 working_dir, // Pass empty FileSpec to use the current working directory
1349 int *status_ptr, // Pass nullptr if you don't want the process exit status
1350 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1353 *command_output, // Pass nullptr if you don't want the command output
1354 const Timeout<std::micro> &timeout) {
1356 return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr,
1357 command_output, timeout);
1359 return Status("unimplemented");
1362 bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
1366 auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath());
1369 std::tie(high, low) = Result->words();
1373 void Platform::SetLocalCacheDirectory(const char *local) {
1374 m_local_cache_directory.assign(local);
1377 const char *Platform::GetLocalCacheDirectory() {
1378 return m_local_cache_directory.c_str();
1381 static OptionDefinition g_rsync_option_table[] = {
1382 {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
1383 nullptr, 0, eArgTypeNone, "Enable rsync."},
1384 {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
1385 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCommandName,
1386 "Platform-specific options required for rsync to work."},
1387 {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P',
1388 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCommandName,
1389 "Platform-specific rsync prefix put before the remote path."},
1390 {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i',
1391 OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone,
1392 "Do not automatically fill in the remote hostname when composing the "
1396 static OptionDefinition g_ssh_option_table[] = {
1397 {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
1398 nullptr, 0, eArgTypeNone, "Enable SSH."},
1399 {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
1400 nullptr, nullptr, 0, eArgTypeCommandName,
1401 "Platform-specific options required for SSH to work."},
1404 static OptionDefinition g_caching_option_table[] = {
1405 {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
1406 OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePath,
1407 "Path in which to store local copies of files."},
1410 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
1411 return llvm::makeArrayRef(g_rsync_option_table);
1414 void OptionGroupPlatformRSync::OptionParsingStarting(
1415 ExecutionContext *execution_context) {
1417 m_rsync_opts.clear();
1418 m_rsync_prefix.clear();
1419 m_ignores_remote_hostname = false;
1422 lldb_private::Status
1423 OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx,
1424 llvm::StringRef option_arg,
1425 ExecutionContext *execution_context) {
1427 char short_option = (char)GetDefinitions()[option_idx].short_option;
1428 switch (short_option) {
1434 m_rsync_opts.assign(option_arg);
1438 m_rsync_prefix.assign(option_arg);
1442 m_ignores_remote_hostname = true;
1446 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1454 Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) {
1455 return lldb::BreakpointSP();
1458 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
1459 return llvm::makeArrayRef(g_ssh_option_table);
1462 void OptionGroupPlatformSSH::OptionParsingStarting(
1463 ExecutionContext *execution_context) {
1468 lldb_private::Status
1469 OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx,
1470 llvm::StringRef option_arg,
1471 ExecutionContext *execution_context) {
1473 char short_option = (char)GetDefinitions()[option_idx].short_option;
1474 switch (short_option) {
1480 m_ssh_opts.assign(option_arg);
1484 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1491 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
1492 return llvm::makeArrayRef(g_caching_option_table);
1495 void OptionGroupPlatformCaching::OptionParsingStarting(
1496 ExecutionContext *execution_context) {
1497 m_cache_dir.clear();
1500 lldb_private::Status OptionGroupPlatformCaching::SetOptionValue(
1501 uint32_t option_idx, llvm::StringRef option_arg,
1502 ExecutionContext *execution_context) {
1504 char short_option = (char)GetDefinitions()[option_idx].short_option;
1505 switch (short_option) {
1507 m_cache_dir.assign(option_arg);
1511 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1518 Environment Platform::GetEnvironment() { return Environment(); }
1520 const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1521 if (!m_calculated_trap_handlers) {
1522 std::lock_guard<std::mutex> guard(m_mutex);
1523 if (!m_calculated_trap_handlers) {
1524 CalculateTrapHandlerSymbolNames();
1525 m_calculated_trap_handlers = true;
1528 return m_trap_handlers;
1531 Status Platform::GetCachedExecutable(
1532 ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1533 const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1534 const auto platform_spec = module_spec.GetFileSpec();
1535 const auto error = LoadCachedExecutable(
1536 module_spec, module_sp, module_search_paths_ptr, remote_platform);
1537 if (error.Success()) {
1538 module_spec.GetFileSpec() = module_sp->GetFileSpec();
1539 module_spec.GetPlatformFileSpec() = platform_spec;
1545 Status Platform::LoadCachedExecutable(
1546 const ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1547 const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1548 return GetRemoteSharedModule(module_spec, nullptr, module_sp,
1549 [&](const ModuleSpec &spec) {
1550 return remote_platform.ResolveExecutable(
1551 spec, module_sp, module_search_paths_ptr);
1556 Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec,
1558 lldb::ModuleSP &module_sp,
1559 const ModuleResolver &module_resolver,
1560 bool *did_create_ptr) {
1561 // Get module information from a target.
1562 ModuleSpec resolved_module_spec;
1563 bool got_module_spec = false;
1565 // Try to get module information from the process
1566 if (process->GetModuleSpec(module_spec.GetFileSpec(),
1567 module_spec.GetArchitecture(),
1568 resolved_module_spec)) {
1569 if (module_spec.GetUUID().IsValid() == false ||
1570 module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1571 got_module_spec = true;
1576 if (module_spec.GetArchitecture().IsValid() == false) {
1578 // No valid architecture was specified, ask the platform for the
1579 // architectures that we should be using (in the correct order) and see if
1580 // we can find a match that way
1581 ModuleSpec arch_module_spec(module_spec);
1582 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
1583 idx, arch_module_spec.GetArchitecture());
1585 error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
1587 // Did we find an executable using one of the
1588 if (error.Success() && module_sp)
1592 got_module_spec = true;
1595 if (!got_module_spec) {
1596 // Get module information from a target.
1597 if (!GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1598 resolved_module_spec)) {
1599 if (module_spec.GetUUID().IsValid() == false ||
1600 module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1601 return module_resolver(module_spec);
1606 // If we are looking for a specific UUID, make sure resolved_module_spec has
1607 // the same one before we search.
1608 if (module_spec.GetUUID().IsValid()) {
1609 resolved_module_spec.GetUUID() = module_spec.GetUUID();
1612 // Trying to find a module by UUID on local file system.
1613 const auto error = module_resolver(resolved_module_spec);
1615 if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr))
1622 bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec,
1623 lldb::ModuleSP &module_sp,
1624 bool *did_create_ptr) {
1625 if (IsHost() || !GetGlobalPlatformProperties()->GetUseModuleCache() ||
1626 !GetGlobalPlatformProperties()->GetModuleCacheDirectory())
1629 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
1631 // Check local cache for a module.
1632 auto error = m_module_cache->GetAndPut(
1633 GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1634 [this](const ModuleSpec &module_spec,
1635 const FileSpec &tmp_download_file_spec) {
1636 return DownloadModuleSlice(
1637 module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1638 module_spec.GetObjectSize(), tmp_download_file_spec);
1641 [this](const ModuleSP &module_sp,
1642 const FileSpec &tmp_download_file_spec) {
1643 return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1645 module_sp, did_create_ptr);
1646 if (error.Success())
1650 log->Printf("Platform::%s - module %s not found in local cache: %s",
1651 __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1656 Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec,
1657 const uint64_t src_offset,
1658 const uint64_t src_size,
1659 const FileSpec &dst_file_spec) {
1663 llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::F_None);
1665 error.SetErrorStringWithFormat("unable to open destination file: %s",
1666 dst_file_spec.GetPath().c_str());
1670 auto src_fd = OpenFile(src_file_spec, File::eOpenOptionRead,
1671 lldb::eFilePermissionsFileDefault, error);
1674 error.SetErrorStringWithFormat("unable to open source file: %s",
1679 std::vector<char> buffer(1024);
1680 auto offset = src_offset;
1681 uint64_t total_bytes_read = 0;
1682 while (total_bytes_read < src_size) {
1683 const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1684 src_size - total_bytes_read);
1685 const uint64_t n_read =
1686 ReadFile(src_fd, offset, &buffer[0], to_read, error);
1690 error.SetErrorString("read 0 bytes");
1694 total_bytes_read += n_read;
1695 dst.write(&buffer[0], n_read);
1699 CloseFile(src_fd, close_error); // Ignoring close error.
1704 Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
1705 const FileSpec &dst_file_spec) {
1707 "Symbol file downloading not supported by the default platform.");
1710 FileSpec Platform::GetModuleCacheRoot() {
1711 auto dir_spec = GetGlobalPlatformProperties()->GetModuleCacheDirectory();
1712 dir_spec.AppendPathComponent(GetName().AsCString());
1716 const char *Platform::GetCacheHostname() { return GetHostname(); }
1718 const UnixSignalsSP &Platform::GetRemoteUnixSignals() {
1719 static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1720 return s_default_unix_signals_sp;
1723 const UnixSignalsSP &Platform::GetUnixSignals() {
1725 return Host::GetUnixSignals();
1726 return GetRemoteUnixSignals();
1729 uint32_t Platform::LoadImage(lldb_private::Process *process,
1730 const lldb_private::FileSpec &local_file,
1731 const lldb_private::FileSpec &remote_file,
1732 lldb_private::Status &error) {
1733 if (local_file && remote_file) {
1734 // Both local and remote file was specified. Install the local file to the
1736 if (IsRemote() || local_file != remote_file) {
1737 error = Install(local_file, remote_file);
1739 return LLDB_INVALID_IMAGE_TOKEN;
1741 return DoLoadImage(process, remote_file, nullptr, error);
1745 // Only local file was specified. Install it to the current working
1747 FileSpec target_file = GetWorkingDirectory();
1748 target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1749 if (IsRemote() || local_file != target_file) {
1750 error = Install(local_file, target_file);
1752 return LLDB_INVALID_IMAGE_TOKEN;
1754 return DoLoadImage(process, target_file, nullptr, error);
1758 // Only remote file was specified so we don't have to do any copying
1759 return DoLoadImage(process, remote_file, nullptr, error);
1762 error.SetErrorString("Neither local nor remote file was specified");
1763 return LLDB_INVALID_IMAGE_TOKEN;
1766 uint32_t Platform::DoLoadImage(lldb_private::Process *process,
1767 const lldb_private::FileSpec &remote_file,
1768 const std::vector<std::string> *paths,
1769 lldb_private::Status &error,
1770 lldb_private::FileSpec *loaded_image) {
1771 error.SetErrorString("LoadImage is not supported on the current platform");
1772 return LLDB_INVALID_IMAGE_TOKEN;
1775 uint32_t Platform::LoadImageUsingPaths(lldb_private::Process *process,
1776 const lldb_private::FileSpec &remote_filename,
1777 const std::vector<std::string> &paths,
1778 lldb_private::Status &error,
1779 lldb_private::FileSpec *loaded_path)
1781 FileSpec file_to_use;
1782 if (remote_filename.IsAbsolute())
1783 file_to_use = FileSpec(remote_filename.GetFilename().GetStringRef(),
1785 remote_filename.GetPathStyle());
1787 file_to_use = remote_filename;
1789 return DoLoadImage(process, file_to_use, &paths, error, loaded_path);
1792 Status Platform::UnloadImage(lldb_private::Process *process,
1793 uint32_t image_token) {
1794 return Status("UnloadImage is not supported on the current platform");
1797 lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
1798 llvm::StringRef plugin_name,
1799 lldb_private::Debugger &debugger,
1800 lldb_private::Target *target,
1801 lldb_private::Status &error) {
1805 TargetSP new_target_sp;
1806 error = debugger.GetTargetList().CreateTarget(debugger, "", "", false,
1807 nullptr, new_target_sp);
1808 target = new_target_sp.get();
1811 if (!target || error.Fail())
1814 debugger.GetTargetList().SetSelectedTarget(target);
1816 lldb::ProcessSP process_sp =
1817 target->CreateProcess(debugger.GetListener(), plugin_name, nullptr);
1822 process_sp->ConnectRemote(debugger.GetOutputFile().get(), connect_url);
1829 size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
1830 lldb_private::Status &error) {
1835 size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target,
1836 BreakpointSite *bp_site) {
1837 ArchSpec arch = target.GetArchitecture();
1838 const uint8_t *trap_opcode = nullptr;
1839 size_t trap_opcode_size = 0;
1841 switch (arch.GetMachine()) {
1842 case llvm::Triple::aarch64: {
1843 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1844 trap_opcode = g_aarch64_opcode;
1845 trap_opcode_size = sizeof(g_aarch64_opcode);
1848 // TODO: support big-endian arm and thumb trap codes.
1849 case llvm::Triple::arm: {
1850 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1851 // linux kernel does otherwise.
1852 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1853 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1855 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
1856 AddressClass addr_class = AddressClass::eUnknown;
1859 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
1860 if (addr_class == AddressClass::eUnknown &&
1861 (bp_loc_sp->GetAddress().GetFileAddress() & 1))
1862 addr_class = AddressClass::eCodeAlternateISA;
1865 if (addr_class == AddressClass::eCodeAlternateISA) {
1866 trap_opcode = g_thumb_breakpoint_opcode;
1867 trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1869 trap_opcode = g_arm_breakpoint_opcode;
1870 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1874 case llvm::Triple::mips:
1875 case llvm::Triple::mips64: {
1876 static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1877 trap_opcode = g_hex_opcode;
1878 trap_opcode_size = sizeof(g_hex_opcode);
1881 case llvm::Triple::mipsel:
1882 case llvm::Triple::mips64el: {
1883 static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1884 trap_opcode = g_hex_opcode;
1885 trap_opcode_size = sizeof(g_hex_opcode);
1888 case llvm::Triple::systemz: {
1889 static const uint8_t g_hex_opcode[] = {0x00, 0x01};
1890 trap_opcode = g_hex_opcode;
1891 trap_opcode_size = sizeof(g_hex_opcode);
1894 case llvm::Triple::hexagon: {
1895 static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
1896 trap_opcode = g_hex_opcode;
1897 trap_opcode_size = sizeof(g_hex_opcode);
1900 case llvm::Triple::ppc:
1901 case llvm::Triple::ppc64: {
1902 static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
1903 trap_opcode = g_ppc_opcode;
1904 trap_opcode_size = sizeof(g_ppc_opcode);
1907 case llvm::Triple::ppc64le: {
1908 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1909 trap_opcode = g_ppc64le_opcode;
1910 trap_opcode_size = sizeof(g_ppc64le_opcode);
1913 case llvm::Triple::x86:
1914 case llvm::Triple::x86_64: {
1915 static const uint8_t g_i386_opcode[] = {0xCC};
1916 trap_opcode = g_i386_opcode;
1917 trap_opcode_size = sizeof(g_i386_opcode);
1922 "Unhandled architecture in Platform::GetSoftwareBreakpointTrapOpcode");
1926 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1927 return trap_opcode_size;