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