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