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.GetStringRef())
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,
318                             const ArchSpec &process_host_arch,
319                             ArchSpec *platform_arch_ptr, Status &error) {
320   lldb::PlatformSP platform_sp;
321   if (arch.IsValid()) {
322     // Scope for locker
323     {
324       // First try exact arch matches across all platforms already created
325       std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
326       for (const auto &platform_sp : GetPlatformList()) {
327         if (platform_sp->IsCompatibleArchitecture(arch, process_host_arch, true,
328                                                   platform_arch_ptr))
329           return platform_sp;
330       }
331 
332       // Next try compatible arch matches across all platforms already created
333       for (const auto &platform_sp : GetPlatformList()) {
334         if (platform_sp->IsCompatibleArchitecture(arch, process_host_arch,
335                                                   false, platform_arch_ptr))
336           return platform_sp;
337       }
338     }
339 
340     PlatformCreateInstance create_callback;
341     // First try exact arch matches across all platform plug-ins
342     uint32_t idx;
343     for (idx = 0; (create_callback =
344                        PluginManager::GetPlatformCreateCallbackAtIndex(idx));
345          ++idx) {
346       if (create_callback) {
347         platform_sp = create_callback(false, &arch);
348         if (platform_sp &&
349             platform_sp->IsCompatibleArchitecture(arch, process_host_arch, true,
350                                                   platform_arch_ptr)) {
351           std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
352           GetPlatformList().push_back(platform_sp);
353           return platform_sp;
354         }
355       }
356     }
357     // Next try compatible arch matches across all platform plug-ins
358     for (idx = 0; (create_callback =
359                        PluginManager::GetPlatformCreateCallbackAtIndex(idx));
360          ++idx) {
361       if (create_callback) {
362         platform_sp = create_callback(false, &arch);
363         if (platform_sp &&
364             platform_sp->IsCompatibleArchitecture(arch, process_host_arch,
365                                                   false, platform_arch_ptr)) {
366           std::lock_guard<std::recursive_mutex> guard(GetPlatformListMutex());
367           GetPlatformList().push_back(platform_sp);
368           return platform_sp;
369         }
370       }
371     }
372   } else
373     error.SetErrorString("invalid platform name");
374   if (platform_arch_ptr)
375     platform_arch_ptr->Clear();
376   platform_sp.reset();
377   return platform_sp;
378 }
379 
380 ArchSpec Platform::GetAugmentedArchSpec(Platform *platform, llvm::StringRef triple) {
381   if (platform)
382     return platform->GetAugmentedArchSpec(triple);
383   return HostInfo::GetAugmentedArchSpec(triple);
384 }
385 
386 /// Default Constructor
387 Platform::Platform(bool is_host)
388     : m_is_host(is_host), m_os_version_set_while_connected(false),
389       m_system_arch_set_while_connected(false), m_max_uid_name_len(0),
390       m_max_gid_name_len(0), m_supports_rsync(false), m_rsync_opts(),
391       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 const char *Platform::GetHostname() {
791   if (IsHost())
792     return "127.0.0.1";
793 
794   if (m_hostname.empty())
795     return nullptr;
796   return m_hostname.c_str();
797 }
798 
799 ConstString Platform::GetFullNameForDylib(ConstString basename) {
800   return basename;
801 }
802 
803 bool Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
804   Log *log = GetLog(LLDBLog::Platform);
805   LLDB_LOGF(log, "Platform::SetRemoteWorkingDirectory('%s')",
806             working_dir.GetCString());
807   m_working_dir = working_dir;
808   return true;
809 }
810 
811 bool Platform::SetOSVersion(llvm::VersionTuple version) {
812   if (IsHost()) {
813     // We don't need anyone setting the OS version for the host platform, we
814     // should be able to figure it out by calling HostInfo::GetOSVersion(...).
815     return false;
816   } else {
817     // We have a remote platform, allow setting the target OS version if we
818     // aren't connected, since if we are connected, we should be able to
819     // request the remote OS version from the connected platform.
820     if (IsConnected())
821       return false;
822     else {
823       // We aren't connected and we might want to set the OS version ahead of
824       // time before we connect so we can peruse files and use a local SDK or
825       // PDK cache of support files to disassemble or do other things.
826       m_os_version = version;
827       return true;
828     }
829   }
830   return false;
831 }
832 
833 Status
834 Platform::ResolveExecutable(const ModuleSpec &module_spec,
835                             lldb::ModuleSP &exe_module_sp,
836                             const FileSpecList *module_search_paths_ptr) {
837   Status error;
838 
839   if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
840     if (module_spec.GetArchitecture().IsValid()) {
841       error = ModuleList::GetSharedModule(module_spec, exe_module_sp,
842                                           module_search_paths_ptr, nullptr,
843                                           nullptr);
844     } else {
845       // No valid architecture was specified, ask the platform for the
846       // architectures that we should be using (in the correct order) and see
847       // if we can find a match that way
848       ModuleSpec arch_module_spec(module_spec);
849       ArchSpec process_host_arch;
850       for (const ArchSpec &arch :
851            GetSupportedArchitectures(process_host_arch)) {
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     ArchSpec process_host_arch;
899     for (const ArchSpec &arch : GetSupportedArchitectures(process_host_arch)) {
900       resolved_module_spec.GetArchitecture() = arch;
901       error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
902                                           module_search_paths_ptr, nullptr,
903                                           nullptr);
904       // Did we find an executable using one of the
905       if (error.Success()) {
906         if (exe_module_sp && exe_module_sp->GetObjectFile())
907           break;
908         else
909           error.SetErrorToGenericError();
910       }
911 
912       arch_names << LS << arch.GetArchitectureName();
913     }
914 
915     if (error.Fail() || !exe_module_sp) {
916       if (FileSystem::Instance().Readable(resolved_module_spec.GetFileSpec())) {
917         error.SetErrorStringWithFormatv(
918             "'{0}' doesn't contain any '{1}' platform architectures: {2}",
919             resolved_module_spec.GetFileSpec(), GetPluginName(),
920             arch_names.GetData());
921       } else {
922         error.SetErrorStringWithFormatv("'{0}' is not readable",
923                                         resolved_module_spec.GetFileSpec());
924       }
925     }
926   } else {
927     error.SetErrorStringWithFormatv("'{0}' does not exist",
928                                     resolved_module_spec.GetFileSpec());
929   }
930 
931   return error;
932 }
933 
934 Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec,
935                                    FileSpec &sym_file) {
936   Status error;
937   if (FileSystem::Instance().Exists(sym_spec.GetSymbolFileSpec()))
938     sym_file = sym_spec.GetSymbolFileSpec();
939   else
940     error.SetErrorString("unable to resolve symbol file");
941   return error;
942 }
943 
944 bool Platform::ResolveRemotePath(const FileSpec &platform_path,
945                                  FileSpec &resolved_platform_path) {
946   resolved_platform_path = platform_path;
947   FileSystem::Instance().Resolve(resolved_platform_path);
948   return true;
949 }
950 
951 const ArchSpec &Platform::GetSystemArchitecture() {
952   if (IsHost()) {
953     if (!m_system_arch.IsValid()) {
954       // We have a local host platform
955       m_system_arch = HostInfo::GetArchitecture();
956       m_system_arch_set_while_connected = m_system_arch.IsValid();
957     }
958   } else {
959     // We have a remote platform. We can only fetch the remote system
960     // architecture if we are connected, and we don't want to do it more than
961     // once.
962 
963     const bool is_connected = IsConnected();
964 
965     bool fetch = false;
966     if (m_system_arch.IsValid()) {
967       // We have valid OS version info, check to make sure it wasn't manually
968       // set prior to connecting. If it was manually set prior to connecting,
969       // then lets fetch the actual OS version info if we are now connected.
970       if (is_connected && !m_system_arch_set_while_connected)
971         fetch = true;
972     } else {
973       // We don't have valid OS version info, fetch it if we are connected
974       fetch = is_connected;
975     }
976 
977     if (fetch) {
978       m_system_arch = GetRemoteSystemArchitecture();
979       m_system_arch_set_while_connected = m_system_arch.IsValid();
980     }
981   }
982   return m_system_arch;
983 }
984 
985 ArchSpec Platform::GetAugmentedArchSpec(llvm::StringRef triple) {
986   if (triple.empty())
987     return ArchSpec();
988   llvm::Triple normalized_triple(llvm::Triple::normalize(triple));
989   if (!ArchSpec::ContainsOnlyArch(normalized_triple))
990     return ArchSpec(triple);
991 
992   if (auto kind = HostInfo::ParseArchitectureKind(triple))
993     return HostInfo::GetArchitecture(*kind);
994 
995   ArchSpec compatible_arch;
996   ArchSpec raw_arch(triple);
997   if (!IsCompatibleArchitecture(raw_arch, {}, false, &compatible_arch))
998     return raw_arch;
999 
1000   if (!compatible_arch.IsValid())
1001     return ArchSpec(normalized_triple);
1002 
1003   const llvm::Triple &compatible_triple = compatible_arch.GetTriple();
1004   if (normalized_triple.getVendorName().empty())
1005     normalized_triple.setVendor(compatible_triple.getVendor());
1006   if (normalized_triple.getOSName().empty())
1007     normalized_triple.setOS(compatible_triple.getOS());
1008   if (normalized_triple.getEnvironmentName().empty())
1009     normalized_triple.setEnvironment(compatible_triple.getEnvironment());
1010   return ArchSpec(normalized_triple);
1011 }
1012 
1013 Status Platform::ConnectRemote(Args &args) {
1014   Status error;
1015   if (IsHost())
1016     error.SetErrorStringWithFormatv(
1017         "The currently selected platform ({0}) is "
1018         "the host platform and is always connected.",
1019         GetPluginName());
1020   else
1021     error.SetErrorStringWithFormatv(
1022         "Platform::ConnectRemote() is not supported by {0}", GetPluginName());
1023   return error;
1024 }
1025 
1026 Status Platform::DisconnectRemote() {
1027   Status error;
1028   if (IsHost())
1029     error.SetErrorStringWithFormatv(
1030         "The currently selected platform ({0}) is "
1031         "the host platform and is always connected.",
1032         GetPluginName());
1033   else
1034     error.SetErrorStringWithFormatv(
1035         "Platform::DisconnectRemote() is not supported by {0}",
1036         GetPluginName());
1037   return error;
1038 }
1039 
1040 bool Platform::GetProcessInfo(lldb::pid_t pid,
1041                               ProcessInstanceInfo &process_info) {
1042   // Take care of the host case so that each subclass can just call this
1043   // function to get the host functionality.
1044   if (IsHost())
1045     return Host::GetProcessInfo(pid, process_info);
1046   return false;
1047 }
1048 
1049 uint32_t Platform::FindProcesses(const ProcessInstanceInfoMatch &match_info,
1050                                  ProcessInstanceInfoList &process_infos) {
1051   // Take care of the host case so that each subclass can just call this
1052   // function to get the host functionality.
1053   uint32_t match_count = 0;
1054   if (IsHost())
1055     match_count = Host::FindProcesses(match_info, process_infos);
1056   return match_count;
1057 }
1058 
1059 Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) {
1060   Status error;
1061   Log *log = GetLog(LLDBLog::Platform);
1062   LLDB_LOGF(log, "Platform::%s()", __FUNCTION__);
1063 
1064   // Take care of the host case so that each subclass can just call this
1065   // function to get the host functionality.
1066   if (IsHost()) {
1067     if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
1068       launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
1069 
1070     if (launch_info.GetFlags().Test(eLaunchFlagLaunchInShell)) {
1071       const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1072       const bool first_arg_is_full_shell_command = false;
1073       uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info);
1074       if (log) {
1075         const FileSpec &shell = launch_info.GetShell();
1076         std::string shell_str = (shell) ? shell.GetPath() : "<null>";
1077         LLDB_LOGF(log,
1078                   "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32
1079                   ", shell is '%s'",
1080                   __FUNCTION__, num_resumes, shell_str.c_str());
1081       }
1082 
1083       if (!launch_info.ConvertArgumentsForLaunchingInShell(
1084               error, will_debug, first_arg_is_full_shell_command, num_resumes))
1085         return error;
1086     } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1087       error = ShellExpandArguments(launch_info);
1088       if (error.Fail()) {
1089         error.SetErrorStringWithFormat("shell expansion failed (reason: %s). "
1090                                        "consider launching with 'process "
1091                                        "launch'.",
1092                                        error.AsCString("unknown"));
1093         return error;
1094       }
1095     }
1096 
1097     LLDB_LOGF(log, "Platform::%s final launch_info resume count: %" PRIu32,
1098               __FUNCTION__, launch_info.GetResumeCount());
1099 
1100     error = Host::LaunchProcess(launch_info);
1101   } else
1102     error.SetErrorString(
1103         "base lldb_private::Platform class can't launch remote processes");
1104   return error;
1105 }
1106 
1107 Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
1108   if (IsHost())
1109     return Host::ShellExpandArguments(launch_info);
1110   return Status("base lldb_private::Platform class can't expand arguments");
1111 }
1112 
1113 Status Platform::KillProcess(const lldb::pid_t pid) {
1114   Log *log = GetLog(LLDBLog::Platform);
1115   LLDB_LOGF(log, "Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
1116 
1117   if (!IsHost()) {
1118     return Status(
1119         "base lldb_private::Platform class can't kill remote processes");
1120   }
1121   Host::Kill(pid, SIGKILL);
1122   return Status();
1123 }
1124 
1125 lldb::ProcessSP Platform::DebugProcess(ProcessLaunchInfo &launch_info,
1126                                        Debugger &debugger, Target &target,
1127                                        Status &error) {
1128   Log *log = GetLog(LLDBLog::Platform);
1129   LLDB_LOG(log, "target = {0})", &target);
1130 
1131   ProcessSP process_sp;
1132   // Make sure we stop at the entry point
1133   launch_info.GetFlags().Set(eLaunchFlagDebug);
1134   // We always launch the process we are going to debug in a separate process
1135   // group, since then we can handle ^C interrupts ourselves w/o having to
1136   // worry about the target getting them as well.
1137   launch_info.SetLaunchInSeparateProcessGroup(true);
1138 
1139   // Allow any StructuredData process-bound plugins to adjust the launch info
1140   // if needed
1141   size_t i = 0;
1142   bool iteration_complete = false;
1143   // Note iteration can't simply go until a nullptr callback is returned, as it
1144   // is valid for a plugin to not supply a filter.
1145   auto get_filter_func = PluginManager::GetStructuredDataFilterCallbackAtIndex;
1146   for (auto filter_callback = get_filter_func(i, iteration_complete);
1147        !iteration_complete;
1148        filter_callback = get_filter_func(++i, iteration_complete)) {
1149     if (filter_callback) {
1150       // Give this ProcessLaunchInfo filter a chance to adjust the launch info.
1151       error = (*filter_callback)(launch_info, &target);
1152       if (!error.Success()) {
1153         LLDB_LOGF(log,
1154                   "Platform::%s() StructuredDataPlugin launch "
1155                   "filter failed.",
1156                   __FUNCTION__);
1157         return process_sp;
1158       }
1159     }
1160   }
1161 
1162   error = LaunchProcess(launch_info);
1163   if (error.Success()) {
1164     LLDB_LOGF(log,
1165               "Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")",
1166               __FUNCTION__, launch_info.GetProcessID());
1167     if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1168       ProcessAttachInfo attach_info(launch_info);
1169       process_sp = Attach(attach_info, debugger, &target, error);
1170       if (process_sp) {
1171         LLDB_LOG(log, "Attach() succeeded, Process plugin: {0}",
1172                  process_sp->GetPluginName());
1173         launch_info.SetHijackListener(attach_info.GetHijackListener());
1174 
1175         // Since we attached to the process, it will think it needs to detach
1176         // if the process object just goes away without an explicit call to
1177         // Process::Kill() or Process::Detach(), so let it know to kill the
1178         // process if this happens.
1179         process_sp->SetShouldDetach(false);
1180 
1181         // If we didn't have any file actions, the pseudo terminal might have
1182         // been used where the secondary side was given as the file to open for
1183         // stdin/out/err after we have already opened the primary so we can
1184         // read/write stdin/out/err.
1185         int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
1186         if (pty_fd != PseudoTerminal::invalid_fd) {
1187           process_sp->SetSTDIOFileDescriptor(pty_fd);
1188         }
1189       } else {
1190         LLDB_LOGF(log, "Platform::%s Attach() failed: %s", __FUNCTION__,
1191                   error.AsCString());
1192       }
1193     } else {
1194       LLDB_LOGF(log,
1195                 "Platform::%s LaunchProcess() returned launch_info with "
1196                 "invalid process id",
1197                 __FUNCTION__);
1198     }
1199   } else {
1200     LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
1201               error.AsCString());
1202   }
1203 
1204   return process_sp;
1205 }
1206 
1207 lldb::PlatformSP
1208 Platform::GetPlatformForArchitecture(const ArchSpec &arch,
1209                                      const ArchSpec &process_host_arch,
1210                                      ArchSpec *platform_arch_ptr) {
1211   lldb::PlatformSP platform_sp;
1212   Status error;
1213   if (arch.IsValid())
1214     platform_sp =
1215         Platform::Create(arch, process_host_arch, platform_arch_ptr, error);
1216   return platform_sp;
1217 }
1218 
1219 std::vector<ArchSpec>
1220 Platform::CreateArchList(llvm::ArrayRef<llvm::Triple::ArchType> archs,
1221                          llvm::Triple::OSType os) {
1222   std::vector<ArchSpec> list;
1223   for(auto arch : archs) {
1224     llvm::Triple triple;
1225     triple.setArch(arch);
1226     triple.setOS(os);
1227     list.push_back(ArchSpec(triple));
1228   }
1229   return list;
1230 }
1231 
1232 /// Lets a platform answer if it is compatible with a given
1233 /// architecture and the target triple contained within.
1234 bool Platform::IsCompatibleArchitecture(const ArchSpec &arch,
1235                                         const ArchSpec &process_host_arch,
1236                                         bool exact_arch_match,
1237                                         ArchSpec *compatible_arch_ptr) {
1238   // If the architecture is invalid, we must answer true...
1239   if (arch.IsValid()) {
1240     ArchSpec platform_arch;
1241     auto match = exact_arch_match ? &ArchSpec::IsExactMatch
1242                                   : &ArchSpec::IsCompatibleMatch;
1243     for (const ArchSpec &platform_arch :
1244          GetSupportedArchitectures(process_host_arch)) {
1245       if ((arch.*match)(platform_arch)) {
1246         if (compatible_arch_ptr)
1247           *compatible_arch_ptr = platform_arch;
1248         return true;
1249       }
1250     }
1251   }
1252   if (compatible_arch_ptr)
1253     compatible_arch_ptr->Clear();
1254   return false;
1255 }
1256 
1257 Status Platform::PutFile(const FileSpec &source, const FileSpec &destination,
1258                          uint32_t uid, uint32_t gid) {
1259   Log *log = GetLog(LLDBLog::Platform);
1260   LLDB_LOGF(log, "[PutFile] Using block by block transfer....\n");
1261 
1262   auto source_open_options =
1263       File::eOpenOptionReadOnly | File::eOpenOptionCloseOnExec;
1264   namespace fs = llvm::sys::fs;
1265   if (fs::is_symlink_file(source.GetPath()))
1266     source_open_options |= File::eOpenOptionDontFollowSymlinks;
1267 
1268   auto source_file = FileSystem::Instance().Open(source, source_open_options,
1269                                                  lldb::eFilePermissionsUserRW);
1270   if (!source_file)
1271     return Status(source_file.takeError());
1272   Status error;
1273   uint32_t permissions = source_file.get()->GetPermissions(error);
1274   if (permissions == 0)
1275     permissions = lldb::eFilePermissionsFileDefault;
1276 
1277   lldb::user_id_t dest_file = OpenFile(
1278       destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly |
1279                        File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec,
1280       permissions, error);
1281   LLDB_LOGF(log, "dest_file = %" PRIu64 "\n", dest_file);
1282 
1283   if (error.Fail())
1284     return error;
1285   if (dest_file == UINT64_MAX)
1286     return Status("unable to open target file");
1287   lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024 * 16, 0));
1288   uint64_t offset = 0;
1289   for (;;) {
1290     size_t bytes_read = buffer_sp->GetByteSize();
1291     error = source_file.get()->Read(buffer_sp->GetBytes(), bytes_read);
1292     if (error.Fail() || bytes_read == 0)
1293       break;
1294 
1295     const uint64_t bytes_written =
1296         WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error);
1297     if (error.Fail())
1298       break;
1299 
1300     offset += bytes_written;
1301     if (bytes_written != bytes_read) {
1302       // We didn't write the correct number of bytes, so adjust the file
1303       // position in the source file we are reading from...
1304       source_file.get()->SeekFromStart(offset);
1305     }
1306   }
1307   CloseFile(dest_file, error);
1308 
1309   if (uid == UINT32_MAX && gid == UINT32_MAX)
1310     return error;
1311 
1312   // TODO: ChownFile?
1313 
1314   return error;
1315 }
1316 
1317 Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) {
1318   Status error("unimplemented");
1319   return error;
1320 }
1321 
1322 Status
1323 Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1324                         const FileSpec &dst) // The symlink points to dst
1325 {
1326   Status error("unimplemented");
1327   return error;
1328 }
1329 
1330 bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) {
1331   return false;
1332 }
1333 
1334 Status Platform::Unlink(const FileSpec &path) {
1335   Status error("unimplemented");
1336   return error;
1337 }
1338 
1339 MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr,
1340                                           addr_t length, unsigned prot,
1341                                           unsigned flags, addr_t fd,
1342                                           addr_t offset) {
1343   uint64_t flags_platform = 0;
1344   if (flags & eMmapFlagsPrivate)
1345     flags_platform |= MAP_PRIVATE;
1346   if (flags & eMmapFlagsAnon)
1347     flags_platform |= MAP_ANON;
1348 
1349   MmapArgList args({addr, length, prot, flags_platform, fd, offset});
1350   return args;
1351 }
1352 
1353 lldb_private::Status Platform::RunShellCommand(
1354     llvm::StringRef command,
1355     const FileSpec &
1356         working_dir, // Pass empty FileSpec to use the current working directory
1357     int *status_ptr, // Pass nullptr if you don't want the process exit status
1358     int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1359                     // process to exit
1360     std::string
1361         *command_output, // Pass nullptr if you don't want the command output
1362     const Timeout<std::micro> &timeout) {
1363   return RunShellCommand(llvm::StringRef(), command, working_dir, status_ptr,
1364                          signo_ptr, command_output, timeout);
1365 }
1366 
1367 lldb_private::Status Platform::RunShellCommand(
1368     llvm::StringRef shell,   // Pass empty if you want to use the default
1369                              // shell interpreter
1370     llvm::StringRef command, // Shouldn't be empty
1371     const FileSpec &
1372         working_dir, // Pass empty FileSpec to use the current working directory
1373     int *status_ptr, // Pass nullptr if you don't want the process exit status
1374     int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1375                     // process to exit
1376     std::string
1377         *command_output, // Pass nullptr if you don't want the command output
1378     const Timeout<std::micro> &timeout) {
1379   if (IsHost())
1380     return Host::RunShellCommand(shell, command, working_dir, status_ptr,
1381                                  signo_ptr, command_output, timeout);
1382   else
1383     return Status("unimplemented");
1384 }
1385 
1386 bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
1387                             uint64_t &high) {
1388   if (!IsHost())
1389     return false;
1390   auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath());
1391   if (!Result)
1392     return false;
1393   std::tie(high, low) = Result->words();
1394   return true;
1395 }
1396 
1397 void Platform::SetLocalCacheDirectory(const char *local) {
1398   m_local_cache_directory.assign(local);
1399 }
1400 
1401 const char *Platform::GetLocalCacheDirectory() {
1402   return m_local_cache_directory.c_str();
1403 }
1404 
1405 static constexpr OptionDefinition g_rsync_option_table[] = {
1406     {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
1407      {}, 0, eArgTypeNone, "Enable rsync."},
1408     {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
1409      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1410      "Platform-specific options required for rsync to work."},
1411     {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P',
1412      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1413      "Platform-specific rsync prefix put before the remote path."},
1414     {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i',
1415      OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
1416      "Do not automatically fill in the remote hostname when composing the "
1417      "rsync command."},
1418 };
1419 
1420 static constexpr OptionDefinition g_ssh_option_table[] = {
1421     {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
1422      {}, 0, eArgTypeNone, "Enable SSH."},
1423     {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
1424      nullptr, {}, 0, eArgTypeCommandName,
1425      "Platform-specific options required for SSH to work."},
1426 };
1427 
1428 static constexpr OptionDefinition g_caching_option_table[] = {
1429     {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
1430      OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePath,
1431      "Path in which to store local copies of files."},
1432 };
1433 
1434 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
1435   return llvm::makeArrayRef(g_rsync_option_table);
1436 }
1437 
1438 void OptionGroupPlatformRSync::OptionParsingStarting(
1439     ExecutionContext *execution_context) {
1440   m_rsync = false;
1441   m_rsync_opts.clear();
1442   m_rsync_prefix.clear();
1443   m_ignores_remote_hostname = false;
1444 }
1445 
1446 lldb_private::Status
1447 OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx,
1448                                          llvm::StringRef option_arg,
1449                                          ExecutionContext *execution_context) {
1450   Status error;
1451   char short_option = (char)GetDefinitions()[option_idx].short_option;
1452   switch (short_option) {
1453   case 'r':
1454     m_rsync = true;
1455     break;
1456 
1457   case 'R':
1458     m_rsync_opts.assign(std::string(option_arg));
1459     break;
1460 
1461   case 'P':
1462     m_rsync_prefix.assign(std::string(option_arg));
1463     break;
1464 
1465   case 'i':
1466     m_ignores_remote_hostname = true;
1467     break;
1468 
1469   default:
1470     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1471     break;
1472   }
1473 
1474   return error;
1475 }
1476 
1477 lldb::BreakpointSP
1478 Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) {
1479   return lldb::BreakpointSP();
1480 }
1481 
1482 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
1483   return llvm::makeArrayRef(g_ssh_option_table);
1484 }
1485 
1486 void OptionGroupPlatformSSH::OptionParsingStarting(
1487     ExecutionContext *execution_context) {
1488   m_ssh = false;
1489   m_ssh_opts.clear();
1490 }
1491 
1492 lldb_private::Status
1493 OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx,
1494                                        llvm::StringRef option_arg,
1495                                        ExecutionContext *execution_context) {
1496   Status error;
1497   char short_option = (char)GetDefinitions()[option_idx].short_option;
1498   switch (short_option) {
1499   case 's':
1500     m_ssh = true;
1501     break;
1502 
1503   case 'S':
1504     m_ssh_opts.assign(std::string(option_arg));
1505     break;
1506 
1507   default:
1508     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1509     break;
1510   }
1511 
1512   return error;
1513 }
1514 
1515 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
1516   return llvm::makeArrayRef(g_caching_option_table);
1517 }
1518 
1519 void OptionGroupPlatformCaching::OptionParsingStarting(
1520     ExecutionContext *execution_context) {
1521   m_cache_dir.clear();
1522 }
1523 
1524 lldb_private::Status OptionGroupPlatformCaching::SetOptionValue(
1525     uint32_t option_idx, llvm::StringRef option_arg,
1526     ExecutionContext *execution_context) {
1527   Status error;
1528   char short_option = (char)GetDefinitions()[option_idx].short_option;
1529   switch (short_option) {
1530   case 'c':
1531     m_cache_dir.assign(std::string(option_arg));
1532     break;
1533 
1534   default:
1535     error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1536     break;
1537   }
1538 
1539   return error;
1540 }
1541 
1542 Environment Platform::GetEnvironment() { return Environment(); }
1543 
1544 const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1545   if (!m_calculated_trap_handlers) {
1546     std::lock_guard<std::mutex> guard(m_mutex);
1547     if (!m_calculated_trap_handlers) {
1548       CalculateTrapHandlerSymbolNames();
1549       m_calculated_trap_handlers = true;
1550     }
1551   }
1552   return m_trap_handlers;
1553 }
1554 
1555 Status
1556 Platform::GetCachedExecutable(ModuleSpec &module_spec,
1557                               lldb::ModuleSP &module_sp,
1558                               const FileSpecList *module_search_paths_ptr) {
1559   FileSpec platform_spec = module_spec.GetFileSpec();
1560   Status error = GetRemoteSharedModule(
1561       module_spec, nullptr, module_sp,
1562       [&](const ModuleSpec &spec) {
1563         return ResolveRemoteExecutable(spec, module_sp,
1564                                        module_search_paths_ptr);
1565       },
1566       nullptr);
1567   if (error.Success()) {
1568     module_spec.GetFileSpec() = module_sp->GetFileSpec();
1569     module_spec.GetPlatformFileSpec() = platform_spec;
1570   }
1571 
1572   return error;
1573 }
1574 
1575 Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec,
1576                                        Process *process,
1577                                        lldb::ModuleSP &module_sp,
1578                                        const ModuleResolver &module_resolver,
1579                                        bool *did_create_ptr) {
1580   // Get module information from a target.
1581   ModuleSpec resolved_module_spec;
1582   ArchSpec process_host_arch;
1583   bool got_module_spec = false;
1584   if (process) {
1585     process_host_arch = process->GetSystemArchitecture();
1586     // Try to get module information from the process
1587     if (process->GetModuleSpec(module_spec.GetFileSpec(),
1588                                module_spec.GetArchitecture(),
1589                                resolved_module_spec)) {
1590       if (!module_spec.GetUUID().IsValid() ||
1591           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1592         got_module_spec = true;
1593       }
1594     }
1595   }
1596 
1597   if (!module_spec.GetArchitecture().IsValid()) {
1598     Status error;
1599     // No valid architecture was specified, ask the platform for the
1600     // architectures that we should be using (in the correct order) and see if
1601     // we can find a match that way
1602     ModuleSpec arch_module_spec(module_spec);
1603     for (const ArchSpec &arch : GetSupportedArchitectures(process_host_arch)) {
1604       arch_module_spec.GetArchitecture() = arch;
1605       error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
1606                                           nullptr, nullptr);
1607       // Did we find an executable using one of the
1608       if (error.Success() && module_sp)
1609         break;
1610     }
1611     if (module_sp) {
1612       resolved_module_spec = arch_module_spec;
1613       got_module_spec = true;
1614     }
1615   }
1616 
1617   if (!got_module_spec) {
1618     // Get module information from a target.
1619     if (GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1620                       resolved_module_spec)) {
1621       if (!module_spec.GetUUID().IsValid() ||
1622           module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1623         got_module_spec = true;
1624       }
1625     }
1626   }
1627 
1628   if (!got_module_spec) {
1629     // Fall back to the given module resolver, which may have its own
1630     // search logic.
1631     return module_resolver(module_spec);
1632   }
1633 
1634   // If we are looking for a specific UUID, make sure resolved_module_spec has
1635   // the same one before we search.
1636   if (module_spec.GetUUID().IsValid()) {
1637     resolved_module_spec.GetUUID() = module_spec.GetUUID();
1638   }
1639 
1640   // Trying to find a module by UUID on local file system.
1641   const auto error = module_resolver(resolved_module_spec);
1642   if (error.Fail()) {
1643     if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr))
1644       return Status();
1645   }
1646 
1647   return error;
1648 }
1649 
1650 bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec,
1651                                      lldb::ModuleSP &module_sp,
1652                                      bool *did_create_ptr) {
1653   if (IsHost() || !GetGlobalPlatformProperties().GetUseModuleCache() ||
1654       !GetGlobalPlatformProperties().GetModuleCacheDirectory())
1655     return false;
1656 
1657   Log *log = GetLog(LLDBLog::Platform);
1658 
1659   // Check local cache for a module.
1660   auto error = m_module_cache->GetAndPut(
1661       GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1662       [this](const ModuleSpec &module_spec,
1663              const FileSpec &tmp_download_file_spec) {
1664         return DownloadModuleSlice(
1665             module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1666             module_spec.GetObjectSize(), tmp_download_file_spec);
1667 
1668       },
1669       [this](const ModuleSP &module_sp,
1670              const FileSpec &tmp_download_file_spec) {
1671         return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1672       },
1673       module_sp, did_create_ptr);
1674   if (error.Success())
1675     return true;
1676 
1677   LLDB_LOGF(log, "Platform::%s - module %s not found in local cache: %s",
1678             __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1679             error.AsCString());
1680   return false;
1681 }
1682 
1683 Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec,
1684                                      const uint64_t src_offset,
1685                                      const uint64_t src_size,
1686                                      const FileSpec &dst_file_spec) {
1687   Status error;
1688 
1689   std::error_code EC;
1690   llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::OF_None);
1691   if (EC) {
1692     error.SetErrorStringWithFormat("unable to open destination file: %s",
1693                                    dst_file_spec.GetPath().c_str());
1694     return error;
1695   }
1696 
1697   auto src_fd = OpenFile(src_file_spec, File::eOpenOptionReadOnly,
1698                          lldb::eFilePermissionsFileDefault, error);
1699 
1700   if (error.Fail()) {
1701     error.SetErrorStringWithFormat("unable to open source file: %s",
1702                                    error.AsCString());
1703     return error;
1704   }
1705 
1706   std::vector<char> buffer(1024);
1707   auto offset = src_offset;
1708   uint64_t total_bytes_read = 0;
1709   while (total_bytes_read < src_size) {
1710     const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1711                                   src_size - total_bytes_read);
1712     const uint64_t n_read =
1713         ReadFile(src_fd, offset, &buffer[0], to_read, error);
1714     if (error.Fail())
1715       break;
1716     if (n_read == 0) {
1717       error.SetErrorString("read 0 bytes");
1718       break;
1719     }
1720     offset += n_read;
1721     total_bytes_read += n_read;
1722     dst.write(&buffer[0], n_read);
1723   }
1724 
1725   Status close_error;
1726   CloseFile(src_fd, close_error); // Ignoring close error.
1727 
1728   return error;
1729 }
1730 
1731 Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
1732                                     const FileSpec &dst_file_spec) {
1733   return Status(
1734       "Symbol file downloading not supported by the default platform.");
1735 }
1736 
1737 FileSpec Platform::GetModuleCacheRoot() {
1738   auto dir_spec = GetGlobalPlatformProperties().GetModuleCacheDirectory();
1739   dir_spec.AppendPathComponent(GetPluginName());
1740   return dir_spec;
1741 }
1742 
1743 const char *Platform::GetCacheHostname() { return GetHostname(); }
1744 
1745 const UnixSignalsSP &Platform::GetRemoteUnixSignals() {
1746   static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1747   return s_default_unix_signals_sp;
1748 }
1749 
1750 UnixSignalsSP Platform::GetUnixSignals() {
1751   if (IsHost())
1752     return UnixSignals::CreateForHost();
1753   return GetRemoteUnixSignals();
1754 }
1755 
1756 uint32_t Platform::LoadImage(lldb_private::Process *process,
1757                              const lldb_private::FileSpec &local_file,
1758                              const lldb_private::FileSpec &remote_file,
1759                              lldb_private::Status &error) {
1760   if (local_file && remote_file) {
1761     // Both local and remote file was specified. Install the local file to the
1762     // given location.
1763     if (IsRemote() || local_file != remote_file) {
1764       error = Install(local_file, remote_file);
1765       if (error.Fail())
1766         return LLDB_INVALID_IMAGE_TOKEN;
1767     }
1768     return DoLoadImage(process, remote_file, nullptr, error);
1769   }
1770 
1771   if (local_file) {
1772     // Only local file was specified. Install it to the current working
1773     // directory.
1774     FileSpec target_file = GetWorkingDirectory();
1775     target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1776     if (IsRemote() || local_file != target_file) {
1777       error = Install(local_file, target_file);
1778       if (error.Fail())
1779         return LLDB_INVALID_IMAGE_TOKEN;
1780     }
1781     return DoLoadImage(process, target_file, nullptr, error);
1782   }
1783 
1784   if (remote_file) {
1785     // Only remote file was specified so we don't have to do any copying
1786     return DoLoadImage(process, remote_file, nullptr, error);
1787   }
1788 
1789   error.SetErrorString("Neither local nor remote file was specified");
1790   return LLDB_INVALID_IMAGE_TOKEN;
1791 }
1792 
1793 uint32_t Platform::DoLoadImage(lldb_private::Process *process,
1794                                const lldb_private::FileSpec &remote_file,
1795                                const std::vector<std::string> *paths,
1796                                lldb_private::Status &error,
1797                                lldb_private::FileSpec *loaded_image) {
1798   error.SetErrorString("LoadImage is not supported on the current platform");
1799   return LLDB_INVALID_IMAGE_TOKEN;
1800 }
1801 
1802 uint32_t Platform::LoadImageUsingPaths(lldb_private::Process *process,
1803                                const lldb_private::FileSpec &remote_filename,
1804                                const std::vector<std::string> &paths,
1805                                lldb_private::Status &error,
1806                                lldb_private::FileSpec *loaded_path)
1807 {
1808   FileSpec file_to_use;
1809   if (remote_filename.IsAbsolute())
1810     file_to_use = FileSpec(remote_filename.GetFilename().GetStringRef(),
1811 
1812                            remote_filename.GetPathStyle());
1813   else
1814     file_to_use = remote_filename;
1815 
1816   return DoLoadImage(process, file_to_use, &paths, error, loaded_path);
1817 }
1818 
1819 Status Platform::UnloadImage(lldb_private::Process *process,
1820                              uint32_t image_token) {
1821   return Status("UnloadImage is not supported on the current platform");
1822 }
1823 
1824 lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
1825                                          llvm::StringRef plugin_name,
1826                                          Debugger &debugger, Target *target,
1827                                          Status &error) {
1828   return DoConnectProcess(connect_url, plugin_name, debugger, nullptr, target,
1829                           error);
1830 }
1831 
1832 lldb::ProcessSP Platform::ConnectProcessSynchronous(
1833     llvm::StringRef connect_url, llvm::StringRef plugin_name,
1834     Debugger &debugger, Stream &stream, Target *target, Status &error) {
1835   return DoConnectProcess(connect_url, plugin_name, debugger, &stream, target,
1836                           error);
1837 }
1838 
1839 lldb::ProcessSP Platform::DoConnectProcess(llvm::StringRef connect_url,
1840                                            llvm::StringRef plugin_name,
1841                                            Debugger &debugger, Stream *stream,
1842                                            Target *target, Status &error) {
1843   error.Clear();
1844 
1845   if (!target) {
1846     ArchSpec arch;
1847     if (target && target->GetArchitecture().IsValid())
1848       arch = target->GetArchitecture();
1849     else
1850       arch = Target::GetDefaultArchitecture();
1851 
1852     const char *triple = "";
1853     if (arch.IsValid())
1854       triple = arch.GetTriple().getTriple().c_str();
1855 
1856     TargetSP new_target_sp;
1857     error = debugger.GetTargetList().CreateTarget(
1858         debugger, "", triple, eLoadDependentsNo, nullptr, new_target_sp);
1859     target = new_target_sp.get();
1860   }
1861 
1862   if (!target || error.Fail())
1863     return nullptr;
1864 
1865   lldb::ProcessSP process_sp =
1866       target->CreateProcess(debugger.GetListener(), plugin_name, nullptr, true);
1867 
1868   if (!process_sp)
1869     return nullptr;
1870 
1871   // If this private method is called with a stream we are synchronous.
1872   const bool synchronous = stream != nullptr;
1873 
1874   ListenerSP listener_sp(
1875       Listener::MakeListener("lldb.Process.ConnectProcess.hijack"));
1876   if (synchronous)
1877     process_sp->HijackProcessEvents(listener_sp);
1878 
1879   error = process_sp->ConnectRemote(connect_url);
1880   if (error.Fail()) {
1881     if (synchronous)
1882       process_sp->RestoreProcessEvents();
1883     return nullptr;
1884   }
1885 
1886   if (synchronous) {
1887     EventSP event_sp;
1888     process_sp->WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp,
1889                                      nullptr);
1890     process_sp->RestoreProcessEvents();
1891     bool pop_process_io_handler = false;
1892     Process::HandleProcessStateChangedEvent(event_sp, stream,
1893                                             pop_process_io_handler);
1894   }
1895 
1896   return process_sp;
1897 }
1898 
1899 size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
1900                                            lldb_private::Status &error) {
1901   error.Clear();
1902   return 0;
1903 }
1904 
1905 size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target,
1906                                                  BreakpointSite *bp_site) {
1907   ArchSpec arch = target.GetArchitecture();
1908   assert(arch.IsValid());
1909   const uint8_t *trap_opcode = nullptr;
1910   size_t trap_opcode_size = 0;
1911 
1912   switch (arch.GetMachine()) {
1913   case llvm::Triple::aarch64_32:
1914   case llvm::Triple::aarch64: {
1915     static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1916     trap_opcode = g_aarch64_opcode;
1917     trap_opcode_size = sizeof(g_aarch64_opcode);
1918   } break;
1919 
1920   case llvm::Triple::arc: {
1921     static const uint8_t g_hex_opcode[] = { 0xff, 0x7f };
1922     trap_opcode = g_hex_opcode;
1923     trap_opcode_size = sizeof(g_hex_opcode);
1924   } break;
1925 
1926   // TODO: support big-endian arm and thumb trap codes.
1927   case llvm::Triple::arm: {
1928     // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1929     // linux kernel does otherwise.
1930     static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1931     static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1932 
1933     lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
1934     AddressClass addr_class = AddressClass::eUnknown;
1935 
1936     if (bp_loc_sp) {
1937       addr_class = bp_loc_sp->GetAddress().GetAddressClass();
1938       if (addr_class == AddressClass::eUnknown &&
1939           (bp_loc_sp->GetAddress().GetFileAddress() & 1))
1940         addr_class = AddressClass::eCodeAlternateISA;
1941     }
1942 
1943     if (addr_class == AddressClass::eCodeAlternateISA) {
1944       trap_opcode = g_thumb_breakpoint_opcode;
1945       trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1946     } else {
1947       trap_opcode = g_arm_breakpoint_opcode;
1948       trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1949     }
1950   } break;
1951 
1952   case llvm::Triple::avr: {
1953     static const uint8_t g_hex_opcode[] = {0x98, 0x95};
1954     trap_opcode = g_hex_opcode;
1955     trap_opcode_size = sizeof(g_hex_opcode);
1956   } break;
1957 
1958   case llvm::Triple::mips:
1959   case llvm::Triple::mips64: {
1960     static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1961     trap_opcode = g_hex_opcode;
1962     trap_opcode_size = sizeof(g_hex_opcode);
1963   } break;
1964 
1965   case llvm::Triple::mipsel:
1966   case llvm::Triple::mips64el: {
1967     static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1968     trap_opcode = g_hex_opcode;
1969     trap_opcode_size = sizeof(g_hex_opcode);
1970   } break;
1971 
1972   case llvm::Triple::systemz: {
1973     static const uint8_t g_hex_opcode[] = {0x00, 0x01};
1974     trap_opcode = g_hex_opcode;
1975     trap_opcode_size = sizeof(g_hex_opcode);
1976   } break;
1977 
1978   case llvm::Triple::hexagon: {
1979     static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
1980     trap_opcode = g_hex_opcode;
1981     trap_opcode_size = sizeof(g_hex_opcode);
1982   } break;
1983 
1984   case llvm::Triple::ppc:
1985   case llvm::Triple::ppc64: {
1986     static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
1987     trap_opcode = g_ppc_opcode;
1988     trap_opcode_size = sizeof(g_ppc_opcode);
1989   } break;
1990 
1991   case llvm::Triple::ppc64le: {
1992     static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1993     trap_opcode = g_ppc64le_opcode;
1994     trap_opcode_size = sizeof(g_ppc64le_opcode);
1995   } break;
1996 
1997   case llvm::Triple::x86:
1998   case llvm::Triple::x86_64: {
1999     static const uint8_t g_i386_opcode[] = {0xCC};
2000     trap_opcode = g_i386_opcode;
2001     trap_opcode_size = sizeof(g_i386_opcode);
2002   } break;
2003 
2004   default:
2005     return 0;
2006   }
2007 
2008   assert(bp_site);
2009   if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
2010     return trap_opcode_size;
2011 
2012   return 0;
2013 }
2014 
2015 CompilerType Platform::GetSiginfoType(const llvm::Triple& triple) {
2016   return CompilerType();
2017 }
2018