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