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