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   std::string s;
402   strm.Printf("  Platform: %s\n", GetPluginName().GetCString());
403 
404   ArchSpec arch(GetSystemArchitecture());
405   if (arch.IsValid()) {
406     if (!arch.GetTriple().str().empty()) {
407       strm.Printf("    Triple: ");
408       arch.DumpTriple(strm.AsRawOstream());
409       strm.EOL();
410     }
411   }
412 
413   llvm::VersionTuple os_version = GetOSVersion();
414   if (!os_version.empty()) {
415     strm.Format("OS Version: {0}", os_version.getAsString());
416 
417     if (GetOSBuildString(s))
418       strm.Printf(" (%s)", s.c_str());
419 
420     strm.EOL();
421   }
422 
423   if (IsHost()) {
424     strm.Printf("  Hostname: %s\n", GetHostname());
425   } else {
426     const bool is_connected = IsConnected();
427     if (is_connected)
428       strm.Printf("  Hostname: %s\n", GetHostname());
429     strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no");
430   }
431 
432   if (GetWorkingDirectory()) {
433     strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetCString());
434   }
435   if (!IsConnected())
436     return;
437 
438   std::string specific_info(GetPlatformSpecificConnectionInformation());
439 
440   if (!specific_info.empty())
441     strm.Printf("Platform-specific connection: %s\n", specific_info.c_str());
442 
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 bool Platform::GetOSBuildString(std::string &s) {
490   s.clear();
491 
492   if (IsHost())
493     return HostInfo::GetOSBuildString(s);
494   return GetRemoteOSBuildString(s);
495 }
496 
497 bool Platform::GetOSKernelDescription(std::string &s) {
498   if (IsHost())
499     return HostInfo::GetOSKernelDescription(s);
500   return GetRemoteOSKernelDescription(s);
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 = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_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 = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_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.SetErrorStringWithFormat("remote platform %s doesn't support %s",
756                                    GetPluginName().GetCString(),
757                                    LLVM_PRETTY_FUNCTION);
758     return error;
759   }
760 }
761 
762 Status Platform::GetFilePermissions(const FileSpec &file_spec,
763                                     uint32_t &file_permissions) {
764   if (IsHost()) {
765     auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath());
766     if (Value)
767       file_permissions = Value.get();
768     return Status(Value.getError());
769   } else {
770     Status error;
771     error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
772                                    GetPluginName().GetCString(),
773                                    LLVM_PRETTY_FUNCTION);
774     return error;
775   }
776 }
777 
778 Status Platform::SetFilePermissions(const FileSpec &file_spec,
779                                     uint32_t file_permissions) {
780   if (IsHost()) {
781     auto Perms = static_cast<llvm::sys::fs::perms>(file_permissions);
782     return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms);
783   } else {
784     Status error;
785     error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
786                                    GetPluginName().GetCString(),
787                                    LLVM_PRETTY_FUNCTION);
788     return error;
789   }
790 }
791 
792 ConstString Platform::GetName() { return GetPluginName(); }
793 
794 const char *Platform::GetHostname() {
795   if (IsHost())
796     return "127.0.0.1";
797 
798   if (m_name.empty())
799     return nullptr;
800   return m_name.c_str();
801 }
802 
803 ConstString Platform::GetFullNameForDylib(ConstString basename) {
804   return basename;
805 }
806 
807 bool Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
808   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
809   LLDB_LOGF(log, "Platform::SetRemoteWorkingDirectory('%s')",
810             working_dir.GetCString());
811   m_working_dir = working_dir;
812   return true;
813 }
814 
815 bool Platform::SetOSVersion(llvm::VersionTuple version) {
816   if (IsHost()) {
817     // We don't need anyone setting the OS version for the host platform, we
818     // should be able to figure it out by calling HostInfo::GetOSVersion(...).
819     return false;
820   } else {
821     // We have a remote platform, allow setting the target OS version if we
822     // aren't connected, since if we are connected, we should be able to
823     // request the remote OS version from the connected platform.
824     if (IsConnected())
825       return false;
826     else {
827       // We aren't connected and we might want to set the OS version ahead of
828       // time before we connect so we can peruse files and use a local SDK or
829       // PDK cache of support files to disassemble or do other things.
830       m_os_version = version;
831       return true;
832     }
833   }
834   return false;
835 }
836 
837 Status
838 Platform::ResolveExecutable(const ModuleSpec &module_spec,
839                             lldb::ModuleSP &exe_module_sp,
840                             const FileSpecList *module_search_paths_ptr) {
841   Status error;
842   if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
843     if (module_spec.GetArchitecture().IsValid()) {
844       error = ModuleList::GetSharedModule(module_spec, exe_module_sp,
845                                           module_search_paths_ptr, nullptr,
846                                           nullptr);
847     } else {
848       // No valid architecture was specified, ask the platform for the
849       // architectures that we should be using (in the correct order) and see
850       // if we can find a match that way
851       ModuleSpec arch_module_spec(module_spec);
852       for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
853                idx, arch_module_spec.GetArchitecture());
854            ++idx) {
855         error = ModuleList::GetSharedModule(arch_module_spec, exe_module_sp,
856                                             module_search_paths_ptr, nullptr,
857                                             nullptr);
858         // Did we find an executable using one of the
859         if (error.Success() && exe_module_sp)
860           break;
861       }
862     }
863   } else {
864     error.SetErrorStringWithFormat("'%s' does not exist",
865                                    module_spec.GetFileSpec().GetPath().c_str());
866   }
867   return error;
868 }
869 
870 Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec,
871                                    FileSpec &sym_file) {
872   Status error;
873   if (FileSystem::Instance().Exists(sym_spec.GetSymbolFileSpec()))
874     sym_file = sym_spec.GetSymbolFileSpec();
875   else
876     error.SetErrorString("unable to resolve symbol file");
877   return error;
878 }
879 
880 bool Platform::ResolveRemotePath(const FileSpec &platform_path,
881                                  FileSpec &resolved_platform_path) {
882   resolved_platform_path = platform_path;
883   FileSystem::Instance().Resolve(resolved_platform_path);
884   return true;
885 }
886 
887 const ArchSpec &Platform::GetSystemArchitecture() {
888   if (IsHost()) {
889     if (!m_system_arch.IsValid()) {
890       // We have a local host platform
891       m_system_arch = HostInfo::GetArchitecture();
892       m_system_arch_set_while_connected = m_system_arch.IsValid();
893     }
894   } else {
895     // We have a remote platform. We can only fetch the remote system
896     // architecture if we are connected, and we don't want to do it more than
897     // once.
898 
899     const bool is_connected = IsConnected();
900 
901     bool fetch = false;
902     if (m_system_arch.IsValid()) {
903       // We have valid OS version info, check to make sure it wasn't manually
904       // set prior to connecting. If it was manually set prior to connecting,
905       // then lets fetch the actual OS version info if we are now connected.
906       if (is_connected && !m_system_arch_set_while_connected)
907         fetch = true;
908     } else {
909       // We don't have valid OS version info, fetch it if we are connected
910       fetch = is_connected;
911     }
912 
913     if (fetch) {
914       m_system_arch = GetRemoteSystemArchitecture();
915       m_system_arch_set_while_connected = m_system_arch.IsValid();
916     }
917   }
918   return m_system_arch;
919 }
920 
921 ArchSpec Platform::GetAugmentedArchSpec(llvm::StringRef triple) {
922   if (triple.empty())
923     return ArchSpec();
924   llvm::Triple normalized_triple(llvm::Triple::normalize(triple));
925   if (!ArchSpec::ContainsOnlyArch(normalized_triple))
926     return ArchSpec(triple);
927 
928   if (auto kind = HostInfo::ParseArchitectureKind(triple))
929     return HostInfo::GetArchitecture(*kind);
930 
931   ArchSpec compatible_arch;
932   ArchSpec raw_arch(triple);
933   if (!IsCompatibleArchitecture(raw_arch, false, &compatible_arch))
934     return raw_arch;
935 
936   if (!compatible_arch.IsValid())
937     return ArchSpec(normalized_triple);
938 
939   const llvm::Triple &compatible_triple = compatible_arch.GetTriple();
940   if (normalized_triple.getVendorName().empty())
941     normalized_triple.setVendor(compatible_triple.getVendor());
942   if (normalized_triple.getOSName().empty())
943     normalized_triple.setOS(compatible_triple.getOS());
944   if (normalized_triple.getEnvironmentName().empty())
945     normalized_triple.setEnvironment(compatible_triple.getEnvironment());
946   return ArchSpec(normalized_triple);
947 }
948 
949 Status Platform::ConnectRemote(Args &args) {
950   Status error;
951   if (IsHost())
952     error.SetErrorStringWithFormat("The currently selected platform (%s) is "
953                                    "the host platform and is always connected.",
954                                    GetPluginName().GetCString());
955   else
956     error.SetErrorStringWithFormat(
957         "Platform::ConnectRemote() is not supported by %s",
958         GetPluginName().GetCString());
959   return error;
960 }
961 
962 Status Platform::DisconnectRemote() {
963   Status error;
964   if (IsHost())
965     error.SetErrorStringWithFormat("The currently selected platform (%s) is "
966                                    "the host platform and is always connected.",
967                                    GetPluginName().GetCString());
968   else
969     error.SetErrorStringWithFormat(
970         "Platform::DisconnectRemote() is not supported by %s",
971         GetPluginName().GetCString());
972   return error;
973 }
974 
975 bool Platform::GetProcessInfo(lldb::pid_t pid,
976                               ProcessInstanceInfo &process_info) {
977   // Take care of the host case so that each subclass can just call this
978   // function to get the host functionality.
979   if (IsHost())
980     return Host::GetProcessInfo(pid, process_info);
981   return false;
982 }
983 
984 uint32_t Platform::FindProcesses(const ProcessInstanceInfoMatch &match_info,
985                                  ProcessInstanceInfoList &process_infos) {
986   // Take care of the host case so that each subclass can just call this
987   // function to get the host functionality.
988   uint32_t match_count = 0;
989   if (IsHost())
990     match_count = Host::FindProcesses(match_info, process_infos);
991   return match_count;
992 }
993 
994 Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) {
995   Status error;
996   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
997   LLDB_LOGF(log, "Platform::%s()", __FUNCTION__);
998 
999   // Take care of the host case so that each subclass can just call this
1000   // function to get the host functionality.
1001   if (IsHost()) {
1002     if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
1003       launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
1004 
1005     if (launch_info.GetFlags().Test(eLaunchFlagLaunchInShell)) {
1006       const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1007       const bool first_arg_is_full_shell_command = false;
1008       uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info);
1009       if (log) {
1010         const FileSpec &shell = launch_info.GetShell();
1011         std::string shell_str = (shell) ? shell.GetPath() : "<null>";
1012         LLDB_LOGF(log,
1013                   "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32
1014                   ", shell is '%s'",
1015                   __FUNCTION__, num_resumes, shell_str.c_str());
1016       }
1017 
1018       if (!launch_info.ConvertArgumentsForLaunchingInShell(
1019               error, will_debug, first_arg_is_full_shell_command, num_resumes))
1020         return error;
1021     } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1022       error = ShellExpandArguments(launch_info);
1023       if (error.Fail()) {
1024         error.SetErrorStringWithFormat("shell expansion failed (reason: %s). "
1025                                        "consider launching with 'process "
1026                                        "launch'.",
1027                                        error.AsCString("unknown"));
1028         return error;
1029       }
1030     }
1031 
1032     LLDB_LOGF(log, "Platform::%s final launch_info resume count: %" PRIu32,
1033               __FUNCTION__, launch_info.GetResumeCount());
1034 
1035     error = Host::LaunchProcess(launch_info);
1036   } else
1037     error.SetErrorString(
1038         "base lldb_private::Platform class can't launch remote processes");
1039   return error;
1040 }
1041 
1042 Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
1043   if (IsHost())
1044     return Host::ShellExpandArguments(launch_info);
1045   return Status("base lldb_private::Platform class can't expand arguments");
1046 }
1047 
1048 Status Platform::KillProcess(const lldb::pid_t pid) {
1049   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1050   LLDB_LOGF(log, "Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
1051 
1052   // Try to find a process plugin to handle this Kill request.  If we can't,
1053   // fall back to the default OS implementation.
1054   size_t num_debuggers = Debugger::GetNumDebuggers();
1055   for (size_t didx = 0; didx < num_debuggers; ++didx) {
1056     DebuggerSP debugger = Debugger::GetDebuggerAtIndex(didx);
1057     lldb_private::TargetList &targets = debugger->GetTargetList();
1058     for (int tidx = 0; tidx < targets.GetNumTargets(); ++tidx) {
1059       ProcessSP process = targets.GetTargetAtIndex(tidx)->GetProcessSP();
1060       if (process->GetID() == pid)
1061         return process->Destroy(true);
1062     }
1063   }
1064 
1065   if (!IsHost()) {
1066     return Status(
1067         "base lldb_private::Platform class can't kill remote processes unless "
1068         "they are controlled by a process plugin");
1069   }
1070   Host::Kill(pid, SIGTERM);
1071   return Status();
1072 }
1073 
1074 lldb::ProcessSP Platform::DebugProcess(ProcessLaunchInfo &launch_info,
1075                                        Debugger &debugger, Target &target,
1076                                        Status &error) {
1077   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1078   LLDB_LOG(log, "target = {0})", &target);
1079 
1080   ProcessSP process_sp;
1081   // Make sure we stop at the entry point
1082   launch_info.GetFlags().Set(eLaunchFlagDebug);
1083   // We always launch the process we are going to debug in a separate process
1084   // group, since then we can handle ^C interrupts ourselves w/o having to
1085   // worry about the target getting them as well.
1086   launch_info.SetLaunchInSeparateProcessGroup(true);
1087 
1088   // Allow any StructuredData process-bound plugins to adjust the launch info
1089   // if needed
1090   size_t i = 0;
1091   bool iteration_complete = false;
1092   // Note iteration can't simply go until a nullptr callback is returned, as it
1093   // is valid for a plugin to not supply a filter.
1094   auto get_filter_func = PluginManager::GetStructuredDataFilterCallbackAtIndex;
1095   for (auto filter_callback = get_filter_func(i, iteration_complete);
1096        !iteration_complete;
1097        filter_callback = get_filter_func(++i, iteration_complete)) {
1098     if (filter_callback) {
1099       // Give this ProcessLaunchInfo filter a chance to adjust the launch info.
1100       error = (*filter_callback)(launch_info, &target);
1101       if (!error.Success()) {
1102         LLDB_LOGF(log,
1103                   "Platform::%s() StructuredDataPlugin launch "
1104                   "filter failed.",
1105                   __FUNCTION__);
1106         return process_sp;
1107       }
1108     }
1109   }
1110 
1111   error = LaunchProcess(launch_info);
1112   if (error.Success()) {
1113     LLDB_LOGF(log,
1114               "Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")",
1115               __FUNCTION__, launch_info.GetProcessID());
1116     if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1117       ProcessAttachInfo attach_info(launch_info);
1118       process_sp = Attach(attach_info, debugger, &target, error);
1119       if (process_sp) {
1120         LLDB_LOGF(log, "Platform::%s Attach() succeeded, Process plugin: %s",
1121                   __FUNCTION__, process_sp->GetPluginName().AsCString());
1122         launch_info.SetHijackListener(attach_info.GetHijackListener());
1123 
1124         // Since we attached to the process, it will think it needs to detach
1125         // if the process object just goes away without an explicit call to
1126         // Process::Kill() or Process::Detach(), so let it know to kill the
1127         // process if this happens.
1128         process_sp->SetShouldDetach(false);
1129 
1130         // If we didn't have any file actions, the pseudo terminal might have
1131         // been used where the secondary side was given as the file to open for
1132         // stdin/out/err after we have already opened the master so we can
1133         // read/write stdin/out/err.
1134         int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
1135         if (pty_fd != PseudoTerminal::invalid_fd) {
1136           process_sp->SetSTDIOFileDescriptor(pty_fd);
1137         }
1138       } else {
1139         LLDB_LOGF(log, "Platform::%s Attach() failed: %s", __FUNCTION__,
1140                   error.AsCString());
1141       }
1142     } else {
1143       LLDB_LOGF(log,
1144                 "Platform::%s LaunchProcess() returned launch_info with "
1145                 "invalid process id",
1146                 __FUNCTION__);
1147     }
1148   } else {
1149     LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
1150               error.AsCString());
1151   }
1152 
1153   return process_sp;
1154 }
1155 
1156 lldb::PlatformSP
1157 Platform::GetPlatformForArchitecture(const ArchSpec &arch,
1158                                      ArchSpec *platform_arch_ptr) {
1159   lldb::PlatformSP platform_sp;
1160   Status error;
1161   if (arch.IsValid())
1162     platform_sp = Platform::Create(arch, platform_arch_ptr, error);
1163   return platform_sp;
1164 }
1165 
1166 /// Lets a platform answer if it is compatible with a given
1167 /// architecture and the target triple contained within.
1168 bool Platform::IsCompatibleArchitecture(const ArchSpec &arch,
1169                                         bool exact_arch_match,
1170                                         ArchSpec *compatible_arch_ptr) {
1171   // If the architecture is invalid, we must answer true...
1172   if (arch.IsValid()) {
1173     ArchSpec platform_arch;
1174     // Try for an exact architecture match first.
1175     if (exact_arch_match) {
1176       for (uint32_t arch_idx = 0;
1177            GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1178            ++arch_idx) {
1179         if (arch.IsExactMatch(platform_arch)) {
1180           if (compatible_arch_ptr)
1181             *compatible_arch_ptr = platform_arch;
1182           return true;
1183         }
1184       }
1185     } else {
1186       for (uint32_t arch_idx = 0;
1187            GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1188            ++arch_idx) {
1189         if (arch.IsCompatibleMatch(platform_arch)) {
1190           if (compatible_arch_ptr)
1191             *compatible_arch_ptr = platform_arch;
1192           return true;
1193         }
1194       }
1195     }
1196   }
1197   if (compatible_arch_ptr)
1198     compatible_arch_ptr->Clear();
1199   return false;
1200 }
1201 
1202 Status Platform::PutFile(const FileSpec &source, const FileSpec &destination,
1203                          uint32_t uid, uint32_t gid) {
1204   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1205   LLDB_LOGF(log, "[PutFile] Using block by block transfer....\n");
1206 
1207   auto source_open_options =
1208       File::eOpenOptionReadOnly | File::eOpenOptionCloseOnExec;
1209   namespace fs = llvm::sys::fs;
1210   if (fs::is_symlink_file(source.GetPath()))
1211     source_open_options |= File::eOpenOptionDontFollowSymlinks;
1212 
1213   auto source_file = FileSystem::Instance().Open(source, source_open_options,
1214                                                  lldb::eFilePermissionsUserRW);
1215   if (!source_file)
1216     return Status(source_file.takeError());
1217   Status error;
1218   uint32_t permissions = source_file.get()->GetPermissions(error);
1219   if (permissions == 0)
1220     permissions = lldb::eFilePermissionsFileDefault;
1221 
1222   lldb::user_id_t dest_file = OpenFile(
1223       destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly |
1224                        File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec,
1225       permissions, error);
1226   LLDB_LOGF(log, "dest_file = %" PRIu64 "\n", dest_file);
1227 
1228   if (error.Fail())
1229     return error;
1230   if (dest_file == UINT64_MAX)
1231     return Status("unable to open target file");
1232   lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024 * 16, 0));
1233   uint64_t offset = 0;
1234   for (;;) {
1235     size_t bytes_read = buffer_sp->GetByteSize();
1236     error = source_file.get()->Read(buffer_sp->GetBytes(), bytes_read);
1237     if (error.Fail() || bytes_read == 0)
1238       break;
1239 
1240     const uint64_t bytes_written =
1241         WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error);
1242     if (error.Fail())
1243       break;
1244 
1245     offset += bytes_written;
1246     if (bytes_written != bytes_read) {
1247       // We didn't write the correct number of bytes, so adjust the file
1248       // position in the source file we are reading from...
1249       source_file.get()->SeekFromStart(offset);
1250     }
1251   }
1252   CloseFile(dest_file, error);
1253 
1254   if (uid == UINT32_MAX && gid == UINT32_MAX)
1255     return error;
1256 
1257   // TODO: ChownFile?
1258 
1259   return error;
1260 }
1261 
1262 Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) {
1263   Status error("unimplemented");
1264   return error;
1265 }
1266 
1267 Status
1268 Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1269                         const FileSpec &dst) // The symlink points to dst
1270 {
1271   Status error("unimplemented");
1272   return error;
1273 }
1274 
1275 bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) {
1276   return false;
1277 }
1278 
1279 Status Platform::Unlink(const FileSpec &path) {
1280   Status error("unimplemented");
1281   return error;
1282 }
1283 
1284 MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr,
1285                                           addr_t length, unsigned prot,
1286                                           unsigned flags, addr_t fd,
1287                                           addr_t offset) {
1288   uint64_t flags_platform = 0;
1289   if (flags & eMmapFlagsPrivate)
1290     flags_platform |= MAP_PRIVATE;
1291   if (flags & eMmapFlagsAnon)
1292     flags_platform |= MAP_ANON;
1293 
1294   MmapArgList args({addr, length, prot, flags_platform, fd, offset});
1295   return args;
1296 }
1297 
1298 lldb_private::Status Platform::RunShellCommand(
1299     llvm::StringRef command,
1300     const FileSpec &
1301         working_dir, // Pass empty FileSpec to use the current working directory
1302     int *status_ptr, // Pass nullptr if you don't want the process exit status
1303     int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1304                     // process to exit
1305     std::string
1306         *command_output, // Pass nullptr if you don't want the command output
1307     const Timeout<std::micro> &timeout) {
1308   return RunShellCommand(llvm::StringRef(), command, working_dir, status_ptr,
1309                          signo_ptr, command_output, timeout);
1310 }
1311 
1312 lldb_private::Status Platform::RunShellCommand(
1313     llvm::StringRef shell,   // Pass empty if you want to use the default
1314                              // shell interpreter
1315     llvm::StringRef command, // Shouldn't be empty
1316     const FileSpec &
1317         working_dir, // Pass empty FileSpec to use the current working directory
1318     int *status_ptr, // Pass nullptr if you don't want the process exit status
1319     int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1320                     // process to exit
1321     std::string
1322         *command_output, // Pass nullptr if you don't want the command output
1323     const Timeout<std::micro> &timeout) {
1324   if (IsHost())
1325     return Host::RunShellCommand(shell, command, working_dir, status_ptr,
1326                                  signo_ptr, command_output, timeout);
1327   else
1328     return Status("unimplemented");
1329 }
1330 
1331 bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
1332                             uint64_t &high) {
1333   if (!IsHost())
1334     return false;
1335   auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath());
1336   if (!Result)
1337     return false;
1338   std::tie(high, low) = Result->words();
1339   return true;
1340 }
1341 
1342 void Platform::SetLocalCacheDirectory(const char *local) {
1343   m_local_cache_directory.assign(local);
1344 }
1345 
1346 const char *Platform::GetLocalCacheDirectory() {
1347   return m_local_cache_directory.c_str();
1348 }
1349 
1350 static constexpr OptionDefinition g_rsync_option_table[] = {
1351     {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
1352      {}, 0, eArgTypeNone, "Enable rsync."},
1353     {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
1354      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1355      "Platform-specific options required for rsync to work."},
1356     {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P',
1357      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1358      "Platform-specific rsync prefix put before the remote path."},
1359     {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i',
1360      OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
1361      "Do not automatically fill in the remote hostname when composing the "
1362      "rsync command."},
1363 };
1364 
1365 static constexpr OptionDefinition g_ssh_option_table[] = {
1366     {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
1367      {}, 0, eArgTypeNone, "Enable SSH."},
1368     {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
1369      nullptr, {}, 0, eArgTypeCommandName,
1370      "Platform-specific options required for SSH to work."},
1371 };
1372 
1373 static constexpr OptionDefinition g_caching_option_table[] = {
1374     {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
1375      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePath,
1376      "Path in which to store local copies of files."},
1377 };
1378 
1379 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
1380   return llvm::makeArrayRef(g_rsync_option_table);
1381 }
1382 
1383 void OptionGroupPlatformRSync::OptionParsingStarting(
1384     ExecutionContext *execution_context) {
1385   m_rsync = false;
1386   m_rsync_opts.clear();
1387   m_rsync_prefix.clear();
1388   m_ignores_remote_hostname = false;
1389 }
1390 
1391 lldb_private::Status
1392 OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx,
1393                                          llvm::StringRef option_arg,
1394                                          ExecutionContext *execution_context) {
1395   Status error;
1396   char short_option = (char)GetDefinitions()[option_idx].short_option;
1397   switch (short_option) {
1398   case 'r':
1399     m_rsync = true;
1400     break;
1401 
1402   case 'R':
1403     m_rsync_opts.assign(std::string(option_arg));
1404     break;
1405 
1406   case 'P':
1407     m_rsync_prefix.assign(std::string(option_arg));
1408     break;
1409 
1410   case 'i':
1411     m_ignores_remote_hostname = true;
1412     break;
1413 
1414   default:
1415     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1416     break;
1417   }
1418 
1419   return error;
1420 }
1421 
1422 lldb::BreakpointSP
1423 Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) {
1424   return lldb::BreakpointSP();
1425 }
1426 
1427 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
1428   return llvm::makeArrayRef(g_ssh_option_table);
1429 }
1430 
1431 void OptionGroupPlatformSSH::OptionParsingStarting(
1432     ExecutionContext *execution_context) {
1433   m_ssh = false;
1434   m_ssh_opts.clear();
1435 }
1436 
1437 lldb_private::Status
1438 OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx,
1439                                        llvm::StringRef option_arg,
1440                                        ExecutionContext *execution_context) {
1441   Status error;
1442   char short_option = (char)GetDefinitions()[option_idx].short_option;
1443   switch (short_option) {
1444   case 's':
1445     m_ssh = true;
1446     break;
1447 
1448   case 'S':
1449     m_ssh_opts.assign(std::string(option_arg));
1450     break;
1451 
1452   default:
1453     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1454     break;
1455   }
1456 
1457   return error;
1458 }
1459 
1460 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
1461   return llvm::makeArrayRef(g_caching_option_table);
1462 }
1463 
1464 void OptionGroupPlatformCaching::OptionParsingStarting(
1465     ExecutionContext *execution_context) {
1466   m_cache_dir.clear();
1467 }
1468 
1469 lldb_private::Status OptionGroupPlatformCaching::SetOptionValue(
1470     uint32_t option_idx, llvm::StringRef option_arg,
1471     ExecutionContext *execution_context) {
1472   Status error;
1473   char short_option = (char)GetDefinitions()[option_idx].short_option;
1474   switch (short_option) {
1475   case 'c':
1476     m_cache_dir.assign(std::string(option_arg));
1477     break;
1478 
1479   default:
1480     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1481     break;
1482   }
1483 
1484   return error;
1485 }
1486 
1487 Environment Platform::GetEnvironment() { return Environment(); }
1488 
1489 const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1490   if (!m_calculated_trap_handlers) {
1491     std::lock_guard<std::mutex> guard(m_mutex);
1492     if (!m_calculated_trap_handlers) {
1493       CalculateTrapHandlerSymbolNames();
1494       m_calculated_trap_handlers = true;
1495     }
1496   }
1497   return m_trap_handlers;
1498 }
1499 
1500 Status Platform::GetCachedExecutable(
1501     ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1502     const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1503   const auto platform_spec = module_spec.GetFileSpec();
1504   const auto error = LoadCachedExecutable(
1505       module_spec, module_sp, module_search_paths_ptr, remote_platform);
1506   if (error.Success()) {
1507     module_spec.GetFileSpec() = module_sp->GetFileSpec();
1508     module_spec.GetPlatformFileSpec() = platform_spec;
1509   }
1510 
1511   return error;
1512 }
1513 
1514 Status Platform::LoadCachedExecutable(
1515     const ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1516     const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1517   return GetRemoteSharedModule(module_spec, nullptr, module_sp,
1518                                [&](const ModuleSpec &spec) {
1519                                  return remote_platform.ResolveExecutable(
1520                                      spec, module_sp, module_search_paths_ptr);
1521                                },
1522                                nullptr);
1523 }
1524 
1525 Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec,
1526                                        Process *process,
1527                                        lldb::ModuleSP &module_sp,
1528                                        const ModuleResolver &module_resolver,
1529                                        bool *did_create_ptr) {
1530   // Get module information from a target.
1531   ModuleSpec resolved_module_spec;
1532   bool got_module_spec = false;
1533   if (process) {
1534     // Try to get module information from the process
1535     if (process->GetModuleSpec(module_spec.GetFileSpec(),
1536                                module_spec.GetArchitecture(),
1537                                resolved_module_spec)) {
1538       if (!module_spec.GetUUID().IsValid() ||
1539           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1540         got_module_spec = true;
1541       }
1542     }
1543   }
1544 
1545   if (!module_spec.GetArchitecture().IsValid()) {
1546     Status error;
1547     // No valid architecture was specified, ask the platform for the
1548     // architectures that we should be using (in the correct order) and see if
1549     // we can find a match that way
1550     ModuleSpec arch_module_spec(module_spec);
1551     for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
1552              idx, arch_module_spec.GetArchitecture());
1553          ++idx) {
1554       error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
1555                                           nullptr, nullptr);
1556       // Did we find an executable using one of the
1557       if (error.Success() && module_sp)
1558         break;
1559     }
1560     if (module_sp) {
1561       resolved_module_spec = arch_module_spec;
1562       got_module_spec = true;
1563     }
1564   }
1565 
1566   if (!got_module_spec) {
1567     // Get module information from a target.
1568     if (GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1569                       resolved_module_spec)) {
1570       if (!module_spec.GetUUID().IsValid() ||
1571           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1572         got_module_spec = true;
1573       }
1574     }
1575   }
1576 
1577   if (!got_module_spec) {
1578     // Fall back to the given module resolver, which may have its own
1579     // search logic.
1580     return module_resolver(module_spec);
1581   }
1582 
1583   // If we are looking for a specific UUID, make sure resolved_module_spec has
1584   // the same one before we search.
1585   if (module_spec.GetUUID().IsValid()) {
1586     resolved_module_spec.GetUUID() = module_spec.GetUUID();
1587   }
1588 
1589   // Trying to find a module by UUID on local file system.
1590   const auto error = module_resolver(resolved_module_spec);
1591   if (error.Fail()) {
1592     if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr))
1593       return Status();
1594   }
1595 
1596   return error;
1597 }
1598 
1599 bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec,
1600                                      lldb::ModuleSP &module_sp,
1601                                      bool *did_create_ptr) {
1602   if (IsHost() || !GetGlobalPlatformProperties().GetUseModuleCache() ||
1603       !GetGlobalPlatformProperties().GetModuleCacheDirectory())
1604     return false;
1605 
1606   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
1607 
1608   // Check local cache for a module.
1609   auto error = m_module_cache->GetAndPut(
1610       GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1611       [this](const ModuleSpec &module_spec,
1612              const FileSpec &tmp_download_file_spec) {
1613         return DownloadModuleSlice(
1614             module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1615             module_spec.GetObjectSize(), tmp_download_file_spec);
1616 
1617       },
1618       [this](const ModuleSP &module_sp,
1619              const FileSpec &tmp_download_file_spec) {
1620         return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1621       },
1622       module_sp, did_create_ptr);
1623   if (error.Success())
1624     return true;
1625 
1626   LLDB_LOGF(log, "Platform::%s - module %s not found in local cache: %s",
1627             __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1628             error.AsCString());
1629   return false;
1630 }
1631 
1632 Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec,
1633                                      const uint64_t src_offset,
1634                                      const uint64_t src_size,
1635                                      const FileSpec &dst_file_spec) {
1636   Status error;
1637 
1638   std::error_code EC;
1639   llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::OF_None);
1640   if (EC) {
1641     error.SetErrorStringWithFormat("unable to open destination file: %s",
1642                                    dst_file_spec.GetPath().c_str());
1643     return error;
1644   }
1645 
1646   auto src_fd = OpenFile(src_file_spec, File::eOpenOptionReadOnly,
1647                          lldb::eFilePermissionsFileDefault, error);
1648 
1649   if (error.Fail()) {
1650     error.SetErrorStringWithFormat("unable to open source file: %s",
1651                                    error.AsCString());
1652     return error;
1653   }
1654 
1655   std::vector<char> buffer(1024);
1656   auto offset = src_offset;
1657   uint64_t total_bytes_read = 0;
1658   while (total_bytes_read < src_size) {
1659     const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1660                                   src_size - total_bytes_read);
1661     const uint64_t n_read =
1662         ReadFile(src_fd, offset, &buffer[0], to_read, error);
1663     if (error.Fail())
1664       break;
1665     if (n_read == 0) {
1666       error.SetErrorString("read 0 bytes");
1667       break;
1668     }
1669     offset += n_read;
1670     total_bytes_read += n_read;
1671     dst.write(&buffer[0], n_read);
1672   }
1673 
1674   Status close_error;
1675   CloseFile(src_fd, close_error); // Ignoring close error.
1676 
1677   return error;
1678 }
1679 
1680 Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
1681                                     const FileSpec &dst_file_spec) {
1682   return Status(
1683       "Symbol file downloading not supported by the default platform.");
1684 }
1685 
1686 FileSpec Platform::GetModuleCacheRoot() {
1687   auto dir_spec = GetGlobalPlatformProperties().GetModuleCacheDirectory();
1688   dir_spec.AppendPathComponent(GetName().AsCString());
1689   return dir_spec;
1690 }
1691 
1692 const char *Platform::GetCacheHostname() { return GetHostname(); }
1693 
1694 const UnixSignalsSP &Platform::GetRemoteUnixSignals() {
1695   static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1696   return s_default_unix_signals_sp;
1697 }
1698 
1699 UnixSignalsSP Platform::GetUnixSignals() {
1700   if (IsHost())
1701     return UnixSignals::CreateForHost();
1702   return GetRemoteUnixSignals();
1703 }
1704 
1705 uint32_t Platform::LoadImage(lldb_private::Process *process,
1706                              const lldb_private::FileSpec &local_file,
1707                              const lldb_private::FileSpec &remote_file,
1708                              lldb_private::Status &error) {
1709   if (local_file && remote_file) {
1710     // Both local and remote file was specified. Install the local file to the
1711     // given location.
1712     if (IsRemote() || local_file != remote_file) {
1713       error = Install(local_file, remote_file);
1714       if (error.Fail())
1715         return LLDB_INVALID_IMAGE_TOKEN;
1716     }
1717     return DoLoadImage(process, remote_file, nullptr, error);
1718   }
1719 
1720   if (local_file) {
1721     // Only local file was specified. Install it to the current working
1722     // directory.
1723     FileSpec target_file = GetWorkingDirectory();
1724     target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1725     if (IsRemote() || local_file != target_file) {
1726       error = Install(local_file, target_file);
1727       if (error.Fail())
1728         return LLDB_INVALID_IMAGE_TOKEN;
1729     }
1730     return DoLoadImage(process, target_file, nullptr, error);
1731   }
1732 
1733   if (remote_file) {
1734     // Only remote file was specified so we don't have to do any copying
1735     return DoLoadImage(process, remote_file, nullptr, error);
1736   }
1737 
1738   error.SetErrorString("Neither local nor remote file was specified");
1739   return LLDB_INVALID_IMAGE_TOKEN;
1740 }
1741 
1742 uint32_t Platform::DoLoadImage(lldb_private::Process *process,
1743                                const lldb_private::FileSpec &remote_file,
1744                                const std::vector<std::string> *paths,
1745                                lldb_private::Status &error,
1746                                lldb_private::FileSpec *loaded_image) {
1747   error.SetErrorString("LoadImage is not supported on the current platform");
1748   return LLDB_INVALID_IMAGE_TOKEN;
1749 }
1750 
1751 uint32_t Platform::LoadImageUsingPaths(lldb_private::Process *process,
1752                                const lldb_private::FileSpec &remote_filename,
1753                                const std::vector<std::string> &paths,
1754                                lldb_private::Status &error,
1755                                lldb_private::FileSpec *loaded_path)
1756 {
1757   FileSpec file_to_use;
1758   if (remote_filename.IsAbsolute())
1759     file_to_use = FileSpec(remote_filename.GetFilename().GetStringRef(),
1760 
1761                            remote_filename.GetPathStyle());
1762   else
1763     file_to_use = remote_filename;
1764 
1765   return DoLoadImage(process, file_to_use, &paths, error, loaded_path);
1766 }
1767 
1768 Status Platform::UnloadImage(lldb_private::Process *process,
1769                              uint32_t image_token) {
1770   return Status("UnloadImage is not supported on the current platform");
1771 }
1772 
1773 lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
1774                                          llvm::StringRef plugin_name,
1775                                          Debugger &debugger, Target *target,
1776                                          Status &error) {
1777   return DoConnectProcess(connect_url, plugin_name, debugger, nullptr, target,
1778                           error);
1779 }
1780 
1781 lldb::ProcessSP Platform::ConnectProcessSynchronous(
1782     llvm::StringRef connect_url, llvm::StringRef plugin_name,
1783     Debugger &debugger, Stream &stream, Target *target, Status &error) {
1784   return DoConnectProcess(connect_url, plugin_name, debugger, &stream, target,
1785                           error);
1786 }
1787 
1788 lldb::ProcessSP Platform::DoConnectProcess(llvm::StringRef connect_url,
1789                                            llvm::StringRef plugin_name,
1790                                            Debugger &debugger, Stream *stream,
1791                                            Target *target, Status &error) {
1792   error.Clear();
1793 
1794   if (!target) {
1795     ArchSpec arch;
1796     if (target && target->GetArchitecture().IsValid())
1797       arch = target->GetArchitecture();
1798     else
1799       arch = Target::GetDefaultArchitecture();
1800 
1801     const char *triple = "";
1802     if (arch.IsValid())
1803       triple = arch.GetTriple().getTriple().c_str();
1804 
1805     TargetSP new_target_sp;
1806     error = debugger.GetTargetList().CreateTarget(
1807         debugger, "", triple, eLoadDependentsNo, nullptr, new_target_sp);
1808     target = new_target_sp.get();
1809   }
1810 
1811   if (!target || error.Fail())
1812     return nullptr;
1813 
1814   lldb::ProcessSP process_sp =
1815       target->CreateProcess(debugger.GetListener(), plugin_name, nullptr, true);
1816 
1817   if (!process_sp)
1818     return nullptr;
1819 
1820   // If this private method is called with a stream we are synchronous.
1821   const bool synchronous = stream != nullptr;
1822 
1823   ListenerSP listener_sp(
1824       Listener::MakeListener("lldb.Process.ConnectProcess.hijack"));
1825   if (synchronous)
1826     process_sp->HijackProcessEvents(listener_sp);
1827 
1828   error = process_sp->ConnectRemote(connect_url);
1829   if (error.Fail()) {
1830     if (synchronous)
1831       process_sp->RestoreProcessEvents();
1832     return nullptr;
1833   }
1834 
1835   if (synchronous) {
1836     EventSP event_sp;
1837     process_sp->WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp,
1838                                      nullptr);
1839     process_sp->RestoreProcessEvents();
1840     bool pop_process_io_handler = false;
1841     Process::HandleProcessStateChangedEvent(event_sp, stream,
1842                                             pop_process_io_handler);
1843   }
1844 
1845   return process_sp;
1846 }
1847 
1848 size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
1849                                            lldb_private::Status &error) {
1850   error.Clear();
1851   return 0;
1852 }
1853 
1854 size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target,
1855                                                  BreakpointSite *bp_site) {
1856   ArchSpec arch = target.GetArchitecture();
1857   assert(arch.IsValid());
1858   const uint8_t *trap_opcode = nullptr;
1859   size_t trap_opcode_size = 0;
1860 
1861   switch (arch.GetMachine()) {
1862   case llvm::Triple::aarch64_32:
1863   case llvm::Triple::aarch64: {
1864     static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1865     trap_opcode = g_aarch64_opcode;
1866     trap_opcode_size = sizeof(g_aarch64_opcode);
1867   } break;
1868 
1869   case llvm::Triple::arc: {
1870     static const uint8_t g_hex_opcode[] = { 0xff, 0x7f };
1871     trap_opcode = g_hex_opcode;
1872     trap_opcode_size = sizeof(g_hex_opcode);
1873   } break;
1874 
1875   // TODO: support big-endian arm and thumb trap codes.
1876   case llvm::Triple::arm: {
1877     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1878     // linux kernel does otherwise.
1879     static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1880     static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1881 
1882     lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
1883     AddressClass addr_class = AddressClass::eUnknown;
1884 
1885     if (bp_loc_sp) {
1886       addr_class = bp_loc_sp->GetAddress().GetAddressClass();
1887       if (addr_class == AddressClass::eUnknown &&
1888           (bp_loc_sp->GetAddress().GetFileAddress() & 1))
1889         addr_class = AddressClass::eCodeAlternateISA;
1890     }
1891 
1892     if (addr_class == AddressClass::eCodeAlternateISA) {
1893       trap_opcode = g_thumb_breakpoint_opcode;
1894       trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1895     } else {
1896       trap_opcode = g_arm_breakpoint_opcode;
1897       trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1898     }
1899   } break;
1900 
1901   case llvm::Triple::avr: {
1902     static const uint8_t g_hex_opcode[] = {0x98, 0x95};
1903     trap_opcode = g_hex_opcode;
1904     trap_opcode_size = sizeof(g_hex_opcode);
1905   } break;
1906 
1907   case llvm::Triple::mips:
1908   case llvm::Triple::mips64: {
1909     static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1910     trap_opcode = g_hex_opcode;
1911     trap_opcode_size = sizeof(g_hex_opcode);
1912   } break;
1913 
1914   case llvm::Triple::mipsel:
1915   case llvm::Triple::mips64el: {
1916     static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1917     trap_opcode = g_hex_opcode;
1918     trap_opcode_size = sizeof(g_hex_opcode);
1919   } break;
1920 
1921   case llvm::Triple::systemz: {
1922     static const uint8_t g_hex_opcode[] = {0x00, 0x01};
1923     trap_opcode = g_hex_opcode;
1924     trap_opcode_size = sizeof(g_hex_opcode);
1925   } break;
1926 
1927   case llvm::Triple::hexagon: {
1928     static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
1929     trap_opcode = g_hex_opcode;
1930     trap_opcode_size = sizeof(g_hex_opcode);
1931   } break;
1932 
1933   case llvm::Triple::ppc:
1934   case llvm::Triple::ppc64: {
1935     static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
1936     trap_opcode = g_ppc_opcode;
1937     trap_opcode_size = sizeof(g_ppc_opcode);
1938   } break;
1939 
1940   case llvm::Triple::ppc64le: {
1941     static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1942     trap_opcode = g_ppc64le_opcode;
1943     trap_opcode_size = sizeof(g_ppc64le_opcode);
1944   } break;
1945 
1946   case llvm::Triple::x86:
1947   case llvm::Triple::x86_64: {
1948     static const uint8_t g_i386_opcode[] = {0xCC};
1949     trap_opcode = g_i386_opcode;
1950     trap_opcode_size = sizeof(g_i386_opcode);
1951   } break;
1952 
1953   default:
1954     return 0;
1955   }
1956 
1957   assert(bp_site);
1958   if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1959     return trap_opcode_size;
1960 
1961   return 0;
1962 }
1963