1 //===-- Platform.cpp ------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include <algorithm>
10 #include <csignal>
11 #include <fstream>
12 #include <memory>
13 #include <vector>
14 
15 #include "lldb/Breakpoint/BreakpointIDList.h"
16 #include "lldb/Breakpoint/BreakpointLocation.h"
17 #include "lldb/Core/Debugger.h"
18 #include "lldb/Core/Module.h"
19 #include "lldb/Core/ModuleSpec.h"
20 #include "lldb/Core/PluginManager.h"
21 #include "lldb/Core/StreamFile.h"
22 #include "lldb/Host/FileSystem.h"
23 #include "lldb/Host/Host.h"
24 #include "lldb/Host/HostInfo.h"
25 #include "lldb/Host/OptionParser.h"
26 #include "lldb/Interpreter/OptionValueFileSpec.h"
27 #include "lldb/Interpreter/OptionValueProperties.h"
28 #include "lldb/Interpreter/Property.h"
29 #include "lldb/Symbol/ObjectFile.h"
30 #include "lldb/Target/ModuleCache.h"
31 #include "lldb/Target/Platform.h"
32 #include "lldb/Target/Process.h"
33 #include "lldb/Target/Target.h"
34 #include "lldb/Target/UnixSignals.h"
35 #include "lldb/Utility/DataBufferHeap.h"
36 #include "lldb/Utility/FileSpec.h"
37 #include "lldb/Utility/Log.h"
38 #include "lldb/Utility/Status.h"
39 #include "lldb/Utility/StructuredData.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/Path.h"
42 
43 // Define these constants from POSIX mman.h rather than include the file so
44 // that they will be correct even when compiled on Linux.
45 #define MAP_PRIVATE 2
46 #define MAP_ANON 0x1000
47 
48 using namespace lldb;
49 using namespace lldb_private;
50 
51 static uint32_t g_initialize_count = 0;
52 
53 // Use a singleton function for g_local_platform_sp to avoid init constructors
54 // since LLDB is often part of a shared library
55 static PlatformSP &GetHostPlatformSP() {
56   static PlatformSP g_platform_sp;
57   return g_platform_sp;
58 }
59 
60 const char *Platform::GetHostPlatformName() { return "host"; }
61 
62 namespace {
63 
64 #define LLDB_PROPERTIES_platform
65 #include "TargetProperties.inc"
66 
67 enum {
68 #define LLDB_PROPERTIES_platform
69 #include "TargetPropertiesEnum.inc"
70 };
71 
72 } // namespace
73 
74 ConstString PlatformProperties::GetSettingName() {
75   static ConstString g_setting_name("platform");
76   return g_setting_name;
77 }
78 
79 PlatformProperties::PlatformProperties() {
80   m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
81   m_collection_sp->Initialize(g_platform_properties);
82 
83   auto module_cache_dir = GetModuleCacheDirectory();
84   if (module_cache_dir)
85     return;
86 
87   llvm::SmallString<64> user_home_dir;
88   if (!FileSystem::Instance().GetHomeDirectory(user_home_dir))
89     return;
90 
91   module_cache_dir = FileSpec(user_home_dir.c_str());
92   module_cache_dir.AppendPathComponent(".lldb");
93   module_cache_dir.AppendPathComponent("module_cache");
94   SetDefaultModuleCacheDirectory(module_cache_dir);
95   SetModuleCacheDirectory(module_cache_dir);
96 }
97 
98 bool PlatformProperties::GetUseModuleCache() const {
99   const auto idx = ePropertyUseModuleCache;
100   return m_collection_sp->GetPropertyAtIndexAsBoolean(
101       nullptr, idx, g_platform_properties[idx].default_uint_value != 0);
102 }
103 
104 bool PlatformProperties::SetUseModuleCache(bool use_module_cache) {
105   return m_collection_sp->SetPropertyAtIndexAsBoolean(
106       nullptr, ePropertyUseModuleCache, use_module_cache);
107 }
108 
109 FileSpec PlatformProperties::GetModuleCacheDirectory() const {
110   return m_collection_sp->GetPropertyAtIndexAsFileSpec(
111       nullptr, ePropertyModuleCacheDirectory);
112 }
113 
114 bool PlatformProperties::SetModuleCacheDirectory(const FileSpec &dir_spec) {
115   return m_collection_sp->SetPropertyAtIndexAsFileSpec(
116       nullptr, ePropertyModuleCacheDirectory, dir_spec);
117 }
118 
119 void PlatformProperties::SetDefaultModuleCacheDirectory(
120     const FileSpec &dir_spec) {
121   auto f_spec_opt = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(
122         nullptr, false, ePropertyModuleCacheDirectory);
123   assert(f_spec_opt);
124   f_spec_opt->SetDefaultValue(dir_spec);
125 }
126 
127 /// Get the native host platform plug-in.
128 ///
129 /// There should only be one of these for each host that LLDB runs
130 /// upon that should be statically compiled in and registered using
131 /// preprocessor macros or other similar build mechanisms.
132 ///
133 /// This platform will be used as the default platform when launching
134 /// or attaching to processes unless another platform is specified.
135 PlatformSP Platform::GetHostPlatform() { return GetHostPlatformSP(); }
136 
137 static std::vector<PlatformSP> &GetPlatformList() {
138   static std::vector<PlatformSP> g_platform_list;
139   return g_platform_list;
140 }
141 
142 static std::recursive_mutex &GetPlatformListMutex() {
143   static std::recursive_mutex g_mutex;
144   return g_mutex;
145 }
146 
147 void Platform::Initialize() { g_initialize_count++; }
148 
149 void Platform::Terminate() {
150   if (g_initialize_count > 0) {
151     if (--g_initialize_count == 0) {
152       std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
153       GetPlatformList().clear();
154     }
155   }
156 }
157 
158 const PlatformPropertiesSP &Platform::GetGlobalPlatformProperties() {
159   static const auto g_settings_sp(std::make_shared<PlatformProperties>());
160   return g_settings_sp;
161 }
162 
163 void Platform::SetHostPlatform(const lldb::PlatformSP &platform_sp) {
164   // The native platform should use its static void Platform::Initialize()
165   // function to register itself as the native platform.
166   GetHostPlatformSP() = platform_sp;
167 
168   if (platform_sp) {
169     std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
170     GetPlatformList().push_back(platform_sp);
171   }
172 }
173 
174 Status Platform::GetFileWithUUID(const FileSpec &platform_file,
175                                  const UUID *uuid_ptr, FileSpec &local_file) {
176   // Default to the local case
177   local_file = platform_file;
178   return Status();
179 }
180 
181 FileSpecList
182 Platform::LocateExecutableScriptingResources(Target *target, Module &module,
183                                              Stream *feedback_stream) {
184   return FileSpecList();
185 }
186 
187 // PlatformSP
188 // Platform::FindPlugin (Process *process, ConstString plugin_name)
189 //{
190 //    PlatformCreateInstance create_callback = nullptr;
191 //    if (plugin_name)
192 //    {
193 //        create_callback  =
194 //        PluginManager::GetPlatformCreateCallbackForPluginName (plugin_name);
195 //        if (create_callback)
196 //        {
197 //            ArchSpec arch;
198 //            if (process)
199 //            {
200 //                arch = process->GetTarget().GetArchitecture();
201 //            }
202 //            PlatformSP platform_sp(create_callback(process, &arch));
203 //            if (platform_sp)
204 //                return platform_sp;
205 //        }
206 //    }
207 //    else
208 //    {
209 //        for (uint32_t idx = 0; (create_callback =
210 //        PluginManager::GetPlatformCreateCallbackAtIndex(idx)) != nullptr;
211 //        ++idx)
212 //        {
213 //            PlatformSP platform_sp(create_callback(process, nullptr));
214 //            if (platform_sp)
215 //                return platform_sp;
216 //        }
217 //    }
218 //    return PlatformSP();
219 //}
220 
221 Status Platform::GetSharedModule(
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 will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1024       const bool first_arg_is_full_shell_command = false;
1025       uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info);
1026       if (log) {
1027         const FileSpec &shell = launch_info.GetShell();
1028         std::string shell_str = (shell) ? shell.GetPath() : "<null>";
1029         LLDB_LOGF(log,
1030                   "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32
1031                   ", shell is '%s'",
1032                   __FUNCTION__, num_resumes, shell_str.c_str());
1033       }
1034 
1035       if (!launch_info.ConvertArgumentsForLaunchingInShell(
1036               error, will_debug, first_arg_is_full_shell_command, num_resumes))
1037         return error;
1038     } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1039       error = ShellExpandArguments(launch_info);
1040       if (error.Fail()) {
1041         error.SetErrorStringWithFormat("shell expansion failed (reason: %s). "
1042                                        "consider launching with 'process "
1043                                        "launch'.",
1044                                        error.AsCString("unknown"));
1045         return error;
1046       }
1047     }
1048 
1049     LLDB_LOGF(log, "Platform::%s final launch_info resume count: %" PRIu32,
1050               __FUNCTION__, launch_info.GetResumeCount());
1051 
1052     error = Host::LaunchProcess(launch_info);
1053   } else
1054     error.SetErrorString(
1055         "base lldb_private::Platform class can't launch remote processes");
1056   return error;
1057 }
1058 
1059 Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
1060   if (IsHost())
1061     return Host::ShellExpandArguments(launch_info);
1062   return Status("base lldb_private::Platform class can't expand arguments");
1063 }
1064 
1065 Status Platform::KillProcess(const lldb::pid_t pid) {
1066   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1067   LLDB_LOGF(log, "Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
1068 
1069   // Try to find a process plugin to handle this Kill request.  If we can't,
1070   // fall back to the default OS implementation.
1071   size_t num_debuggers = Debugger::GetNumDebuggers();
1072   for (size_t didx = 0; didx < num_debuggers; ++didx) {
1073     DebuggerSP debugger = Debugger::GetDebuggerAtIndex(didx);
1074     lldb_private::TargetList &targets = debugger->GetTargetList();
1075     for (int tidx = 0; tidx < targets.GetNumTargets(); ++tidx) {
1076       ProcessSP process = targets.GetTargetAtIndex(tidx)->GetProcessSP();
1077       if (process->GetID() == pid)
1078         return process->Destroy(true);
1079     }
1080   }
1081 
1082   if (!IsHost()) {
1083     return Status(
1084         "base lldb_private::Platform class can't kill remote processes unless "
1085         "they are controlled by a process plugin");
1086   }
1087   Host::Kill(pid, SIGTERM);
1088   return Status();
1089 }
1090 
1091 lldb::ProcessSP Platform::DebugProcess(ProcessLaunchInfo &launch_info,
1092                                        Debugger &debugger, Target &target,
1093                                        Status &error) {
1094   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1095   LLDB_LOG(log, "target = {0})", &target);
1096 
1097   ProcessSP process_sp;
1098   // Make sure we stop at the entry point
1099   launch_info.GetFlags().Set(eLaunchFlagDebug);
1100   // We always launch the process we are going to debug in a separate process
1101   // group, since then we can handle ^C interrupts ourselves w/o having to
1102   // worry about the target getting them as well.
1103   launch_info.SetLaunchInSeparateProcessGroup(true);
1104 
1105   // Allow any StructuredData process-bound plugins to adjust the launch info
1106   // if needed
1107   size_t i = 0;
1108   bool iteration_complete = false;
1109   // Note iteration can't simply go until a nullptr callback is returned, as it
1110   // is valid for a plugin to not supply a filter.
1111   auto get_filter_func = PluginManager::GetStructuredDataFilterCallbackAtIndex;
1112   for (auto filter_callback = get_filter_func(i, iteration_complete);
1113        !iteration_complete;
1114        filter_callback = get_filter_func(++i, iteration_complete)) {
1115     if (filter_callback) {
1116       // Give this ProcessLaunchInfo filter a chance to adjust the launch info.
1117       error = (*filter_callback)(launch_info, &target);
1118       if (!error.Success()) {
1119         LLDB_LOGF(log,
1120                   "Platform::%s() StructuredDataPlugin launch "
1121                   "filter failed.",
1122                   __FUNCTION__);
1123         return process_sp;
1124       }
1125     }
1126   }
1127 
1128   error = LaunchProcess(launch_info);
1129   if (error.Success()) {
1130     LLDB_LOGF(log,
1131               "Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")",
1132               __FUNCTION__, launch_info.GetProcessID());
1133     if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1134       ProcessAttachInfo attach_info(launch_info);
1135       process_sp = Attach(attach_info, debugger, &target, error);
1136       if (process_sp) {
1137         LLDB_LOGF(log, "Platform::%s Attach() succeeded, Process plugin: %s",
1138                   __FUNCTION__, process_sp->GetPluginName().AsCString());
1139         launch_info.SetHijackListener(attach_info.GetHijackListener());
1140 
1141         // Since we attached to the process, it will think it needs to detach
1142         // if the process object just goes away without an explicit call to
1143         // Process::Kill() or Process::Detach(), so let it know to kill the
1144         // process if this happens.
1145         process_sp->SetShouldDetach(false);
1146 
1147         // If we didn't have any file actions, the pseudo terminal might have
1148         // been used where the secondary side was given as the file to open for
1149         // stdin/out/err after we have already opened the master so we can
1150         // read/write stdin/out/err.
1151         int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
1152         if (pty_fd != PseudoTerminal::invalid_fd) {
1153           process_sp->SetSTDIOFileDescriptor(pty_fd);
1154         }
1155       } else {
1156         LLDB_LOGF(log, "Platform::%s Attach() failed: %s", __FUNCTION__,
1157                   error.AsCString());
1158       }
1159     } else {
1160       LLDB_LOGF(log,
1161                 "Platform::%s LaunchProcess() returned launch_info with "
1162                 "invalid process id",
1163                 __FUNCTION__);
1164     }
1165   } else {
1166     LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
1167               error.AsCString());
1168   }
1169 
1170   return process_sp;
1171 }
1172 
1173 lldb::PlatformSP
1174 Platform::GetPlatformForArchitecture(const ArchSpec &arch,
1175                                      ArchSpec *platform_arch_ptr) {
1176   lldb::PlatformSP platform_sp;
1177   Status error;
1178   if (arch.IsValid())
1179     platform_sp = Platform::Create(arch, platform_arch_ptr, error);
1180   return platform_sp;
1181 }
1182 
1183 /// Lets a platform answer if it is compatible with a given
1184 /// architecture and the target triple contained within.
1185 bool Platform::IsCompatibleArchitecture(const ArchSpec &arch,
1186                                         bool exact_arch_match,
1187                                         ArchSpec *compatible_arch_ptr) {
1188   // If the architecture is invalid, we must answer true...
1189   if (arch.IsValid()) {
1190     ArchSpec platform_arch;
1191     // Try for an exact architecture match first.
1192     if (exact_arch_match) {
1193       for (uint32_t arch_idx = 0;
1194            GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1195            ++arch_idx) {
1196         if (arch.IsExactMatch(platform_arch)) {
1197           if (compatible_arch_ptr)
1198             *compatible_arch_ptr = platform_arch;
1199           return true;
1200         }
1201       }
1202     } else {
1203       for (uint32_t arch_idx = 0;
1204            GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1205            ++arch_idx) {
1206         if (arch.IsCompatibleMatch(platform_arch)) {
1207           if (compatible_arch_ptr)
1208             *compatible_arch_ptr = platform_arch;
1209           return true;
1210         }
1211       }
1212     }
1213   }
1214   if (compatible_arch_ptr)
1215     compatible_arch_ptr->Clear();
1216   return false;
1217 }
1218 
1219 Status Platform::PutFile(const FileSpec &source, const FileSpec &destination,
1220                          uint32_t uid, uint32_t gid) {
1221   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1222   LLDB_LOGF(log, "[PutFile] Using block by block transfer....\n");
1223 
1224   auto source_open_options =
1225       File::eOpenOptionReadOnly | File::eOpenOptionCloseOnExec;
1226   namespace fs = llvm::sys::fs;
1227   if (fs::is_symlink_file(source.GetPath()))
1228     source_open_options |= File::eOpenOptionDontFollowSymlinks;
1229 
1230   auto source_file = FileSystem::Instance().Open(source, source_open_options,
1231                                                  lldb::eFilePermissionsUserRW);
1232   if (!source_file)
1233     return Status(source_file.takeError());
1234   Status error;
1235   uint32_t permissions = source_file.get()->GetPermissions(error);
1236   if (permissions == 0)
1237     permissions = lldb::eFilePermissionsFileDefault;
1238 
1239   lldb::user_id_t dest_file = OpenFile(
1240       destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly |
1241                        File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec,
1242       permissions, error);
1243   LLDB_LOGF(log, "dest_file = %" PRIu64 "\n", dest_file);
1244 
1245   if (error.Fail())
1246     return error;
1247   if (dest_file == UINT64_MAX)
1248     return Status("unable to open target file");
1249   lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024 * 16, 0));
1250   uint64_t offset = 0;
1251   for (;;) {
1252     size_t bytes_read = buffer_sp->GetByteSize();
1253     error = source_file.get()->Read(buffer_sp->GetBytes(), bytes_read);
1254     if (error.Fail() || bytes_read == 0)
1255       break;
1256 
1257     const uint64_t bytes_written =
1258         WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error);
1259     if (error.Fail())
1260       break;
1261 
1262     offset += bytes_written;
1263     if (bytes_written != bytes_read) {
1264       // We didn't write the correct number of bytes, so adjust the file
1265       // position in the source file we are reading from...
1266       source_file.get()->SeekFromStart(offset);
1267     }
1268   }
1269   CloseFile(dest_file, error);
1270 
1271   if (uid == UINT32_MAX && gid == UINT32_MAX)
1272     return error;
1273 
1274   // TODO: ChownFile?
1275 
1276   return error;
1277 }
1278 
1279 Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) {
1280   Status error("unimplemented");
1281   return error;
1282 }
1283 
1284 Status
1285 Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1286                         const FileSpec &dst) // The symlink points to dst
1287 {
1288   Status error("unimplemented");
1289   return error;
1290 }
1291 
1292 bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) {
1293   return false;
1294 }
1295 
1296 Status Platform::Unlink(const FileSpec &path) {
1297   Status error("unimplemented");
1298   return error;
1299 }
1300 
1301 MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr,
1302                                           addr_t length, unsigned prot,
1303                                           unsigned flags, addr_t fd,
1304                                           addr_t offset) {
1305   uint64_t flags_platform = 0;
1306   if (flags & eMmapFlagsPrivate)
1307     flags_platform |= MAP_PRIVATE;
1308   if (flags & eMmapFlagsAnon)
1309     flags_platform |= MAP_ANON;
1310 
1311   MmapArgList args({addr, length, prot, flags_platform, fd, offset});
1312   return args;
1313 }
1314 
1315 lldb_private::Status Platform::RunShellCommand(
1316     llvm::StringRef command,
1317     const FileSpec &
1318         working_dir, // Pass empty FileSpec to use the current working directory
1319     int *status_ptr, // Pass nullptr if you don't want the process exit status
1320     int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1321                     // process to exit
1322     std::string
1323         *command_output, // Pass nullptr if you don't want the command output
1324     const Timeout<std::micro> &timeout) {
1325   return RunShellCommand(llvm::StringRef(), command, working_dir, status_ptr,
1326                          signo_ptr, command_output, timeout);
1327 }
1328 
1329 lldb_private::Status Platform::RunShellCommand(
1330     llvm::StringRef shell,   // Pass empty if you want to use the default
1331                              // shell interpreter
1332     llvm::StringRef command, // Shouldn't be empty
1333     const FileSpec &
1334         working_dir, // Pass empty FileSpec to use the current working directory
1335     int *status_ptr, // Pass nullptr if you don't want the process exit status
1336     int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1337                     // process to exit
1338     std::string
1339         *command_output, // Pass nullptr if you don't want the command output
1340     const Timeout<std::micro> &timeout) {
1341   if (IsHost())
1342     return Host::RunShellCommand(shell, command, working_dir, status_ptr,
1343                                  signo_ptr, command_output, timeout);
1344   else
1345     return Status("unimplemented");
1346 }
1347 
1348 bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
1349                             uint64_t &high) {
1350   if (!IsHost())
1351     return false;
1352   auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath());
1353   if (!Result)
1354     return false;
1355   std::tie(high, low) = Result->words();
1356   return true;
1357 }
1358 
1359 void Platform::SetLocalCacheDirectory(const char *local) {
1360   m_local_cache_directory.assign(local);
1361 }
1362 
1363 const char *Platform::GetLocalCacheDirectory() {
1364   return m_local_cache_directory.c_str();
1365 }
1366 
1367 static constexpr OptionDefinition g_rsync_option_table[] = {
1368     {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
1369      {}, 0, eArgTypeNone, "Enable rsync."},
1370     {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
1371      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1372      "Platform-specific options required for rsync to work."},
1373     {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P',
1374      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1375      "Platform-specific rsync prefix put before the remote path."},
1376     {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i',
1377      OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
1378      "Do not automatically fill in the remote hostname when composing the "
1379      "rsync command."},
1380 };
1381 
1382 static constexpr OptionDefinition g_ssh_option_table[] = {
1383     {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
1384      {}, 0, eArgTypeNone, "Enable SSH."},
1385     {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
1386      nullptr, {}, 0, eArgTypeCommandName,
1387      "Platform-specific options required for SSH to work."},
1388 };
1389 
1390 static constexpr OptionDefinition g_caching_option_table[] = {
1391     {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
1392      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePath,
1393      "Path in which to store local copies of files."},
1394 };
1395 
1396 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
1397   return llvm::makeArrayRef(g_rsync_option_table);
1398 }
1399 
1400 void OptionGroupPlatformRSync::OptionParsingStarting(
1401     ExecutionContext *execution_context) {
1402   m_rsync = false;
1403   m_rsync_opts.clear();
1404   m_rsync_prefix.clear();
1405   m_ignores_remote_hostname = false;
1406 }
1407 
1408 lldb_private::Status
1409 OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx,
1410                                          llvm::StringRef option_arg,
1411                                          ExecutionContext *execution_context) {
1412   Status error;
1413   char short_option = (char)GetDefinitions()[option_idx].short_option;
1414   switch (short_option) {
1415   case 'r':
1416     m_rsync = true;
1417     break;
1418 
1419   case 'R':
1420     m_rsync_opts.assign(std::string(option_arg));
1421     break;
1422 
1423   case 'P':
1424     m_rsync_prefix.assign(std::string(option_arg));
1425     break;
1426 
1427   case 'i':
1428     m_ignores_remote_hostname = true;
1429     break;
1430 
1431   default:
1432     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1433     break;
1434   }
1435 
1436   return error;
1437 }
1438 
1439 lldb::BreakpointSP
1440 Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) {
1441   return lldb::BreakpointSP();
1442 }
1443 
1444 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
1445   return llvm::makeArrayRef(g_ssh_option_table);
1446 }
1447 
1448 void OptionGroupPlatformSSH::OptionParsingStarting(
1449     ExecutionContext *execution_context) {
1450   m_ssh = false;
1451   m_ssh_opts.clear();
1452 }
1453 
1454 lldb_private::Status
1455 OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx,
1456                                        llvm::StringRef option_arg,
1457                                        ExecutionContext *execution_context) {
1458   Status error;
1459   char short_option = (char)GetDefinitions()[option_idx].short_option;
1460   switch (short_option) {
1461   case 's':
1462     m_ssh = true;
1463     break;
1464 
1465   case 'S':
1466     m_ssh_opts.assign(std::string(option_arg));
1467     break;
1468 
1469   default:
1470     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1471     break;
1472   }
1473 
1474   return error;
1475 }
1476 
1477 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
1478   return llvm::makeArrayRef(g_caching_option_table);
1479 }
1480 
1481 void OptionGroupPlatformCaching::OptionParsingStarting(
1482     ExecutionContext *execution_context) {
1483   m_cache_dir.clear();
1484 }
1485 
1486 lldb_private::Status OptionGroupPlatformCaching::SetOptionValue(
1487     uint32_t option_idx, llvm::StringRef option_arg,
1488     ExecutionContext *execution_context) {
1489   Status error;
1490   char short_option = (char)GetDefinitions()[option_idx].short_option;
1491   switch (short_option) {
1492   case 'c':
1493     m_cache_dir.assign(std::string(option_arg));
1494     break;
1495 
1496   default:
1497     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1498     break;
1499   }
1500 
1501   return error;
1502 }
1503 
1504 Environment Platform::GetEnvironment() { return Environment(); }
1505 
1506 const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1507   if (!m_calculated_trap_handlers) {
1508     std::lock_guard<std::mutex> guard(m_mutex);
1509     if (!m_calculated_trap_handlers) {
1510       CalculateTrapHandlerSymbolNames();
1511       m_calculated_trap_handlers = true;
1512     }
1513   }
1514   return m_trap_handlers;
1515 }
1516 
1517 Status Platform::GetCachedExecutable(
1518     ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1519     const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1520   const auto platform_spec = module_spec.GetFileSpec();
1521   const auto error = LoadCachedExecutable(
1522       module_spec, module_sp, module_search_paths_ptr, remote_platform);
1523   if (error.Success()) {
1524     module_spec.GetFileSpec() = module_sp->GetFileSpec();
1525     module_spec.GetPlatformFileSpec() = platform_spec;
1526   }
1527 
1528   return error;
1529 }
1530 
1531 Status Platform::LoadCachedExecutable(
1532     const ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1533     const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1534   return GetRemoteSharedModule(module_spec, nullptr, module_sp,
1535                                [&](const ModuleSpec &spec) {
1536                                  return remote_platform.ResolveExecutable(
1537                                      spec, module_sp, module_search_paths_ptr);
1538                                },
1539                                nullptr);
1540 }
1541 
1542 Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec,
1543                                        Process *process,
1544                                        lldb::ModuleSP &module_sp,
1545                                        const ModuleResolver &module_resolver,
1546                                        bool *did_create_ptr) {
1547   // Get module information from a target.
1548   ModuleSpec resolved_module_spec;
1549   bool got_module_spec = false;
1550   if (process) {
1551     // Try to get module information from the process
1552     if (process->GetModuleSpec(module_spec.GetFileSpec(),
1553                                module_spec.GetArchitecture(),
1554                                resolved_module_spec)) {
1555       if (!module_spec.GetUUID().IsValid() ||
1556           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1557         got_module_spec = true;
1558       }
1559     }
1560   }
1561 
1562   if (!module_spec.GetArchitecture().IsValid()) {
1563     Status error;
1564     // No valid architecture was specified, ask the platform for the
1565     // architectures that we should be using (in the correct order) and see if
1566     // we can find a match that way
1567     ModuleSpec arch_module_spec(module_spec);
1568     for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
1569              idx, arch_module_spec.GetArchitecture());
1570          ++idx) {
1571       error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
1572                                           nullptr, nullptr);
1573       // Did we find an executable using one of the
1574       if (error.Success() && module_sp)
1575         break;
1576     }
1577     if (module_sp) {
1578       resolved_module_spec = arch_module_spec;
1579       got_module_spec = true;
1580     }
1581   }
1582 
1583   if (!got_module_spec) {
1584     // Get module information from a target.
1585     if (GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1586                       resolved_module_spec)) {
1587       if (!module_spec.GetUUID().IsValid() ||
1588           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1589         got_module_spec = true;
1590       }
1591     }
1592   }
1593 
1594   if (!got_module_spec) {
1595     // Fall back to the given module resolver, which may have its own
1596     // search logic.
1597     return module_resolver(module_spec);
1598   }
1599 
1600   // If we are looking for a specific UUID, make sure resolved_module_spec has
1601   // the same one before we search.
1602   if (module_spec.GetUUID().IsValid()) {
1603     resolved_module_spec.GetUUID() = module_spec.GetUUID();
1604   }
1605 
1606   // Trying to find a module by UUID on local file system.
1607   const auto error = module_resolver(resolved_module_spec);
1608   if (error.Fail()) {
1609     if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr))
1610       return Status();
1611   }
1612 
1613   return error;
1614 }
1615 
1616 bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec,
1617                                      lldb::ModuleSP &module_sp,
1618                                      bool *did_create_ptr) {
1619   if (IsHost() || !GetGlobalPlatformProperties()->GetUseModuleCache() ||
1620       !GetGlobalPlatformProperties()->GetModuleCacheDirectory())
1621     return false;
1622 
1623   Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
1624 
1625   // Check local cache for a module.
1626   auto error = m_module_cache->GetAndPut(
1627       GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1628       [this](const ModuleSpec &module_spec,
1629              const FileSpec &tmp_download_file_spec) {
1630         return DownloadModuleSlice(
1631             module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1632             module_spec.GetObjectSize(), tmp_download_file_spec);
1633 
1634       },
1635       [this](const ModuleSP &module_sp,
1636              const FileSpec &tmp_download_file_spec) {
1637         return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1638       },
1639       module_sp, did_create_ptr);
1640   if (error.Success())
1641     return true;
1642 
1643   LLDB_LOGF(log, "Platform::%s - module %s not found in local cache: %s",
1644             __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1645             error.AsCString());
1646   return false;
1647 }
1648 
1649 Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec,
1650                                      const uint64_t src_offset,
1651                                      const uint64_t src_size,
1652                                      const FileSpec &dst_file_spec) {
1653   Status error;
1654 
1655   std::error_code EC;
1656   llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::OF_None);
1657   if (EC) {
1658     error.SetErrorStringWithFormat("unable to open destination file: %s",
1659                                    dst_file_spec.GetPath().c_str());
1660     return error;
1661   }
1662 
1663   auto src_fd = OpenFile(src_file_spec, File::eOpenOptionReadOnly,
1664                          lldb::eFilePermissionsFileDefault, error);
1665 
1666   if (error.Fail()) {
1667     error.SetErrorStringWithFormat("unable to open source file: %s",
1668                                    error.AsCString());
1669     return error;
1670   }
1671 
1672   std::vector<char> buffer(1024);
1673   auto offset = src_offset;
1674   uint64_t total_bytes_read = 0;
1675   while (total_bytes_read < src_size) {
1676     const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1677                                   src_size - total_bytes_read);
1678     const uint64_t n_read =
1679         ReadFile(src_fd, offset, &buffer[0], to_read, error);
1680     if (error.Fail())
1681       break;
1682     if (n_read == 0) {
1683       error.SetErrorString("read 0 bytes");
1684       break;
1685     }
1686     offset += n_read;
1687     total_bytes_read += n_read;
1688     dst.write(&buffer[0], n_read);
1689   }
1690 
1691   Status close_error;
1692   CloseFile(src_fd, close_error); // Ignoring close error.
1693 
1694   return error;
1695 }
1696 
1697 Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
1698                                     const FileSpec &dst_file_spec) {
1699   return Status(
1700       "Symbol file downloading not supported by the default platform.");
1701 }
1702 
1703 FileSpec Platform::GetModuleCacheRoot() {
1704   auto dir_spec = GetGlobalPlatformProperties()->GetModuleCacheDirectory();
1705   dir_spec.AppendPathComponent(GetName().AsCString());
1706   return dir_spec;
1707 }
1708 
1709 const char *Platform::GetCacheHostname() { return GetHostname(); }
1710 
1711 const UnixSignalsSP &Platform::GetRemoteUnixSignals() {
1712   static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1713   return s_default_unix_signals_sp;
1714 }
1715 
1716 UnixSignalsSP Platform::GetUnixSignals() {
1717   if (IsHost())
1718     return UnixSignals::CreateForHost();
1719   return GetRemoteUnixSignals();
1720 }
1721 
1722 uint32_t Platform::LoadImage(lldb_private::Process *process,
1723                              const lldb_private::FileSpec &local_file,
1724                              const lldb_private::FileSpec &remote_file,
1725                              lldb_private::Status &error) {
1726   if (local_file && remote_file) {
1727     // Both local and remote file was specified. Install the local file to the
1728     // given location.
1729     if (IsRemote() || local_file != remote_file) {
1730       error = Install(local_file, remote_file);
1731       if (error.Fail())
1732         return LLDB_INVALID_IMAGE_TOKEN;
1733     }
1734     return DoLoadImage(process, remote_file, nullptr, error);
1735   }
1736 
1737   if (local_file) {
1738     // Only local file was specified. Install it to the current working
1739     // directory.
1740     FileSpec target_file = GetWorkingDirectory();
1741     target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1742     if (IsRemote() || local_file != target_file) {
1743       error = Install(local_file, target_file);
1744       if (error.Fail())
1745         return LLDB_INVALID_IMAGE_TOKEN;
1746     }
1747     return DoLoadImage(process, target_file, nullptr, error);
1748   }
1749 
1750   if (remote_file) {
1751     // Only remote file was specified so we don't have to do any copying
1752     return DoLoadImage(process, remote_file, nullptr, error);
1753   }
1754 
1755   error.SetErrorString("Neither local nor remote file was specified");
1756   return LLDB_INVALID_IMAGE_TOKEN;
1757 }
1758 
1759 uint32_t Platform::DoLoadImage(lldb_private::Process *process,
1760                                const lldb_private::FileSpec &remote_file,
1761                                const std::vector<std::string> *paths,
1762                                lldb_private::Status &error,
1763                                lldb_private::FileSpec *loaded_image) {
1764   error.SetErrorString("LoadImage is not supported on the current platform");
1765   return LLDB_INVALID_IMAGE_TOKEN;
1766 }
1767 
1768 uint32_t Platform::LoadImageUsingPaths(lldb_private::Process *process,
1769                                const lldb_private::FileSpec &remote_filename,
1770                                const std::vector<std::string> &paths,
1771                                lldb_private::Status &error,
1772                                lldb_private::FileSpec *loaded_path)
1773 {
1774   FileSpec file_to_use;
1775   if (remote_filename.IsAbsolute())
1776     file_to_use = FileSpec(remote_filename.GetFilename().GetStringRef(),
1777 
1778                            remote_filename.GetPathStyle());
1779   else
1780     file_to_use = remote_filename;
1781 
1782   return DoLoadImage(process, file_to_use, &paths, error, loaded_path);
1783 }
1784 
1785 Status Platform::UnloadImage(lldb_private::Process *process,
1786                              uint32_t image_token) {
1787   return Status("UnloadImage is not supported on the current platform");
1788 }
1789 
1790 lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
1791                                          llvm::StringRef plugin_name,
1792                                          Debugger &debugger, Target *target,
1793                                          Status &error) {
1794   return DoConnectProcess(connect_url, plugin_name, debugger, nullptr, target,
1795                           error);
1796 }
1797 
1798 lldb::ProcessSP Platform::ConnectProcessSynchronous(
1799     llvm::StringRef connect_url, llvm::StringRef plugin_name,
1800     Debugger &debugger, Stream &stream, Target *target, Status &error) {
1801   return DoConnectProcess(connect_url, plugin_name, debugger, &stream, target,
1802                           error);
1803 }
1804 
1805 lldb::ProcessSP Platform::DoConnectProcess(llvm::StringRef connect_url,
1806                                            llvm::StringRef plugin_name,
1807                                            Debugger &debugger, Stream *stream,
1808                                            Target *target, Status &error) {
1809   error.Clear();
1810 
1811   if (!target) {
1812     ArchSpec arch;
1813     if (target && target->GetArchitecture().IsValid())
1814       arch = target->GetArchitecture();
1815     else
1816       arch = Target::GetDefaultArchitecture();
1817 
1818     const char *triple = "";
1819     if (arch.IsValid())
1820       triple = arch.GetTriple().getTriple().c_str();
1821 
1822     TargetSP new_target_sp;
1823     error = debugger.GetTargetList().CreateTarget(
1824         debugger, "", triple, eLoadDependentsNo, nullptr, new_target_sp);
1825     target = new_target_sp.get();
1826   }
1827 
1828   if (!target || error.Fail())
1829     return nullptr;
1830 
1831   lldb::ProcessSP process_sp =
1832       target->CreateProcess(debugger.GetListener(), plugin_name, nullptr, true);
1833 
1834   if (!process_sp)
1835     return nullptr;
1836 
1837   // If this private method is called with a stream we are synchronous.
1838   const bool synchronous = stream != nullptr;
1839 
1840   ListenerSP listener_sp(
1841       Listener::MakeListener("lldb.Process.ConnectProcess.hijack"));
1842   if (synchronous)
1843     process_sp->HijackProcessEvents(listener_sp);
1844 
1845   error = process_sp->ConnectRemote(connect_url);
1846   if (error.Fail()) {
1847     if (synchronous)
1848       process_sp->RestoreProcessEvents();
1849     return nullptr;
1850   }
1851 
1852   if (synchronous) {
1853     EventSP event_sp;
1854     process_sp->WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp,
1855                                      nullptr);
1856     process_sp->RestoreProcessEvents();
1857     bool pop_process_io_handler = false;
1858     Process::HandleProcessStateChangedEvent(event_sp, stream,
1859                                             pop_process_io_handler);
1860   }
1861 
1862   return process_sp;
1863 }
1864 
1865 size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
1866                                            lldb_private::Status &error) {
1867   error.Clear();
1868   return 0;
1869 }
1870 
1871 size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target,
1872                                                  BreakpointSite *bp_site) {
1873   ArchSpec arch = target.GetArchitecture();
1874   assert(arch.IsValid());
1875   const uint8_t *trap_opcode = nullptr;
1876   size_t trap_opcode_size = 0;
1877 
1878   switch (arch.GetMachine()) {
1879   case llvm::Triple::aarch64_32:
1880   case llvm::Triple::aarch64: {
1881     static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1882     trap_opcode = g_aarch64_opcode;
1883     trap_opcode_size = sizeof(g_aarch64_opcode);
1884   } break;
1885 
1886   case llvm::Triple::arc: {
1887     static const uint8_t g_hex_opcode[] = { 0xff, 0x7f };
1888     trap_opcode = g_hex_opcode;
1889     trap_opcode_size = sizeof(g_hex_opcode);
1890   } break;
1891 
1892   // TODO: support big-endian arm and thumb trap codes.
1893   case llvm::Triple::arm: {
1894     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1895     // linux kernel does otherwise.
1896     static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1897     static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1898 
1899     lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
1900     AddressClass addr_class = AddressClass::eUnknown;
1901 
1902     if (bp_loc_sp) {
1903       addr_class = bp_loc_sp->GetAddress().GetAddressClass();
1904       if (addr_class == AddressClass::eUnknown &&
1905           (bp_loc_sp->GetAddress().GetFileAddress() & 1))
1906         addr_class = AddressClass::eCodeAlternateISA;
1907     }
1908 
1909     if (addr_class == AddressClass::eCodeAlternateISA) {
1910       trap_opcode = g_thumb_breakpoint_opcode;
1911       trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1912     } else {
1913       trap_opcode = g_arm_breakpoint_opcode;
1914       trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1915     }
1916   } break;
1917 
1918   case llvm::Triple::avr: {
1919     static const uint8_t g_hex_opcode[] = {0x98, 0x95};
1920     trap_opcode = g_hex_opcode;
1921     trap_opcode_size = sizeof(g_hex_opcode);
1922   } break;
1923 
1924   case llvm::Triple::mips:
1925   case llvm::Triple::mips64: {
1926     static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1927     trap_opcode = g_hex_opcode;
1928     trap_opcode_size = sizeof(g_hex_opcode);
1929   } break;
1930 
1931   case llvm::Triple::mipsel:
1932   case llvm::Triple::mips64el: {
1933     static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1934     trap_opcode = g_hex_opcode;
1935     trap_opcode_size = sizeof(g_hex_opcode);
1936   } break;
1937 
1938   case llvm::Triple::systemz: {
1939     static const uint8_t g_hex_opcode[] = {0x00, 0x01};
1940     trap_opcode = g_hex_opcode;
1941     trap_opcode_size = sizeof(g_hex_opcode);
1942   } break;
1943 
1944   case llvm::Triple::hexagon: {
1945     static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
1946     trap_opcode = g_hex_opcode;
1947     trap_opcode_size = sizeof(g_hex_opcode);
1948   } break;
1949 
1950   case llvm::Triple::ppc:
1951   case llvm::Triple::ppc64: {
1952     static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
1953     trap_opcode = g_ppc_opcode;
1954     trap_opcode_size = sizeof(g_ppc_opcode);
1955   } break;
1956 
1957   case llvm::Triple::ppc64le: {
1958     static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1959     trap_opcode = g_ppc64le_opcode;
1960     trap_opcode_size = sizeof(g_ppc64le_opcode);
1961   } break;
1962 
1963   case llvm::Triple::x86:
1964   case llvm::Triple::x86_64: {
1965     static const uint8_t g_i386_opcode[] = {0xCC};
1966     trap_opcode = g_i386_opcode;
1967     trap_opcode_size = sizeof(g_i386_opcode);
1968   } break;
1969 
1970   default:
1971     return 0;
1972   }
1973 
1974   assert(bp_site);
1975   if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1976     return trap_opcode_size;
1977 
1978   return 0;
1979 }
1980