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