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