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