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