xref: /freebsd/contrib/llvm-project/lldb/source/Target/Platform.cpp (revision 06e20d1babecec1f45ffda513f55a8db5f1c0f56)
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(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     const char *command, // Shouldn't be nullptr
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   if (IsHost())
1332     return Host::RunShellCommand(command, working_dir, status_ptr, signo_ptr,
1333                                  command_output, timeout);
1334   else
1335     return Status("unimplemented");
1336 }
1337 
1338 bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
1339                             uint64_t &high) {
1340   if (!IsHost())
1341     return false;
1342   auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath());
1343   if (!Result)
1344     return false;
1345   std::tie(high, low) = Result->words();
1346   return true;
1347 }
1348 
1349 void Platform::SetLocalCacheDirectory(const char *local) {
1350   m_local_cache_directory.assign(local);
1351 }
1352 
1353 const char *Platform::GetLocalCacheDirectory() {
1354   return m_local_cache_directory.c_str();
1355 }
1356 
1357 static constexpr OptionDefinition g_rsync_option_table[] = {
1358     {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
1359      {}, 0, eArgTypeNone, "Enable rsync."},
1360     {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
1361      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1362      "Platform-specific options required for rsync to work."},
1363     {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P',
1364      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1365      "Platform-specific rsync prefix put before the remote path."},
1366     {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i',
1367      OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
1368      "Do not automatically fill in the remote hostname when composing the "
1369      "rsync command."},
1370 };
1371 
1372 static constexpr OptionDefinition g_ssh_option_table[] = {
1373     {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
1374      {}, 0, eArgTypeNone, "Enable SSH."},
1375     {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
1376      nullptr, {}, 0, eArgTypeCommandName,
1377      "Platform-specific options required for SSH to work."},
1378 };
1379 
1380 static constexpr OptionDefinition g_caching_option_table[] = {
1381     {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
1382      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePath,
1383      "Path in which to store local copies of files."},
1384 };
1385 
1386 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
1387   return llvm::makeArrayRef(g_rsync_option_table);
1388 }
1389 
1390 void OptionGroupPlatformRSync::OptionParsingStarting(
1391     ExecutionContext *execution_context) {
1392   m_rsync = false;
1393   m_rsync_opts.clear();
1394   m_rsync_prefix.clear();
1395   m_ignores_remote_hostname = false;
1396 }
1397 
1398 lldb_private::Status
1399 OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx,
1400                                          llvm::StringRef option_arg,
1401                                          ExecutionContext *execution_context) {
1402   Status error;
1403   char short_option = (char)GetDefinitions()[option_idx].short_option;
1404   switch (short_option) {
1405   case 'r':
1406     m_rsync = true;
1407     break;
1408 
1409   case 'R':
1410     m_rsync_opts.assign(std::string(option_arg));
1411     break;
1412 
1413   case 'P':
1414     m_rsync_prefix.assign(std::string(option_arg));
1415     break;
1416 
1417   case 'i':
1418     m_ignores_remote_hostname = true;
1419     break;
1420 
1421   default:
1422     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1423     break;
1424   }
1425 
1426   return error;
1427 }
1428 
1429 lldb::BreakpointSP
1430 Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) {
1431   return lldb::BreakpointSP();
1432 }
1433 
1434 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
1435   return llvm::makeArrayRef(g_ssh_option_table);
1436 }
1437 
1438 void OptionGroupPlatformSSH::OptionParsingStarting(
1439     ExecutionContext *execution_context) {
1440   m_ssh = false;
1441   m_ssh_opts.clear();
1442 }
1443 
1444 lldb_private::Status
1445 OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx,
1446                                        llvm::StringRef option_arg,
1447                                        ExecutionContext *execution_context) {
1448   Status error;
1449   char short_option = (char)GetDefinitions()[option_idx].short_option;
1450   switch (short_option) {
1451   case 's':
1452     m_ssh = true;
1453     break;
1454 
1455   case 'S':
1456     m_ssh_opts.assign(std::string(option_arg));
1457     break;
1458 
1459   default:
1460     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1461     break;
1462   }
1463 
1464   return error;
1465 }
1466 
1467 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
1468   return llvm::makeArrayRef(g_caching_option_table);
1469 }
1470 
1471 void OptionGroupPlatformCaching::OptionParsingStarting(
1472     ExecutionContext *execution_context) {
1473   m_cache_dir.clear();
1474 }
1475 
1476 lldb_private::Status OptionGroupPlatformCaching::SetOptionValue(
1477     uint32_t option_idx, llvm::StringRef option_arg,
1478     ExecutionContext *execution_context) {
1479   Status error;
1480   char short_option = (char)GetDefinitions()[option_idx].short_option;
1481   switch (short_option) {
1482   case 'c':
1483     m_cache_dir.assign(std::string(option_arg));
1484     break;
1485 
1486   default:
1487     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1488     break;
1489   }
1490 
1491   return error;
1492 }
1493 
1494 Environment Platform::GetEnvironment() { return Environment(); }
1495 
1496 const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1497   if (!m_calculated_trap_handlers) {
1498     std::lock_guard<std::mutex> guard(m_mutex);
1499     if (!m_calculated_trap_handlers) {
1500       CalculateTrapHandlerSymbolNames();
1501       m_calculated_trap_handlers = true;
1502     }
1503   }
1504   return m_trap_handlers;
1505 }
1506 
1507 Status Platform::GetCachedExecutable(
1508     ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1509     const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1510   const auto platform_spec = module_spec.GetFileSpec();
1511   const auto error = LoadCachedExecutable(
1512       module_spec, module_sp, module_search_paths_ptr, remote_platform);
1513   if (error.Success()) {
1514     module_spec.GetFileSpec() = module_sp->GetFileSpec();
1515     module_spec.GetPlatformFileSpec() = platform_spec;
1516   }
1517 
1518   return error;
1519 }
1520 
1521 Status Platform::LoadCachedExecutable(
1522     const ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1523     const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1524   return GetRemoteSharedModule(module_spec, nullptr, module_sp,
1525                                [&](const ModuleSpec &spec) {
1526                                  return remote_platform.ResolveExecutable(
1527                                      spec, module_sp, module_search_paths_ptr);
1528                                },
1529                                nullptr);
1530 }
1531 
1532 Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec,
1533                                        Process *process,
1534                                        lldb::ModuleSP &module_sp,
1535                                        const ModuleResolver &module_resolver,
1536                                        bool *did_create_ptr) {
1537   // Get module information from a target.
1538   ModuleSpec resolved_module_spec;
1539   bool got_module_spec = false;
1540   if (process) {
1541     // Try to get module information from the process
1542     if (process->GetModuleSpec(module_spec.GetFileSpec(),
1543                                module_spec.GetArchitecture(),
1544                                resolved_module_spec)) {
1545       if (!module_spec.GetUUID().IsValid() ||
1546           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1547         got_module_spec = true;
1548       }
1549     }
1550   }
1551 
1552   if (!module_spec.GetArchitecture().IsValid()) {
1553     Status error;
1554     // No valid architecture was specified, ask the platform for the
1555     // architectures that we should be using (in the correct order) and see if
1556     // we can find a match that way
1557     ModuleSpec arch_module_spec(module_spec);
1558     for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
1559              idx, arch_module_spec.GetArchitecture());
1560          ++idx) {
1561       error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
1562                                           nullptr, nullptr);
1563       // Did we find an executable using one of the
1564       if (error.Success() && module_sp)
1565         break;
1566     }
1567     if (module_sp)
1568       got_module_spec = true;
1569   }
1570 
1571   if (!got_module_spec) {
1572     // Get module information from a target.
1573     if (!GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1574                        resolved_module_spec)) {
1575       if (!module_spec.GetUUID().IsValid() ||
1576           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1577         return module_resolver(module_spec);
1578       }
1579     }
1580   }
1581 
1582   // If we are looking for a specific UUID, make sure resolved_module_spec has
1583   // the same one before we search.
1584   if (module_spec.GetUUID().IsValid()) {
1585     resolved_module_spec.GetUUID() = module_spec.GetUUID();
1586   }
1587 
1588   // Trying to find a module by UUID on local file system.
1589   const auto error = module_resolver(resolved_module_spec);
1590   if (error.Fail()) {
1591     if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr))
1592       return Status();
1593   }
1594 
1595   return error;
1596 }
1597 
1598 bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec,
1599                                      lldb::ModuleSP &module_sp,
1600                                      bool *did_create_ptr) {
1601   if (IsHost() || !GetGlobalPlatformProperties()->GetUseModuleCache() ||
1602       !GetGlobalPlatformProperties()->GetModuleCacheDirectory())
1603     return false;
1604 
1605   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
1606 
1607   // Check local cache for a module.
1608   auto error = m_module_cache->GetAndPut(
1609       GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1610       [this](const ModuleSpec &module_spec,
1611              const FileSpec &tmp_download_file_spec) {
1612         return DownloadModuleSlice(
1613             module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1614             module_spec.GetObjectSize(), tmp_download_file_spec);
1615 
1616       },
1617       [this](const ModuleSP &module_sp,
1618              const FileSpec &tmp_download_file_spec) {
1619         return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1620       },
1621       module_sp, did_create_ptr);
1622   if (error.Success())
1623     return true;
1624 
1625   LLDB_LOGF(log, "Platform::%s - module %s not found in local cache: %s",
1626             __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1627             error.AsCString());
1628   return false;
1629 }
1630 
1631 Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec,
1632                                      const uint64_t src_offset,
1633                                      const uint64_t src_size,
1634                                      const FileSpec &dst_file_spec) {
1635   Status error;
1636 
1637   std::error_code EC;
1638   llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::OF_None);
1639   if (EC) {
1640     error.SetErrorStringWithFormat("unable to open destination file: %s",
1641                                    dst_file_spec.GetPath().c_str());
1642     return error;
1643   }
1644 
1645   auto src_fd = OpenFile(src_file_spec, File::eOpenOptionRead,
1646                          lldb::eFilePermissionsFileDefault, error);
1647 
1648   if (error.Fail()) {
1649     error.SetErrorStringWithFormat("unable to open source file: %s",
1650                                    error.AsCString());
1651     return error;
1652   }
1653 
1654   std::vector<char> buffer(1024);
1655   auto offset = src_offset;
1656   uint64_t total_bytes_read = 0;
1657   while (total_bytes_read < src_size) {
1658     const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1659                                   src_size - total_bytes_read);
1660     const uint64_t n_read =
1661         ReadFile(src_fd, offset, &buffer[0], to_read, error);
1662     if (error.Fail())
1663       break;
1664     if (n_read == 0) {
1665       error.SetErrorString("read 0 bytes");
1666       break;
1667     }
1668     offset += n_read;
1669     total_bytes_read += n_read;
1670     dst.write(&buffer[0], n_read);
1671   }
1672 
1673   Status close_error;
1674   CloseFile(src_fd, close_error); // Ignoring close error.
1675 
1676   return error;
1677 }
1678 
1679 Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
1680                                     const FileSpec &dst_file_spec) {
1681   return Status(
1682       "Symbol file downloading not supported by the default platform.");
1683 }
1684 
1685 FileSpec Platform::GetModuleCacheRoot() {
1686   auto dir_spec = GetGlobalPlatformProperties()->GetModuleCacheDirectory();
1687   dir_spec.AppendPathComponent(GetName().AsCString());
1688   return dir_spec;
1689 }
1690 
1691 const char *Platform::GetCacheHostname() { return GetHostname(); }
1692 
1693 const UnixSignalsSP &Platform::GetRemoteUnixSignals() {
1694   static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1695   return s_default_unix_signals_sp;
1696 }
1697 
1698 UnixSignalsSP Platform::GetUnixSignals() {
1699   if (IsHost())
1700     return UnixSignals::CreateForHost();
1701   return GetRemoteUnixSignals();
1702 }
1703 
1704 uint32_t Platform::LoadImage(lldb_private::Process *process,
1705                              const lldb_private::FileSpec &local_file,
1706                              const lldb_private::FileSpec &remote_file,
1707                              lldb_private::Status &error) {
1708   if (local_file && remote_file) {
1709     // Both local and remote file was specified. Install the local file to the
1710     // given location.
1711     if (IsRemote() || local_file != remote_file) {
1712       error = Install(local_file, remote_file);
1713       if (error.Fail())
1714         return LLDB_INVALID_IMAGE_TOKEN;
1715     }
1716     return DoLoadImage(process, remote_file, nullptr, error);
1717   }
1718 
1719   if (local_file) {
1720     // Only local file was specified. Install it to the current working
1721     // directory.
1722     FileSpec target_file = GetWorkingDirectory();
1723     target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1724     if (IsRemote() || local_file != target_file) {
1725       error = Install(local_file, target_file);
1726       if (error.Fail())
1727         return LLDB_INVALID_IMAGE_TOKEN;
1728     }
1729     return DoLoadImage(process, target_file, nullptr, error);
1730   }
1731 
1732   if (remote_file) {
1733     // Only remote file was specified so we don't have to do any copying
1734     return DoLoadImage(process, remote_file, nullptr, error);
1735   }
1736 
1737   error.SetErrorString("Neither local nor remote file was specified");
1738   return LLDB_INVALID_IMAGE_TOKEN;
1739 }
1740 
1741 uint32_t Platform::DoLoadImage(lldb_private::Process *process,
1742                                const lldb_private::FileSpec &remote_file,
1743                                const std::vector<std::string> *paths,
1744                                lldb_private::Status &error,
1745                                lldb_private::FileSpec *loaded_image) {
1746   error.SetErrorString("LoadImage is not supported on the current platform");
1747   return LLDB_INVALID_IMAGE_TOKEN;
1748 }
1749 
1750 uint32_t Platform::LoadImageUsingPaths(lldb_private::Process *process,
1751                                const lldb_private::FileSpec &remote_filename,
1752                                const std::vector<std::string> &paths,
1753                                lldb_private::Status &error,
1754                                lldb_private::FileSpec *loaded_path)
1755 {
1756   FileSpec file_to_use;
1757   if (remote_filename.IsAbsolute())
1758     file_to_use = FileSpec(remote_filename.GetFilename().GetStringRef(),
1759 
1760                            remote_filename.GetPathStyle());
1761   else
1762     file_to_use = remote_filename;
1763 
1764   return DoLoadImage(process, file_to_use, &paths, error, loaded_path);
1765 }
1766 
1767 Status Platform::UnloadImage(lldb_private::Process *process,
1768                              uint32_t image_token) {
1769   return Status("UnloadImage is not supported on the current platform");
1770 }
1771 
1772 lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
1773                                          llvm::StringRef plugin_name,
1774                                          Debugger &debugger, Target *target,
1775                                          Status &error) {
1776   return DoConnectProcess(connect_url, plugin_name, debugger, nullptr, target,
1777                           error);
1778 }
1779 
1780 lldb::ProcessSP Platform::ConnectProcessSynchronous(
1781     llvm::StringRef connect_url, llvm::StringRef plugin_name,
1782     Debugger &debugger, Stream &stream, Target *target, Status &error) {
1783   return DoConnectProcess(connect_url, plugin_name, debugger, &stream, target,
1784                           error);
1785 }
1786 
1787 lldb::ProcessSP Platform::DoConnectProcess(llvm::StringRef connect_url,
1788                                            llvm::StringRef plugin_name,
1789                                            Debugger &debugger, Stream *stream,
1790                                            Target *target, Status &error) {
1791   error.Clear();
1792 
1793   if (!target) {
1794     ArchSpec arch;
1795     if (target && target->GetArchitecture().IsValid())
1796       arch = target->GetArchitecture();
1797     else
1798       arch = Target::GetDefaultArchitecture();
1799 
1800     const char *triple = "";
1801     if (arch.IsValid())
1802       triple = arch.GetTriple().getTriple().c_str();
1803 
1804     TargetSP new_target_sp;
1805     error = debugger.GetTargetList().CreateTarget(
1806         debugger, "", triple, eLoadDependentsNo, nullptr, new_target_sp);
1807     target = new_target_sp.get();
1808   }
1809 
1810   if (!target || error.Fail())
1811     return nullptr;
1812 
1813   debugger.GetTargetList().SetSelectedTarget(target);
1814 
1815   lldb::ProcessSP process_sp =
1816       target->CreateProcess(debugger.GetListener(), plugin_name, nullptr);
1817 
1818   if (!process_sp)
1819     return nullptr;
1820 
1821   // If this private method is called with a stream we are synchronous.
1822   const bool synchronous = stream != nullptr;
1823 
1824   ListenerSP listener_sp(
1825       Listener::MakeListener("lldb.Process.ConnectProcess.hijack"));
1826   if (synchronous)
1827     process_sp->HijackProcessEvents(listener_sp);
1828 
1829   error = process_sp->ConnectRemote(connect_url);
1830   if (error.Fail()) {
1831     if (synchronous)
1832       process_sp->RestoreProcessEvents();
1833     return nullptr;
1834   }
1835 
1836   if (synchronous) {
1837     EventSP event_sp;
1838     process_sp->WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp,
1839                                      nullptr);
1840     process_sp->RestoreProcessEvents();
1841     bool pop_process_io_handler = false;
1842     Process::HandleProcessStateChangedEvent(event_sp, stream,
1843                                             pop_process_io_handler);
1844   }
1845 
1846   return process_sp;
1847 }
1848 
1849 size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
1850                                            lldb_private::Status &error) {
1851   error.Clear();
1852   return 0;
1853 }
1854 
1855 size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target,
1856                                                  BreakpointSite *bp_site) {
1857   ArchSpec arch = target.GetArchitecture();
1858   assert(arch.IsValid());
1859   const uint8_t *trap_opcode = nullptr;
1860   size_t trap_opcode_size = 0;
1861 
1862   switch (arch.GetMachine()) {
1863   case llvm::Triple::aarch64_32:
1864   case llvm::Triple::aarch64: {
1865     static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1866     trap_opcode = g_aarch64_opcode;
1867     trap_opcode_size = sizeof(g_aarch64_opcode);
1868   } break;
1869 
1870   case llvm::Triple::arc: {
1871     static const uint8_t g_hex_opcode[] = { 0xff, 0x7f };
1872     trap_opcode = g_hex_opcode;
1873     trap_opcode_size = sizeof(g_hex_opcode);
1874   } break;
1875 
1876   // TODO: support big-endian arm and thumb trap codes.
1877   case llvm::Triple::arm: {
1878     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1879     // linux kernel does otherwise.
1880     static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1881     static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1882 
1883     lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
1884     AddressClass addr_class = AddressClass::eUnknown;
1885 
1886     if (bp_loc_sp) {
1887       addr_class = bp_loc_sp->GetAddress().GetAddressClass();
1888       if (addr_class == AddressClass::eUnknown &&
1889           (bp_loc_sp->GetAddress().GetFileAddress() & 1))
1890         addr_class = AddressClass::eCodeAlternateISA;
1891     }
1892 
1893     if (addr_class == AddressClass::eCodeAlternateISA) {
1894       trap_opcode = g_thumb_breakpoint_opcode;
1895       trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1896     } else {
1897       trap_opcode = g_arm_breakpoint_opcode;
1898       trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1899     }
1900   } break;
1901 
1902   case llvm::Triple::avr: {
1903     static const uint8_t g_hex_opcode[] = {0x98, 0x95};
1904     trap_opcode = g_hex_opcode;
1905     trap_opcode_size = sizeof(g_hex_opcode);
1906   } break;
1907 
1908   case llvm::Triple::mips:
1909   case llvm::Triple::mips64: {
1910     static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1911     trap_opcode = g_hex_opcode;
1912     trap_opcode_size = sizeof(g_hex_opcode);
1913   } break;
1914 
1915   case llvm::Triple::mipsel:
1916   case llvm::Triple::mips64el: {
1917     static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1918     trap_opcode = g_hex_opcode;
1919     trap_opcode_size = sizeof(g_hex_opcode);
1920   } break;
1921 
1922   case llvm::Triple::systemz: {
1923     static const uint8_t g_hex_opcode[] = {0x00, 0x01};
1924     trap_opcode = g_hex_opcode;
1925     trap_opcode_size = sizeof(g_hex_opcode);
1926   } break;
1927 
1928   case llvm::Triple::hexagon: {
1929     static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
1930     trap_opcode = g_hex_opcode;
1931     trap_opcode_size = sizeof(g_hex_opcode);
1932   } break;
1933 
1934   case llvm::Triple::ppc:
1935   case llvm::Triple::ppc64: {
1936     static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
1937     trap_opcode = g_ppc_opcode;
1938     trap_opcode_size = sizeof(g_ppc_opcode);
1939   } break;
1940 
1941   case llvm::Triple::ppc64le: {
1942     static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1943     trap_opcode = g_ppc64le_opcode;
1944     trap_opcode_size = sizeof(g_ppc64le_opcode);
1945   } break;
1946 
1947   case llvm::Triple::x86:
1948   case llvm::Triple::x86_64: {
1949     static const uint8_t g_i386_opcode[] = {0xCC};
1950     trap_opcode = g_i386_opcode;
1951     trap_opcode_size = sizeof(g_i386_opcode);
1952   } break;
1953 
1954   default:
1955     return 0;
1956   }
1957 
1958   assert(bp_site);
1959   if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1960     return trap_opcode_size;
1961 
1962   return 0;
1963 }
1964