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