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