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