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/Target/Platform.h"
22 #include "lldb/Breakpoint/BreakpointIDList.h"
23 #include "lldb/Breakpoint/BreakpointLocation.h"
24 #include "lldb/Core/DataBufferHeap.h"
25 #include "lldb/Core/Debugger.h"
26 #include "lldb/Core/Error.h"
27 #include "lldb/Core/Log.h"
28 #include "lldb/Core/Module.h"
29 #include "lldb/Core/ModuleSpec.h"
30 #include "lldb/Core/PluginManager.h"
31 #include "lldb/Core/StreamFile.h"
32 #include "lldb/Core/StructuredData.h"
33 #include "lldb/Host/FileSpec.h"
34 #include "lldb/Host/FileSystem.h"
35 #include "lldb/Host/Host.h"
36 #include "lldb/Host/HostInfo.h"
37 #include "lldb/Interpreter/OptionValueProperties.h"
38 #include "lldb/Interpreter/Property.h"
39 #include "lldb/Symbol/ObjectFile.h"
40 #include "lldb/Target/Process.h"
41 #include "lldb/Target/Target.h"
42 #include "lldb/Target/UnixSignals.h"
43 #include "lldb/Utility/Utils.h"
44 #include "Utility/ModuleCache.h"
46 // Define these constants from POSIX mman.h rather than include the file
47 // so that they will be correct even when compiled on Linux.
49 #define MAP_ANON 0x1000
52 using namespace lldb_private;
54 static uint32_t g_initialize_count = 0;
56 // Use a singleton function for g_local_platform_sp to avoid init
57 // constructors since LLDB is often part of a shared library
61 static PlatformSP g_platform_sp;
66 Platform::GetHostPlatformName ()
76 { "use-module-cache" , OptionValue::eTypeBoolean , true, true, nullptr, nullptr, "Use module cache." },
77 { "module-cache-directory", OptionValue::eTypeFileSpec, true, 0 , nullptr, nullptr, "Root directory for cached modules." },
78 { nullptr , OptionValue::eTypeInvalid , false, 0, nullptr, nullptr, nullptr }
83 ePropertyUseModuleCache,
84 ePropertyModuleCacheDirectory
91 PlatformProperties::GetSettingName ()
93 static ConstString g_setting_name("platform");
94 return g_setting_name;
97 PlatformProperties::PlatformProperties ()
99 m_collection_sp.reset (new OptionValueProperties (GetSettingName ()));
100 m_collection_sp->Initialize (g_properties);
102 auto module_cache_dir = GetModuleCacheDirectory ();
103 if (module_cache_dir)
106 llvm::SmallString<64> user_home_dir;
107 if (!llvm::sys::path::home_directory (user_home_dir))
110 module_cache_dir = FileSpec (user_home_dir.c_str(), false);
111 module_cache_dir.AppendPathComponent (".lldb");
112 module_cache_dir.AppendPathComponent ("module_cache");
113 SetModuleCacheDirectory (module_cache_dir);
117 PlatformProperties::GetUseModuleCache () const
119 const auto idx = ePropertyUseModuleCache;
120 return m_collection_sp->GetPropertyAtIndexAsBoolean (
121 nullptr, idx, g_properties[idx].default_uint_value != 0);
125 PlatformProperties::SetUseModuleCache (bool use_module_cache)
127 return m_collection_sp->SetPropertyAtIndexAsBoolean (nullptr, ePropertyUseModuleCache, use_module_cache);
131 PlatformProperties::GetModuleCacheDirectory () const
133 return m_collection_sp->GetPropertyAtIndexAsFileSpec (nullptr, ePropertyModuleCacheDirectory);
137 PlatformProperties::SetModuleCacheDirectory (const FileSpec& dir_spec)
139 return m_collection_sp->SetPropertyAtIndexAsFileSpec (nullptr, ePropertyModuleCacheDirectory, dir_spec);
142 //------------------------------------------------------------------
143 /// Get the native host platform plug-in.
145 /// There should only be one of these for each host that LLDB runs
146 /// upon that should be statically compiled in and registered using
147 /// preprocessor macros or other similar build mechanisms.
149 /// This platform will be used as the default platform when launching
150 /// or attaching to processes unless another platform is specified.
151 //------------------------------------------------------------------
153 Platform::GetHostPlatform ()
155 return GetHostPlatformSP ();
158 static std::vector<PlatformSP> &
161 static std::vector<PlatformSP> g_platform_list;
162 return g_platform_list;
165 static std::recursive_mutex &
166 GetPlatformListMutex()
168 static std::recursive_mutex g_mutex;
173 Platform::Initialize ()
175 g_initialize_count++;
179 Platform::Terminate ()
181 if (g_initialize_count > 0)
183 if (--g_initialize_count == 0)
185 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
186 GetPlatformList().clear();
191 const PlatformPropertiesSP &
192 Platform::GetGlobalPlatformProperties ()
194 static const auto g_settings_sp (std::make_shared<PlatformProperties> ());
195 return g_settings_sp;
199 Platform::SetHostPlatform (const lldb::PlatformSP &platform_sp)
201 // The native platform should use its static void Platform::Initialize()
202 // function to register itself as the native platform.
203 GetHostPlatformSP () = platform_sp;
207 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
208 GetPlatformList().push_back(platform_sp);
213 Platform::GetFileWithUUID (const FileSpec &platform_file,
214 const UUID *uuid_ptr,
215 FileSpec &local_file)
217 // Default to the local case
218 local_file = platform_file;
223 Platform::LocateExecutableScriptingResources (Target *target, Module &module, Stream* feedback_stream)
225 return FileSpecList();
229 //Platform::FindPlugin (Process *process, const ConstString &plugin_name)
231 // PlatformCreateInstance create_callback = nullptr;
234 // create_callback = PluginManager::GetPlatformCreateCallbackForPluginName (plugin_name);
235 // if (create_callback)
240 // arch = process->GetTarget().GetArchitecture();
242 // PlatformSP platform_sp(create_callback(process, &arch));
244 // return platform_sp;
249 // for (uint32_t idx = 0; (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex(idx)) != nullptr; ++idx)
251 // PlatformSP platform_sp(create_callback(process, nullptr));
253 // return platform_sp;
256 // return PlatformSP();
260 Platform::GetSharedModule (const ModuleSpec &module_spec,
263 const FileSpecList *module_search_paths_ptr,
264 ModuleSP *old_module_sp_ptr,
265 bool *did_create_ptr)
268 return ModuleList::GetSharedModule (module_spec,
270 module_search_paths_ptr,
275 return GetRemoteSharedModule (module_spec,
278 [&](const ModuleSpec &spec)
280 Error error = ModuleList::GetSharedModule (
281 spec, module_sp, module_search_paths_ptr, old_module_sp_ptr, did_create_ptr, false);
282 if (error.Success() && module_sp)
283 module_sp->SetPlatformFileSpec(spec.GetFileSpec());
290 Platform::GetModuleSpec (const FileSpec& module_file_spec,
291 const ArchSpec& arch,
292 ModuleSpec &module_spec)
294 ModuleSpecList module_specs;
295 if (ObjectFile::GetModuleSpecifications (module_file_spec, 0, 0, module_specs) == 0)
298 ModuleSpec matched_module_spec;
299 return module_specs.FindMatchingModuleSpec (ModuleSpec (module_file_spec, arch),
304 Platform::Find (const ConstString &name)
308 static ConstString g_host_platform_name ("host");
309 if (name == g_host_platform_name)
310 return GetHostPlatform();
312 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
313 for (const auto &platform_sp : GetPlatformList())
315 if (platform_sp->GetName() == name)
323 Platform::Create (const ConstString &name, Error &error)
325 PlatformCreateInstance create_callback = nullptr;
326 lldb::PlatformSP platform_sp;
329 static ConstString g_host_platform_name ("host");
330 if (name == g_host_platform_name)
331 return GetHostPlatform();
333 create_callback = PluginManager::GetPlatformCreateCallbackForPluginName (name);
335 platform_sp = create_callback(true, nullptr);
337 error.SetErrorStringWithFormat ("unable to find a plug-in for the platform named \"%s\"", name.GetCString());
340 error.SetErrorString ("invalid platform name");
344 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
345 GetPlatformList().push_back(platform_sp);
352 Platform::Create (const ArchSpec &arch, ArchSpec *platform_arch_ptr, Error &error)
354 lldb::PlatformSP platform_sp;
359 // First try exact arch matches across all platforms already created
360 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
361 for (const auto &platform_sp : GetPlatformList())
363 if (platform_sp->IsCompatibleArchitecture(arch, true, platform_arch_ptr))
367 // Next try compatible arch matches across all platforms already created
368 for (const auto &platform_sp : GetPlatformList())
370 if (platform_sp->IsCompatibleArchitecture(arch, false, platform_arch_ptr))
375 PlatformCreateInstance create_callback;
376 // First try exact arch matches across all platform plug-ins
378 for (idx = 0; (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex (idx)); ++idx)
382 platform_sp = create_callback(false, &arch);
383 if (platform_sp && platform_sp->IsCompatibleArchitecture(arch, true, platform_arch_ptr))
385 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
386 GetPlatformList().push_back(platform_sp);
391 // Next try compatible arch matches across all platform plug-ins
392 for (idx = 0; (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex (idx)); ++idx)
396 platform_sp = create_callback(false, &arch);
397 if (platform_sp && platform_sp->IsCompatibleArchitecture(arch, false, platform_arch_ptr))
399 std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
400 GetPlatformList().push_back(platform_sp);
407 error.SetErrorString ("invalid platform name");
408 if (platform_arch_ptr)
409 platform_arch_ptr->Clear();
414 //------------------------------------------------------------------
415 /// Default Constructor
416 //------------------------------------------------------------------
417 Platform::Platform(bool is_host)
418 : m_is_host(is_host),
419 m_os_version_set_while_connected(false),
420 m_system_arch_set_while_connected(false),
426 m_major_os_version(UINT32_MAX),
427 m_minor_os_version(UINT32_MAX),
428 m_update_os_version(UINT32_MAX),
433 m_max_uid_name_len(0),
434 m_max_gid_name_len(0),
435 m_supports_rsync(false),
438 m_supports_ssh(false),
440 m_ignores_remote_hostname(false),
442 m_calculated_trap_handlers(false),
443 m_module_cache(llvm::make_unique<ModuleCache>())
445 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
447 log->Printf("%p Platform::Platform()", static_cast<void *>(this));
450 //------------------------------------------------------------------
453 /// The destructor is virtual since this class is designed to be
454 /// inherited from by the plug-in instance.
455 //------------------------------------------------------------------
456 Platform::~Platform()
458 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
460 log->Printf ("%p Platform::~Platform()", static_cast<void*>(this));
464 Platform::GetStatus (Stream &strm)
466 uint32_t major = UINT32_MAX;
467 uint32_t minor = UINT32_MAX;
468 uint32_t update = UINT32_MAX;
470 strm.Printf (" Platform: %s\n", GetPluginName().GetCString());
472 ArchSpec arch (GetSystemArchitecture());
475 if (!arch.GetTriple().str().empty())
477 strm.Printf(" Triple: ");
478 arch.DumpTriple(strm);
483 if (GetOSVersion(major, minor, update))
485 strm.Printf("OS Version: %u", major);
486 if (minor != UINT32_MAX)
487 strm.Printf(".%u", minor);
488 if (update != UINT32_MAX)
489 strm.Printf(".%u", update);
491 if (GetOSBuildString (s))
492 strm.Printf(" (%s)", s.c_str());
497 if (GetOSKernelDescription (s))
498 strm.Printf(" Kernel: %s\n", s.c_str());
502 strm.Printf(" Hostname: %s\n", GetHostname());
506 const bool is_connected = IsConnected();
508 strm.Printf(" Hostname: %s\n", GetHostname());
509 strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no");
512 if (GetWorkingDirectory())
514 strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString());
519 std::string specific_info(GetPlatformSpecificConnectionInformation());
521 if (!specific_info.empty())
522 strm.Printf("Platform-specific connection: %s\n", specific_info.c_str());
526 Platform::GetOSVersion (uint32_t &major,
531 std::lock_guard<std::mutex> guard(m_mutex);
533 bool success = m_major_os_version != UINT32_MAX;
538 // We have a local host platform
539 success = HostInfo::GetOSVersion(m_major_os_version, m_minor_os_version, m_update_os_version);
540 m_os_version_set_while_connected = success;
545 // We have a remote platform. We can only fetch the remote
546 // OS version if we are connected, and we don't want to do it
549 const bool is_connected = IsConnected();
554 // We have valid OS version info, check to make sure it wasn't
555 // manually set prior to connecting. If it was manually set prior
556 // to connecting, then lets fetch the actual OS version info
557 // if we are now connected.
558 if (is_connected && !m_os_version_set_while_connected)
563 // We don't have valid OS version info, fetch it if we are connected
564 fetch = is_connected;
569 success = GetRemoteOSVersion ();
570 m_os_version_set_while_connected = success;
576 major = m_major_os_version;
577 minor = m_minor_os_version;
578 update = m_update_os_version;
582 // Check with the process in case it can answer the question if
583 // a process was provided
584 return process->GetHostOSVersion(major, minor, update);
590 Platform::GetOSBuildString (std::string &s)
595 #if !defined(__linux__)
596 return HostInfo::GetOSBuildString(s);
601 return GetRemoteOSBuildString (s);
605 Platform::GetOSKernelDescription (std::string &s)
608 #if !defined(__linux__)
609 return HostInfo::GetOSKernelDescription(s);
614 return GetRemoteOSKernelDescription (s);
618 Platform::AddClangModuleCompilationOptions (Target *target, std::vector<std::string> &options)
620 std::vector<std::string> default_compilation_options =
622 "-x", "c++", "-Xclang", "-nostdsysteminc", "-Xclang", "-nostdsysteminc"
625 options.insert(options.end(),
626 default_compilation_options.begin(),
627 default_compilation_options.end());
631 Platform::GetWorkingDirectory ()
636 if (getcwd(cwd, sizeof(cwd)))
637 return FileSpec{cwd, true};
644 m_working_dir = GetRemoteWorkingDirectory();
645 return m_working_dir;
649 struct RecurseCopyBaton
652 Platform *platform_ptr;
656 static FileSpec::EnumerateDirectoryResult
657 RecurseCopy_Callback (void *baton,
658 FileSpec::FileType file_type,
661 RecurseCopyBaton* rc_baton = (RecurseCopyBaton*)baton;
664 case FileSpec::eFileTypePipe:
665 case FileSpec::eFileTypeSocket:
666 // we have no way to copy pipes and sockets - ignore them and continue
667 return FileSpec::eEnumerateDirectoryResultNext;
670 case FileSpec::eFileTypeDirectory:
672 // make the new directory and get in there
673 FileSpec dst_dir = rc_baton->dst;
674 if (!dst_dir.GetFilename())
675 dst_dir.GetFilename() = src.GetLastPathComponent();
676 Error error = rc_baton->platform_ptr->MakeDirectory(dst_dir, lldb::eFilePermissionsDirectoryDefault);
679 rc_baton->error.SetErrorStringWithFormat("unable to setup directory %s on remote end",
680 dst_dir.GetCString());
681 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
685 std::string src_dir_path (src.GetPath());
687 // Make a filespec that only fills in the directory of a FileSpec so
688 // when we enumerate we can quickly fill in the filename for dst copies
689 FileSpec recurse_dst;
690 recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str());
691 RecurseCopyBaton rc_baton2 = { recurse_dst, rc_baton->platform_ptr, Error() };
692 FileSpec::EnumerateDirectory(src_dir_path.c_str(), true, true, true, RecurseCopy_Callback, &rc_baton2);
693 if (rc_baton2.error.Fail())
695 rc_baton->error.SetErrorString(rc_baton2.error.AsCString());
696 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
698 return FileSpec::eEnumerateDirectoryResultNext;
702 case FileSpec::eFileTypeSymbolicLink:
704 // copy the file and keep going
705 FileSpec dst_file = rc_baton->dst;
706 if (!dst_file.GetFilename())
707 dst_file.GetFilename() = src.GetFilename();
709 FileSpec src_resolved;
711 rc_baton->error = FileSystem::Readlink(src, src_resolved);
713 if (rc_baton->error.Fail())
714 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
716 rc_baton->error = rc_baton->platform_ptr->CreateSymlink(dst_file, src_resolved);
718 if (rc_baton->error.Fail())
719 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
721 return FileSpec::eEnumerateDirectoryResultNext;
725 case FileSpec::eFileTypeRegular:
727 // copy the file and keep going
728 FileSpec dst_file = rc_baton->dst;
729 if (!dst_file.GetFilename())
730 dst_file.GetFilename() = src.GetFilename();
731 Error err = rc_baton->platform_ptr->PutFile(src, dst_file);
734 rc_baton->error.SetErrorString(err.AsCString());
735 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
737 return FileSpec::eEnumerateDirectoryResultNext;
741 case FileSpec::eFileTypeInvalid:
742 case FileSpec::eFileTypeOther:
743 case FileSpec::eFileTypeUnknown:
744 rc_baton->error.SetErrorStringWithFormat("invalid file detected during copy: %s", src.GetPath().c_str());
745 return FileSpec::eEnumerateDirectoryResultQuit; // got an error, bail out
748 llvm_unreachable("Unhandled FileSpec::FileType!");
752 Platform::Install (const FileSpec& src, const FileSpec& dst)
756 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
758 log->Printf ("Platform::Install (src='%s', dst='%s')", src.GetPath().c_str(), dst.GetPath().c_str());
759 FileSpec fixed_dst(dst);
761 if (!fixed_dst.GetFilename())
762 fixed_dst.GetFilename() = src.GetFilename();
764 FileSpec working_dir = GetWorkingDirectory();
768 if (dst.GetDirectory())
770 const char first_dst_dir_char = dst.GetDirectory().GetCString()[0];
771 if (first_dst_dir_char == '/' || first_dst_dir_char == '\\')
773 fixed_dst.GetDirectory() = dst.GetDirectory();
775 // If the fixed destination file doesn't have a directory yet,
776 // then we must have a relative path. We will resolve this relative
777 // path against the platform's working directory
778 if (!fixed_dst.GetDirectory())
780 FileSpec relative_spec;
784 relative_spec = working_dir;
785 relative_spec.AppendPathComponent(dst.GetPath());
786 fixed_dst.GetDirectory() = relative_spec.GetDirectory();
790 error.SetErrorStringWithFormat("platform working directory must be valid for relative path '%s'", dst.GetPath().c_str());
799 fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
803 error.SetErrorStringWithFormat("platform working directory must be valid for relative path '%s'", dst.GetPath().c_str());
812 fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
816 error.SetErrorStringWithFormat("platform working directory must be valid when destination directory is empty");
822 log->Printf ("Platform::Install (src='%s', dst='%s') fixed_dst='%s'", src.GetPath().c_str(), dst.GetPath().c_str(), fixed_dst.GetPath().c_str());
824 if (GetSupportsRSync())
826 error = PutFile(src, dst);
830 switch (src.GetFileType())
832 case FileSpec::eFileTypeDirectory:
834 if (GetFileExists (fixed_dst))
836 uint32_t permissions = src.GetPermissions();
837 if (permissions == 0)
838 permissions = eFilePermissionsDirectoryDefault;
839 error = MakeDirectory(fixed_dst, permissions);
842 // Make a filespec that only fills in the directory of a FileSpec so
843 // when we enumerate we can quickly fill in the filename for dst copies
844 FileSpec recurse_dst;
845 recurse_dst.GetDirectory().SetCString(fixed_dst.GetCString());
846 std::string src_dir_path (src.GetPath());
847 RecurseCopyBaton baton = { recurse_dst, this, Error() };
848 FileSpec::EnumerateDirectory(src_dir_path.c_str(), true, true, true, RecurseCopy_Callback, &baton);
854 case FileSpec::eFileTypeRegular:
855 if (GetFileExists (fixed_dst))
857 error = PutFile(src, fixed_dst);
860 case FileSpec::eFileTypeSymbolicLink:
862 if (GetFileExists (fixed_dst))
864 FileSpec src_resolved;
865 error = FileSystem::Readlink(src, src_resolved);
867 error = CreateSymlink(dst, src_resolved);
870 case FileSpec::eFileTypePipe:
871 error.SetErrorString("platform install doesn't handle pipes");
873 case FileSpec::eFileTypeSocket:
874 error.SetErrorString("platform install doesn't handle sockets");
876 case FileSpec::eFileTypeInvalid:
877 case FileSpec::eFileTypeUnknown:
878 case FileSpec::eFileTypeOther:
879 error.SetErrorString("platform install doesn't handle non file or directory items");
887 Platform::SetWorkingDirectory(const FileSpec &file_spec)
891 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
893 log->Printf("Platform::SetWorkingDirectory('%s')",
894 file_spec.GetCString());
897 if (::chdir(file_spec.GetCString()) == 0)
904 m_working_dir.Clear();
905 return SetRemoteWorkingDirectory(file_spec);
910 Platform::MakeDirectory(const FileSpec &file_spec, uint32_t permissions)
913 return FileSystem::MakeDirectory(file_spec, permissions);
917 error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
923 Platform::GetFilePermissions(const FileSpec &file_spec, uint32_t &file_permissions)
926 return FileSystem::GetFilePermissions(file_spec, file_permissions);
930 error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
936 Platform::SetFilePermissions(const FileSpec &file_spec, uint32_t file_permissions)
939 return FileSystem::SetFilePermissions(file_spec, file_permissions);
943 error.SetErrorStringWithFormat("remote platform %s doesn't support %s", GetPluginName().GetCString(), __PRETTY_FUNCTION__);
951 return GetPluginName();
955 Platform::GetHostname ()
962 return m_name.c_str();
966 Platform::GetFullNameForDylib (ConstString basename)
972 Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir)
974 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
976 log->Printf("Platform::SetRemoteWorkingDirectory('%s')",
977 working_dir.GetCString());
978 m_working_dir = working_dir;
983 Platform::GetUserName (uint32_t uid)
985 #if !defined(LLDB_DISABLE_POSIX)
986 const char *user_name = GetCachedUserName(uid);
992 if (HostInfo::LookupUserName(uid, name))
993 return SetCachedUserName (uid, name.c_str(), name.size());
1000 Platform::GetGroupName (uint32_t gid)
1002 #if !defined(LLDB_DISABLE_POSIX)
1003 const char *group_name = GetCachedGroupName(gid);
1009 if (HostInfo::LookupGroupName(gid, name))
1010 return SetCachedGroupName (gid, name.c_str(), name.size());
1017 Platform::SetOSVersion (uint32_t major,
1023 // We don't need anyone setting the OS version for the host platform,
1024 // we should be able to figure it out by calling HostInfo::GetOSVersion(...).
1029 // We have a remote platform, allow setting the target OS version if
1030 // we aren't connected, since if we are connected, we should be able to
1031 // request the remote OS version from the connected platform.
1036 // We aren't connected and we might want to set the OS version
1037 // ahead of time before we connect so we can peruse files and
1038 // use a local SDK or PDK cache of support files to disassemble
1039 // or do other things.
1040 m_major_os_version = major;
1041 m_minor_os_version = minor;
1042 m_update_os_version = update;
1050 Platform::ResolveExecutable (const ModuleSpec &module_spec,
1051 lldb::ModuleSP &exe_module_sp,
1052 const FileSpecList *module_search_paths_ptr)
1055 if (module_spec.GetFileSpec().Exists())
1057 if (module_spec.GetArchitecture().IsValid())
1059 error = ModuleList::GetSharedModule(module_spec,
1061 module_search_paths_ptr,
1067 // No valid architecture was specified, ask the platform for
1068 // the architectures that we should be using (in the correct order)
1069 // and see if we can find a match that way
1070 ModuleSpec arch_module_spec(module_spec);
1071 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex (idx, arch_module_spec.GetArchitecture()); ++idx)
1073 error = ModuleList::GetSharedModule(arch_module_spec,
1075 module_search_paths_ptr,
1078 // Did we find an executable using one of the
1079 if (error.Success() && exe_module_sp)
1086 error.SetErrorStringWithFormat ("'%s' does not exist",
1087 module_spec.GetFileSpec().GetPath().c_str());
1093 Platform::ResolveSymbolFile (Target &target,
1094 const ModuleSpec &sym_spec,
1098 if (sym_spec.GetSymbolFileSpec().Exists())
1099 sym_file = sym_spec.GetSymbolFileSpec();
1101 error.SetErrorString("unable to resolve symbol file");
1106 Platform::ResolveRemotePath (const FileSpec &platform_path,
1107 FileSpec &resolved_platform_path)
1109 resolved_platform_path = platform_path;
1110 return resolved_platform_path.ResolvePath();
1114 Platform::GetSystemArchitecture()
1118 if (!m_system_arch.IsValid())
1120 // We have a local host platform
1121 m_system_arch = HostInfo::GetArchitecture();
1122 m_system_arch_set_while_connected = m_system_arch.IsValid();
1127 // We have a remote platform. We can only fetch the remote
1128 // system architecture if we are connected, and we don't want to do it
1131 const bool is_connected = IsConnected();
1134 if (m_system_arch.IsValid())
1136 // We have valid OS version info, check to make sure it wasn't
1137 // manually set prior to connecting. If it was manually set prior
1138 // to connecting, then lets fetch the actual OS version info
1139 // if we are now connected.
1140 if (is_connected && !m_system_arch_set_while_connected)
1145 // We don't have valid OS version info, fetch it if we are connected
1146 fetch = is_connected;
1151 m_system_arch = GetRemoteSystemArchitecture ();
1152 m_system_arch_set_while_connected = m_system_arch.IsValid();
1155 return m_system_arch;
1159 Platform::ConnectRemote (Args& args)
1163 error.SetErrorStringWithFormat ("The currently selected platform (%s) is the host platform and is always connected.", GetPluginName().GetCString());
1165 error.SetErrorStringWithFormat ("Platform::ConnectRemote() is not supported by %s", GetPluginName().GetCString());
1170 Platform::DisconnectRemote ()
1174 error.SetErrorStringWithFormat ("The currently selected platform (%s) is the host platform and is always connected.", GetPluginName().GetCString());
1176 error.SetErrorStringWithFormat ("Platform::DisconnectRemote() is not supported by %s", GetPluginName().GetCString());
1181 Platform::GetProcessInfo (lldb::pid_t pid, ProcessInstanceInfo &process_info)
1183 // Take care of the host case so that each subclass can just
1184 // call this function to get the host functionality.
1186 return Host::GetProcessInfo (pid, process_info);
1191 Platform::FindProcesses (const ProcessInstanceInfoMatch &match_info,
1192 ProcessInstanceInfoList &process_infos)
1194 // Take care of the host case so that each subclass can just
1195 // call this function to get the host functionality.
1196 uint32_t match_count = 0;
1198 match_count = Host::FindProcesses (match_info, process_infos);
1203 Platform::LaunchProcess (ProcessLaunchInfo &launch_info)
1206 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM));
1208 log->Printf ("Platform::%s()", __FUNCTION__);
1210 // Take care of the host case so that each subclass can just
1211 // call this function to get the host functionality.
1214 if (::getenv ("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
1215 launch_info.GetFlags().Set (eLaunchFlagLaunchInTTY);
1217 if (launch_info.GetFlags().Test (eLaunchFlagLaunchInShell))
1219 const bool is_localhost = true;
1220 const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1221 const bool first_arg_is_full_shell_command = false;
1222 uint32_t num_resumes = GetResumeCountForLaunchInfo (launch_info);
1225 const FileSpec &shell = launch_info.GetShell();
1226 const char *shell_str = (shell) ? shell.GetPath().c_str() : "<null>";
1227 log->Printf ("Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32 ", shell is '%s'",
1233 if (!launch_info.ConvertArgumentsForLaunchingInShell (error,
1236 first_arg_is_full_shell_command,
1240 else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments))
1242 error = ShellExpandArguments(launch_info);
1245 error.SetErrorStringWithFormat("shell expansion failed (reason: %s). consider launching with 'process launch'.",
1246 error.AsCString("unknown"));
1252 log->Printf ("Platform::%s final launch_info resume count: %" PRIu32, __FUNCTION__, launch_info.GetResumeCount ());
1254 error = Host::LaunchProcess (launch_info);
1257 error.SetErrorString ("base lldb_private::Platform class can't launch remote processes");
1262 Platform::ShellExpandArguments (ProcessLaunchInfo &launch_info)
1265 return Host::ShellExpandArguments(launch_info);
1266 return Error("base lldb_private::Platform class can't expand arguments");
1270 Platform::KillProcess (const lldb::pid_t pid)
1272 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM));
1274 log->Printf ("Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
1276 // Try to find a process plugin to handle this Kill request. If we can't, fall back to
1277 // the default OS implementation.
1278 size_t num_debuggers = Debugger::GetNumDebuggers();
1279 for (size_t didx = 0; didx < num_debuggers; ++didx)
1281 DebuggerSP debugger = Debugger::GetDebuggerAtIndex(didx);
1282 lldb_private::TargetList &targets = debugger->GetTargetList();
1283 for (int tidx = 0; tidx < targets.GetNumTargets(); ++tidx)
1285 ProcessSP process = targets.GetTargetAtIndex(tidx)->GetProcessSP();
1286 if (process->GetID() == pid)
1287 return process->Destroy(true);
1293 return Error("base lldb_private::Platform class can't kill remote processes unless "
1294 "they are controlled by a process plugin");
1296 Host::Kill(pid, SIGTERM);
1301 Platform::DebugProcess (ProcessLaunchInfo &launch_info,
1303 Target *target, // Can be nullptr, if nullptr create a new target, else use existing one
1306 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM));
1308 log->Printf ("Platform::%s entered (target %p)", __FUNCTION__, static_cast<void*>(target));
1310 ProcessSP process_sp;
1311 // Make sure we stop at the entry point
1312 launch_info.GetFlags ().Set (eLaunchFlagDebug);
1313 // We always launch the process we are going to debug in a separate process
1314 // group, since then we can handle ^C interrupts ourselves w/o having to worry
1315 // about the target getting them as well.
1316 launch_info.SetLaunchInSeparateProcessGroup(true);
1318 error = LaunchProcess (launch_info);
1319 if (error.Success())
1322 log->Printf ("Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")", __FUNCTION__, launch_info.GetProcessID ());
1323 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID)
1325 ProcessAttachInfo attach_info (launch_info);
1326 process_sp = Attach (attach_info, debugger, target, error);
1330 log->Printf ("Platform::%s Attach() succeeded, Process plugin: %s", __FUNCTION__, process_sp->GetPluginName ().AsCString ());
1331 launch_info.SetHijackListener(attach_info.GetHijackListener());
1333 // Since we attached to the process, it will think it needs to detach
1334 // if the process object just goes away without an explicit call to
1335 // Process::Kill() or Process::Detach(), so let it know to kill the
1336 // process if this happens.
1337 process_sp->SetShouldDetach (false);
1339 // If we didn't have any file actions, the pseudo terminal might
1340 // have been used where the slave side was given as the file to
1341 // open for stdin/out/err after we have already opened the master
1342 // so we can read/write stdin/out/err.
1343 int pty_fd = launch_info.GetPTY().ReleaseMasterFileDescriptor();
1344 if (pty_fd != lldb_utility::PseudoTerminal::invalid_fd)
1346 process_sp->SetSTDIOFileDescriptor(pty_fd);
1352 log->Printf ("Platform::%s Attach() failed: %s", __FUNCTION__, error.AsCString ());
1358 log->Printf ("Platform::%s LaunchProcess() returned launch_info with invalid process id", __FUNCTION__);
1364 log->Printf ("Platform::%s LaunchProcess() failed: %s", __FUNCTION__, error.AsCString ());
1371 Platform::GetPlatformForArchitecture (const ArchSpec &arch, ArchSpec *platform_arch_ptr)
1373 lldb::PlatformSP platform_sp;
1376 platform_sp = Platform::Create (arch, platform_arch_ptr, error);
1380 //------------------------------------------------------------------
1381 /// Lets a platform answer if it is compatible with a given
1382 /// architecture and the target triple contained within.
1383 //------------------------------------------------------------------
1385 Platform::IsCompatibleArchitecture (const ArchSpec &arch, bool exact_arch_match, ArchSpec *compatible_arch_ptr)
1387 // If the architecture is invalid, we must answer true...
1390 ArchSpec platform_arch;
1391 // Try for an exact architecture match first.
1392 if (exact_arch_match)
1394 for (uint32_t arch_idx=0; GetSupportedArchitectureAtIndex (arch_idx, platform_arch); ++arch_idx)
1396 if (arch.IsExactMatch(platform_arch))
1398 if (compatible_arch_ptr)
1399 *compatible_arch_ptr = platform_arch;
1406 for (uint32_t arch_idx=0; GetSupportedArchitectureAtIndex (arch_idx, platform_arch); ++arch_idx)
1408 if (arch.IsCompatibleMatch(platform_arch))
1410 if (compatible_arch_ptr)
1411 *compatible_arch_ptr = platform_arch;
1417 if (compatible_arch_ptr)
1418 compatible_arch_ptr->Clear();
1423 Platform::PutFile (const FileSpec& source,
1424 const FileSpec& destination,
1428 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_PLATFORM));
1430 log->Printf("[PutFile] Using block by block transfer....\n");
1432 uint32_t source_open_options = File::eOpenOptionRead | File::eOpenOptionCloseOnExec;
1433 if (source.GetFileType() == FileSpec::eFileTypeSymbolicLink)
1434 source_open_options |= File::eOpenOptionDontFollowSymlinks;
1436 File source_file(source, source_open_options, lldb::eFilePermissionsUserRW);
1438 uint32_t permissions = source_file.GetPermissions(error);
1439 if (permissions == 0)
1440 permissions = lldb::eFilePermissionsFileDefault;
1442 if (!source_file.IsValid())
1443 return Error("PutFile: unable to open source file");
1444 lldb::user_id_t dest_file = OpenFile (destination,
1445 File::eOpenOptionCanCreate |
1446 File::eOpenOptionWrite |
1447 File::eOpenOptionTruncate |
1448 File::eOpenOptionCloseOnExec,
1452 log->Printf ("dest_file = %" PRIu64 "\n", dest_file);
1456 if (dest_file == UINT64_MAX)
1457 return Error("unable to open target file");
1458 lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024, 0));
1459 uint64_t offset = 0;
1462 size_t bytes_read = buffer_sp->GetByteSize();
1463 error = source_file.Read(buffer_sp->GetBytes(), bytes_read);
1464 if (error.Fail() || bytes_read == 0)
1467 const uint64_t bytes_written = WriteFile(dest_file, offset,
1468 buffer_sp->GetBytes(), bytes_read, error);
1472 offset += bytes_written;
1473 if (bytes_written != bytes_read)
1475 // We didn't write the correct number of bytes, so adjust
1476 // the file position in the source file we are reading from...
1477 source_file.SeekFromStart(offset);
1480 CloseFile(dest_file, error);
1482 if (uid == UINT32_MAX && gid == UINT32_MAX)
1491 Platform::GetFile(const FileSpec &source,
1492 const FileSpec &destination)
1494 Error error("unimplemented");
1499 Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1500 const FileSpec &dst) // The symlink points to dst
1502 Error error("unimplemented");
1507 Platform::GetFileExists(const lldb_private::FileSpec &file_spec)
1513 Platform::Unlink(const FileSpec &path)
1515 Error error("unimplemented");
1520 Platform::ConvertMmapFlagsToPlatform(const ArchSpec &arch, unsigned flags)
1522 uint64_t flags_platform = 0;
1523 if (flags & eMmapFlagsPrivate)
1524 flags_platform |= MAP_PRIVATE;
1525 if (flags & eMmapFlagsAnon)
1526 flags_platform |= MAP_ANON;
1527 return flags_platform;
1531 Platform::RunShellCommand(const char *command, // Shouldn't be nullptr
1532 const FileSpec &working_dir, // Pass empty FileSpec to use the current working directory
1533 int *status_ptr, // Pass nullptr if you don't want the process exit status
1534 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the process to exit
1535 std::string *command_output, // Pass nullptr if you don't want the command output
1536 uint32_t timeout_sec) // Timeout in seconds to wait for shell program to finish
1539 return Host::RunShellCommand (command, working_dir, status_ptr, signo_ptr, command_output, timeout_sec);
1541 return Error("unimplemented");
1545 Platform::CalculateMD5 (const FileSpec& file_spec,
1550 return FileSystem::CalculateMD5(file_spec, low, high);
1556 Platform::SetLocalCacheDirectory (const char* local)
1558 m_local_cache_directory.assign(local);
1562 Platform::GetLocalCacheDirectory ()
1564 return m_local_cache_directory.c_str();
1567 static OptionDefinition
1568 g_rsync_option_table[] =
1570 { LLDB_OPT_SET_ALL, false, "rsync" , 'r', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone , "Enable rsync." },
1571 { LLDB_OPT_SET_ALL, false, "rsync-opts" , 'R', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCommandName , "Platform-specific options required for rsync to work." },
1572 { LLDB_OPT_SET_ALL, false, "rsync-prefix" , 'P', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCommandName , "Platform-specific rsync prefix put before the remote path." },
1573 { LLDB_OPT_SET_ALL, false, "ignore-remote-hostname" , 'i', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone , "Do not automatically fill in the remote hostname when composing the rsync command." },
1576 static OptionDefinition
1577 g_ssh_option_table[] =
1579 { LLDB_OPT_SET_ALL, false, "ssh" , 's', OptionParser::eNoArgument, nullptr, nullptr, 0, eArgTypeNone , "Enable SSH." },
1580 { LLDB_OPT_SET_ALL, false, "ssh-opts" , 'S', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypeCommandName , "Platform-specific options required for SSH to work." },
1583 static OptionDefinition
1584 g_caching_option_table[] =
1586 { LLDB_OPT_SET_ALL, false, "local-cache-dir" , 'c', OptionParser::eRequiredArgument, nullptr, nullptr, 0, eArgTypePath , "Path in which to store local copies of files." },
1589 const lldb_private::OptionDefinition*
1590 OptionGroupPlatformRSync::GetDefinitions ()
1592 return g_rsync_option_table;
1596 OptionGroupPlatformRSync::OptionParsingStarting (CommandInterpreter &interpreter)
1599 m_rsync_opts.clear();
1600 m_rsync_prefix.clear();
1601 m_ignores_remote_hostname = false;
1605 OptionGroupPlatformRSync::SetOptionValue (CommandInterpreter &interpreter,
1606 uint32_t option_idx,
1607 const char *option_arg)
1610 char short_option = (char) GetDefinitions()[option_idx].short_option;
1611 switch (short_option)
1618 m_rsync_opts.assign(option_arg);
1622 m_rsync_prefix.assign(option_arg);
1626 m_ignores_remote_hostname = true;
1630 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1638 OptionGroupPlatformRSync::GetNumDefinitions ()
1640 return llvm::array_lengthof(g_rsync_option_table);
1644 Platform::SetThreadCreationBreakpoint (lldb_private::Target &target)
1646 return lldb::BreakpointSP();
1649 const lldb_private::OptionDefinition*
1650 OptionGroupPlatformSSH::GetDefinitions ()
1652 return g_ssh_option_table;
1656 OptionGroupPlatformSSH::OptionParsingStarting (CommandInterpreter &interpreter)
1663 OptionGroupPlatformSSH::SetOptionValue (CommandInterpreter &interpreter,
1664 uint32_t option_idx,
1665 const char *option_arg)
1668 char short_option = (char) GetDefinitions()[option_idx].short_option;
1669 switch (short_option)
1676 m_ssh_opts.assign(option_arg);
1680 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1688 OptionGroupPlatformSSH::GetNumDefinitions ()
1690 return llvm::array_lengthof(g_ssh_option_table);
1693 const lldb_private::OptionDefinition*
1694 OptionGroupPlatformCaching::GetDefinitions ()
1696 return g_caching_option_table;
1700 OptionGroupPlatformCaching::OptionParsingStarting (CommandInterpreter &interpreter)
1702 m_cache_dir.clear();
1706 OptionGroupPlatformCaching::SetOptionValue (CommandInterpreter &interpreter,
1707 uint32_t option_idx,
1708 const char *option_arg)
1711 char short_option = (char) GetDefinitions()[option_idx].short_option;
1712 switch (short_option)
1715 m_cache_dir.assign(option_arg);
1719 error.SetErrorStringWithFormat ("unrecognized option '%c'", short_option);
1727 OptionGroupPlatformCaching::GetNumDefinitions ()
1729 return llvm::array_lengthof(g_caching_option_table);
1733 Platform::GetEnvironment (StringList &environment)
1735 environment.Clear();
1739 const std::vector<ConstString> &
1740 Platform::GetTrapHandlerSymbolNames ()
1742 if (!m_calculated_trap_handlers)
1744 std::lock_guard<std::mutex> guard(m_mutex);
1745 if (!m_calculated_trap_handlers)
1747 CalculateTrapHandlerSymbolNames();
1748 m_calculated_trap_handlers = true;
1751 return m_trap_handlers;
1755 Platform::GetCachedExecutable (ModuleSpec &module_spec,
1756 lldb::ModuleSP &module_sp,
1757 const FileSpecList *module_search_paths_ptr,
1758 Platform &remote_platform)
1760 const auto platform_spec = module_spec.GetFileSpec ();
1761 const auto error = LoadCachedExecutable (module_spec,
1763 module_search_paths_ptr,
1765 if (error.Success ())
1767 module_spec.GetFileSpec () = module_sp->GetFileSpec ();
1768 module_spec.GetPlatformFileSpec () = platform_spec;
1775 Platform::LoadCachedExecutable (const ModuleSpec &module_spec,
1776 lldb::ModuleSP &module_sp,
1777 const FileSpecList *module_search_paths_ptr,
1778 Platform &remote_platform)
1780 return GetRemoteSharedModule (module_spec,
1783 [&](const ModuleSpec &spec)
1785 return remote_platform.ResolveExecutable (
1786 spec, module_sp, module_search_paths_ptr);
1792 Platform::GetRemoteSharedModule (const ModuleSpec &module_spec,
1794 lldb::ModuleSP &module_sp,
1795 const ModuleResolver &module_resolver,
1796 bool *did_create_ptr)
1798 // Get module information from a target.
1799 ModuleSpec resolved_module_spec;
1800 bool got_module_spec = false;
1803 // Try to get module information from the process
1804 if (process->GetModuleSpec (module_spec.GetFileSpec (), module_spec.GetArchitecture (), resolved_module_spec))
1806 if (module_spec.GetUUID().IsValid() == false || module_spec.GetUUID() == resolved_module_spec.GetUUID())
1808 got_module_spec = true;
1813 if (!got_module_spec)
1815 // Get module information from a target.
1816 if (!GetModuleSpec (module_spec.GetFileSpec (), module_spec.GetArchitecture (), resolved_module_spec))
1818 if (module_spec.GetUUID().IsValid() == false || module_spec.GetUUID() == resolved_module_spec.GetUUID())
1820 return module_resolver (module_spec);
1825 // If we are looking for a specific UUID, make sure resolved_module_spec has the same one before we search.
1826 if (module_spec.GetUUID().IsValid())
1828 resolved_module_spec.GetUUID() = module_spec.GetUUID();
1831 // Trying to find a module by UUID on local file system.
1832 const auto error = module_resolver (resolved_module_spec);
1835 if (GetCachedSharedModule (resolved_module_spec, module_sp, did_create_ptr))
1843 Platform::GetCachedSharedModule (const ModuleSpec &module_spec,
1844 lldb::ModuleSP &module_sp,
1845 bool *did_create_ptr)
1848 !GetGlobalPlatformProperties ()->GetUseModuleCache () ||
1849 !GetGlobalPlatformProperties ()->GetModuleCacheDirectory ())
1852 Log *log = GetLogIfAnyCategoriesSet (LIBLLDB_LOG_PLATFORM);
1854 // Check local cache for a module.
1855 auto error = m_module_cache->GetAndPut (
1856 GetModuleCacheRoot (),
1857 GetCacheHostname (),
1859 [this](const ModuleSpec &module_spec, const FileSpec &tmp_download_file_spec)
1861 return DownloadModuleSlice (module_spec.GetFileSpec (),
1862 module_spec.GetObjectOffset (),
1863 module_spec.GetObjectSize (),
1864 tmp_download_file_spec);
1867 [this](const ModuleSP& module_sp, const FileSpec& tmp_download_file_spec)
1869 return DownloadSymbolFile (module_sp, tmp_download_file_spec);
1873 if (error.Success ())
1877 log->Printf("Platform::%s - module %s not found in local cache: %s",
1878 __FUNCTION__, module_spec.GetUUID ().GetAsString ().c_str (), error.AsCString ());
1883 Platform::DownloadModuleSlice (const FileSpec& src_file_spec,
1884 const uint64_t src_offset,
1885 const uint64_t src_size,
1886 const FileSpec& dst_file_spec)
1890 std::ofstream dst (dst_file_spec.GetPath(), std::ios::out | std::ios::binary);
1893 error.SetErrorStringWithFormat ("unable to open destination file: %s", dst_file_spec.GetPath ().c_str ());
1897 auto src_fd = OpenFile (src_file_spec,
1898 File::eOpenOptionRead,
1899 lldb::eFilePermissionsFileDefault,
1904 error.SetErrorStringWithFormat ("unable to open source file: %s", error.AsCString ());
1908 std::vector<char> buffer (1024);
1909 auto offset = src_offset;
1910 uint64_t total_bytes_read = 0;
1911 while (total_bytes_read < src_size)
1913 const auto to_read = std::min (static_cast<uint64_t>(buffer.size ()), src_size - total_bytes_read);
1914 const uint64_t n_read = ReadFile (src_fd, offset, &buffer[0], to_read, error);
1919 error.SetErrorString ("read 0 bytes");
1923 total_bytes_read += n_read;
1924 dst.write (&buffer[0], n_read);
1928 CloseFile (src_fd, close_error); // Ignoring close error.
1934 Platform::DownloadSymbolFile (const lldb::ModuleSP& module_sp, const FileSpec& dst_file_spec)
1936 return Error ("Symbol file downloading not supported by the default platform.");
1940 Platform::GetModuleCacheRoot ()
1942 auto dir_spec = GetGlobalPlatformProperties ()->GetModuleCacheDirectory ();
1943 dir_spec.AppendPathComponent (GetName ().AsCString ());
1948 Platform::GetCacheHostname ()
1950 return GetHostname ();
1953 const UnixSignalsSP &
1954 Platform::GetRemoteUnixSignals()
1956 static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1957 return s_default_unix_signals_sp;
1960 const UnixSignalsSP &
1961 Platform::GetUnixSignals()
1964 return Host::GetUnixSignals();
1965 return GetRemoteUnixSignals();
1969 Platform::LoadImage(lldb_private::Process* process,
1970 const lldb_private::FileSpec& local_file,
1971 const lldb_private::FileSpec& remote_file,
1972 lldb_private::Error& error)
1974 if (local_file && remote_file)
1976 // Both local and remote file was specified. Install the local file to the given location.
1977 if (IsRemote() || local_file != remote_file)
1979 error = Install(local_file, remote_file);
1981 return LLDB_INVALID_IMAGE_TOKEN;
1983 return DoLoadImage(process, remote_file, error);
1988 // Only local file was specified. Install it to the current working directory.
1989 FileSpec target_file = GetWorkingDirectory();
1990 target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1991 if (IsRemote() || local_file != target_file)
1993 error = Install(local_file, target_file);
1995 return LLDB_INVALID_IMAGE_TOKEN;
1997 return DoLoadImage(process, target_file, error);
2002 // Only remote file was specified so we don't have to do any copying
2003 return DoLoadImage(process, remote_file, error);
2006 error.SetErrorString("Neither local nor remote file was specified");
2007 return LLDB_INVALID_IMAGE_TOKEN;
2011 Platform::DoLoadImage (lldb_private::Process* process,
2012 const lldb_private::FileSpec& remote_file,
2013 lldb_private::Error& error)
2015 error.SetErrorString("LoadImage is not supported on the current platform");
2016 return LLDB_INVALID_IMAGE_TOKEN;
2020 Platform::UnloadImage(lldb_private::Process* process, uint32_t image_token)
2022 return Error("UnloadImage is not supported on the current platform");
2026 Platform::ConnectProcess(const char* connect_url,
2027 const char* plugin_name,
2028 lldb_private::Debugger &debugger,
2029 lldb_private::Target *target,
2030 lldb_private::Error &error)
2036 TargetSP new_target_sp;
2037 error = debugger.GetTargetList().CreateTarget(debugger,
2043 target = new_target_sp.get();
2046 if (!target || error.Fail())
2049 debugger.GetTargetList().SetSelectedTarget(target);
2051 lldb::ProcessSP process_sp = target->CreateProcess(debugger.GetListener(),
2057 error = process_sp->ConnectRemote(debugger.GetOutputFile().get(), connect_url);
2065 Platform::ConnectToWaitingProcesses(lldb_private::Debugger& debugger, lldb_private::Error& error)
2072 Platform::GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site)
2074 ArchSpec arch = target.GetArchitecture();
2075 const uint8_t *trap_opcode = nullptr;
2076 size_t trap_opcode_size = 0;
2078 switch (arch.GetMachine())
2080 case llvm::Triple::aarch64:
2082 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
2083 trap_opcode = g_aarch64_opcode;
2084 trap_opcode_size = sizeof(g_aarch64_opcode);
2088 // TODO: support big-endian arm and thumb trap codes.
2089 case llvm::Triple::arm:
2091 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe
2092 // but the linux kernel does otherwise.
2093 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
2094 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
2096 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
2097 AddressClass addr_class = eAddressClassUnknown;
2101 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
2102 if (addr_class == eAddressClassUnknown && (bp_loc_sp->GetAddress().GetFileAddress() & 1))
2103 addr_class = eAddressClassCodeAlternateISA;
2106 if (addr_class == eAddressClassCodeAlternateISA)
2108 trap_opcode = g_thumb_breakpoint_opcode;
2109 trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
2113 trap_opcode = g_arm_breakpoint_opcode;
2114 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
2119 case llvm::Triple::mips:
2120 case llvm::Triple::mips64:
2122 static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
2123 trap_opcode = g_hex_opcode;
2124 trap_opcode_size = sizeof(g_hex_opcode);
2128 case llvm::Triple::mipsel:
2129 case llvm::Triple::mips64el:
2131 static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
2132 trap_opcode = g_hex_opcode;
2133 trap_opcode_size = sizeof(g_hex_opcode);
2137 case llvm::Triple::systemz:
2139 static const uint8_t g_hex_opcode[] = {0x00, 0x01};
2140 trap_opcode = g_hex_opcode;
2141 trap_opcode_size = sizeof(g_hex_opcode);
2145 case llvm::Triple::hexagon:
2147 static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
2148 trap_opcode = g_hex_opcode;
2149 trap_opcode_size = sizeof(g_hex_opcode);
2153 case llvm::Triple::ppc:
2154 case llvm::Triple::ppc64:
2156 static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
2157 trap_opcode = g_ppc_opcode;
2158 trap_opcode_size = sizeof(g_ppc_opcode);
2162 case llvm::Triple::x86:
2163 case llvm::Triple::x86_64:
2165 static const uint8_t g_i386_opcode[] = {0xCC};
2166 trap_opcode = g_i386_opcode;
2167 trap_opcode_size = sizeof(g_i386_opcode);
2172 assert(!"Unhandled architecture in Platform::GetSoftwareBreakpointTrapOpcode");
2177 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
2178 return trap_opcode_size;