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