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