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