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