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