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