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