180814287SRaphael Isemann //===-- Platform.cpp ------------------------------------------------------===//
2e996fd30SGreg Clayton //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e996fd30SGreg Clayton //
7e996fd30SGreg Clayton //===----------------------------------------------------------------------===//
8e996fd30SGreg Clayton 
963acdfdeSOleksiy Vyalov #include <algorithm>
10bc4987b8SPavel Labath #include <csignal>
1163acdfdeSOleksiy Vyalov #include <fstream>
12796ac80bSJonas Devlieghere #include <memory>
1363acdfdeSOleksiy Vyalov #include <vector>
1463acdfdeSOleksiy Vyalov 
154116e93dSGreg Clayton #include "lldb/Breakpoint/BreakpointIDList.h"
16933d8db9SAidan Dodds #include "lldb/Breakpoint/BreakpointLocation.h"
177271bab3SZachary Turner #include "lldb/Core/Debugger.h"
1863acdfdeSOleksiy Vyalov #include "lldb/Core/Module.h"
191f746071SGreg Clayton #include "lldb/Core/ModuleSpec.h"
20e996fd30SGreg Clayton #include "lldb/Core/PluginManager.h"
21ccd6cffbSTamas Berghammer #include "lldb/Core/StreamFile.h"
22331150a4SPavel Labath #include "lldb/Host/FileCache.h"
23c00cf4a0SZachary Turner #include "lldb/Host/FileSystem.h"
24ded470d3SGreg Clayton #include "lldb/Host/Host.h"
2597a14e60SZachary Turner #include "lldb/Host/HostInfo.h"
263eb2b44dSZachary Turner #include "lldb/Host/OptionParser.h"
27fe74df01STatyana Krasnukha #include "lldb/Interpreter/OptionValueFileSpec.h"
2863acdfdeSOleksiy Vyalov #include "lldb/Interpreter/OptionValueProperties.h"
2963acdfdeSOleksiy Vyalov #include "lldb/Interpreter/Property.h"
3063acdfdeSOleksiy Vyalov #include "lldb/Symbol/ObjectFile.h"
3101c3243fSZachary Turner #include "lldb/Target/ModuleCache.h"
32b9c1b51eSKate Stone #include "lldb/Target/Platform.h"
338b82f087SGreg Clayton #include "lldb/Target/Process.h"
34e996fd30SGreg Clayton #include "lldb/Target/Target.h"
3598d0a4b3SChaoren Lin #include "lldb/Target/UnixSignals.h"
36666cc0b2SZachary Turner #include "lldb/Utility/DataBufferHeap.h"
375713a05bSZachary Turner #include "lldb/Utility/FileSpec.h"
38c34698a8SPavel Labath #include "lldb/Utility/LLDBLog.h"
396f9e6901SZachary Turner #include "lldb/Utility/Log.h"
4097206d57SZachary Turner #include "lldb/Utility/Status.h"
41f2a8bccfSPavel Labath #include "lldb/Utility/StructuredData.h"
42a114ec0cSJonas Devlieghere #include "llvm/ADT/STLExtras.h"
437d86ee5aSZachary Turner #include "llvm/Support/FileSystem.h"
44706cccb8SJonas Devlieghere #include "llvm/Support/Path.h"
457d86ee5aSZachary Turner 
4605097246SAdrian Prantl // Define these constants from POSIX mman.h rather than include the file so
4705097246SAdrian Prantl // that they will be correct even when compiled on Linux.
4896ad3de5SRobert Flack #define MAP_PRIVATE 2
4996ad3de5SRobert Flack #define MAP_ANON 0x1000
5096ad3de5SRobert Flack 
51e996fd30SGreg Clayton using namespace lldb;
52e996fd30SGreg Clayton using namespace lldb_private;
53e996fd30SGreg Clayton 
5405097246SAdrian Prantl // Use a singleton function for g_local_platform_sp to avoid init constructors
5505097246SAdrian Prantl // since LLDB is often part of a shared library
GetHostPlatformSP()56b9c1b51eSKate Stone static PlatformSP &GetHostPlatformSP() {
57615eb7e6SGreg Clayton   static PlatformSP g_platform_sp;
58615eb7e6SGreg Clayton   return g_platform_sp;
59e996fd30SGreg Clayton }
60e996fd30SGreg Clayton 
GetHostPlatformName()61b9c1b51eSKate Stone const char *Platform::GetHostPlatformName() { return "host"; }
62ab65b34fSGreg Clayton 
6363acdfdeSOleksiy Vyalov namespace {
6463acdfdeSOleksiy Vyalov 
65971f9ca6SJonas Devlieghere #define LLDB_PROPERTIES_platform
666a253d37SJordan Rupprecht #include "TargetProperties.inc"
6763acdfdeSOleksiy Vyalov 
68971f9ca6SJonas Devlieghere enum {
69971f9ca6SJonas Devlieghere #define LLDB_PROPERTIES_platform
706a253d37SJordan Rupprecht #include "TargetPropertiesEnum.inc"
71971f9ca6SJonas Devlieghere };
7263acdfdeSOleksiy Vyalov 
7363acdfdeSOleksiy Vyalov } // namespace
7463acdfdeSOleksiy Vyalov 
GetSettingName()75b9c1b51eSKate Stone ConstString PlatformProperties::GetSettingName() {
7663acdfdeSOleksiy Vyalov   static ConstString g_setting_name("platform");
7763acdfdeSOleksiy Vyalov   return g_setting_name;
7863acdfdeSOleksiy Vyalov }
7963acdfdeSOleksiy Vyalov 
PlatformProperties()80b9c1b51eSKate Stone PlatformProperties::PlatformProperties() {
81796ac80bSJonas Devlieghere   m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
82a8ea5955SJonas Devlieghere   m_collection_sp->Initialize(g_platform_properties);
8363acdfdeSOleksiy Vyalov 
8463acdfdeSOleksiy Vyalov   auto module_cache_dir = GetModuleCacheDirectory();
85d21ca280SOleksiy Vyalov   if (module_cache_dir)
86d21ca280SOleksiy Vyalov     return;
87d21ca280SOleksiy Vyalov 
88d21ca280SOleksiy Vyalov   llvm::SmallString<64> user_home_dir;
89921c1b7dSJonas Devlieghere   if (!FileSystem::Instance().GetHomeDirectory(user_home_dir))
90d21ca280SOleksiy Vyalov     return;
91d21ca280SOleksiy Vyalov 
928f3be7a3SJonas Devlieghere   module_cache_dir = FileSpec(user_home_dir.c_str());
93d21ca280SOleksiy Vyalov   module_cache_dir.AppendPathComponent(".lldb");
9463acdfdeSOleksiy Vyalov   module_cache_dir.AppendPathComponent("module_cache");
95fe74df01STatyana Krasnukha   SetDefaultModuleCacheDirectory(module_cache_dir);
9663acdfdeSOleksiy Vyalov   SetModuleCacheDirectory(module_cache_dir);
9763acdfdeSOleksiy Vyalov }
9863acdfdeSOleksiy Vyalov 
GetUseModuleCache() const99b9c1b51eSKate Stone bool PlatformProperties::GetUseModuleCache() const {
10063acdfdeSOleksiy Vyalov   const auto idx = ePropertyUseModuleCache;
10163acdfdeSOleksiy Vyalov   return m_collection_sp->GetPropertyAtIndexAsBoolean(
102a8ea5955SJonas Devlieghere       nullptr, idx, g_platform_properties[idx].default_uint_value != 0);
10363acdfdeSOleksiy Vyalov }
10463acdfdeSOleksiy Vyalov 
SetUseModuleCache(bool use_module_cache)105b9c1b51eSKate Stone bool PlatformProperties::SetUseModuleCache(bool use_module_cache) {
106b9c1b51eSKate Stone   return m_collection_sp->SetPropertyAtIndexAsBoolean(
107b9c1b51eSKate Stone       nullptr, ePropertyUseModuleCache, use_module_cache);
10863acdfdeSOleksiy Vyalov }
10963acdfdeSOleksiy Vyalov 
GetModuleCacheDirectory() const110b9c1b51eSKate Stone FileSpec PlatformProperties::GetModuleCacheDirectory() const {
111b9c1b51eSKate Stone   return m_collection_sp->GetPropertyAtIndexAsFileSpec(
112b9c1b51eSKate Stone       nullptr, ePropertyModuleCacheDirectory);
11363acdfdeSOleksiy Vyalov }
11463acdfdeSOleksiy Vyalov 
SetModuleCacheDirectory(const FileSpec & dir_spec)115b9c1b51eSKate Stone bool PlatformProperties::SetModuleCacheDirectory(const FileSpec &dir_spec) {
116b9c1b51eSKate Stone   return m_collection_sp->SetPropertyAtIndexAsFileSpec(
117b9c1b51eSKate Stone       nullptr, ePropertyModuleCacheDirectory, dir_spec);
11863acdfdeSOleksiy Vyalov }
11963acdfdeSOleksiy Vyalov 
SetDefaultModuleCacheDirectory(const FileSpec & dir_spec)120fe74df01STatyana Krasnukha void PlatformProperties::SetDefaultModuleCacheDirectory(
121fe74df01STatyana Krasnukha     const FileSpec &dir_spec) {
122fe74df01STatyana Krasnukha   auto f_spec_opt = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(
123fe74df01STatyana Krasnukha         nullptr, false, ePropertyModuleCacheDirectory);
124fe74df01STatyana Krasnukha   assert(f_spec_opt);
125fe74df01STatyana Krasnukha   f_spec_opt->SetDefaultValue(dir_spec);
126fe74df01STatyana Krasnukha }
127fe74df01STatyana Krasnukha 
128e996fd30SGreg Clayton /// Get the native host platform plug-in.
129e996fd30SGreg Clayton ///
130e996fd30SGreg Clayton /// There should only be one of these for each host that LLDB runs
131e996fd30SGreg Clayton /// upon that should be statically compiled in and registered using
132e996fd30SGreg Clayton /// preprocessor macros or other similar build mechanisms.
133e996fd30SGreg Clayton ///
134e996fd30SGreg Clayton /// This platform will be used as the default platform when launching
135e996fd30SGreg Clayton /// or attaching to processes unless another platform is specified.
GetHostPlatform()136b9c1b51eSKate Stone PlatformSP Platform::GetHostPlatform() { return GetHostPlatformSP(); }
137615eb7e6SGreg Clayton 
Initialize()138af921006SPavel Labath void Platform::Initialize() {}
139615eb7e6SGreg Clayton 
Terminate()140af921006SPavel Labath void Platform::Terminate() {}
141a114ec0cSJonas Devlieghere 
GetGlobalPlatformProperties()1423d7161e3SPavel Labath PlatformProperties &Platform::GetGlobalPlatformProperties() {
1433d7161e3SPavel Labath   static PlatformProperties g_settings;
1443d7161e3SPavel Labath   return g_settings;
14563acdfdeSOleksiy Vyalov }
14663acdfdeSOleksiy Vyalov 
SetHostPlatform(const lldb::PlatformSP & platform_sp)147b9c1b51eSKate Stone void Platform::SetHostPlatform(const lldb::PlatformSP &platform_sp) {
148e996fd30SGreg Clayton   // The native platform should use its static void Platform::Initialize()
149e996fd30SGreg Clayton   // function to register itself as the native platform.
150615eb7e6SGreg Clayton   GetHostPlatformSP() = platform_sp;
151e996fd30SGreg Clayton }
152e996fd30SGreg Clayton 
GetFileWithUUID(const FileSpec & platform_file,const UUID * uuid_ptr,FileSpec & local_file)15397206d57SZachary Turner Status Platform::GetFileWithUUID(const FileSpec &platform_file,
154b9c1b51eSKate Stone                                  const UUID *uuid_ptr, FileSpec &local_file) {
155e996fd30SGreg Clayton   // Default to the local case
156e996fd30SGreg Clayton   local_file = platform_file;
15797206d57SZachary Turner   return Status();
158e996fd30SGreg Clayton }
159e996fd30SGreg Clayton 
16091c0e749SGreg Clayton FileSpecList
LocateExecutableScriptingResources(Target * target,Module & module,Stream * feedback_stream)161b9c1b51eSKate Stone Platform::LocateExecutableScriptingResources(Target *target, Module &module,
162b9c1b51eSKate Stone                                              Stream *feedback_stream) {
16391c0e749SGreg Clayton   return FileSpecList();
1641759848bSEnrico Granata }
1651759848bSEnrico Granata 
166615eb7e6SGreg Clayton // PlatformSP
1670e4c4821SAdrian Prantl // Platform::FindPlugin (Process *process, ConstString plugin_name)
168615eb7e6SGreg Clayton //{
1699394d772SEugene Zelenko //    PlatformCreateInstance create_callback = nullptr;
170615eb7e6SGreg Clayton //    if (plugin_name)
171615eb7e6SGreg Clayton //    {
172b9c1b51eSKate Stone //        create_callback  =
173b9c1b51eSKate Stone //        PluginManager::GetPlatformCreateCallbackForPluginName (plugin_name);
174615eb7e6SGreg Clayton //        if (create_callback)
175615eb7e6SGreg Clayton //        {
176615eb7e6SGreg Clayton //            ArchSpec arch;
177615eb7e6SGreg Clayton //            if (process)
178615eb7e6SGreg Clayton //            {
179615eb7e6SGreg Clayton //                arch = process->GetTarget().GetArchitecture();
180615eb7e6SGreg Clayton //            }
181615eb7e6SGreg Clayton //            PlatformSP platform_sp(create_callback(process, &arch));
182615eb7e6SGreg Clayton //            if (platform_sp)
183615eb7e6SGreg Clayton //                return platform_sp;
184615eb7e6SGreg Clayton //        }
185615eb7e6SGreg Clayton //    }
186615eb7e6SGreg Clayton //    else
187615eb7e6SGreg Clayton //    {
188b9c1b51eSKate Stone //        for (uint32_t idx = 0; (create_callback =
189b9c1b51eSKate Stone //        PluginManager::GetPlatformCreateCallbackAtIndex(idx)) != nullptr;
190b9c1b51eSKate Stone //        ++idx)
191615eb7e6SGreg Clayton //        {
192615eb7e6SGreg Clayton //            PlatformSP platform_sp(create_callback(process, nullptr));
193615eb7e6SGreg Clayton //            if (platform_sp)
194615eb7e6SGreg Clayton //                return platform_sp;
195615eb7e6SGreg Clayton //        }
196615eb7e6SGreg Clayton //    }
197615eb7e6SGreg Clayton //    return PlatformSP();
198615eb7e6SGreg Clayton //}
1991c627543SJason Molenda 
GetSharedModule(const ModuleSpec & module_spec,Process * process,ModuleSP & module_sp,const FileSpecList * module_search_paths_ptr,llvm::SmallVectorImpl<lldb::ModuleSP> * old_modules,bool * did_create_ptr)20061bfc703SJoseph Tremoulet Status Platform::GetSharedModule(
20161bfc703SJoseph Tremoulet     const ModuleSpec &module_spec, Process *process, ModuleSP &module_sp,
202c859e2d5SGreg Clayton     const FileSpecList *module_search_paths_ptr,
20361bfc703SJoseph Tremoulet     llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules, bool *did_create_ptr) {
204037f6b9cSOleksiy Vyalov   if (IsHost())
20561bfc703SJoseph Tremoulet     return ModuleList::GetSharedModule(module_spec, module_sp,
20661bfc703SJoseph Tremoulet                                        module_search_paths_ptr, old_modules,
207b9c1b51eSKate Stone                                        did_create_ptr, false);
208037f6b9cSOleksiy Vyalov 
2091f8639afSPavel Labath   // Module resolver lambda.
2101f8639afSPavel Labath   auto resolver = [&](const ModuleSpec &spec) {
2111f8639afSPavel Labath     Status error(eErrorTypeGeneric);
2121f8639afSPavel Labath     ModuleSpec resolved_spec;
2131f8639afSPavel Labath     // Check if we have sysroot set.
2141f8639afSPavel Labath     if (m_sdk_sysroot) {
2151f8639afSPavel Labath       // Prepend sysroot to module spec.
2161f8639afSPavel Labath       resolved_spec = spec;
2171f8639afSPavel Labath       resolved_spec.GetFileSpec().PrependPathComponent(
2181f8639afSPavel Labath           m_sdk_sysroot.GetStringRef());
2191f8639afSPavel Labath       // Try to get shared module with resolved spec.
22061bfc703SJoseph Tremoulet       error = ModuleList::GetSharedModule(resolved_spec, module_sp,
22161bfc703SJoseph Tremoulet                                           module_search_paths_ptr, old_modules,
2221f8639afSPavel Labath                                           did_create_ptr, false);
2231f8639afSPavel Labath     }
2241f8639afSPavel Labath     // If we don't have sysroot or it didn't work then
2251f8639afSPavel Labath     // try original module spec.
2261f8639afSPavel Labath     if (!error.Success()) {
2271f8639afSPavel Labath       resolved_spec = spec;
22861bfc703SJoseph Tremoulet       error = ModuleList::GetSharedModule(resolved_spec, module_sp,
22961bfc703SJoseph Tremoulet                                           module_search_paths_ptr, old_modules,
2301f8639afSPavel Labath                                           did_create_ptr, false);
2311f8639afSPavel Labath     }
232980662eeSTamas Berghammer     if (error.Success() && module_sp)
2331f8639afSPavel Labath       module_sp->SetPlatformFileSpec(resolved_spec.GetFileSpec());
234980662eeSTamas Berghammer     return error;
2351f8639afSPavel Labath   };
2361f8639afSPavel Labath 
2371f8639afSPavel Labath   return GetRemoteSharedModule(module_spec, process, module_sp, resolver,
238037f6b9cSOleksiy Vyalov                                did_create_ptr);
23963acdfdeSOleksiy Vyalov }
24063acdfdeSOleksiy Vyalov 
GetModuleSpec(const FileSpec & module_file_spec,const ArchSpec & arch,ModuleSpec & module_spec)241b9c1b51eSKate Stone bool Platform::GetModuleSpec(const FileSpec &module_file_spec,
242b9c1b51eSKate Stone                              const ArchSpec &arch, ModuleSpec &module_spec) {
24363acdfdeSOleksiy Vyalov   ModuleSpecList module_specs;
244b9c1b51eSKate Stone   if (ObjectFile::GetModuleSpecifications(module_file_spec, 0, 0,
245b9c1b51eSKate Stone                                           module_specs) == 0)
24663acdfdeSOleksiy Vyalov     return false;
24763acdfdeSOleksiy Vyalov 
24863acdfdeSOleksiy Vyalov   ModuleSpec matched_module_spec;
24963acdfdeSOleksiy Vyalov   return module_specs.FindMatchingModuleSpec(ModuleSpec(module_file_spec, arch),
25063acdfdeSOleksiy Vyalov                                              module_spec);
25132e0a750SGreg Clayton }
25232e0a750SGreg Clayton 
Create(llvm::StringRef name)253af921006SPavel Labath PlatformSP Platform::Create(llvm::StringRef name) {
254af921006SPavel Labath   lldb::PlatformSP platform_sp;
255af921006SPavel Labath   if (name == GetHostPlatformName())
256615eb7e6SGreg Clayton     return GetHostPlatform();
257615eb7e6SGreg Clayton 
258af921006SPavel Labath   if (PlatformCreateInstance create_callback =
259af921006SPavel Labath           PluginManager::GetPlatformCreateCallbackForPluginName(name))
260af921006SPavel Labath     return create_callback(true, nullptr);
261af921006SPavel Labath   return nullptr;
262b3a40ba8SGreg Clayton }
263b3a40ba8SGreg Clayton 
GetAugmentedArchSpec(Platform * platform,llvm::StringRef triple)2647263f1bdSPavel Labath ArchSpec Platform::GetAugmentedArchSpec(Platform *platform, llvm::StringRef triple) {
2657263f1bdSPavel Labath   if (platform)
2667263f1bdSPavel Labath     return platform->GetAugmentedArchSpec(triple);
2677263f1bdSPavel Labath   return HostInfo::GetAugmentedArchSpec(triple);
2687263f1bdSPavel Labath }
2697263f1bdSPavel Labath 
270e996fd30SGreg Clayton /// Default Constructor
Platform(bool is_host)27116ff8604SSaleem Abdulrasool Platform::Platform(bool is_host)
272b9c1b51eSKate Stone     : m_is_host(is_host), m_os_version_set_while_connected(false),
273a53c5c66SPavel Labath       m_system_arch_set_while_connected(false), m_max_uid_name_len(0),
274a53c5c66SPavel Labath       m_max_gid_name_len(0), m_supports_rsync(false), m_rsync_opts(),
275a53c5c66SPavel Labath       m_rsync_prefix(), m_supports_ssh(false), m_ssh_opts(),
276aa51e6a6SPavel Labath       m_ignores_remote_hostname(false), m_trap_handlers(),
277aa51e6a6SPavel Labath       m_calculated_trap_handlers(false),
278a8f3ae7cSJonas Devlieghere       m_module_cache(std::make_unique<ModuleCache>()) {
279a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Object);
28063e5fb76SJonas Devlieghere   LLDB_LOGF(log, "%p Platform::Platform()", static_cast<void *>(this));
281e996fd30SGreg Clayton }
282e996fd30SGreg Clayton 
283482c53faSRaphael Isemann Platform::~Platform() = default;
284482c53faSRaphael Isemann 
GetStatus(Stream & strm)285b9c1b51eSKate Stone void Platform::GetStatus(Stream &strm) {
286a3939e15SPavel Labath   strm.Format("  Platform: {0}\n", GetPluginName());
2871cb6496eSGreg Clayton 
2881cb6496eSGreg Clayton   ArchSpec arch(GetSystemArchitecture());
289b9c1b51eSKate Stone   if (arch.IsValid()) {
290b9c1b51eSKate Stone     if (!arch.GetTriple().str().empty()) {
2917df337f8STodd Fiala       strm.Printf("    Triple: ");
2922f1e7b3dSRaphael Isemann       arch.DumpTriple(strm.AsRawOstream());
2937df337f8STodd Fiala       strm.EOL();
2947df337f8STodd Fiala     }
2951cb6496eSGreg Clayton   }
2961cb6496eSGreg Clayton 
2972272c481SPavel Labath   llvm::VersionTuple os_version = GetOSVersion();
2982272c481SPavel Labath   if (!os_version.empty()) {
2992272c481SPavel Labath     strm.Format("OS Version: {0}", os_version.getAsString());
3001cb6496eSGreg Clayton 
30140e4ac3eSPavel Labath     if (llvm::Optional<std::string> s = GetOSBuildString())
30240e4ac3eSPavel Labath       strm.Format(" ({0})", *s);
3031cb6496eSGreg Clayton 
3041cb6496eSGreg Clayton     strm.EOL();
3051cb6496eSGreg Clayton   }
3061cb6496eSGreg Clayton 
307b9c1b51eSKate Stone   if (IsHost()) {
3081cb6496eSGreg Clayton     strm.Printf("  Hostname: %s\n", GetHostname());
309b9c1b51eSKate Stone   } else {
31032e0a750SGreg Clayton     const bool is_connected = IsConnected();
31132e0a750SGreg Clayton     if (is_connected)
31232e0a750SGreg Clayton       strm.Printf("  Hostname: %s\n", GetHostname());
31332e0a750SGreg Clayton     strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no");
3141cb6496eSGreg Clayton   }
315e0f8f574SDaniel Malea 
31690342453SPavel Labath   if (GetSDKRootDirectory()) {
31790342453SPavel Labath     strm.Format("   Sysroot: {0}\n", GetSDKRootDirectory());
31890342453SPavel Labath   }
319b9c1b51eSKate Stone   if (GetWorkingDirectory()) {
320*1b4b12a3SNico Weber     strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString());
321fbb76349SGreg Clayton   }
322e0f8f574SDaniel Malea   if (!IsConnected())
323e0f8f574SDaniel Malea     return;
324e0f8f574SDaniel Malea 
325e0f8f574SDaniel Malea   std::string specific_info(GetPlatformSpecificConnectionInformation());
326e0f8f574SDaniel Malea 
3279394d772SEugene Zelenko   if (!specific_info.empty())
328e0f8f574SDaniel Malea     strm.Printf("Platform-specific connection: %s\n", specific_info.c_str());
329d3bdd51fSJonas Devlieghere 
330f5158ca4SPavel Labath   if (llvm::Optional<std::string> s = GetOSKernelDescription())
331f5158ca4SPavel Labath     strm.Format("    Kernel: {0}\n", *s);
3321cb6496eSGreg Clayton }
3331cb6496eSGreg Clayton 
GetOSVersion(Process * process)3342272c481SPavel Labath llvm::VersionTuple Platform::GetOSVersion(Process *process) {
33516ff8604SSaleem Abdulrasool   std::lock_guard<std::mutex> guard(m_mutex);
3367597b353SGreg Clayton 
337b9c1b51eSKate Stone   if (IsHost()) {
3382272c481SPavel Labath     if (m_os_version.empty()) {
339ded470d3SGreg Clayton       // We have a local host platform
3402272c481SPavel Labath       m_os_version = HostInfo::GetOSVersion();
3412272c481SPavel Labath       m_os_version_set_while_connected = !m_os_version.empty();
342ded470d3SGreg Clayton     }
343b9c1b51eSKate Stone   } else {
344ded470d3SGreg Clayton     // We have a remote platform. We can only fetch the remote
345ded470d3SGreg Clayton     // OS version if we are connected, and we don't want to do it
346ded470d3SGreg Clayton     // more than once.
347ded470d3SGreg Clayton 
348ded470d3SGreg Clayton     const bool is_connected = IsConnected();
349ded470d3SGreg Clayton 
3501cb6496eSGreg Clayton     bool fetch = false;
3512272c481SPavel Labath     if (!m_os_version.empty()) {
35205097246SAdrian Prantl       // We have valid OS version info, check to make sure it wasn't manually
35305097246SAdrian Prantl       // set prior to connecting. If it was manually set prior to connecting,
35405097246SAdrian Prantl       // then lets fetch the actual OS version info if we are now connected.
355ded470d3SGreg Clayton       if (is_connected && !m_os_version_set_while_connected)
3561cb6496eSGreg Clayton         fetch = true;
357b9c1b51eSKate Stone     } else {
358ded470d3SGreg Clayton       // We don't have valid OS version info, fetch it if we are connected
3591cb6496eSGreg Clayton       fetch = is_connected;
360ded470d3SGreg Clayton     }
361ded470d3SGreg Clayton 
3622272c481SPavel Labath     if (fetch)
3632272c481SPavel Labath       m_os_version_set_while_connected = GetRemoteOSVersion();
364ded470d3SGreg Clayton   }
365ded470d3SGreg Clayton 
3662272c481SPavel Labath   if (!m_os_version.empty())
3672272c481SPavel Labath     return m_os_version;
3682272c481SPavel Labath   if (process) {
36905097246SAdrian Prantl     // Check with the process in case it can answer the question if a process
37005097246SAdrian Prantl     // was provided
3712272c481SPavel Labath     return process->GetHostOSVersion();
37213c30d2fSJim Ingham   }
3732272c481SPavel Labath   return llvm::VersionTuple();
374ded470d3SGreg Clayton }
375ded470d3SGreg Clayton 
GetOSBuildString()37640e4ac3eSPavel Labath llvm::Optional<std::string> Platform::GetOSBuildString() {
37740e4ac3eSPavel Labath   if (IsHost())
37840e4ac3eSPavel Labath     return HostInfo::GetOSBuildString();
37940e4ac3eSPavel Labath   return GetRemoteOSBuildString();
3801cb6496eSGreg Clayton }
3811cb6496eSGreg Clayton 
GetOSKernelDescription()382f5158ca4SPavel Labath llvm::Optional<std::string> Platform::GetOSKernelDescription() {
383f5158ca4SPavel Labath   if (IsHost())
384f5158ca4SPavel Labath     return HostInfo::GetOSKernelDescription();
385f5158ca4SPavel Labath   return GetRemoteOSKernelDescription();
3861cb6496eSGreg Clayton }
3871cb6496eSGreg Clayton 
AddClangModuleCompilationOptions(Target * target,std::vector<std::string> & options)388b9c1b51eSKate Stone void Platform::AddClangModuleCompilationOptions(
389b9c1b51eSKate Stone     Target *target, std::vector<std::string> &options) {
390b9c1b51eSKate Stone   std::vector<std::string> default_compilation_options = {
391b9c1b51eSKate Stone       "-x", "c++", "-Xclang", "-nostdsysteminc", "-Xclang", "-nostdsysteminc"};
3925dc2981cSSean Callanan 
393b9c1b51eSKate Stone   options.insert(options.end(), default_compilation_options.begin(),
3945dc2981cSSean Callanan                  default_compilation_options.end());
3955dc2981cSSean Callanan }
3965dc2981cSSean Callanan 
GetWorkingDirectory()397b9c1b51eSKate Stone FileSpec Platform::GetWorkingDirectory() {
398b9c1b51eSKate Stone   if (IsHost()) {
3991d5855b1SPavel Labath     llvm::SmallString<64> cwd;
4001d5855b1SPavel Labath     if (llvm::sys::fs::current_path(cwd))
4018f3be7a3SJonas Devlieghere       return {};
4028f3be7a3SJonas Devlieghere     else {
4038f3be7a3SJonas Devlieghere       FileSpec file_spec(cwd);
4048f3be7a3SJonas Devlieghere       FileSystem::Instance().Resolve(file_spec);
4058f3be7a3SJonas Devlieghere       return file_spec;
4068f3be7a3SJonas Devlieghere     }
407b9c1b51eSKate Stone   } else {
408fbb76349SGreg Clayton     if (!m_working_dir)
409fbb76349SGreg Clayton       m_working_dir = GetRemoteWorkingDirectory();
410fbb76349SGreg Clayton     return m_working_dir;
411fbb76349SGreg Clayton   }
412fbb76349SGreg Clayton }
413fbb76349SGreg Clayton 
414b9c1b51eSKate Stone struct RecurseCopyBaton {
415fbb76349SGreg Clayton   const FileSpec &dst;
416fbb76349SGreg Clayton   Platform *platform_ptr;
41797206d57SZachary Turner   Status error;
418fbb76349SGreg Clayton };
419fbb76349SGreg Clayton 
42035e4c84cSJonas Devlieghere static FileSystem::EnumerateDirectoryResult
RecurseCopy_Callback(void * baton,llvm::sys::fs::file_type ft,llvm::StringRef path)4217d86ee5aSZachary Turner RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft,
42235e4c84cSJonas Devlieghere                      llvm::StringRef path) {
423fbb76349SGreg Clayton   RecurseCopyBaton *rc_baton = (RecurseCopyBaton *)baton;
4248f3be7a3SJonas Devlieghere   FileSpec src(path);
4257d86ee5aSZachary Turner   namespace fs = llvm::sys::fs;
4267d86ee5aSZachary Turner   switch (ft) {
4277d86ee5aSZachary Turner   case fs::file_type::fifo_file:
4287d86ee5aSZachary Turner   case fs::file_type::socket_file:
429fbb76349SGreg Clayton     // we have no way to copy pipes and sockets - ignore them and continue
43035e4c84cSJonas Devlieghere     return FileSystem::eEnumerateDirectoryResultNext;
431fbb76349SGreg Clayton     break;
432fbb76349SGreg Clayton 
4337d86ee5aSZachary Turner   case fs::file_type::directory_file: {
434fbb76349SGreg Clayton     // make the new directory and get in there
435fbb76349SGreg Clayton     FileSpec dst_dir = rc_baton->dst;
436fbb76349SGreg Clayton     if (!dst_dir.GetFilename())
437*1b4b12a3SNico Weber       dst_dir.GetFilename() = src.GetLastPathComponent();
43897206d57SZachary Turner     Status error = rc_baton->platform_ptr->MakeDirectory(
439b9c1b51eSKate Stone         dst_dir, lldb::eFilePermissionsDirectoryDefault);
440b9c1b51eSKate Stone     if (error.Fail()) {
441b9c1b51eSKate Stone       rc_baton->error.SetErrorStringWithFormat(
442*1b4b12a3SNico Weber           "unable to setup directory %s on remote end", dst_dir.GetCString());
44335e4c84cSJonas Devlieghere       return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
444fbb76349SGreg Clayton     }
445fbb76349SGreg Clayton 
446fbb76349SGreg Clayton     // now recurse
447fbb76349SGreg Clayton     std::string src_dir_path(src.GetPath());
448fbb76349SGreg Clayton 
44905097246SAdrian Prantl     // Make a filespec that only fills in the directory of a FileSpec so when
45005097246SAdrian Prantl     // we enumerate we can quickly fill in the filename for dst copies
451fbb76349SGreg Clayton     FileSpec recurse_dst;
452*1b4b12a3SNico Weber     recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str());
45397206d57SZachary Turner     RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr,
45497206d57SZachary Turner                                   Status()};
45535e4c84cSJonas Devlieghere     FileSystem::Instance().EnumerateDirectory(src_dir_path, true, true, true,
456b9c1b51eSKate Stone                                               RecurseCopy_Callback, &rc_baton2);
457b9c1b51eSKate Stone     if (rc_baton2.error.Fail()) {
458fbb76349SGreg Clayton       rc_baton->error.SetErrorString(rc_baton2.error.AsCString());
45935e4c84cSJonas Devlieghere       return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
460fbb76349SGreg Clayton     }
46135e4c84cSJonas Devlieghere     return FileSystem::eEnumerateDirectoryResultNext;
462b9c1b51eSKate Stone   } break;
463fbb76349SGreg Clayton 
4647d86ee5aSZachary Turner   case fs::file_type::symlink_file: {
465fbb76349SGreg Clayton     // copy the file and keep going
466fbb76349SGreg Clayton     FileSpec dst_file = rc_baton->dst;
467fbb76349SGreg Clayton     if (!dst_file.GetFilename())
468*1b4b12a3SNico Weber       dst_file.GetFilename() = src.GetFilename();
469fbb76349SGreg Clayton 
470d3173f34SChaoren Lin     FileSpec src_resolved;
471fbb76349SGreg Clayton 
47246376966SJonas Devlieghere     rc_baton->error = FileSystem::Instance().Readlink(src, src_resolved);
473fbb76349SGreg Clayton 
474fbb76349SGreg Clayton     if (rc_baton->error.Fail())
47535e4c84cSJonas Devlieghere       return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
476fbb76349SGreg Clayton 
477b9c1b51eSKate Stone     rc_baton->error =
478b9c1b51eSKate Stone         rc_baton->platform_ptr->CreateSymlink(dst_file, src_resolved);
479fbb76349SGreg Clayton 
480fbb76349SGreg Clayton     if (rc_baton->error.Fail())
48135e4c84cSJonas Devlieghere       return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
482fbb76349SGreg Clayton 
48335e4c84cSJonas Devlieghere     return FileSystem::eEnumerateDirectoryResultNext;
484b9c1b51eSKate Stone   } break;
4859394d772SEugene Zelenko 
4867d86ee5aSZachary Turner   case fs::file_type::regular_file: {
487fbb76349SGreg Clayton     // copy the file and keep going
488fbb76349SGreg Clayton     FileSpec dst_file = rc_baton->dst;
489fbb76349SGreg Clayton     if (!dst_file.GetFilename())
490*1b4b12a3SNico Weber       dst_file.GetFilename() = src.GetFilename();
49197206d57SZachary Turner     Status err = rc_baton->platform_ptr->PutFile(src, dst_file);
492b9c1b51eSKate Stone     if (err.Fail()) {
493fbb76349SGreg Clayton       rc_baton->error.SetErrorString(err.AsCString());
49435e4c84cSJonas Devlieghere       return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
495fbb76349SGreg Clayton     }
49635e4c84cSJonas Devlieghere     return FileSystem::eEnumerateDirectoryResultNext;
497b9c1b51eSKate Stone   } break;
498fbb76349SGreg Clayton 
4997d86ee5aSZachary Turner   default:
500b9c1b51eSKate Stone     rc_baton->error.SetErrorStringWithFormat(
501b9c1b51eSKate Stone         "invalid file detected during copy: %s", src.GetPath().c_str());
50235e4c84cSJonas Devlieghere     return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
503fbb76349SGreg Clayton     break;
504fbb76349SGreg Clayton   }
5057d86ee5aSZachary Turner   llvm_unreachable("Unhandled file_type!");
506fbb76349SGreg Clayton }
507fbb76349SGreg Clayton 
Install(const FileSpec & src,const FileSpec & dst)50897206d57SZachary Turner Status Platform::Install(const FileSpec &src, const FileSpec &dst) {
50997206d57SZachary Turner   Status error;
510fbb76349SGreg Clayton 
511a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
51263e5fb76SJonas Devlieghere   LLDB_LOGF(log, "Platform::Install (src='%s', dst='%s')",
51363e5fb76SJonas Devlieghere             src.GetPath().c_str(), dst.GetPath().c_str());
514fbb76349SGreg Clayton   FileSpec fixed_dst(dst);
515fbb76349SGreg Clayton 
516fbb76349SGreg Clayton   if (!fixed_dst.GetFilename())
517*1b4b12a3SNico Weber     fixed_dst.GetFilename() = src.GetFilename();
518fbb76349SGreg Clayton 
519d3173f34SChaoren Lin   FileSpec working_dir = GetWorkingDirectory();
520fbb76349SGreg Clayton 
521b9c1b51eSKate Stone   if (dst) {
522b9c1b51eSKate Stone     if (dst.GetDirectory()) {
523fbb76349SGreg Clayton       const char first_dst_dir_char = dst.GetDirectory().GetCString()[0];
524b9c1b51eSKate Stone       if (first_dst_dir_char == '/' || first_dst_dir_char == '\\') {
525*1b4b12a3SNico Weber         fixed_dst.GetDirectory() = dst.GetDirectory();
526fbb76349SGreg Clayton       }
52705097246SAdrian Prantl       // If the fixed destination file doesn't have a directory yet, then we
52805097246SAdrian Prantl       // must have a relative path. We will resolve this relative path against
52905097246SAdrian Prantl       // the platform's working directory
530b9c1b51eSKate Stone       if (!fixed_dst.GetDirectory()) {
531fbb76349SGreg Clayton         FileSpec relative_spec;
532fbb76349SGreg Clayton         std::string path;
533b9c1b51eSKate Stone         if (working_dir) {
534d3173f34SChaoren Lin           relative_spec = working_dir;
535d3173f34SChaoren Lin           relative_spec.AppendPathComponent(dst.GetPath());
536*1b4b12a3SNico Weber           fixed_dst.GetDirectory() = relative_spec.GetDirectory();
537b9c1b51eSKate Stone         } else {
538b9c1b51eSKate Stone           error.SetErrorStringWithFormat(
539b9c1b51eSKate Stone               "platform working directory must be valid for relative path '%s'",
540b9c1b51eSKate Stone               dst.GetPath().c_str());
541fbb76349SGreg Clayton           return error;
542fbb76349SGreg Clayton         }
543fbb76349SGreg Clayton       }
544b9c1b51eSKate Stone     } else {
545b9c1b51eSKate Stone       if (working_dir) {
546*1b4b12a3SNico Weber         fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
547b9c1b51eSKate Stone       } else {
548b9c1b51eSKate Stone         error.SetErrorStringWithFormat(
549b9c1b51eSKate Stone             "platform working directory must be valid for relative path '%s'",
550b9c1b51eSKate Stone             dst.GetPath().c_str());
551fbb76349SGreg Clayton         return error;
552fbb76349SGreg Clayton       }
553fbb76349SGreg Clayton     }
554b9c1b51eSKate Stone   } else {
555b9c1b51eSKate Stone     if (working_dir) {
556*1b4b12a3SNico Weber       fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
557b9c1b51eSKate Stone     } else {
558b9c1b51eSKate Stone       error.SetErrorStringWithFormat("platform working directory must be valid "
559b9c1b51eSKate Stone                                      "when destination directory is empty");
560fbb76349SGreg Clayton       return error;
561fbb76349SGreg Clayton     }
562fbb76349SGreg Clayton   }
563fbb76349SGreg Clayton 
56463e5fb76SJonas Devlieghere   LLDB_LOGF(log, "Platform::Install (src='%s', dst='%s') fixed_dst='%s'",
565b9c1b51eSKate Stone             src.GetPath().c_str(), dst.GetPath().c_str(),
566b9c1b51eSKate Stone             fixed_dst.GetPath().c_str());
567fbb76349SGreg Clayton 
568b9c1b51eSKate Stone   if (GetSupportsRSync()) {
569fbb76349SGreg Clayton     error = PutFile(src, dst);
570b9c1b51eSKate Stone   } else {
5717d86ee5aSZachary Turner     namespace fs = llvm::sys::fs;
5727d86ee5aSZachary Turner     switch (fs::get_file_type(src.GetPath(), false)) {
5737d86ee5aSZachary Turner     case fs::file_type::directory_file: {
57407db3f7eSZachary Turner       llvm::sys::fs::remove(fixed_dst.GetPath());
5757c5310bbSJonas Devlieghere       uint32_t permissions = FileSystem::Instance().GetPermissions(src);
576fbb76349SGreg Clayton       if (permissions == 0)
577fbb76349SGreg Clayton         permissions = eFilePermissionsDirectoryDefault;
578d3173f34SChaoren Lin       error = MakeDirectory(fixed_dst, permissions);
579b9c1b51eSKate Stone       if (error.Success()) {
580fbb76349SGreg Clayton         // Make a filespec that only fills in the directory of a FileSpec so
581fbb76349SGreg Clayton         // when we enumerate we can quickly fill in the filename for dst copies
582fbb76349SGreg Clayton         FileSpec recurse_dst;
583*1b4b12a3SNico Weber         recurse_dst.GetDirectory().SetCString(fixed_dst.GetCString());
584fbb76349SGreg Clayton         std::string src_dir_path(src.GetPath());
58597206d57SZachary Turner         RecurseCopyBaton baton = {recurse_dst, this, Status()};
58635e4c84cSJonas Devlieghere         FileSystem::Instance().EnumerateDirectory(
58735e4c84cSJonas Devlieghere             src_dir_path, true, true, true, RecurseCopy_Callback, &baton);
588fbb76349SGreg Clayton         return baton.error;
589fbb76349SGreg Clayton       }
590b9c1b51eSKate Stone     } break;
591fbb76349SGreg Clayton 
5927d86ee5aSZachary Turner     case fs::file_type::regular_file:
59307db3f7eSZachary Turner       llvm::sys::fs::remove(fixed_dst.GetPath());
594fbb76349SGreg Clayton       error = PutFile(src, fixed_dst);
595fbb76349SGreg Clayton       break;
596fbb76349SGreg Clayton 
5977d86ee5aSZachary Turner     case fs::file_type::symlink_file: {
59807db3f7eSZachary Turner       llvm::sys::fs::remove(fixed_dst.GetPath());
599d3173f34SChaoren Lin       FileSpec src_resolved;
60046376966SJonas Devlieghere       error = FileSystem::Instance().Readlink(src, src_resolved);
601fbb76349SGreg Clayton       if (error.Success())
602d3173f34SChaoren Lin         error = CreateSymlink(dst, src_resolved);
603b9c1b51eSKate Stone     } break;
6047d86ee5aSZachary Turner     case fs::file_type::fifo_file:
605fbb76349SGreg Clayton       error.SetErrorString("platform install doesn't handle pipes");
606fbb76349SGreg Clayton       break;
6077d86ee5aSZachary Turner     case fs::file_type::socket_file:
608fbb76349SGreg Clayton       error.SetErrorString("platform install doesn't handle sockets");
609fbb76349SGreg Clayton       break;
6107d86ee5aSZachary Turner     default:
611b9c1b51eSKate Stone       error.SetErrorString(
612b9c1b51eSKate Stone           "platform install doesn't handle non file or directory items");
613fbb76349SGreg Clayton       break;
614fbb76349SGreg Clayton     }
615fbb76349SGreg Clayton   }
616fbb76349SGreg Clayton   return error;
617fbb76349SGreg Clayton }
618fbb76349SGreg Clayton 
SetWorkingDirectory(const FileSpec & file_spec)619b9c1b51eSKate Stone bool Platform::SetWorkingDirectory(const FileSpec &file_spec) {
620b9c1b51eSKate Stone   if (IsHost()) {
621a007a6d8SPavel Labath     Log *log = GetLog(LLDBLog::Platform);
6222d0c5b02SPavel Labath     LLDB_LOG(log, "{0}", file_spec);
6232d0c5b02SPavel Labath     if (std::error_code ec = llvm::sys::fs::set_current_path(file_spec.GetPath())) {
6242d0c5b02SPavel Labath       LLDB_LOG(log, "error: {0}", ec.message());
625fbb76349SGreg Clayton       return false;
6262d0c5b02SPavel Labath     }
6272d0c5b02SPavel Labath     return true;
628b9c1b51eSKate Stone   } else {
6295fb8f797SGreg Clayton     m_working_dir.Clear();
630d3173f34SChaoren Lin     return SetRemoteWorkingDirectory(file_spec);
631fbb76349SGreg Clayton   }
632fbb76349SGreg Clayton }
633fbb76349SGreg Clayton 
MakeDirectory(const FileSpec & file_spec,uint32_t permissions)63497206d57SZachary Turner Status Platform::MakeDirectory(const FileSpec &file_spec,
63597206d57SZachary Turner                                uint32_t permissions) {
636fbb76349SGreg Clayton   if (IsHost())
637d3d95fd6SZachary Turner     return llvm::sys::fs::create_directory(file_spec.GetPath(), permissions);
638b9c1b51eSKate Stone   else {
63997206d57SZachary Turner     Status error;
640a3939e15SPavel Labath     error.SetErrorStringWithFormatv("remote platform {0} doesn't support {1}",
641a3939e15SPavel Labath                                     GetPluginName(), LLVM_PRETTY_FUNCTION);
642fbb76349SGreg Clayton     return error;
643fbb76349SGreg Clayton   }
644fbb76349SGreg Clayton }
645fbb76349SGreg Clayton 
GetFilePermissions(const FileSpec & file_spec,uint32_t & file_permissions)64697206d57SZachary Turner Status Platform::GetFilePermissions(const FileSpec &file_spec,
647b9c1b51eSKate Stone                                     uint32_t &file_permissions) {
6486934e0aaSZachary Turner   if (IsHost()) {
6496934e0aaSZachary Turner     auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath());
6506934e0aaSZachary Turner     if (Value)
6516934e0aaSZachary Turner       file_permissions = Value.get();
65297206d57SZachary Turner     return Status(Value.getError());
6536934e0aaSZachary Turner   } else {
65497206d57SZachary Turner     Status error;
655a3939e15SPavel Labath     error.SetErrorStringWithFormatv("remote platform {0} doesn't support {1}",
656a3939e15SPavel Labath                                     GetPluginName(), LLVM_PRETTY_FUNCTION);
657fbb76349SGreg Clayton     return error;
658fbb76349SGreg Clayton   }
659fbb76349SGreg Clayton }
660fbb76349SGreg Clayton 
SetFilePermissions(const FileSpec & file_spec,uint32_t file_permissions)66197206d57SZachary Turner Status Platform::SetFilePermissions(const FileSpec &file_spec,
662b9c1b51eSKate Stone                                     uint32_t file_permissions) {
6636934e0aaSZachary Turner   if (IsHost()) {
6646934e0aaSZachary Turner     auto Perms = static_cast<llvm::sys::fs::perms>(file_permissions);
6656934e0aaSZachary Turner     return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms);
6666934e0aaSZachary Turner   } else {
66797206d57SZachary Turner     Status error;
668a3939e15SPavel Labath     error.SetErrorStringWithFormatv("remote platform {0} doesn't support {1}",
669a3939e15SPavel Labath                                     GetPluginName(), LLVM_PRETTY_FUNCTION);
670fbb76349SGreg Clayton     return error;
671fbb76349SGreg Clayton   }
672fbb76349SGreg Clayton }
673fbb76349SGreg Clayton 
OpenFile(const FileSpec & file_spec,File::OpenOptions flags,uint32_t mode,Status & error)674331150a4SPavel Labath user_id_t Platform::OpenFile(const FileSpec &file_spec,
675331150a4SPavel Labath                                    File::OpenOptions flags, uint32_t mode,
676331150a4SPavel Labath                                    Status &error) {
677331150a4SPavel Labath   if (IsHost())
678331150a4SPavel Labath     return FileCache::GetInstance().OpenFile(file_spec, flags, mode, error);
679331150a4SPavel Labath   return UINT64_MAX;
680331150a4SPavel Labath }
681331150a4SPavel Labath 
CloseFile(user_id_t fd,Status & error)682331150a4SPavel Labath bool Platform::CloseFile(user_id_t fd, Status &error) {
683331150a4SPavel Labath   if (IsHost())
684331150a4SPavel Labath     return FileCache::GetInstance().CloseFile(fd, error);
685331150a4SPavel Labath   return false;
686331150a4SPavel Labath }
687331150a4SPavel Labath 
GetFileSize(const FileSpec & file_spec)688331150a4SPavel Labath user_id_t Platform::GetFileSize(const FileSpec &file_spec) {
689331150a4SPavel Labath   if (!IsHost())
690331150a4SPavel Labath     return UINT64_MAX;
691331150a4SPavel Labath 
692331150a4SPavel Labath   uint64_t Size;
693331150a4SPavel Labath   if (llvm::sys::fs::file_size(file_spec.GetPath(), Size))
694331150a4SPavel Labath     return 0;
695331150a4SPavel Labath   return Size;
696331150a4SPavel Labath }
697331150a4SPavel Labath 
ReadFile(lldb::user_id_t fd,uint64_t offset,void * dst,uint64_t dst_len,Status & error)698331150a4SPavel Labath uint64_t Platform::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
699331150a4SPavel Labath                             uint64_t dst_len, Status &error) {
700331150a4SPavel Labath   if (IsHost())
701331150a4SPavel Labath     return FileCache::GetInstance().ReadFile(fd, offset, dst, dst_len, error);
702331150a4SPavel Labath   error.SetErrorStringWithFormatv(
703331150a4SPavel Labath       "Platform::ReadFile() is not supported in the {0} platform",
704331150a4SPavel Labath       GetPluginName());
705331150a4SPavel Labath   return -1;
706331150a4SPavel Labath }
707331150a4SPavel Labath 
WriteFile(lldb::user_id_t fd,uint64_t offset,const void * src,uint64_t src_len,Status & error)708331150a4SPavel Labath uint64_t Platform::WriteFile(lldb::user_id_t fd, uint64_t offset,
709331150a4SPavel Labath                              const void *src, uint64_t src_len, Status &error) {
710331150a4SPavel Labath   if (IsHost())
711331150a4SPavel Labath     return FileCache::GetInstance().WriteFile(fd, offset, src, src_len, error);
712331150a4SPavel Labath   error.SetErrorStringWithFormatv(
713331150a4SPavel Labath       "Platform::WriteFile() is not supported in the {0} platform",
714331150a4SPavel Labath       GetPluginName());
715331150a4SPavel Labath   return -1;
716331150a4SPavel Labath }
717331150a4SPavel Labath 
GetUserIDResolver()718331150a4SPavel Labath UserIDResolver &Platform::GetUserIDResolver() {
719331150a4SPavel Labath   if (IsHost())
720331150a4SPavel Labath     return HostInfo::GetUserIDResolver();
721331150a4SPavel Labath   return UserIDResolver::GetNoopResolver();
722331150a4SPavel Labath }
723331150a4SPavel Labath 
GetHostname()724b9c1b51eSKate Stone const char *Platform::GetHostname() {
725ab65b34fSGreg Clayton   if (IsHost())
7261681092fSGreg Clayton     return "127.0.0.1";
72732e0a750SGreg Clayton 
728a53c5c66SPavel Labath   if (m_hostname.empty())
7299394d772SEugene Zelenko     return nullptr;
730a53c5c66SPavel Labath   return m_hostname.c_str();
73132e0a750SGreg Clayton }
73232e0a750SGreg Clayton 
GetFullNameForDylib(ConstString basename)733b9c1b51eSKate Stone ConstString Platform::GetFullNameForDylib(ConstString basename) {
7346e25aeeaSEnrico Granata   return basename;
7356e25aeeaSEnrico Granata }
7366e25aeeaSEnrico Granata 
SetRemoteWorkingDirectory(const FileSpec & working_dir)737b9c1b51eSKate Stone bool Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
738a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
73963e5fb76SJonas Devlieghere   LLDB_LOGF(log, "Platform::SetRemoteWorkingDirectory('%s')",
740*1b4b12a3SNico Weber             working_dir.GetCString());
741d3173f34SChaoren Lin   m_working_dir = working_dir;
7425fb8f797SGreg Clayton   return true;
7435fb8f797SGreg Clayton }
7445fb8f797SGreg Clayton 
SetOSVersion(llvm::VersionTuple version)7452272c481SPavel Labath bool Platform::SetOSVersion(llvm::VersionTuple version) {
746b9c1b51eSKate Stone   if (IsHost()) {
74705097246SAdrian Prantl     // We don't need anyone setting the OS version for the host platform, we
74805097246SAdrian Prantl     // should be able to figure it out by calling HostInfo::GetOSVersion(...).
749ded470d3SGreg Clayton     return false;
750b9c1b51eSKate Stone   } else {
75105097246SAdrian Prantl     // We have a remote platform, allow setting the target OS version if we
75205097246SAdrian Prantl     // aren't connected, since if we are connected, we should be able to
753ded470d3SGreg Clayton     // request the remote OS version from the connected platform.
754ded470d3SGreg Clayton     if (IsConnected())
755ded470d3SGreg Clayton       return false;
756b9c1b51eSKate Stone     else {
75705097246SAdrian Prantl       // We aren't connected and we might want to set the OS version ahead of
75805097246SAdrian Prantl       // time before we connect so we can peruse files and use a local SDK or
75905097246SAdrian Prantl       // PDK cache of support files to disassemble or do other things.
7602272c481SPavel Labath       m_os_version = version;
761ded470d3SGreg Clayton       return true;
762ded470d3SGreg Clayton     }
763ded470d3SGreg Clayton   }
764ded470d3SGreg Clayton   return false;
765ded470d3SGreg Clayton }
766ded470d3SGreg Clayton 
76797206d57SZachary Turner Status
ResolveExecutable(const ModuleSpec & module_spec,lldb::ModuleSP & exe_module_sp,const FileSpecList * module_search_paths_ptr)76897206d57SZachary Turner Platform::ResolveExecutable(const ModuleSpec &module_spec,
769c859e2d5SGreg Clayton                             lldb::ModuleSP &exe_module_sp,
770b9c1b51eSKate Stone                             const FileSpecList *module_search_paths_ptr) {
77197206d57SZachary Turner   Status error;
772098c01c1SPavel Labath 
773dbd7fabaSJonas Devlieghere   if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
774b9c1b51eSKate Stone     if (module_spec.GetArchitecture().IsValid()) {
775b9c1b51eSKate Stone       error = ModuleList::GetSharedModule(module_spec, exe_module_sp,
776b9c1b51eSKate Stone                                           module_search_paths_ptr, nullptr,
7779394d772SEugene Zelenko                                           nullptr);
778b9c1b51eSKate Stone     } else {
77905097246SAdrian Prantl       // No valid architecture was specified, ask the platform for the
78005097246SAdrian Prantl       // architectures that we should be using (in the correct order) and see
78105097246SAdrian Prantl       // if we can find a match that way
7828012cadbSGreg Clayton       ModuleSpec arch_module_spec(module_spec);
783dde487e5SJonas Devlieghere       ArchSpec process_host_arch;
784dde487e5SJonas Devlieghere       for (const ArchSpec &arch :
785dde487e5SJonas Devlieghere            GetSupportedArchitectures(process_host_arch)) {
7863a56f562SPavel Labath         arch_module_spec.GetArchitecture() = arch;
787b9c1b51eSKate Stone         error = ModuleList::GetSharedModule(arch_module_spec, exe_module_sp,
788b9c1b51eSKate Stone                                             module_search_paths_ptr, nullptr,
7899394d772SEugene Zelenko                                             nullptr);
790e996fd30SGreg Clayton         // Did we find an executable using one of the
791e996fd30SGreg Clayton         if (error.Success() && exe_module_sp)
792e996fd30SGreg Clayton           break;
793e996fd30SGreg Clayton       }
794e996fd30SGreg Clayton     }
795b9c1b51eSKate Stone   } else {
796098c01c1SPavel Labath     error.SetErrorStringWithFormat(
797098c01c1SPavel Labath         "'%s' does not exist", module_spec.GetFileSpec().GetPath().c_str());
798e996fd30SGreg Clayton   }
799e996fd30SGreg Clayton   return error;
800e996fd30SGreg Clayton }
801e996fd30SGreg Clayton 
802098c01c1SPavel Labath Status
ResolveRemoteExecutable(const ModuleSpec & module_spec,lldb::ModuleSP & exe_module_sp,const FileSpecList * module_search_paths_ptr)803098c01c1SPavel Labath Platform::ResolveRemoteExecutable(const ModuleSpec &module_spec,
804098c01c1SPavel Labath                             lldb::ModuleSP &exe_module_sp,
805098c01c1SPavel Labath                             const FileSpecList *module_search_paths_ptr) {
806098c01c1SPavel Labath   Status error;
807098c01c1SPavel Labath 
808098c01c1SPavel Labath   // We may connect to a process and use the provided executable (Don't use
809098c01c1SPavel Labath   // local $PATH).
810098c01c1SPavel Labath   ModuleSpec resolved_module_spec(module_spec);
811098c01c1SPavel Labath 
812098c01c1SPavel Labath   // Resolve any executable within a bundle on MacOSX
813098c01c1SPavel Labath   Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
814098c01c1SPavel Labath 
815098c01c1SPavel Labath   if (FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()) ||
816098c01c1SPavel Labath       module_spec.GetUUID().IsValid()) {
817098c01c1SPavel Labath     if (resolved_module_spec.GetArchitecture().IsValid() ||
818098c01c1SPavel Labath         resolved_module_spec.GetUUID().IsValid()) {
819098c01c1SPavel Labath       error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
820098c01c1SPavel Labath                                           module_search_paths_ptr, nullptr,
821098c01c1SPavel Labath                                           nullptr);
822098c01c1SPavel Labath 
823098c01c1SPavel Labath       if (exe_module_sp && exe_module_sp->GetObjectFile())
824098c01c1SPavel Labath         return error;
825098c01c1SPavel Labath       exe_module_sp.reset();
826098c01c1SPavel Labath     }
827098c01c1SPavel Labath     // No valid architecture was specified or the exact arch wasn't found so
828098c01c1SPavel Labath     // ask the platform for the architectures that we should be using (in the
829098c01c1SPavel Labath     // correct order) and see if we can find a match that way
830098c01c1SPavel Labath     StreamString arch_names;
8313a56f562SPavel Labath     llvm::ListSeparator LS;
832dde487e5SJonas Devlieghere     ArchSpec process_host_arch;
833dde487e5SJonas Devlieghere     for (const ArchSpec &arch : GetSupportedArchitectures(process_host_arch)) {
8343a56f562SPavel Labath       resolved_module_spec.GetArchitecture() = arch;
835098c01c1SPavel Labath       error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
836098c01c1SPavel Labath                                           module_search_paths_ptr, nullptr,
837098c01c1SPavel Labath                                           nullptr);
838098c01c1SPavel Labath       // Did we find an executable using one of the
839098c01c1SPavel Labath       if (error.Success()) {
840098c01c1SPavel Labath         if (exe_module_sp && exe_module_sp->GetObjectFile())
841098c01c1SPavel Labath           break;
842098c01c1SPavel Labath         else
843098c01c1SPavel Labath           error.SetErrorToGenericError();
844098c01c1SPavel Labath       }
845098c01c1SPavel Labath 
8463a56f562SPavel Labath       arch_names << LS << arch.GetArchitectureName();
847098c01c1SPavel Labath     }
848098c01c1SPavel Labath 
849098c01c1SPavel Labath     if (error.Fail() || !exe_module_sp) {
850098c01c1SPavel Labath       if (FileSystem::Instance().Readable(resolved_module_spec.GetFileSpec())) {
851098c01c1SPavel Labath         error.SetErrorStringWithFormatv(
852098c01c1SPavel Labath             "'{0}' doesn't contain any '{1}' platform architectures: {2}",
853098c01c1SPavel Labath             resolved_module_spec.GetFileSpec(), GetPluginName(),
854098c01c1SPavel Labath             arch_names.GetData());
855098c01c1SPavel Labath       } else {
856098c01c1SPavel Labath         error.SetErrorStringWithFormatv("'{0}' is not readable",
857098c01c1SPavel Labath                                         resolved_module_spec.GetFileSpec());
858098c01c1SPavel Labath       }
859098c01c1SPavel Labath     }
860098c01c1SPavel Labath   } else {
861098c01c1SPavel Labath     error.SetErrorStringWithFormatv("'{0}' does not exist",
862098c01c1SPavel Labath                                     resolved_module_spec.GetFileSpec());
863098c01c1SPavel Labath   }
864098c01c1SPavel Labath 
865098c01c1SPavel Labath   return error;
866098c01c1SPavel Labath }
867098c01c1SPavel Labath 
ResolveSymbolFile(Target & target,const ModuleSpec & sym_spec,FileSpec & sym_file)86897206d57SZachary Turner Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec,
869b9c1b51eSKate Stone                                    FileSpec &sym_file) {
87097206d57SZachary Turner   Status error;
871dbd7fabaSJonas Devlieghere   if (FileSystem::Instance().Exists(sym_spec.GetSymbolFileSpec()))
872103f0282SGreg Clayton     sym_file = sym_spec.GetSymbolFileSpec();
873103f0282SGreg Clayton   else
874103f0282SGreg Clayton     error.SetErrorString("unable to resolve symbol file");
875103f0282SGreg Clayton   return error;
876103f0282SGreg Clayton }
877103f0282SGreg Clayton 
ResolveRemotePath(const FileSpec & platform_path,FileSpec & resolved_platform_path)878b9c1b51eSKate Stone bool Platform::ResolveRemotePath(const FileSpec &platform_path,
879b9c1b51eSKate Stone                                  FileSpec &resolved_platform_path) {
880aa516843SGreg Clayton   resolved_platform_path = platform_path;
8818f3be7a3SJonas Devlieghere   FileSystem::Instance().Resolve(resolved_platform_path);
8828f3be7a3SJonas Devlieghere   return true;
883aa516843SGreg Clayton }
884aa516843SGreg Clayton 
GetSystemArchitecture()885b9c1b51eSKate Stone const ArchSpec &Platform::GetSystemArchitecture() {
886b9c1b51eSKate Stone   if (IsHost()) {
887b9c1b51eSKate Stone     if (!m_system_arch.IsValid()) {
888ded470d3SGreg Clayton       // We have a local host platform
88913b18261SZachary Turner       m_system_arch = HostInfo::GetArchitecture();
890ded470d3SGreg Clayton       m_system_arch_set_while_connected = m_system_arch.IsValid();
891ded470d3SGreg Clayton     }
892b9c1b51eSKate Stone   } else {
89305097246SAdrian Prantl     // We have a remote platform. We can only fetch the remote system
89405097246SAdrian Prantl     // architecture if we are connected, and we don't want to do it more than
89505097246SAdrian Prantl     // once.
896ded470d3SGreg Clayton 
897ded470d3SGreg Clayton     const bool is_connected = IsConnected();
898ded470d3SGreg Clayton 
899ded470d3SGreg Clayton     bool fetch = false;
900b9c1b51eSKate Stone     if (m_system_arch.IsValid()) {
90105097246SAdrian Prantl       // We have valid OS version info, check to make sure it wasn't manually
90205097246SAdrian Prantl       // set prior to connecting. If it was manually set prior to connecting,
90305097246SAdrian Prantl       // then lets fetch the actual OS version info if we are now connected.
904ded470d3SGreg Clayton       if (is_connected && !m_system_arch_set_while_connected)
905ded470d3SGreg Clayton         fetch = true;
906b9c1b51eSKate Stone     } else {
907ded470d3SGreg Clayton       // We don't have valid OS version info, fetch it if we are connected
908ded470d3SGreg Clayton       fetch = is_connected;
909ded470d3SGreg Clayton     }
910ded470d3SGreg Clayton 
911b9c1b51eSKate Stone     if (fetch) {
9121cb6496eSGreg Clayton       m_system_arch = GetRemoteSystemArchitecture();
913ded470d3SGreg Clayton       m_system_arch_set_while_connected = m_system_arch.IsValid();
914ded470d3SGreg Clayton     }
915ded470d3SGreg Clayton   }
916ded470d3SGreg Clayton   return m_system_arch;
917ded470d3SGreg Clayton }
918ded470d3SGreg Clayton 
GetAugmentedArchSpec(llvm::StringRef triple)9197263f1bdSPavel Labath ArchSpec Platform::GetAugmentedArchSpec(llvm::StringRef triple) {
9207263f1bdSPavel Labath   if (triple.empty())
9217263f1bdSPavel Labath     return ArchSpec();
9227263f1bdSPavel Labath   llvm::Triple normalized_triple(llvm::Triple::normalize(triple));
9237263f1bdSPavel Labath   if (!ArchSpec::ContainsOnlyArch(normalized_triple))
9247263f1bdSPavel Labath     return ArchSpec(triple);
9257263f1bdSPavel Labath 
9264ebb64b9SPavel Labath   if (auto kind = HostInfo::ParseArchitectureKind(triple))
9274ebb64b9SPavel Labath     return HostInfo::GetArchitecture(*kind);
9284ebb64b9SPavel Labath 
9297263f1bdSPavel Labath   ArchSpec compatible_arch;
9307263f1bdSPavel Labath   ArchSpec raw_arch(triple);
931dde487e5SJonas Devlieghere   if (!IsCompatibleArchitecture(raw_arch, {}, false, &compatible_arch))
9327263f1bdSPavel Labath     return raw_arch;
9337263f1bdSPavel Labath 
9347263f1bdSPavel Labath   if (!compatible_arch.IsValid())
9357263f1bdSPavel Labath     return ArchSpec(normalized_triple);
9367263f1bdSPavel Labath 
9377263f1bdSPavel Labath   const llvm::Triple &compatible_triple = compatible_arch.GetTriple();
9387263f1bdSPavel Labath   if (normalized_triple.getVendorName().empty())
9397263f1bdSPavel Labath     normalized_triple.setVendor(compatible_triple.getVendor());
9407263f1bdSPavel Labath   if (normalized_triple.getOSName().empty())
9417263f1bdSPavel Labath     normalized_triple.setOS(compatible_triple.getOS());
9427263f1bdSPavel Labath   if (normalized_triple.getEnvironmentName().empty())
9437263f1bdSPavel Labath     normalized_triple.setEnvironment(compatible_triple.getEnvironment());
9447263f1bdSPavel Labath   return ArchSpec(normalized_triple);
9457263f1bdSPavel Labath }
9467263f1bdSPavel Labath 
ConnectRemote(Args & args)94797206d57SZachary Turner Status Platform::ConnectRemote(Args &args) {
94897206d57SZachary Turner   Status error;
949d314e810SGreg Clayton   if (IsHost())
950a3939e15SPavel Labath     error.SetErrorStringWithFormatv(
951a3939e15SPavel Labath         "The currently selected platform ({0}) is "
952b9c1b51eSKate Stone         "the host platform and is always connected.",
953a3939e15SPavel Labath         GetPluginName());
954d314e810SGreg Clayton   else
955a3939e15SPavel Labath     error.SetErrorStringWithFormatv(
956a3939e15SPavel Labath         "Platform::ConnectRemote() is not supported by {0}", GetPluginName());
957e996fd30SGreg Clayton   return error;
958e996fd30SGreg Clayton }
959e996fd30SGreg Clayton 
DisconnectRemote()96097206d57SZachary Turner Status Platform::DisconnectRemote() {
96197206d57SZachary Turner   Status error;
962d314e810SGreg Clayton   if (IsHost())
963a3939e15SPavel Labath     error.SetErrorStringWithFormatv(
964a3939e15SPavel Labath         "The currently selected platform ({0}) is "
965b9c1b51eSKate Stone         "the host platform and is always connected.",
966a3939e15SPavel Labath         GetPluginName());
967d314e810SGreg Clayton   else
968a3939e15SPavel Labath     error.SetErrorStringWithFormatv(
969a3939e15SPavel Labath         "Platform::DisconnectRemote() is not supported by {0}",
970a3939e15SPavel Labath         GetPluginName());
971e996fd30SGreg Clayton   return error;
972e996fd30SGreg Clayton }
97332e0a750SGreg Clayton 
GetProcessInfo(lldb::pid_t pid,ProcessInstanceInfo & process_info)974b9c1b51eSKate Stone bool Platform::GetProcessInfo(lldb::pid_t pid,
975b9c1b51eSKate Stone                               ProcessInstanceInfo &process_info) {
97605097246SAdrian Prantl   // Take care of the host case so that each subclass can just call this
97705097246SAdrian Prantl   // function to get the host functionality.
97832e0a750SGreg Clayton   if (IsHost())
97932e0a750SGreg Clayton     return Host::GetProcessInfo(pid, process_info);
98032e0a750SGreg Clayton   return false;
98132e0a750SGreg Clayton }
98232e0a750SGreg Clayton 
FindProcesses(const ProcessInstanceInfoMatch & match_info,ProcessInstanceInfoList & process_infos)983b9c1b51eSKate Stone uint32_t Platform::FindProcesses(const ProcessInstanceInfoMatch &match_info,
984b9c1b51eSKate Stone                                  ProcessInstanceInfoList &process_infos) {
98505097246SAdrian Prantl   // Take care of the host case so that each subclass can just call this
98605097246SAdrian Prantl   // function to get the host functionality.
98732e0a750SGreg Clayton   uint32_t match_count = 0;
98832e0a750SGreg Clayton   if (IsHost())
98932e0a750SGreg Clayton     match_count = Host::FindProcesses(match_info, process_infos);
99032e0a750SGreg Clayton   return match_count;
99132e0a750SGreg Clayton }
9928b82f087SGreg Clayton 
LaunchProcess(ProcessLaunchInfo & launch_info)99397206d57SZachary Turner Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) {
99497206d57SZachary Turner   Status error;
995a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
99663e5fb76SJonas Devlieghere   LLDB_LOGF(log, "Platform::%s()", __FUNCTION__);
997ac33cc9cSTodd Fiala 
99805097246SAdrian Prantl   // Take care of the host case so that each subclass can just call this
99905097246SAdrian Prantl   // function to get the host functionality.
1000b9c1b51eSKate Stone   if (IsHost()) {
100184db9105SGreg Clayton     if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
100284db9105SGreg Clayton       launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
100384db9105SGreg Clayton 
1004b9c1b51eSKate Stone     if (launch_info.GetFlags().Test(eLaunchFlagLaunchInShell)) {
1005d1cf11a7SGreg Clayton       const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1006d1cf11a7SGreg Clayton       const bool first_arg_is_full_shell_command = false;
1007d3990793SJim Ingham       uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info);
1008b9c1b51eSKate Stone       if (log) {
100910687b0eSZachary Turner         const FileSpec &shell = launch_info.GetShell();
10103b68761dSJason Molenda         std::string shell_str = (shell) ? shell.GetPath() : "<null>";
101163e5fb76SJonas Devlieghere         LLDB_LOGF(log,
1012b9c1b51eSKate Stone                   "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32
1013b9c1b51eSKate Stone                   ", shell is '%s'",
10143b68761dSJason Molenda                   __FUNCTION__, num_resumes, shell_str.c_str());
101510687b0eSZachary Turner       }
1016ac33cc9cSTodd Fiala 
1017b9c1b51eSKate Stone       if (!launch_info.ConvertArgumentsForLaunchingInShell(
101845c3fc97SRaphael Isemann               error, will_debug, first_arg_is_full_shell_command, num_resumes))
101984db9105SGreg Clayton         return error;
1020b9c1b51eSKate Stone     } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1021b38ef8c2SEnrico Granata       error = ShellExpandArguments(launch_info);
1022b9c1b51eSKate Stone       if (error.Fail()) {
1023b9c1b51eSKate Stone         error.SetErrorStringWithFormat("shell expansion failed (reason: %s). "
1024b9c1b51eSKate Stone                                        "consider launching with 'process "
1025b9c1b51eSKate Stone                                        "launch'.",
10267a37df3fSEnrico Granata                                        error.AsCString("unknown"));
1027d7a83a9cSEnrico Granata         return error;
1028d7a83a9cSEnrico Granata       }
10297a37df3fSEnrico Granata     }
103084db9105SGreg Clayton 
103163e5fb76SJonas Devlieghere     LLDB_LOGF(log, "Platform::%s final launch_info resume count: %" PRIu32,
1032b9c1b51eSKate Stone               __FUNCTION__, launch_info.GetResumeCount());
1033ac33cc9cSTodd Fiala 
10348b82f087SGreg Clayton     error = Host::LaunchProcess(launch_info);
1035b9c1b51eSKate Stone   } else
1036b9c1b51eSKate Stone     error.SetErrorString(
1037b9c1b51eSKate Stone         "base lldb_private::Platform class can't launch remote processes");
10388b82f087SGreg Clayton   return error;
10398b82f087SGreg Clayton }
10408b82f087SGreg Clayton 
ShellExpandArguments(ProcessLaunchInfo & launch_info)104197206d57SZachary Turner Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
104283a14376SEnrico Granata   if (IsHost())
1043b38ef8c2SEnrico Granata     return Host::ShellExpandArguments(launch_info);
104497206d57SZachary Turner   return Status("base lldb_private::Platform class can't expand arguments");
104583a14376SEnrico Granata }
104683a14376SEnrico Granata 
KillProcess(const lldb::pid_t pid)104797206d57SZachary Turner Status Platform::KillProcess(const lldb::pid_t pid) {
1048a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
104963e5fb76SJonas Devlieghere   LLDB_LOGF(log, "Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
10501ef7b2c8SOleksiy Vyalov 
1051b9c1b51eSKate Stone   if (!IsHost()) {
105297206d57SZachary Turner     return Status(
1053a40929dcSPavel Labath         "base lldb_private::Platform class can't kill remote processes");
10547271bab3SZachary Turner   }
1055a40929dcSPavel Labath   Host::Kill(pid, SIGKILL);
105697206d57SZachary Turner   return Status();
10571ef7b2c8SOleksiy Vyalov }
10581ef7b2c8SOleksiy Vyalov 
DebugProcess(ProcessLaunchInfo & launch_info,Debugger & debugger,Target & target,Status & error)1059bd590a5fSPavel Labath lldb::ProcessSP Platform::DebugProcess(ProcessLaunchInfo &launch_info,
1060bd590a5fSPavel Labath                                        Debugger &debugger, Target &target,
106197206d57SZachary Turner                                        Status &error) {
1062a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
1063bd590a5fSPavel Labath   LLDB_LOG(log, "target = {0})", &target);
1064ac33cc9cSTodd Fiala 
10658b82f087SGreg Clayton   ProcessSP process_sp;
10668b82f087SGreg Clayton   // Make sure we stop at the entry point
10678b82f087SGreg Clayton   launch_info.GetFlags().Set(eLaunchFlagDebug);
1068b4451b17SJim Ingham   // We always launch the process we are going to debug in a separate process
106905097246SAdrian Prantl   // group, since then we can handle ^C interrupts ourselves w/o having to
107005097246SAdrian Prantl   // worry about the target getting them as well.
1071b4451b17SJim Ingham   launch_info.SetLaunchInSeparateProcessGroup(true);
1072b4451b17SJim Ingham 
107375930019STodd Fiala   // Allow any StructuredData process-bound plugins to adjust the launch info
107475930019STodd Fiala   // if needed
107575930019STodd Fiala   size_t i = 0;
107675930019STodd Fiala   bool iteration_complete = false;
107705097246SAdrian Prantl   // Note iteration can't simply go until a nullptr callback is returned, as it
107805097246SAdrian Prantl   // is valid for a plugin to not supply a filter.
1079b9c1b51eSKate Stone   auto get_filter_func = PluginManager::GetStructuredDataFilterCallbackAtIndex;
108075930019STodd Fiala   for (auto filter_callback = get_filter_func(i, iteration_complete);
108175930019STodd Fiala        !iteration_complete;
1082b9c1b51eSKate Stone        filter_callback = get_filter_func(++i, iteration_complete)) {
1083b9c1b51eSKate Stone     if (filter_callback) {
108405097246SAdrian Prantl       // Give this ProcessLaunchInfo filter a chance to adjust the launch info.
1085bd590a5fSPavel Labath       error = (*filter_callback)(launch_info, &target);
1086b9c1b51eSKate Stone       if (!error.Success()) {
108763e5fb76SJonas Devlieghere         LLDB_LOGF(log,
108863e5fb76SJonas Devlieghere                   "Platform::%s() StructuredDataPlugin launch "
1089b9c1b51eSKate Stone                   "filter failed.",
1090b9c1b51eSKate Stone                   __FUNCTION__);
109175930019STodd Fiala         return process_sp;
109275930019STodd Fiala       }
109375930019STodd Fiala     }
109475930019STodd Fiala   }
109575930019STodd Fiala 
10968b82f087SGreg Clayton   error = LaunchProcess(launch_info);
1097b9c1b51eSKate Stone   if (error.Success()) {
109863e5fb76SJonas Devlieghere     LLDB_LOGF(log,
109963e5fb76SJonas Devlieghere               "Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")",
1100b9c1b51eSKate Stone               __FUNCTION__, launch_info.GetProcessID());
1101b9c1b51eSKate Stone     if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1102144f3a9cSGreg Clayton       ProcessAttachInfo attach_info(launch_info);
1103bd590a5fSPavel Labath       process_sp = Attach(attach_info, debugger, &target, error);
1104b9c1b51eSKate Stone       if (process_sp) {
1105a3939e15SPavel Labath         LLDB_LOG(log, "Attach() succeeded, Process plugin: {0}",
1106a3939e15SPavel Labath                  process_sp->GetPluginName());
110744d93782SGreg Clayton         launch_info.SetHijackListener(attach_info.GetHijackListener());
110844d93782SGreg Clayton 
1109e24c4acfSGreg Clayton         // Since we attached to the process, it will think it needs to detach
1110e24c4acfSGreg Clayton         // if the process object just goes away without an explicit call to
1111e24c4acfSGreg Clayton         // Process::Kill() or Process::Detach(), so let it know to kill the
1112e24c4acfSGreg Clayton         // process if this happens.
1113e24c4acfSGreg Clayton         process_sp->SetShouldDetach(false);
1114ee95ed50SGreg Clayton 
111505097246SAdrian Prantl         // If we didn't have any file actions, the pseudo terminal might have
111664ec505dSJonas Devlieghere         // been used where the secondary side was given as the file to open for
111752a3ed5bSQuinn Pham         // stdin/out/err after we have already opened the primary so we can
111805097246SAdrian Prantl         // read/write stdin/out/err.
111964ec505dSJonas Devlieghere         int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
112007d6f881SPavel Labath         if (pty_fd != PseudoTerminal::invalid_fd) {
1121ee95ed50SGreg Clayton           process_sp->SetSTDIOFileDescriptor(pty_fd);
1122ee95ed50SGreg Clayton         }
1123b9c1b51eSKate Stone       } else {
112463e5fb76SJonas Devlieghere         LLDB_LOGF(log, "Platform::%s Attach() failed: %s", __FUNCTION__,
1125b9c1b51eSKate Stone                   error.AsCString());
11268b82f087SGreg Clayton       }
1127b9c1b51eSKate Stone     } else {
112863e5fb76SJonas Devlieghere       LLDB_LOGF(log,
112963e5fb76SJonas Devlieghere                 "Platform::%s LaunchProcess() returned launch_info with "
1130b9c1b51eSKate Stone                 "invalid process id",
1131b9c1b51eSKate Stone                 __FUNCTION__);
1132ac33cc9cSTodd Fiala     }
1133b9c1b51eSKate Stone   } else {
113463e5fb76SJonas Devlieghere     LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
1135b9c1b51eSKate Stone               error.AsCString());
1136ac33cc9cSTodd Fiala   }
1137ac33cc9cSTodd Fiala 
11388b82f087SGreg Clayton   return process_sp;
11398b82f087SGreg Clayton }
1140b3a40ba8SGreg Clayton 
1141669e57ebSPavel Labath std::vector<ArchSpec>
CreateArchList(llvm::ArrayRef<llvm::Triple::ArchType> archs,llvm::Triple::OSType os)1142669e57ebSPavel Labath Platform::CreateArchList(llvm::ArrayRef<llvm::Triple::ArchType> archs,
1143669e57ebSPavel Labath                          llvm::Triple::OSType os) {
1144669e57ebSPavel Labath   std::vector<ArchSpec> list;
1145669e57ebSPavel Labath   for(auto arch : archs) {
1146669e57ebSPavel Labath     llvm::Triple triple;
1147669e57ebSPavel Labath     triple.setArch(arch);
1148669e57ebSPavel Labath     triple.setOS(os);
1149669e57ebSPavel Labath     list.push_back(ArchSpec(triple));
1150669e57ebSPavel Labath   }
1151669e57ebSPavel Labath   return list;
1152669e57ebSPavel Labath }
1153669e57ebSPavel Labath 
1154b3a40ba8SGreg Clayton /// Lets a platform answer if it is compatible with a given
1155b3a40ba8SGreg Clayton /// architecture and the target triple contained within.
IsCompatibleArchitecture(const ArchSpec & arch,const ArchSpec & process_host_arch,bool exact_arch_match,ArchSpec * compatible_arch_ptr)1156b9c1b51eSKate Stone bool Platform::IsCompatibleArchitecture(const ArchSpec &arch,
1157dde487e5SJonas Devlieghere                                         const ArchSpec &process_host_arch,
1158b9c1b51eSKate Stone                                         bool exact_arch_match,
1159b9c1b51eSKate Stone                                         ArchSpec *compatible_arch_ptr) {
1160b3a40ba8SGreg Clayton   // If the architecture is invalid, we must answer true...
1161b9c1b51eSKate Stone   if (arch.IsValid()) {
1162b3a40ba8SGreg Clayton     ArchSpec platform_arch;
11633a56f562SPavel Labath     auto match = exact_arch_match ? &ArchSpec::IsExactMatch
11643a56f562SPavel Labath                                   : &ArchSpec::IsCompatibleMatch;
1165dde487e5SJonas Devlieghere     for (const ArchSpec &platform_arch :
1166dde487e5SJonas Devlieghere          GetSupportedArchitectures(process_host_arch)) {
11673a56f562SPavel Labath       if ((arch.*match)(platform_arch)) {
11681e0c8840SGreg Clayton         if (compatible_arch_ptr)
11691e0c8840SGreg Clayton           *compatible_arch_ptr = platform_arch;
11701e0c8840SGreg Clayton         return true;
11711e0c8840SGreg Clayton       }
11721e0c8840SGreg Clayton     }
11731e0c8840SGreg Clayton   }
117470512317SGreg Clayton   if (compatible_arch_ptr)
117570512317SGreg Clayton     compatible_arch_ptr->Clear();
1176b3a40ba8SGreg Clayton   return false;
1177b3a40ba8SGreg Clayton }
1178b3a40ba8SGreg Clayton 
PutFile(const FileSpec & source,const FileSpec & destination,uint32_t uid,uint32_t gid)117997206d57SZachary Turner Status Platform::PutFile(const FileSpec &source, const FileSpec &destination,
1180b9c1b51eSKate Stone                          uint32_t uid, uint32_t gid) {
1181a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
118263e5fb76SJonas Devlieghere   LLDB_LOGF(log, "[PutFile] Using block by block transfer....\n");
11831b5a74eeSVince Harron 
118462c9fe42SLawrence D'Anna   auto source_open_options =
118514735cabSMichał Górny       File::eOpenOptionReadOnly | File::eOpenOptionCloseOnExec;
11867d86ee5aSZachary Turner   namespace fs = llvm::sys::fs;
11877d86ee5aSZachary Turner   if (fs::is_symlink_file(source.GetPath()))
1188ea575b91SFrancis Ricci     source_open_options |= File::eOpenOptionDontFollowSymlinks;
11891b5a74eeSVince Harron 
11907ca15ba7SLawrence D'Anna   auto source_file = FileSystem::Instance().Open(source, source_open_options,
11917ca15ba7SLawrence D'Anna                                                  lldb::eFilePermissionsUserRW);
11922fce1137SLawrence D'Anna   if (!source_file)
11932fce1137SLawrence D'Anna     return Status(source_file.takeError());
11942fce1137SLawrence D'Anna   Status error;
11952fce1137SLawrence D'Anna   uint32_t permissions = source_file.get()->GetPermissions(error);
11961b5a74eeSVince Harron   if (permissions == 0)
11971b5a74eeSVince Harron     permissions = lldb::eFilePermissionsFileDefault;
11981b5a74eeSVince Harron 
1199b9c1b51eSKate Stone   lldb::user_id_t dest_file = OpenFile(
120014735cabSMichał Górny       destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly |
1201b9c1b51eSKate Stone                        File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec,
1202b9c1b51eSKate Stone       permissions, error);
120363e5fb76SJonas Devlieghere   LLDB_LOGF(log, "dest_file = %" PRIu64 "\n", dest_file);
12041b5a74eeSVince Harron 
12051b5a74eeSVince Harron   if (error.Fail())
12061b5a74eeSVince Harron     return error;
12071b5a74eeSVince Harron   if (dest_file == UINT64_MAX)
120897206d57SZachary Turner     return Status("unable to open target file");
1209fc54427eSJonas Devlieghere   lldb::WritableDataBufferSP buffer_sp(new DataBufferHeap(1024 * 16, 0));
12101b5a74eeSVince Harron   uint64_t offset = 0;
1211b9c1b51eSKate Stone   for (;;) {
12121b5a74eeSVince Harron     size_t bytes_read = buffer_sp->GetByteSize();
12132fce1137SLawrence D'Anna     error = source_file.get()->Read(buffer_sp->GetBytes(), bytes_read);
12141b5a74eeSVince Harron     if (error.Fail() || bytes_read == 0)
12151b5a74eeSVince Harron       break;
12161b5a74eeSVince Harron 
1217b9c1b51eSKate Stone     const uint64_t bytes_written =
1218b9c1b51eSKate Stone         WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error);
12191b5a74eeSVince Harron     if (error.Fail())
12201b5a74eeSVince Harron       break;
12211b5a74eeSVince Harron 
12221b5a74eeSVince Harron     offset += bytes_written;
1223b9c1b51eSKate Stone     if (bytes_written != bytes_read) {
122405097246SAdrian Prantl       // We didn't write the correct number of bytes, so adjust the file
122505097246SAdrian Prantl       // position in the source file we are reading from...
12262fce1137SLawrence D'Anna       source_file.get()->SeekFromStart(offset);
12271b5a74eeSVince Harron     }
12281b5a74eeSVince Harron   }
12291b5a74eeSVince Harron   CloseFile(dest_file, error);
12301b5a74eeSVince Harron 
12311b5a74eeSVince Harron   if (uid == UINT32_MAX && gid == UINT32_MAX)
12321b5a74eeSVince Harron     return error;
12331b5a74eeSVince Harron 
12341b5a74eeSVince Harron   // TODO: ChownFile?
12351b5a74eeSVince Harron 
1236e0f8f574SDaniel Malea   return error;
1237e0f8f574SDaniel Malea }
1238e0f8f574SDaniel Malea 
GetFile(const FileSpec & source,const FileSpec & destination)123997206d57SZachary Turner Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) {
124097206d57SZachary Turner   Status error("unimplemented");
1241e0f8f574SDaniel Malea   return error;
1242e0f8f574SDaniel Malea }
1243e0f8f574SDaniel Malea 
124497206d57SZachary Turner Status
CreateSymlink(const FileSpec & src,const FileSpec & dst)124597206d57SZachary Turner Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1246d3173f34SChaoren Lin                         const FileSpec &dst) // The symlink points to dst
1247fbb76349SGreg Clayton {
1248331150a4SPavel Labath   if (IsHost())
1249331150a4SPavel Labath     return FileSystem::Instance().Symlink(src, dst);
1250331150a4SPavel Labath   return Status("unimplemented");
1251fbb76349SGreg Clayton }
1252fbb76349SGreg Clayton 
GetFileExists(const lldb_private::FileSpec & file_spec)1253b9c1b51eSKate Stone bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) {
1254331150a4SPavel Labath   if (IsHost())
1255331150a4SPavel Labath     return FileSystem::Instance().Exists(file_spec);
1256e0f8f574SDaniel Malea   return false;
1257e0f8f574SDaniel Malea }
1258e0f8f574SDaniel Malea 
Unlink(const FileSpec & path)125997206d57SZachary Turner Status Platform::Unlink(const FileSpec &path) {
1260331150a4SPavel Labath   if (IsHost())
1261331150a4SPavel Labath     return llvm::sys::fs::remove(path.GetPath());
1262331150a4SPavel Labath   return Status("unimplemented");
1263fbb76349SGreg Clayton }
1264fbb76349SGreg Clayton 
GetMmapArgumentList(const ArchSpec & arch,addr_t addr,addr_t length,unsigned prot,unsigned flags,addr_t fd,addr_t offset)126537c40af7SEd Maste MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr,
126637c40af7SEd Maste                                           addr_t length, unsigned prot,
126737c40af7SEd Maste                                           unsigned flags, addr_t fd,
126837c40af7SEd Maste                                           addr_t offset) {
126996ad3de5SRobert Flack   uint64_t flags_platform = 0;
127096ad3de5SRobert Flack   if (flags & eMmapFlagsPrivate)
127196ad3de5SRobert Flack     flags_platform |= MAP_PRIVATE;
127296ad3de5SRobert Flack   if (flags & eMmapFlagsAnon)
127396ad3de5SRobert Flack     flags_platform |= MAP_ANON;
127437c40af7SEd Maste 
127537c40af7SEd Maste   MmapArgList args({addr, length, prot, flags_platform, fd, offset});
127637c40af7SEd Maste   return args;
127796ad3de5SRobert Flack }
1278fbb76349SGreg Clayton 
RunShellCommand(llvm::StringRef command,const FileSpec & working_dir,int * status_ptr,int * signo_ptr,std::string * command_output,const Timeout<std::micro> & timeout)127997206d57SZachary Turner lldb_private::Status Platform::RunShellCommand(
1280addb5148SMed Ismail Bennani     llvm::StringRef command,
1281addb5148SMed Ismail Bennani     const FileSpec &
1282addb5148SMed Ismail Bennani         working_dir, // Pass empty FileSpec to use the current working directory
1283addb5148SMed Ismail Bennani     int *status_ptr, // Pass nullptr if you don't want the process exit status
1284addb5148SMed Ismail Bennani     int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1285addb5148SMed Ismail Bennani                     // process to exit
1286addb5148SMed Ismail Bennani     std::string
1287addb5148SMed Ismail Bennani         *command_output, // Pass nullptr if you don't want the command output
1288addb5148SMed Ismail Bennani     const Timeout<std::micro> &timeout) {
1289addb5148SMed Ismail Bennani   return RunShellCommand(llvm::StringRef(), command, working_dir, status_ptr,
1290addb5148SMed Ismail Bennani                          signo_ptr, command_output, timeout);
1291addb5148SMed Ismail Bennani }
1292addb5148SMed Ismail Bennani 
RunShellCommand(llvm::StringRef shell,llvm::StringRef command,const FileSpec & working_dir,int * status_ptr,int * signo_ptr,std::string * command_output,const Timeout<std::micro> & timeout)1293addb5148SMed Ismail Bennani lldb_private::Status Platform::RunShellCommand(
1294addb5148SMed Ismail Bennani     llvm::StringRef shell,   // Pass empty if you want to use the default
1295addb5148SMed Ismail Bennani                              // shell interpreter
1296addb5148SMed Ismail Bennani     llvm::StringRef command, // Shouldn't be empty
1297b9c1b51eSKate Stone     const FileSpec &
1298b9c1b51eSKate Stone         working_dir, // Pass empty FileSpec to use the current working directory
12999394d772SEugene Zelenko     int *status_ptr, // Pass nullptr if you don't want the process exit status
1300b9c1b51eSKate Stone     int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1301b9c1b51eSKate Stone                     // process to exit
1302b9c1b51eSKate Stone     std::string
1303b9c1b51eSKate Stone         *command_output, // Pass nullptr if you don't want the command output
130419dd1a0eSPavel Labath     const Timeout<std::micro> &timeout) {
1305e0f8f574SDaniel Malea   if (IsHost())
1306addb5148SMed Ismail Bennani     return Host::RunShellCommand(shell, command, working_dir, status_ptr,
1307addb5148SMed Ismail Bennani                                  signo_ptr, command_output, timeout);
1308331150a4SPavel Labath   return Status("unable to run a remote command without a platform");
1309e0f8f574SDaniel Malea }
1310e0f8f574SDaniel Malea 
CalculateMD5(const FileSpec & file_spec,uint64_t & low,uint64_t & high)1311b9c1b51eSKate Stone bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
1312b9c1b51eSKate Stone                             uint64_t &high) {
1313076a2599SZachary Turner   if (!IsHost())
1314e0f8f574SDaniel Malea     return false;
1315076a2599SZachary Turner   auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath());
1316076a2599SZachary Turner   if (!Result)
1317076a2599SZachary Turner     return false;
1318076a2599SZachary Turner   std::tie(high, low) = Result->words();
1319076a2599SZachary Turner   return true;
1320e0f8f574SDaniel Malea }
1321e0f8f574SDaniel Malea 
SetLocalCacheDirectory(const char * local)1322b9c1b51eSKate Stone void Platform::SetLocalCacheDirectory(const char *local) {
1323e0f8f574SDaniel Malea   m_local_cache_directory.assign(local);
1324e0f8f574SDaniel Malea }
1325e0f8f574SDaniel Malea 
GetLocalCacheDirectory()1326b9c1b51eSKate Stone const char *Platform::GetLocalCacheDirectory() {
1327e0f8f574SDaniel Malea   return m_local_cache_directory.c_str();
1328e0f8f574SDaniel Malea }
1329e0f8f574SDaniel Malea 
13308fe53c49STatyana Krasnukha static constexpr OptionDefinition g_rsync_option_table[] = {
1331b9c1b51eSKate Stone     {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
13328fe53c49STatyana Krasnukha      {}, 0, eArgTypeNone, "Enable rsync."},
1333b9c1b51eSKate Stone     {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
13348fe53c49STatyana Krasnukha      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1335b9c1b51eSKate Stone      "Platform-specific options required for rsync to work."},
1336b9c1b51eSKate Stone     {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P',
13378fe53c49STatyana Krasnukha      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1338b9c1b51eSKate Stone      "Platform-specific rsync prefix put before the remote path."},
1339b9c1b51eSKate Stone     {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i',
13408fe53c49STatyana Krasnukha      OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
1341b9c1b51eSKate Stone      "Do not automatically fill in the remote hostname when composing the "
1342b9c1b51eSKate Stone      "rsync command."},
1343e0f8f574SDaniel Malea };
1344e0f8f574SDaniel Malea 
13458fe53c49STatyana Krasnukha static constexpr OptionDefinition g_ssh_option_table[] = {
1346b9c1b51eSKate Stone     {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
13478fe53c49STatyana Krasnukha      {}, 0, eArgTypeNone, "Enable SSH."},
1348b9c1b51eSKate Stone     {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
13498fe53c49STatyana Krasnukha      nullptr, {}, 0, eArgTypeCommandName,
1350b9c1b51eSKate Stone      "Platform-specific options required for SSH to work."},
1351e0f8f574SDaniel Malea };
1352e0f8f574SDaniel Malea 
13538fe53c49STatyana Krasnukha static constexpr OptionDefinition g_caching_option_table[] = {
1354b9c1b51eSKate Stone     {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
13558fe53c49STatyana Krasnukha      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePath,
1356b9c1b51eSKate Stone      "Path in which to store local copies of files."},
1357e0f8f574SDaniel Malea };
1358e0f8f574SDaniel Malea 
GetDefinitions()13591f0f5b5bSZachary Turner llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
136070602439SZachary Turner   return llvm::makeArrayRef(g_rsync_option_table);
1361e0f8f574SDaniel Malea }
1362e0f8f574SDaniel Malea 
OptionParsingStarting(ExecutionContext * execution_context)1363b9c1b51eSKate Stone void OptionGroupPlatformRSync::OptionParsingStarting(
1364b9c1b51eSKate Stone     ExecutionContext *execution_context) {
1365e0f8f574SDaniel Malea   m_rsync = false;
1366e0f8f574SDaniel Malea   m_rsync_opts.clear();
1367e0f8f574SDaniel Malea   m_rsync_prefix.clear();
1368e0f8f574SDaniel Malea   m_ignores_remote_hostname = false;
1369e0f8f574SDaniel Malea }
1370e0f8f574SDaniel Malea 
137197206d57SZachary Turner lldb_private::Status
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)1372e1cfbc79STodd Fiala OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx,
13738cef4b0bSZachary Turner                                          llvm::StringRef option_arg,
1374b9c1b51eSKate Stone                                          ExecutionContext *execution_context) {
137597206d57SZachary Turner   Status error;
1376e0f8f574SDaniel Malea   char short_option = (char)GetDefinitions()[option_idx].short_option;
1377b9c1b51eSKate Stone   switch (short_option) {
1378e0f8f574SDaniel Malea   case 'r':
1379e0f8f574SDaniel Malea     m_rsync = true;
1380e0f8f574SDaniel Malea     break;
1381e0f8f574SDaniel Malea 
1382e0f8f574SDaniel Malea   case 'R':
1383adcd0268SBenjamin Kramer     m_rsync_opts.assign(std::string(option_arg));
1384e0f8f574SDaniel Malea     break;
1385e0f8f574SDaniel Malea 
1386e0f8f574SDaniel Malea   case 'P':
1387adcd0268SBenjamin Kramer     m_rsync_prefix.assign(std::string(option_arg));
1388e0f8f574SDaniel Malea     break;
1389e0f8f574SDaniel Malea 
1390e0f8f574SDaniel Malea   case 'i':
1391e0f8f574SDaniel Malea     m_ignores_remote_hostname = true;
1392e0f8f574SDaniel Malea     break;
1393e0f8f574SDaniel Malea 
1394e0f8f574SDaniel Malea   default:
1395e0f8f574SDaniel Malea     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1396e0f8f574SDaniel Malea     break;
1397e0f8f574SDaniel Malea   }
1398e0f8f574SDaniel Malea 
1399e0f8f574SDaniel Malea   return error;
1400e0f8f574SDaniel Malea }
1401e0f8f574SDaniel Malea 
14024116e93dSGreg Clayton lldb::BreakpointSP
SetThreadCreationBreakpoint(lldb_private::Target & target)1403b9c1b51eSKate Stone Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) {
14044116e93dSGreg Clayton   return lldb::BreakpointSP();
14054116e93dSGreg Clayton }
1406b3a40ba8SGreg Clayton 
GetDefinitions()14071f0f5b5bSZachary Turner llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
140870602439SZachary Turner   return llvm::makeArrayRef(g_ssh_option_table);
1409e0f8f574SDaniel Malea }
1410e0f8f574SDaniel Malea 
OptionParsingStarting(ExecutionContext * execution_context)1411b9c1b51eSKate Stone void OptionGroupPlatformSSH::OptionParsingStarting(
1412b9c1b51eSKate Stone     ExecutionContext *execution_context) {
1413e0f8f574SDaniel Malea   m_ssh = false;
1414e0f8f574SDaniel Malea   m_ssh_opts.clear();
1415e0f8f574SDaniel Malea }
1416e0f8f574SDaniel Malea 
141797206d57SZachary Turner lldb_private::Status
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)1418e1cfbc79STodd Fiala OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx,
14198cef4b0bSZachary Turner                                        llvm::StringRef option_arg,
1420b9c1b51eSKate Stone                                        ExecutionContext *execution_context) {
142197206d57SZachary Turner   Status error;
1422e0f8f574SDaniel Malea   char short_option = (char)GetDefinitions()[option_idx].short_option;
1423b9c1b51eSKate Stone   switch (short_option) {
1424e0f8f574SDaniel Malea   case 's':
1425e0f8f574SDaniel Malea     m_ssh = true;
1426e0f8f574SDaniel Malea     break;
1427e0f8f574SDaniel Malea 
1428e0f8f574SDaniel Malea   case 'S':
1429adcd0268SBenjamin Kramer     m_ssh_opts.assign(std::string(option_arg));
1430e0f8f574SDaniel Malea     break;
1431e0f8f574SDaniel Malea 
1432e0f8f574SDaniel Malea   default:
1433e0f8f574SDaniel Malea     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1434e0f8f574SDaniel Malea     break;
1435e0f8f574SDaniel Malea   }
1436e0f8f574SDaniel Malea 
1437e0f8f574SDaniel Malea   return error;
1438e0f8f574SDaniel Malea }
1439e0f8f574SDaniel Malea 
GetDefinitions()14401f0f5b5bSZachary Turner llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
144170602439SZachary Turner   return llvm::makeArrayRef(g_caching_option_table);
1442e0f8f574SDaniel Malea }
1443e0f8f574SDaniel Malea 
OptionParsingStarting(ExecutionContext * execution_context)1444b9c1b51eSKate Stone void OptionGroupPlatformCaching::OptionParsingStarting(
1445b9c1b51eSKate Stone     ExecutionContext *execution_context) {
1446e0f8f574SDaniel Malea   m_cache_dir.clear();
1447e0f8f574SDaniel Malea }
1448e0f8f574SDaniel Malea 
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)144997206d57SZachary Turner lldb_private::Status OptionGroupPlatformCaching::SetOptionValue(
14508cef4b0bSZachary Turner     uint32_t option_idx, llvm::StringRef option_arg,
1451b9c1b51eSKate Stone     ExecutionContext *execution_context) {
145297206d57SZachary Turner   Status error;
1453e0f8f574SDaniel Malea   char short_option = (char)GetDefinitions()[option_idx].short_option;
1454b9c1b51eSKate Stone   switch (short_option) {
1455e0f8f574SDaniel Malea   case 'c':
1456adcd0268SBenjamin Kramer     m_cache_dir.assign(std::string(option_arg));
1457e0f8f574SDaniel Malea     break;
1458e0f8f574SDaniel Malea 
1459e0f8f574SDaniel Malea   default:
1460e0f8f574SDaniel Malea     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1461e0f8f574SDaniel Malea     break;
1462e0f8f574SDaniel Malea   }
1463e0f8f574SDaniel Malea 
1464e0f8f574SDaniel Malea   return error;
1465e0f8f574SDaniel Malea }
1466e0f8f574SDaniel Malea 
GetEnvironment()1467331150a4SPavel Labath Environment Platform::GetEnvironment() {
1468331150a4SPavel Labath   if (IsHost())
1469331150a4SPavel Labath     return Host::GetEnvironment();
1470331150a4SPavel Labath   return Environment();
1471331150a4SPavel Labath }
14722094dbf4SJason Molenda 
GetTrapHandlerSymbolNames()1473b9c1b51eSKate Stone const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1474b9c1b51eSKate Stone   if (!m_calculated_trap_handlers) {
147516ff8604SSaleem Abdulrasool     std::lock_guard<std::mutex> guard(m_mutex);
1476b9c1b51eSKate Stone     if (!m_calculated_trap_handlers) {
14772094dbf4SJason Molenda       CalculateTrapHandlerSymbolNames();
14782094dbf4SJason Molenda       m_calculated_trap_handlers = true;
14792094dbf4SJason Molenda     }
14804da8706eSJason Molenda   }
14812094dbf4SJason Molenda   return m_trap_handlers;
14822094dbf4SJason Molenda }
14832094dbf4SJason Molenda 
1484098c01c1SPavel Labath Status
GetCachedExecutable(ModuleSpec & module_spec,lldb::ModuleSP & module_sp,const FileSpecList * module_search_paths_ptr)1485098c01c1SPavel Labath Platform::GetCachedExecutable(ModuleSpec &module_spec,
1486098c01c1SPavel Labath                               lldb::ModuleSP &module_sp,
1487098c01c1SPavel Labath                               const FileSpecList *module_search_paths_ptr) {
1488a6e67364SPavel Labath   FileSpec platform_spec = module_spec.GetFileSpec();
1489a6e67364SPavel Labath   Status error = GetRemoteSharedModule(
1490098c01c1SPavel Labath       module_spec, nullptr, module_sp,
1491b9c1b51eSKate Stone       [&](const ModuleSpec &spec) {
1492098c01c1SPavel Labath         return ResolveRemoteExecutable(spec, module_sp,
1493098c01c1SPavel Labath                                        module_search_paths_ptr);
1494037f6b9cSOleksiy Vyalov       },
1495037f6b9cSOleksiy Vyalov       nullptr);
1496a6e67364SPavel Labath   if (error.Success()) {
1497a6e67364SPavel Labath     module_spec.GetFileSpec() = module_sp->GetFileSpec();
1498a6e67364SPavel Labath     module_spec.GetPlatformFileSpec() = platform_spec;
1499a6e67364SPavel Labath   }
1500a6e67364SPavel Labath 
1501a6e67364SPavel Labath   return error;
15026474721cSOleksiy Vyalov }
15036474721cSOleksiy Vyalov 
GetRemoteSharedModule(const ModuleSpec & module_spec,Process * process,lldb::ModuleSP & module_sp,const ModuleResolver & module_resolver,bool * did_create_ptr)150497206d57SZachary Turner Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec,
15057cb18bf5STamas Berghammer                                        Process *process,
1506037f6b9cSOleksiy Vyalov                                        lldb::ModuleSP &module_sp,
1507037f6b9cSOleksiy Vyalov                                        const ModuleResolver &module_resolver,
1508b9c1b51eSKate Stone                                        bool *did_create_ptr) {
1509037f6b9cSOleksiy Vyalov   // Get module information from a target.
151063acdfdeSOleksiy Vyalov   ModuleSpec resolved_module_spec;
1511dde487e5SJonas Devlieghere   ArchSpec process_host_arch;
15127cb18bf5STamas Berghammer   bool got_module_spec = false;
1513b9c1b51eSKate Stone   if (process) {
1514dde487e5SJonas Devlieghere     process_host_arch = process->GetSystemArchitecture();
15157cb18bf5STamas Berghammer     // Try to get module information from the process
1516b9c1b51eSKate Stone     if (process->GetModuleSpec(module_spec.GetFileSpec(),
1517b9c1b51eSKate Stone                                module_spec.GetArchitecture(),
1518b9c1b51eSKate Stone                                resolved_module_spec)) {
1519a6682a41SJonas Devlieghere       if (!module_spec.GetUUID().IsValid() ||
1520b9c1b51eSKate Stone           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
15217cb18bf5STamas Berghammer         got_module_spec = true;
15227cb18bf5STamas Berghammer       }
152385967fa3SJason Molenda     }
152485967fa3SJason Molenda   }
15257cb18bf5STamas Berghammer 
1526a6682a41SJonas Devlieghere   if (!module_spec.GetArchitecture().IsValid()) {
152797206d57SZachary Turner     Status error;
152805097246SAdrian Prantl     // No valid architecture was specified, ask the platform for the
152905097246SAdrian Prantl     // architectures that we should be using (in the correct order) and see if
153005097246SAdrian Prantl     // we can find a match that way
15313fce2fdfSJason Molenda     ModuleSpec arch_module_spec(module_spec);
1532dde487e5SJonas Devlieghere     for (const ArchSpec &arch : GetSupportedArchitectures(process_host_arch)) {
15333a56f562SPavel Labath       arch_module_spec.GetArchitecture() = arch;
15343fce2fdfSJason Molenda       error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
15353fce2fdfSJason Molenda                                           nullptr, nullptr);
15363fce2fdfSJason Molenda       // Did we find an executable using one of the
15373fce2fdfSJason Molenda       if (error.Success() && module_sp)
15383fce2fdfSJason Molenda         break;
15393fce2fdfSJason Molenda     }
154020f84257SJoseph Tremoulet     if (module_sp) {
154120f84257SJoseph Tremoulet       resolved_module_spec = arch_module_spec;
15423fce2fdfSJason Molenda       got_module_spec = true;
15433fce2fdfSJason Molenda     }
154420f84257SJoseph Tremoulet   }
15453fce2fdfSJason Molenda 
1546b9c1b51eSKate Stone   if (!got_module_spec) {
15477cb18bf5STamas Berghammer     // Get module information from a target.
154820f84257SJoseph Tremoulet     if (GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1549b9c1b51eSKate Stone                       resolved_module_spec)) {
1550a6682a41SJonas Devlieghere       if (!module_spec.GetUUID().IsValid() ||
1551b9c1b51eSKate Stone           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
155220f84257SJoseph Tremoulet         got_module_spec = true;
155320f84257SJoseph Tremoulet       }
155420f84257SJoseph Tremoulet     }
155520f84257SJoseph Tremoulet   }
155620f84257SJoseph Tremoulet 
155720f84257SJoseph Tremoulet   if (!got_module_spec) {
155820f84257SJoseph Tremoulet     // Fall back to the given module resolver, which may have its own
155920f84257SJoseph Tremoulet     // search logic.
1560037f6b9cSOleksiy Vyalov     return module_resolver(module_spec);
15617cb18bf5STamas Berghammer   }
156285967fa3SJason Molenda 
1563b9c1b51eSKate Stone   // If we are looking for a specific UUID, make sure resolved_module_spec has
1564b9c1b51eSKate Stone   // the same one before we search.
1565b9c1b51eSKate Stone   if (module_spec.GetUUID().IsValid()) {
156685967fa3SJason Molenda     resolved_module_spec.GetUUID() = module_spec.GetUUID();
156785967fa3SJason Molenda   }
156863acdfdeSOleksiy Vyalov 
1569037f6b9cSOleksiy Vyalov   // Trying to find a module by UUID on local file system.
1570037f6b9cSOleksiy Vyalov   const auto error = module_resolver(resolved_module_spec);
1571b9c1b51eSKate Stone   if (error.Fail()) {
1572037f6b9cSOleksiy Vyalov     if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr))
157397206d57SZachary Turner       return Status();
1574037f6b9cSOleksiy Vyalov   }
1575037f6b9cSOleksiy Vyalov 
1576037f6b9cSOleksiy Vyalov   return error;
1577037f6b9cSOleksiy Vyalov }
1578037f6b9cSOleksiy Vyalov 
GetCachedSharedModule(const ModuleSpec & module_spec,lldb::ModuleSP & module_sp,bool * did_create_ptr)1579b9c1b51eSKate Stone bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec,
1580037f6b9cSOleksiy Vyalov                                      lldb::ModuleSP &module_sp,
1581b9c1b51eSKate Stone                                      bool *did_create_ptr) {
15823d7161e3SPavel Labath   if (IsHost() || !GetGlobalPlatformProperties().GetUseModuleCache() ||
15833d7161e3SPavel Labath       !GetGlobalPlatformProperties().GetModuleCacheDirectory())
1584037f6b9cSOleksiy Vyalov     return false;
1585037f6b9cSOleksiy Vyalov 
1586a007a6d8SPavel Labath   Log *log = GetLog(LLDBLog::Platform);
1587037f6b9cSOleksiy Vyalov 
158863acdfdeSOleksiy Vyalov   // Check local cache for a module.
1589280d8dc9SOleksiy Vyalov   auto error = m_module_cache->GetAndPut(
1590b9c1b51eSKate Stone       GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1591b9c1b51eSKate Stone       [this](const ModuleSpec &module_spec,
1592b9c1b51eSKate Stone              const FileSpec &tmp_download_file_spec) {
1593b9c1b51eSKate Stone         return DownloadModuleSlice(
1594b9c1b51eSKate Stone             module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1595b9c1b51eSKate Stone             module_spec.GetObjectSize(), tmp_download_file_spec);
1596280d8dc9SOleksiy Vyalov 
1597280d8dc9SOleksiy Vyalov       },
1598b9c1b51eSKate Stone       [this](const ModuleSP &module_sp,
1599b9c1b51eSKate Stone              const FileSpec &tmp_download_file_spec) {
1600ec3f92a5STamas Berghammer         return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1601ec3f92a5STamas Berghammer       },
1602b9c1b51eSKate Stone       module_sp, did_create_ptr);
160363acdfdeSOleksiy Vyalov   if (error.Success())
160463acdfdeSOleksiy Vyalov     return true;
160563acdfdeSOleksiy Vyalov 
160663e5fb76SJonas Devlieghere   LLDB_LOGF(log, "Platform::%s - module %s not found in local cache: %s",
1607b9c1b51eSKate Stone             __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1608b9c1b51eSKate Stone             error.AsCString());
160963acdfdeSOleksiy Vyalov   return false;
161063acdfdeSOleksiy Vyalov }
161163acdfdeSOleksiy Vyalov 
DownloadModuleSlice(const FileSpec & src_file_spec,const uint64_t src_offset,const uint64_t src_size,const FileSpec & dst_file_spec)161297206d57SZachary Turner Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec,
161363acdfdeSOleksiy Vyalov                                      const uint64_t src_offset,
161463acdfdeSOleksiy Vyalov                                      const uint64_t src_size,
1615b9c1b51eSKate Stone                                      const FileSpec &dst_file_spec) {
161697206d57SZachary Turner   Status error;
161763acdfdeSOleksiy Vyalov 
1618e3ad2e2eSPavel Labath   std::error_code EC;
1619d9b948b6SFangrui Song   llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::OF_None);
1620e3ad2e2eSPavel Labath   if (EC) {
1621b9c1b51eSKate Stone     error.SetErrorStringWithFormat("unable to open destination file: %s",
1622b9c1b51eSKate Stone                                    dst_file_spec.GetPath().c_str());
162363acdfdeSOleksiy Vyalov     return error;
162463acdfdeSOleksiy Vyalov   }
162563acdfdeSOleksiy Vyalov 
162614735cabSMichał Górny   auto src_fd = OpenFile(src_file_spec, File::eOpenOptionReadOnly,
1627b9c1b51eSKate Stone                          lldb::eFilePermissionsFileDefault, error);
162863acdfdeSOleksiy Vyalov 
1629b9c1b51eSKate Stone   if (error.Fail()) {
1630b9c1b51eSKate Stone     error.SetErrorStringWithFormat("unable to open source file: %s",
1631b9c1b51eSKate Stone                                    error.AsCString());
163263acdfdeSOleksiy Vyalov     return error;
163363acdfdeSOleksiy Vyalov   }
163463acdfdeSOleksiy Vyalov 
163563acdfdeSOleksiy Vyalov   std::vector<char> buffer(1024);
163663acdfdeSOleksiy Vyalov   auto offset = src_offset;
163763acdfdeSOleksiy Vyalov   uint64_t total_bytes_read = 0;
1638b9c1b51eSKate Stone   while (total_bytes_read < src_size) {
1639b9c1b51eSKate Stone     const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1640b9c1b51eSKate Stone                                   src_size - total_bytes_read);
1641b9c1b51eSKate Stone     const uint64_t n_read =
1642b9c1b51eSKate Stone         ReadFile(src_fd, offset, &buffer[0], to_read, error);
164363acdfdeSOleksiy Vyalov     if (error.Fail())
164463acdfdeSOleksiy Vyalov       break;
1645b9c1b51eSKate Stone     if (n_read == 0) {
164663acdfdeSOleksiy Vyalov       error.SetErrorString("read 0 bytes");
164763acdfdeSOleksiy Vyalov       break;
164863acdfdeSOleksiy Vyalov     }
164963acdfdeSOleksiy Vyalov     offset += n_read;
165063acdfdeSOleksiy Vyalov     total_bytes_read += n_read;
165163acdfdeSOleksiy Vyalov     dst.write(&buffer[0], n_read);
165263acdfdeSOleksiy Vyalov   }
165363acdfdeSOleksiy Vyalov 
165497206d57SZachary Turner   Status close_error;
165563acdfdeSOleksiy Vyalov   CloseFile(src_fd, close_error); // Ignoring close error.
165663acdfdeSOleksiy Vyalov 
165763acdfdeSOleksiy Vyalov   return error;
165863acdfdeSOleksiy Vyalov }
165963acdfdeSOleksiy Vyalov 
DownloadSymbolFile(const lldb::ModuleSP & module_sp,const FileSpec & dst_file_spec)166097206d57SZachary Turner Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
1661b9c1b51eSKate Stone                                     const FileSpec &dst_file_spec) {
166297206d57SZachary Turner   return Status(
1663b9c1b51eSKate Stone       "Symbol file downloading not supported by the default platform.");
1664ec3f92a5STamas Berghammer }
1665ec3f92a5STamas Berghammer 
GetModuleCacheRoot()1666b9c1b51eSKate Stone FileSpec Platform::GetModuleCacheRoot() {
16673d7161e3SPavel Labath   auto dir_spec = GetGlobalPlatformProperties().GetModuleCacheDirectory();
1668d2edca62SPavel Labath   dir_spec.AppendPathComponent(GetPluginName());
166963acdfdeSOleksiy Vyalov   return dir_spec;
167063acdfdeSOleksiy Vyalov }
16716f001068SOleksiy Vyalov 
GetCacheHostname()1672b9c1b51eSKate Stone const char *Platform::GetCacheHostname() { return GetHostname(); }
167398d0a4b3SChaoren Lin 
GetRemoteUnixSignals()1674b9c1b51eSKate Stone const UnixSignalsSP &Platform::GetRemoteUnixSignals() {
167598d0a4b3SChaoren Lin   static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
167698d0a4b3SChaoren Lin   return s_default_unix_signals_sp;
167798d0a4b3SChaoren Lin }
167898d0a4b3SChaoren Lin 
GetUnixSignals()1679a89ce43cSZachary Turner UnixSignalsSP Platform::GetUnixSignals() {
168098d0a4b3SChaoren Lin   if (IsHost())
1681a89ce43cSZachary Turner     return UnixSignals::CreateForHost();
168298d0a4b3SChaoren Lin   return GetRemoteUnixSignals();
168398d0a4b3SChaoren Lin }
16843cb132a0STamas Berghammer 
LoadImage(lldb_private::Process * process,const lldb_private::FileSpec & local_file,const lldb_private::FileSpec & remote_file,lldb_private::Status & error)1685b9c1b51eSKate Stone uint32_t Platform::LoadImage(lldb_private::Process *process,
16864fbd67acSTamas Berghammer                              const lldb_private::FileSpec &local_file,
16874fbd67acSTamas Berghammer                              const lldb_private::FileSpec &remote_file,
168897206d57SZachary Turner                              lldb_private::Status &error) {
1689b9c1b51eSKate Stone   if (local_file && remote_file) {
1690b9c1b51eSKate Stone     // Both local and remote file was specified. Install the local file to the
1691b9c1b51eSKate Stone     // given location.
1692b9c1b51eSKate Stone     if (IsRemote() || local_file != remote_file) {
16934fbd67acSTamas Berghammer       error = Install(local_file, remote_file);
16944fbd67acSTamas Berghammer       if (error.Fail())
16954fbd67acSTamas Berghammer         return LLDB_INVALID_IMAGE_TOKEN;
16964fbd67acSTamas Berghammer     }
16970d231f71SJim Ingham     return DoLoadImage(process, remote_file, nullptr, error);
16984fbd67acSTamas Berghammer   }
16994fbd67acSTamas Berghammer 
1700b9c1b51eSKate Stone   if (local_file) {
1701b9c1b51eSKate Stone     // Only local file was specified. Install it to the current working
1702b9c1b51eSKate Stone     // directory.
17034fbd67acSTamas Berghammer     FileSpec target_file = GetWorkingDirectory();
17044fbd67acSTamas Berghammer     target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1705b9c1b51eSKate Stone     if (IsRemote() || local_file != target_file) {
17064fbd67acSTamas Berghammer       error = Install(local_file, target_file);
17074fbd67acSTamas Berghammer       if (error.Fail())
17084fbd67acSTamas Berghammer         return LLDB_INVALID_IMAGE_TOKEN;
17094fbd67acSTamas Berghammer     }
17100d231f71SJim Ingham     return DoLoadImage(process, target_file, nullptr, error);
17114fbd67acSTamas Berghammer   }
17124fbd67acSTamas Berghammer 
1713b9c1b51eSKate Stone   if (remote_file) {
17144fbd67acSTamas Berghammer     // Only remote file was specified so we don't have to do any copying
17150d231f71SJim Ingham     return DoLoadImage(process, remote_file, nullptr, error);
17164fbd67acSTamas Berghammer   }
17174fbd67acSTamas Berghammer 
17184fbd67acSTamas Berghammer   error.SetErrorString("Neither local nor remote file was specified");
17194fbd67acSTamas Berghammer   return LLDB_INVALID_IMAGE_TOKEN;
17204fbd67acSTamas Berghammer }
17214fbd67acSTamas Berghammer 
DoLoadImage(lldb_private::Process * process,const lldb_private::FileSpec & remote_file,const std::vector<std::string> * paths,lldb_private::Status & error,lldb_private::FileSpec * loaded_image)1722b9c1b51eSKate Stone uint32_t Platform::DoLoadImage(lldb_private::Process *process,
17234fbd67acSTamas Berghammer                                const lldb_private::FileSpec &remote_file,
17240d231f71SJim Ingham                                const std::vector<std::string> *paths,
17250d231f71SJim Ingham                                lldb_private::Status &error,
17260d231f71SJim Ingham                                lldb_private::FileSpec *loaded_image) {
17273cb132a0STamas Berghammer   error.SetErrorString("LoadImage is not supported on the current platform");
17283cb132a0STamas Berghammer   return LLDB_INVALID_IMAGE_TOKEN;
17293cb132a0STamas Berghammer }
17303cb132a0STamas Berghammer 
LoadImageUsingPaths(lldb_private::Process * process,const lldb_private::FileSpec & remote_filename,const std::vector<std::string> & paths,lldb_private::Status & error,lldb_private::FileSpec * loaded_path)17310d231f71SJim Ingham uint32_t Platform::LoadImageUsingPaths(lldb_private::Process *process,
17320d231f71SJim Ingham                                const lldb_private::FileSpec &remote_filename,
17330d231f71SJim Ingham                                const std::vector<std::string> &paths,
17340d231f71SJim Ingham                                lldb_private::Status &error,
17350d231f71SJim Ingham                                lldb_private::FileSpec *loaded_path)
17360d231f71SJim Ingham {
17370d231f71SJim Ingham   FileSpec file_to_use;
17380d231f71SJim Ingham   if (remote_filename.IsAbsolute())
17390d231f71SJim Ingham     file_to_use = FileSpec(remote_filename.GetFilename().GetStringRef(),
17408f3be7a3SJonas Devlieghere 
17410d231f71SJim Ingham                            remote_filename.GetPathStyle());
17420d231f71SJim Ingham   else
17430d231f71SJim Ingham     file_to_use = remote_filename;
17440d231f71SJim Ingham 
17450d231f71SJim Ingham   return DoLoadImage(process, file_to_use, &paths, error, loaded_path);
17460d231f71SJim Ingham }
17470d231f71SJim Ingham 
UnloadImage(lldb_private::Process * process,uint32_t image_token)174897206d57SZachary Turner Status Platform::UnloadImage(lldb_private::Process *process,
1749b9c1b51eSKate Stone                              uint32_t image_token) {
175097206d57SZachary Turner   return Status("UnloadImage is not supported on the current platform");
17513cb132a0STamas Berghammer }
1752ccd6cffbSTamas Berghammer 
ConnectProcess(llvm::StringRef connect_url,llvm::StringRef plugin_name,Debugger & debugger,Target * target,Status & error)17533165945aSZachary Turner lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
17543165945aSZachary Turner                                          llvm::StringRef plugin_name,
1755706cccb8SJonas Devlieghere                                          Debugger &debugger, Target *target,
1756706cccb8SJonas Devlieghere                                          Status &error) {
1757706cccb8SJonas Devlieghere   return DoConnectProcess(connect_url, plugin_name, debugger, nullptr, target,
1758706cccb8SJonas Devlieghere                           error);
1759706cccb8SJonas Devlieghere }
1760706cccb8SJonas Devlieghere 
ConnectProcessSynchronous(llvm::StringRef connect_url,llvm::StringRef plugin_name,Debugger & debugger,Stream & stream,Target * target,Status & error)1761706cccb8SJonas Devlieghere lldb::ProcessSP Platform::ConnectProcessSynchronous(
1762706cccb8SJonas Devlieghere     llvm::StringRef connect_url, llvm::StringRef plugin_name,
1763706cccb8SJonas Devlieghere     Debugger &debugger, Stream &stream, Target *target, Status &error) {
1764706cccb8SJonas Devlieghere   return DoConnectProcess(connect_url, plugin_name, debugger, &stream, target,
1765706cccb8SJonas Devlieghere                           error);
1766706cccb8SJonas Devlieghere }
1767706cccb8SJonas Devlieghere 
DoConnectProcess(llvm::StringRef connect_url,llvm::StringRef plugin_name,Debugger & debugger,Stream * stream,Target * target,Status & error)1768706cccb8SJonas Devlieghere lldb::ProcessSP Platform::DoConnectProcess(llvm::StringRef connect_url,
1769706cccb8SJonas Devlieghere                                            llvm::StringRef plugin_name,
1770706cccb8SJonas Devlieghere                                            Debugger &debugger, Stream *stream,
1771706cccb8SJonas Devlieghere                                            Target *target, Status &error) {
1772ccd6cffbSTamas Berghammer   error.Clear();
1773ccd6cffbSTamas Berghammer 
1774b9c1b51eSKate Stone   if (!target) {
1775df9f796fSJason Molenda     ArchSpec arch;
1776df9f796fSJason Molenda     if (target && target->GetArchitecture().IsValid())
1777df9f796fSJason Molenda       arch = target->GetArchitecture();
1778df9f796fSJason Molenda     else
1779df9f796fSJason Molenda       arch = Target::GetDefaultArchitecture();
1780df9f796fSJason Molenda 
1781df9f796fSJason Molenda     const char *triple = "";
1782df9f796fSJason Molenda     if (arch.IsValid())
1783df9f796fSJason Molenda       triple = arch.GetTriple().getTriple().c_str();
1784df9f796fSJason Molenda 
1785ccd6cffbSTamas Berghammer     TargetSP new_target_sp;
1786f9a07e9fSJonas Devlieghere     error = debugger.GetTargetList().CreateTarget(
1787df9f796fSJason Molenda         debugger, "", triple, eLoadDependentsNo, nullptr, new_target_sp);
1788ccd6cffbSTamas Berghammer     target = new_target_sp.get();
1789ccd6cffbSTamas Berghammer   }
1790ccd6cffbSTamas Berghammer 
1791ccd6cffbSTamas Berghammer   if (!target || error.Fail())
1792ccd6cffbSTamas Berghammer     return nullptr;
1793ccd6cffbSTamas Berghammer 
1794b9c1b51eSKate Stone   lldb::ProcessSP process_sp =
179518e4272aSMichał Górny       target->CreateProcess(debugger.GetListener(), plugin_name, nullptr, true);
1796706cccb8SJonas Devlieghere 
1797ccd6cffbSTamas Berghammer   if (!process_sp)
1798ccd6cffbSTamas Berghammer     return nullptr;
1799ccd6cffbSTamas Berghammer 
1800706cccb8SJonas Devlieghere   // If this private method is called with a stream we are synchronous.
1801706cccb8SJonas Devlieghere   const bool synchronous = stream != nullptr;
1802706cccb8SJonas Devlieghere 
1803706cccb8SJonas Devlieghere   ListenerSP listener_sp(
1804706cccb8SJonas Devlieghere       Listener::MakeListener("lldb.Process.ConnectProcess.hijack"));
1805706cccb8SJonas Devlieghere   if (synchronous)
1806706cccb8SJonas Devlieghere     process_sp->HijackProcessEvents(listener_sp);
1807706cccb8SJonas Devlieghere 
180832d35fb7SJonas Devlieghere   error = process_sp->ConnectRemote(connect_url);
1809706cccb8SJonas Devlieghere   if (error.Fail()) {
1810706cccb8SJonas Devlieghere     if (synchronous)
1811706cccb8SJonas Devlieghere       process_sp->RestoreProcessEvents();
1812ccd6cffbSTamas Berghammer     return nullptr;
1813706cccb8SJonas Devlieghere   }
1814706cccb8SJonas Devlieghere 
1815706cccb8SJonas Devlieghere   if (synchronous) {
1816706cccb8SJonas Devlieghere     EventSP event_sp;
1817706cccb8SJonas Devlieghere     process_sp->WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp,
1818706cccb8SJonas Devlieghere                                      nullptr);
1819706cccb8SJonas Devlieghere     process_sp->RestoreProcessEvents();
1820706cccb8SJonas Devlieghere     bool pop_process_io_handler = false;
1821706cccb8SJonas Devlieghere     Process::HandleProcessStateChangedEvent(event_sp, stream,
1822706cccb8SJonas Devlieghere                                             pop_process_io_handler);
1823706cccb8SJonas Devlieghere   }
1824ccd6cffbSTamas Berghammer 
1825ccd6cffbSTamas Berghammer   return process_sp;
1826ccd6cffbSTamas Berghammer }
1827ccd6cffbSTamas Berghammer 
ConnectToWaitingProcesses(lldb_private::Debugger & debugger,lldb_private::Status & error)1828b9c1b51eSKate Stone size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
182997206d57SZachary Turner                                            lldb_private::Status &error) {
1830ccd6cffbSTamas Berghammer   error.Clear();
1831ccd6cffbSTamas Berghammer   return 0;
1832ccd6cffbSTamas Berghammer }
1833933d8db9SAidan Dodds 
GetSoftwareBreakpointTrapOpcode(Target & target,BreakpointSite * bp_site)1834b9c1b51eSKate Stone size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target,
1835b9c1b51eSKate Stone                                                  BreakpointSite *bp_site) {
1836933d8db9SAidan Dodds   ArchSpec arch = target.GetArchitecture();
18371fcd234aSJonas Devlieghere   assert(arch.IsValid());
1838933d8db9SAidan Dodds   const uint8_t *trap_opcode = nullptr;
1839933d8db9SAidan Dodds   size_t trap_opcode_size = 0;
1840933d8db9SAidan Dodds 
1841b9c1b51eSKate Stone   switch (arch.GetMachine()) {
18427dd7a360SJason Molenda   case llvm::Triple::aarch64_32:
1843b9c1b51eSKate Stone   case llvm::Triple::aarch64: {
1844933d8db9SAidan Dodds     static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1845933d8db9SAidan Dodds     trap_opcode = g_aarch64_opcode;
1846933d8db9SAidan Dodds     trap_opcode_size = sizeof(g_aarch64_opcode);
1847b9c1b51eSKate Stone   } break;
1848933d8db9SAidan Dodds 
1849faf6b254STatyana Krasnukha   case llvm::Triple::arc: {
1850faf6b254STatyana Krasnukha     static const uint8_t g_hex_opcode[] = { 0xff, 0x7f };
1851faf6b254STatyana Krasnukha     trap_opcode = g_hex_opcode;
1852faf6b254STatyana Krasnukha     trap_opcode_size = sizeof(g_hex_opcode);
1853faf6b254STatyana Krasnukha   } break;
1854faf6b254STatyana Krasnukha 
1855933d8db9SAidan Dodds   // TODO: support big-endian arm and thumb trap codes.
1856b9c1b51eSKate Stone   case llvm::Triple::arm: {
185705097246SAdrian Prantl     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
185805097246SAdrian Prantl     // linux kernel does otherwise.
1859933d8db9SAidan Dodds     static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1860933d8db9SAidan Dodds     static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1861933d8db9SAidan Dodds 
1862933d8db9SAidan Dodds     lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
186304803b3eSTatyana Krasnukha     AddressClass addr_class = AddressClass::eUnknown;
1864933d8db9SAidan Dodds 
1865b9c1b51eSKate Stone     if (bp_loc_sp) {
1866933d8db9SAidan Dodds       addr_class = bp_loc_sp->GetAddress().GetAddressClass();
186704803b3eSTatyana Krasnukha       if (addr_class == AddressClass::eUnknown &&
1868b9c1b51eSKate Stone           (bp_loc_sp->GetAddress().GetFileAddress() & 1))
186904803b3eSTatyana Krasnukha         addr_class = AddressClass::eCodeAlternateISA;
1870933d8db9SAidan Dodds     }
1871933d8db9SAidan Dodds 
187204803b3eSTatyana Krasnukha     if (addr_class == AddressClass::eCodeAlternateISA) {
1873933d8db9SAidan Dodds       trap_opcode = g_thumb_breakpoint_opcode;
1874933d8db9SAidan Dodds       trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1875b9c1b51eSKate Stone     } else {
1876933d8db9SAidan Dodds       trap_opcode = g_arm_breakpoint_opcode;
1877933d8db9SAidan Dodds       trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1878933d8db9SAidan Dodds     }
1879b9c1b51eSKate Stone   } break;
1880933d8db9SAidan Dodds 
18810818e6cfSAyke van Laethem   case llvm::Triple::avr: {
18820818e6cfSAyke van Laethem     static const uint8_t g_hex_opcode[] = {0x98, 0x95};
18830818e6cfSAyke van Laethem     trap_opcode = g_hex_opcode;
18840818e6cfSAyke van Laethem     trap_opcode_size = sizeof(g_hex_opcode);
18850818e6cfSAyke van Laethem   } break;
18860818e6cfSAyke van Laethem 
18877f6e9d53SAidan Dodds   case llvm::Triple::mips:
1888b9c1b51eSKate Stone   case llvm::Triple::mips64: {
1889933d8db9SAidan Dodds     static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1890933d8db9SAidan Dodds     trap_opcode = g_hex_opcode;
1891933d8db9SAidan Dodds     trap_opcode_size = sizeof(g_hex_opcode);
1892b9c1b51eSKate Stone   } break;
1893933d8db9SAidan Dodds 
18947f6e9d53SAidan Dodds   case llvm::Triple::mipsel:
1895b9c1b51eSKate Stone   case llvm::Triple::mips64el: {
1896933d8db9SAidan Dodds     static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1897933d8db9SAidan Dodds     trap_opcode = g_hex_opcode;
1898933d8db9SAidan Dodds     trap_opcode_size = sizeof(g_hex_opcode);
1899b9c1b51eSKate Stone   } break;
1900933d8db9SAidan Dodds 
1901b9c1b51eSKate Stone   case llvm::Triple::systemz: {
1902bb00d0b6SUlrich Weigand     static const uint8_t g_hex_opcode[] = {0x00, 0x01};
1903bb00d0b6SUlrich Weigand     trap_opcode = g_hex_opcode;
1904bb00d0b6SUlrich Weigand     trap_opcode_size = sizeof(g_hex_opcode);
1905b9c1b51eSKate Stone   } break;
1906bb00d0b6SUlrich Weigand 
1907b9c1b51eSKate Stone   case llvm::Triple::hexagon: {
1908933d8db9SAidan Dodds     static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
1909933d8db9SAidan Dodds     trap_opcode = g_hex_opcode;
1910933d8db9SAidan Dodds     trap_opcode_size = sizeof(g_hex_opcode);
1911b9c1b51eSKate Stone   } break;
1912933d8db9SAidan Dodds 
1913933d8db9SAidan Dodds   case llvm::Triple::ppc:
1914b9c1b51eSKate Stone   case llvm::Triple::ppc64: {
1915933d8db9SAidan Dodds     static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
1916933d8db9SAidan Dodds     trap_opcode = g_ppc_opcode;
1917933d8db9SAidan Dodds     trap_opcode_size = sizeof(g_ppc_opcode);
1918b9c1b51eSKate Stone   } break;
1919933d8db9SAidan Dodds 
1920aae0a752SEugene Zemtsov   case llvm::Triple::ppc64le: {
1921aae0a752SEugene Zemtsov     static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1922aae0a752SEugene Zemtsov     trap_opcode = g_ppc64le_opcode;
1923aae0a752SEugene Zemtsov     trap_opcode_size = sizeof(g_ppc64le_opcode);
1924aae0a752SEugene Zemtsov   } break;
1925aae0a752SEugene Zemtsov 
1926933d8db9SAidan Dodds   case llvm::Triple::x86:
1927b9c1b51eSKate Stone   case llvm::Triple::x86_64: {
1928933d8db9SAidan Dodds     static const uint8_t g_i386_opcode[] = {0xCC};
1929933d8db9SAidan Dodds     trap_opcode = g_i386_opcode;
1930933d8db9SAidan Dodds     trap_opcode_size = sizeof(g_i386_opcode);
1931b9c1b51eSKate Stone   } break;
1932933d8db9SAidan Dodds 
1933933d8db9SAidan Dodds   default:
19341fcd234aSJonas Devlieghere     return 0;
1935933d8db9SAidan Dodds   }
1936933d8db9SAidan Dodds 
1937933d8db9SAidan Dodds   assert(bp_site);
1938933d8db9SAidan Dodds   if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1939933d8db9SAidan Dodds     return trap_opcode_size;
1940933d8db9SAidan Dodds 
1941933d8db9SAidan Dodds   return 0;
1942933d8db9SAidan Dodds }
19433053e143SMichał Górny 
GetSiginfoType(const llvm::Triple & triple)19443053e143SMichał Górny CompilerType Platform::GetSiginfoType(const llvm::Triple& triple) {
19453053e143SMichał Górny   return CompilerType();
19463053e143SMichał Górny }
1947af921006SPavel Labath 
GetExtraStartupCommands()1948bff4673bSJim Ingham Args Platform::GetExtraStartupCommands() {
1949bff4673bSJim Ingham   return {};
1950bff4673bSJim Ingham }
1951bff4673bSJim Ingham 
GetOrCreate(llvm::StringRef name)1952af921006SPavel Labath PlatformSP PlatformList::GetOrCreate(llvm::StringRef name) {
1953af921006SPavel Labath   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1954af921006SPavel Labath   for (const PlatformSP &platform_sp : m_platforms) {
1955af921006SPavel Labath     if (platform_sp->GetName() == name)
1956af921006SPavel Labath       return platform_sp;
1957af921006SPavel Labath   }
1958af921006SPavel Labath   return Create(name);
1959af921006SPavel Labath }
1960af921006SPavel Labath 
GetOrCreate(const ArchSpec & arch,const ArchSpec & process_host_arch,ArchSpec * platform_arch_ptr,Status & error)1961af921006SPavel Labath PlatformSP PlatformList::GetOrCreate(const ArchSpec &arch,
1962af921006SPavel Labath                                      const ArchSpec &process_host_arch,
1963af921006SPavel Labath                                      ArchSpec *platform_arch_ptr,
1964af921006SPavel Labath                                      Status &error) {
1965af921006SPavel Labath   std::lock_guard<std::recursive_mutex> guard(m_mutex);
1966af921006SPavel Labath   // First try exact arch matches across all platforms already created
1967af921006SPavel Labath   for (const auto &platform_sp : m_platforms) {
1968af921006SPavel Labath     if (platform_sp->IsCompatibleArchitecture(arch, process_host_arch, true,
1969af921006SPavel Labath                                               platform_arch_ptr))
1970af921006SPavel Labath       return platform_sp;
1971af921006SPavel Labath   }
1972af921006SPavel Labath 
1973af921006SPavel Labath   // Next try compatible arch matches across all platforms already created
1974af921006SPavel Labath   for (const auto &platform_sp : m_platforms) {
1975af921006SPavel Labath     if (platform_sp->IsCompatibleArchitecture(arch, process_host_arch, false,
1976af921006SPavel Labath                                               platform_arch_ptr))
1977af921006SPavel Labath       return platform_sp;
1978af921006SPavel Labath   }
1979af921006SPavel Labath 
1980af921006SPavel Labath   PlatformCreateInstance create_callback;
1981af921006SPavel Labath   // First try exact arch matches across all platform plug-ins
1982af921006SPavel Labath   uint32_t idx;
1983af921006SPavel Labath   for (idx = 0;
1984af921006SPavel Labath        (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex(idx));
1985af921006SPavel Labath        ++idx) {
1986af921006SPavel Labath     PlatformSP platform_sp = create_callback(false, &arch);
1987af921006SPavel Labath     if (platform_sp && platform_sp->IsCompatibleArchitecture(
1988af921006SPavel Labath                            arch, process_host_arch, true, platform_arch_ptr)) {
1989af921006SPavel Labath       m_platforms.push_back(platform_sp);
1990af921006SPavel Labath       return platform_sp;
1991af921006SPavel Labath     }
1992af921006SPavel Labath   }
1993af921006SPavel Labath   // Next try compatible arch matches across all platform plug-ins
1994af921006SPavel Labath   for (idx = 0;
1995af921006SPavel Labath        (create_callback = PluginManager::GetPlatformCreateCallbackAtIndex(idx));
1996af921006SPavel Labath        ++idx) {
1997af921006SPavel Labath     PlatformSP platform_sp = create_callback(false, &arch);
1998af921006SPavel Labath     if (platform_sp && platform_sp->IsCompatibleArchitecture(
1999af921006SPavel Labath                            arch, process_host_arch, false, platform_arch_ptr)) {
2000af921006SPavel Labath       m_platforms.push_back(platform_sp);
2001af921006SPavel Labath       return platform_sp;
2002af921006SPavel Labath     }
2003af921006SPavel Labath   }
2004af921006SPavel Labath   if (platform_arch_ptr)
2005af921006SPavel Labath     platform_arch_ptr->Clear();
2006af921006SPavel Labath   return nullptr;
2007af921006SPavel Labath }
2008af921006SPavel Labath 
GetOrCreate(const ArchSpec & arch,const ArchSpec & process_host_arch,ArchSpec * platform_arch_ptr)2009af921006SPavel Labath PlatformSP PlatformList::GetOrCreate(const ArchSpec &arch,
2010af921006SPavel Labath                                      const ArchSpec &process_host_arch,
2011af921006SPavel Labath                                      ArchSpec *platform_arch_ptr) {
2012af921006SPavel Labath   Status error;
2013af921006SPavel Labath   if (arch.IsValid())
2014af921006SPavel Labath     return GetOrCreate(arch, process_host_arch, platform_arch_ptr, error);
2015af921006SPavel Labath   return nullptr;
2016af921006SPavel Labath }
2017af921006SPavel Labath 
GetOrCreate(llvm::ArrayRef<ArchSpec> archs,const ArchSpec & process_host_arch,std::vector<PlatformSP> & candidates)2018af921006SPavel Labath PlatformSP PlatformList::GetOrCreate(llvm::ArrayRef<ArchSpec> archs,
2019af921006SPavel Labath                                      const ArchSpec &process_host_arch,
2020af921006SPavel Labath                                      std::vector<PlatformSP> &candidates) {
2021af921006SPavel Labath   candidates.clear();
2022af921006SPavel Labath   candidates.reserve(archs.size());
2023af921006SPavel Labath 
2024af921006SPavel Labath   if (archs.empty())
2025af921006SPavel Labath     return nullptr;
2026af921006SPavel Labath 
2027af921006SPavel Labath   PlatformSP host_platform_sp = Platform::GetHostPlatform();
2028af921006SPavel Labath 
2029af921006SPavel Labath   // Prefer the selected platform if it matches at least one architecture.
2030af921006SPavel Labath   if (m_selected_platform_sp) {
2031af921006SPavel Labath     for (const ArchSpec &arch : archs) {
2032af921006SPavel Labath       if (m_selected_platform_sp->IsCompatibleArchitecture(
2033af921006SPavel Labath               arch, process_host_arch, false, nullptr))
2034af921006SPavel Labath         return m_selected_platform_sp;
2035af921006SPavel Labath     }
2036af921006SPavel Labath   }
2037af921006SPavel Labath 
2038af921006SPavel Labath   // Prefer the host platform if it matches at least one architecture.
2039af921006SPavel Labath   if (host_platform_sp) {
2040af921006SPavel Labath     for (const ArchSpec &arch : archs) {
2041af921006SPavel Labath       if (host_platform_sp->IsCompatibleArchitecture(arch, process_host_arch,
2042af921006SPavel Labath                                                      false, nullptr))
2043af921006SPavel Labath         return host_platform_sp;
2044af921006SPavel Labath     }
2045af921006SPavel Labath   }
2046af921006SPavel Labath 
2047af921006SPavel Labath   // Collect a list of candidate platforms for the architectures.
2048af921006SPavel Labath   for (const ArchSpec &arch : archs) {
2049af921006SPavel Labath     if (PlatformSP platform = GetOrCreate(arch, process_host_arch, nullptr))
2050af921006SPavel Labath       candidates.push_back(platform);
2051af921006SPavel Labath   }
2052af921006SPavel Labath 
2053af921006SPavel Labath   // The selected or host platform didn't match any of the architectures. If
2054af921006SPavel Labath   // the same platform supports all architectures then that's the obvious next
2055af921006SPavel Labath   // best thing.
2056af921006SPavel Labath   if (candidates.size() == archs.size()) {
2057af921006SPavel Labath     if (std::all_of(candidates.begin(), candidates.end(),
2058af921006SPavel Labath                     [&](const PlatformSP &p) -> bool {
2059af921006SPavel Labath                       return p->GetName() == candidates.front()->GetName();
2060af921006SPavel Labath                     })) {
2061af921006SPavel Labath       return candidates.front();
2062af921006SPavel Labath     }
2063af921006SPavel Labath   }
2064af921006SPavel Labath 
2065af921006SPavel Labath   // At this point we either have no platforms that match the given
2066af921006SPavel Labath   // architectures or multiple platforms with no good way to disambiguate
2067af921006SPavel Labath   // between them.
2068af921006SPavel Labath   return nullptr;
2069af921006SPavel Labath }
2070af921006SPavel Labath 
Create(llvm::StringRef name)2071af921006SPavel Labath PlatformSP PlatformList::Create(llvm::StringRef name) {
2072af921006SPavel Labath   std::lock_guard<std::recursive_mutex> guard(m_mutex);
2073af921006SPavel Labath   PlatformSP platform_sp = Platform::Create(name);
2074af921006SPavel Labath   m_platforms.push_back(platform_sp);
2075af921006SPavel Labath   return platform_sp;
2076af921006SPavel Labath }
2077