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