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