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 PlatformProperties &Platform::GetGlobalPlatformProperties() {
159 static PlatformProperties g_settings;
160 return g_settings;
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 return HostInfo::GetOSBuildString(s);
501 return GetRemoteOSBuildString(s);
502 }
503
GetOSKernelDescription(std::string & s)504 bool Platform::GetOSKernelDescription(std::string &s) {
505 if (IsHost())
506 return HostInfo::GetOSKernelDescription(s);
507 return GetRemoteOSKernelDescription(s);
508 }
509
AddClangModuleCompilationOptions(Target * target,std::vector<std::string> & options)510 void Platform::AddClangModuleCompilationOptions(
511 Target *target, std::vector<std::string> &options) {
512 std::vector<std::string> default_compilation_options = {
513 "-x", "c++", "-Xclang", "-nostdsysteminc", "-Xclang", "-nostdsysteminc"};
514
515 options.insert(options.end(), default_compilation_options.begin(),
516 default_compilation_options.end());
517 }
518
GetWorkingDirectory()519 FileSpec Platform::GetWorkingDirectory() {
520 if (IsHost()) {
521 llvm::SmallString<64> cwd;
522 if (llvm::sys::fs::current_path(cwd))
523 return {};
524 else {
525 FileSpec file_spec(cwd);
526 FileSystem::Instance().Resolve(file_spec);
527 return file_spec;
528 }
529 } else {
530 if (!m_working_dir)
531 m_working_dir = GetRemoteWorkingDirectory();
532 return m_working_dir;
533 }
534 }
535
536 struct RecurseCopyBaton {
537 const FileSpec &dst;
538 Platform *platform_ptr;
539 Status error;
540 };
541
542 static FileSystem::EnumerateDirectoryResult
RecurseCopy_Callback(void * baton,llvm::sys::fs::file_type ft,llvm::StringRef path)543 RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft,
544 llvm::StringRef path) {
545 RecurseCopyBaton *rc_baton = (RecurseCopyBaton *)baton;
546 FileSpec src(path);
547 namespace fs = llvm::sys::fs;
548 switch (ft) {
549 case fs::file_type::fifo_file:
550 case fs::file_type::socket_file:
551 // we have no way to copy pipes and sockets - ignore them and continue
552 return FileSystem::eEnumerateDirectoryResultNext;
553 break;
554
555 case fs::file_type::directory_file: {
556 // make the new directory and get in there
557 FileSpec dst_dir = rc_baton->dst;
558 if (!dst_dir.GetFilename())
559 dst_dir.GetFilename() = src.GetLastPathComponent();
560 Status error = rc_baton->platform_ptr->MakeDirectory(
561 dst_dir, lldb::eFilePermissionsDirectoryDefault);
562 if (error.Fail()) {
563 rc_baton->error.SetErrorStringWithFormat(
564 "unable to setup directory %s on remote end", dst_dir.GetCString());
565 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
566 }
567
568 // now recurse
569 std::string src_dir_path(src.GetPath());
570
571 // Make a filespec that only fills in the directory of a FileSpec so when
572 // we enumerate we can quickly fill in the filename for dst copies
573 FileSpec recurse_dst;
574 recurse_dst.GetDirectory().SetCString(dst_dir.GetPath().c_str());
575 RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr,
576 Status()};
577 FileSystem::Instance().EnumerateDirectory(src_dir_path, true, true, true,
578 RecurseCopy_Callback, &rc_baton2);
579 if (rc_baton2.error.Fail()) {
580 rc_baton->error.SetErrorString(rc_baton2.error.AsCString());
581 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
582 }
583 return FileSystem::eEnumerateDirectoryResultNext;
584 } break;
585
586 case fs::file_type::symlink_file: {
587 // copy the file and keep going
588 FileSpec dst_file = rc_baton->dst;
589 if (!dst_file.GetFilename())
590 dst_file.GetFilename() = src.GetFilename();
591
592 FileSpec src_resolved;
593
594 rc_baton->error = FileSystem::Instance().Readlink(src, src_resolved);
595
596 if (rc_baton->error.Fail())
597 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
598
599 rc_baton->error =
600 rc_baton->platform_ptr->CreateSymlink(dst_file, src_resolved);
601
602 if (rc_baton->error.Fail())
603 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
604
605 return FileSystem::eEnumerateDirectoryResultNext;
606 } break;
607
608 case fs::file_type::regular_file: {
609 // copy the file and keep going
610 FileSpec dst_file = rc_baton->dst;
611 if (!dst_file.GetFilename())
612 dst_file.GetFilename() = src.GetFilename();
613 Status err = rc_baton->platform_ptr->PutFile(src, dst_file);
614 if (err.Fail()) {
615 rc_baton->error.SetErrorString(err.AsCString());
616 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
617 }
618 return FileSystem::eEnumerateDirectoryResultNext;
619 } break;
620
621 default:
622 rc_baton->error.SetErrorStringWithFormat(
623 "invalid file detected during copy: %s", src.GetPath().c_str());
624 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
625 break;
626 }
627 llvm_unreachable("Unhandled file_type!");
628 }
629
Install(const FileSpec & src,const FileSpec & dst)630 Status Platform::Install(const FileSpec &src, const FileSpec &dst) {
631 Status error;
632
633 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
634 LLDB_LOGF(log, "Platform::Install (src='%s', dst='%s')",
635 src.GetPath().c_str(), dst.GetPath().c_str());
636 FileSpec fixed_dst(dst);
637
638 if (!fixed_dst.GetFilename())
639 fixed_dst.GetFilename() = src.GetFilename();
640
641 FileSpec working_dir = GetWorkingDirectory();
642
643 if (dst) {
644 if (dst.GetDirectory()) {
645 const char first_dst_dir_char = dst.GetDirectory().GetCString()[0];
646 if (first_dst_dir_char == '/' || first_dst_dir_char == '\\') {
647 fixed_dst.GetDirectory() = dst.GetDirectory();
648 }
649 // If the fixed destination file doesn't have a directory yet, then we
650 // must have a relative path. We will resolve this relative path against
651 // the platform's working directory
652 if (!fixed_dst.GetDirectory()) {
653 FileSpec relative_spec;
654 std::string path;
655 if (working_dir) {
656 relative_spec = working_dir;
657 relative_spec.AppendPathComponent(dst.GetPath());
658 fixed_dst.GetDirectory() = relative_spec.GetDirectory();
659 } else {
660 error.SetErrorStringWithFormat(
661 "platform working directory must be valid for relative path '%s'",
662 dst.GetPath().c_str());
663 return error;
664 }
665 }
666 } else {
667 if (working_dir) {
668 fixed_dst.GetDirectory().SetCString(working_dir.GetCString());
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("platform working directory must be valid "
681 "when destination directory is empty");
682 return error;
683 }
684 }
685
686 LLDB_LOGF(log, "Platform::Install (src='%s', dst='%s') fixed_dst='%s'",
687 src.GetPath().c_str(), dst.GetPath().c_str(),
688 fixed_dst.GetPath().c_str());
689
690 if (GetSupportsRSync()) {
691 error = PutFile(src, dst);
692 } else {
693 namespace fs = llvm::sys::fs;
694 switch (fs::get_file_type(src.GetPath(), false)) {
695 case fs::file_type::directory_file: {
696 llvm::sys::fs::remove(fixed_dst.GetPath());
697 uint32_t permissions = FileSystem::Instance().GetPermissions(src);
698 if (permissions == 0)
699 permissions = eFilePermissionsDirectoryDefault;
700 error = MakeDirectory(fixed_dst, permissions);
701 if (error.Success()) {
702 // Make a filespec that only fills in the directory of a FileSpec so
703 // when we enumerate we can quickly fill in the filename for dst copies
704 FileSpec recurse_dst;
705 recurse_dst.GetDirectory().SetCString(fixed_dst.GetCString());
706 std::string src_dir_path(src.GetPath());
707 RecurseCopyBaton baton = {recurse_dst, this, Status()};
708 FileSystem::Instance().EnumerateDirectory(
709 src_dir_path, true, true, true, RecurseCopy_Callback, &baton);
710 return baton.error;
711 }
712 } break;
713
714 case fs::file_type::regular_file:
715 llvm::sys::fs::remove(fixed_dst.GetPath());
716 error = PutFile(src, fixed_dst);
717 break;
718
719 case fs::file_type::symlink_file: {
720 llvm::sys::fs::remove(fixed_dst.GetPath());
721 FileSpec src_resolved;
722 error = FileSystem::Instance().Readlink(src, src_resolved);
723 if (error.Success())
724 error = CreateSymlink(dst, src_resolved);
725 } break;
726 case fs::file_type::fifo_file:
727 error.SetErrorString("platform install doesn't handle pipes");
728 break;
729 case fs::file_type::socket_file:
730 error.SetErrorString("platform install doesn't handle sockets");
731 break;
732 default:
733 error.SetErrorString(
734 "platform install doesn't handle non file or directory items");
735 break;
736 }
737 }
738 return error;
739 }
740
SetWorkingDirectory(const FileSpec & file_spec)741 bool Platform::SetWorkingDirectory(const FileSpec &file_spec) {
742 if (IsHost()) {
743 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
744 LLDB_LOG(log, "{0}", file_spec);
745 if (std::error_code ec = llvm::sys::fs::set_current_path(file_spec.GetPath())) {
746 LLDB_LOG(log, "error: {0}", ec.message());
747 return false;
748 }
749 return true;
750 } else {
751 m_working_dir.Clear();
752 return SetRemoteWorkingDirectory(file_spec);
753 }
754 }
755
MakeDirectory(const FileSpec & file_spec,uint32_t permissions)756 Status Platform::MakeDirectory(const FileSpec &file_spec,
757 uint32_t permissions) {
758 if (IsHost())
759 return llvm::sys::fs::create_directory(file_spec.GetPath(), permissions);
760 else {
761 Status error;
762 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
763 GetPluginName().GetCString(),
764 LLVM_PRETTY_FUNCTION);
765 return error;
766 }
767 }
768
GetFilePermissions(const FileSpec & file_spec,uint32_t & file_permissions)769 Status Platform::GetFilePermissions(const FileSpec &file_spec,
770 uint32_t &file_permissions) {
771 if (IsHost()) {
772 auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath());
773 if (Value)
774 file_permissions = Value.get();
775 return Status(Value.getError());
776 } else {
777 Status error;
778 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
779 GetPluginName().GetCString(),
780 LLVM_PRETTY_FUNCTION);
781 return error;
782 }
783 }
784
SetFilePermissions(const FileSpec & file_spec,uint32_t file_permissions)785 Status Platform::SetFilePermissions(const FileSpec &file_spec,
786 uint32_t file_permissions) {
787 if (IsHost()) {
788 auto Perms = static_cast<llvm::sys::fs::perms>(file_permissions);
789 return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms);
790 } else {
791 Status error;
792 error.SetErrorStringWithFormat("remote platform %s doesn't support %s",
793 GetPluginName().GetCString(),
794 LLVM_PRETTY_FUNCTION);
795 return error;
796 }
797 }
798
GetName()799 ConstString Platform::GetName() { return GetPluginName(); }
800
GetHostname()801 const char *Platform::GetHostname() {
802 if (IsHost())
803 return "127.0.0.1";
804
805 if (m_name.empty())
806 return nullptr;
807 return m_name.c_str();
808 }
809
GetFullNameForDylib(ConstString basename)810 ConstString Platform::GetFullNameForDylib(ConstString basename) {
811 return basename;
812 }
813
SetRemoteWorkingDirectory(const FileSpec & working_dir)814 bool Platform::SetRemoteWorkingDirectory(const FileSpec &working_dir) {
815 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
816 LLDB_LOGF(log, "Platform::SetRemoteWorkingDirectory('%s')",
817 working_dir.GetCString());
818 m_working_dir = working_dir;
819 return true;
820 }
821
SetOSVersion(llvm::VersionTuple version)822 bool Platform::SetOSVersion(llvm::VersionTuple version) {
823 if (IsHost()) {
824 // We don't need anyone setting the OS version for the host platform, we
825 // should be able to figure it out by calling HostInfo::GetOSVersion(...).
826 return false;
827 } else {
828 // We have a remote platform, allow setting the target OS version if we
829 // aren't connected, since if we are connected, we should be able to
830 // request the remote OS version from the connected platform.
831 if (IsConnected())
832 return false;
833 else {
834 // We aren't connected and we might want to set the OS version ahead of
835 // time before we connect so we can peruse files and use a local SDK or
836 // PDK cache of support files to disassemble or do other things.
837 m_os_version = version;
838 return true;
839 }
840 }
841 return false;
842 }
843
844 Status
ResolveExecutable(const ModuleSpec & module_spec,lldb::ModuleSP & exe_module_sp,const FileSpecList * module_search_paths_ptr)845 Platform::ResolveExecutable(const ModuleSpec &module_spec,
846 lldb::ModuleSP &exe_module_sp,
847 const FileSpecList *module_search_paths_ptr) {
848 Status error;
849 if (FileSystem::Instance().Exists(module_spec.GetFileSpec())) {
850 if (module_spec.GetArchitecture().IsValid()) {
851 error = ModuleList::GetSharedModule(module_spec, exe_module_sp,
852 module_search_paths_ptr, nullptr,
853 nullptr);
854 } else {
855 // No valid architecture was specified, ask the platform for the
856 // architectures that we should be using (in the correct order) and see
857 // if we can find a match that way
858 ModuleSpec arch_module_spec(module_spec);
859 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
860 idx, arch_module_spec.GetArchitecture());
861 ++idx) {
862 error = ModuleList::GetSharedModule(arch_module_spec, exe_module_sp,
863 module_search_paths_ptr, nullptr,
864 nullptr);
865 // Did we find an executable using one of the
866 if (error.Success() && exe_module_sp)
867 break;
868 }
869 }
870 } else {
871 error.SetErrorStringWithFormat("'%s' does not exist",
872 module_spec.GetFileSpec().GetPath().c_str());
873 }
874 return error;
875 }
876
ResolveSymbolFile(Target & target,const ModuleSpec & sym_spec,FileSpec & sym_file)877 Status Platform::ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec,
878 FileSpec &sym_file) {
879 Status error;
880 if (FileSystem::Instance().Exists(sym_spec.GetSymbolFileSpec()))
881 sym_file = sym_spec.GetSymbolFileSpec();
882 else
883 error.SetErrorString("unable to resolve symbol file");
884 return error;
885 }
886
ResolveRemotePath(const FileSpec & platform_path,FileSpec & resolved_platform_path)887 bool Platform::ResolveRemotePath(const FileSpec &platform_path,
888 FileSpec &resolved_platform_path) {
889 resolved_platform_path = platform_path;
890 FileSystem::Instance().Resolve(resolved_platform_path);
891 return true;
892 }
893
GetSystemArchitecture()894 const ArchSpec &Platform::GetSystemArchitecture() {
895 if (IsHost()) {
896 if (!m_system_arch.IsValid()) {
897 // We have a local host platform
898 m_system_arch = HostInfo::GetArchitecture();
899 m_system_arch_set_while_connected = m_system_arch.IsValid();
900 }
901 } else {
902 // We have a remote platform. We can only fetch the remote system
903 // architecture if we are connected, and we don't want to do it more than
904 // once.
905
906 const bool is_connected = IsConnected();
907
908 bool fetch = false;
909 if (m_system_arch.IsValid()) {
910 // We have valid OS version info, check to make sure it wasn't manually
911 // set prior to connecting. If it was manually set prior to connecting,
912 // then lets fetch the actual OS version info if we are now connected.
913 if (is_connected && !m_system_arch_set_while_connected)
914 fetch = true;
915 } else {
916 // We don't have valid OS version info, fetch it if we are connected
917 fetch = is_connected;
918 }
919
920 if (fetch) {
921 m_system_arch = GetRemoteSystemArchitecture();
922 m_system_arch_set_while_connected = m_system_arch.IsValid();
923 }
924 }
925 return m_system_arch;
926 }
927
GetAugmentedArchSpec(llvm::StringRef triple)928 ArchSpec Platform::GetAugmentedArchSpec(llvm::StringRef triple) {
929 if (triple.empty())
930 return ArchSpec();
931 llvm::Triple normalized_triple(llvm::Triple::normalize(triple));
932 if (!ArchSpec::ContainsOnlyArch(normalized_triple))
933 return ArchSpec(triple);
934
935 if (auto kind = HostInfo::ParseArchitectureKind(triple))
936 return HostInfo::GetArchitecture(*kind);
937
938 ArchSpec compatible_arch;
939 ArchSpec raw_arch(triple);
940 if (!IsCompatibleArchitecture(raw_arch, false, &compatible_arch))
941 return raw_arch;
942
943 if (!compatible_arch.IsValid())
944 return ArchSpec(normalized_triple);
945
946 const llvm::Triple &compatible_triple = compatible_arch.GetTriple();
947 if (normalized_triple.getVendorName().empty())
948 normalized_triple.setVendor(compatible_triple.getVendor());
949 if (normalized_triple.getOSName().empty())
950 normalized_triple.setOS(compatible_triple.getOS());
951 if (normalized_triple.getEnvironmentName().empty())
952 normalized_triple.setEnvironment(compatible_triple.getEnvironment());
953 return ArchSpec(normalized_triple);
954 }
955
ConnectRemote(Args & args)956 Status Platform::ConnectRemote(Args &args) {
957 Status error;
958 if (IsHost())
959 error.SetErrorStringWithFormat("The currently selected platform (%s) is "
960 "the host platform and is always connected.",
961 GetPluginName().GetCString());
962 else
963 error.SetErrorStringWithFormat(
964 "Platform::ConnectRemote() is not supported by %s",
965 GetPluginName().GetCString());
966 return error;
967 }
968
DisconnectRemote()969 Status Platform::DisconnectRemote() {
970 Status error;
971 if (IsHost())
972 error.SetErrorStringWithFormat("The currently selected platform (%s) is "
973 "the host platform and is always connected.",
974 GetPluginName().GetCString());
975 else
976 error.SetErrorStringWithFormat(
977 "Platform::DisconnectRemote() is not supported by %s",
978 GetPluginName().GetCString());
979 return error;
980 }
981
GetProcessInfo(lldb::pid_t pid,ProcessInstanceInfo & process_info)982 bool Platform::GetProcessInfo(lldb::pid_t pid,
983 ProcessInstanceInfo &process_info) {
984 // Take care of the host case so that each subclass can just call this
985 // function to get the host functionality.
986 if (IsHost())
987 return Host::GetProcessInfo(pid, process_info);
988 return false;
989 }
990
FindProcesses(const ProcessInstanceInfoMatch & match_info,ProcessInstanceInfoList & process_infos)991 uint32_t Platform::FindProcesses(const ProcessInstanceInfoMatch &match_info,
992 ProcessInstanceInfoList &process_infos) {
993 // Take care of the host case so that each subclass can just call this
994 // function to get the host functionality.
995 uint32_t match_count = 0;
996 if (IsHost())
997 match_count = Host::FindProcesses(match_info, process_infos);
998 return match_count;
999 }
1000
LaunchProcess(ProcessLaunchInfo & launch_info)1001 Status Platform::LaunchProcess(ProcessLaunchInfo &launch_info) {
1002 Status error;
1003 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1004 LLDB_LOGF(log, "Platform::%s()", __FUNCTION__);
1005
1006 // Take care of the host case so that each subclass can just call this
1007 // function to get the host functionality.
1008 if (IsHost()) {
1009 if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
1010 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
1011
1012 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInShell)) {
1013 const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1014 const bool first_arg_is_full_shell_command = false;
1015 uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info);
1016 if (log) {
1017 const FileSpec &shell = launch_info.GetShell();
1018 std::string shell_str = (shell) ? shell.GetPath() : "<null>";
1019 LLDB_LOGF(log,
1020 "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32
1021 ", shell is '%s'",
1022 __FUNCTION__, num_resumes, shell_str.c_str());
1023 }
1024
1025 if (!launch_info.ConvertArgumentsForLaunchingInShell(
1026 error, will_debug, first_arg_is_full_shell_command, num_resumes))
1027 return error;
1028 } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1029 error = ShellExpandArguments(launch_info);
1030 if (error.Fail()) {
1031 error.SetErrorStringWithFormat("shell expansion failed (reason: %s). "
1032 "consider launching with 'process "
1033 "launch'.",
1034 error.AsCString("unknown"));
1035 return error;
1036 }
1037 }
1038
1039 LLDB_LOGF(log, "Platform::%s final launch_info resume count: %" PRIu32,
1040 __FUNCTION__, launch_info.GetResumeCount());
1041
1042 error = Host::LaunchProcess(launch_info);
1043 } else
1044 error.SetErrorString(
1045 "base lldb_private::Platform class can't launch remote processes");
1046 return error;
1047 }
1048
ShellExpandArguments(ProcessLaunchInfo & launch_info)1049 Status Platform::ShellExpandArguments(ProcessLaunchInfo &launch_info) {
1050 if (IsHost())
1051 return Host::ShellExpandArguments(launch_info);
1052 return Status("base lldb_private::Platform class can't expand arguments");
1053 }
1054
KillProcess(const lldb::pid_t pid)1055 Status Platform::KillProcess(const lldb::pid_t pid) {
1056 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1057 LLDB_LOGF(log, "Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
1058
1059 // Try to find a process plugin to handle this Kill request. If we can't,
1060 // fall back to the default OS implementation.
1061 size_t num_debuggers = Debugger::GetNumDebuggers();
1062 for (size_t didx = 0; didx < num_debuggers; ++didx) {
1063 DebuggerSP debugger = Debugger::GetDebuggerAtIndex(didx);
1064 lldb_private::TargetList &targets = debugger->GetTargetList();
1065 for (int tidx = 0; tidx < targets.GetNumTargets(); ++tidx) {
1066 ProcessSP process = targets.GetTargetAtIndex(tidx)->GetProcessSP();
1067 if (process->GetID() == pid)
1068 return process->Destroy(true);
1069 }
1070 }
1071
1072 if (!IsHost()) {
1073 return Status(
1074 "base lldb_private::Platform class can't kill remote processes unless "
1075 "they are controlled by a process plugin");
1076 }
1077 Host::Kill(pid, SIGTERM);
1078 return Status();
1079 }
1080
DebugProcess(ProcessLaunchInfo & launch_info,Debugger & debugger,Target & target,Status & error)1081 lldb::ProcessSP Platform::DebugProcess(ProcessLaunchInfo &launch_info,
1082 Debugger &debugger, Target &target,
1083 Status &error) {
1084 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1085 LLDB_LOG(log, "target = {0})", &target);
1086
1087 ProcessSP process_sp;
1088 // Make sure we stop at the entry point
1089 launch_info.GetFlags().Set(eLaunchFlagDebug);
1090 // We always launch the process we are going to debug in a separate process
1091 // group, since then we can handle ^C interrupts ourselves w/o having to
1092 // worry about the target getting them as well.
1093 launch_info.SetLaunchInSeparateProcessGroup(true);
1094
1095 // Allow any StructuredData process-bound plugins to adjust the launch info
1096 // if needed
1097 size_t i = 0;
1098 bool iteration_complete = false;
1099 // Note iteration can't simply go until a nullptr callback is returned, as it
1100 // is valid for a plugin to not supply a filter.
1101 auto get_filter_func = PluginManager::GetStructuredDataFilterCallbackAtIndex;
1102 for (auto filter_callback = get_filter_func(i, iteration_complete);
1103 !iteration_complete;
1104 filter_callback = get_filter_func(++i, iteration_complete)) {
1105 if (filter_callback) {
1106 // Give this ProcessLaunchInfo filter a chance to adjust the launch info.
1107 error = (*filter_callback)(launch_info, &target);
1108 if (!error.Success()) {
1109 LLDB_LOGF(log,
1110 "Platform::%s() StructuredDataPlugin launch "
1111 "filter failed.",
1112 __FUNCTION__);
1113 return process_sp;
1114 }
1115 }
1116 }
1117
1118 error = LaunchProcess(launch_info);
1119 if (error.Success()) {
1120 LLDB_LOGF(log,
1121 "Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")",
1122 __FUNCTION__, launch_info.GetProcessID());
1123 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1124 ProcessAttachInfo attach_info(launch_info);
1125 process_sp = Attach(attach_info, debugger, &target, error);
1126 if (process_sp) {
1127 LLDB_LOGF(log, "Platform::%s Attach() succeeded, Process plugin: %s",
1128 __FUNCTION__, process_sp->GetPluginName().AsCString());
1129 launch_info.SetHijackListener(attach_info.GetHijackListener());
1130
1131 // Since we attached to the process, it will think it needs to detach
1132 // if the process object just goes away without an explicit call to
1133 // Process::Kill() or Process::Detach(), so let it know to kill the
1134 // process if this happens.
1135 process_sp->SetShouldDetach(false);
1136
1137 // If we didn't have any file actions, the pseudo terminal might have
1138 // been used where the secondary side was given as the file to open for
1139 // stdin/out/err after we have already opened the master so we can
1140 // read/write stdin/out/err.
1141 int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
1142 if (pty_fd != PseudoTerminal::invalid_fd) {
1143 process_sp->SetSTDIOFileDescriptor(pty_fd);
1144 }
1145 } else {
1146 LLDB_LOGF(log, "Platform::%s Attach() failed: %s", __FUNCTION__,
1147 error.AsCString());
1148 }
1149 } else {
1150 LLDB_LOGF(log,
1151 "Platform::%s LaunchProcess() returned launch_info with "
1152 "invalid process id",
1153 __FUNCTION__);
1154 }
1155 } else {
1156 LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
1157 error.AsCString());
1158 }
1159
1160 return process_sp;
1161 }
1162
1163 lldb::PlatformSP
GetPlatformForArchitecture(const ArchSpec & arch,ArchSpec * platform_arch_ptr)1164 Platform::GetPlatformForArchitecture(const ArchSpec &arch,
1165 ArchSpec *platform_arch_ptr) {
1166 lldb::PlatformSP platform_sp;
1167 Status error;
1168 if (arch.IsValid())
1169 platform_sp = Platform::Create(arch, platform_arch_ptr, error);
1170 return platform_sp;
1171 }
1172
1173 /// Lets a platform answer if it is compatible with a given
1174 /// architecture and the target triple contained within.
IsCompatibleArchitecture(const ArchSpec & arch,bool exact_arch_match,ArchSpec * compatible_arch_ptr)1175 bool Platform::IsCompatibleArchitecture(const ArchSpec &arch,
1176 bool exact_arch_match,
1177 ArchSpec *compatible_arch_ptr) {
1178 // If the architecture is invalid, we must answer true...
1179 if (arch.IsValid()) {
1180 ArchSpec platform_arch;
1181 // Try for an exact architecture match first.
1182 if (exact_arch_match) {
1183 for (uint32_t arch_idx = 0;
1184 GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1185 ++arch_idx) {
1186 if (arch.IsExactMatch(platform_arch)) {
1187 if (compatible_arch_ptr)
1188 *compatible_arch_ptr = platform_arch;
1189 return true;
1190 }
1191 }
1192 } else {
1193 for (uint32_t arch_idx = 0;
1194 GetSupportedArchitectureAtIndex(arch_idx, platform_arch);
1195 ++arch_idx) {
1196 if (arch.IsCompatibleMatch(platform_arch)) {
1197 if (compatible_arch_ptr)
1198 *compatible_arch_ptr = platform_arch;
1199 return true;
1200 }
1201 }
1202 }
1203 }
1204 if (compatible_arch_ptr)
1205 compatible_arch_ptr->Clear();
1206 return false;
1207 }
1208
PutFile(const FileSpec & source,const FileSpec & destination,uint32_t uid,uint32_t gid)1209 Status Platform::PutFile(const FileSpec &source, const FileSpec &destination,
1210 uint32_t uid, uint32_t gid) {
1211 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PLATFORM));
1212 LLDB_LOGF(log, "[PutFile] Using block by block transfer....\n");
1213
1214 auto source_open_options =
1215 File::eOpenOptionReadOnly | File::eOpenOptionCloseOnExec;
1216 namespace fs = llvm::sys::fs;
1217 if (fs::is_symlink_file(source.GetPath()))
1218 source_open_options |= File::eOpenOptionDontFollowSymlinks;
1219
1220 auto source_file = FileSystem::Instance().Open(source, source_open_options,
1221 lldb::eFilePermissionsUserRW);
1222 if (!source_file)
1223 return Status(source_file.takeError());
1224 Status error;
1225 uint32_t permissions = source_file.get()->GetPermissions(error);
1226 if (permissions == 0)
1227 permissions = lldb::eFilePermissionsFileDefault;
1228
1229 lldb::user_id_t dest_file = OpenFile(
1230 destination, File::eOpenOptionCanCreate | File::eOpenOptionWriteOnly |
1231 File::eOpenOptionTruncate | File::eOpenOptionCloseOnExec,
1232 permissions, error);
1233 LLDB_LOGF(log, "dest_file = %" PRIu64 "\n", dest_file);
1234
1235 if (error.Fail())
1236 return error;
1237 if (dest_file == UINT64_MAX)
1238 return Status("unable to open target file");
1239 lldb::DataBufferSP buffer_sp(new DataBufferHeap(1024 * 16, 0));
1240 uint64_t offset = 0;
1241 for (;;) {
1242 size_t bytes_read = buffer_sp->GetByteSize();
1243 error = source_file.get()->Read(buffer_sp->GetBytes(), bytes_read);
1244 if (error.Fail() || bytes_read == 0)
1245 break;
1246
1247 const uint64_t bytes_written =
1248 WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error);
1249 if (error.Fail())
1250 break;
1251
1252 offset += bytes_written;
1253 if (bytes_written != bytes_read) {
1254 // We didn't write the correct number of bytes, so adjust the file
1255 // position in the source file we are reading from...
1256 source_file.get()->SeekFromStart(offset);
1257 }
1258 }
1259 CloseFile(dest_file, error);
1260
1261 if (uid == UINT32_MAX && gid == UINT32_MAX)
1262 return error;
1263
1264 // TODO: ChownFile?
1265
1266 return error;
1267 }
1268
GetFile(const FileSpec & source,const FileSpec & destination)1269 Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) {
1270 Status error("unimplemented");
1271 return error;
1272 }
1273
1274 Status
CreateSymlink(const FileSpec & src,const FileSpec & dst)1275 Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1276 const FileSpec &dst) // The symlink points to dst
1277 {
1278 Status error("unimplemented");
1279 return error;
1280 }
1281
GetFileExists(const lldb_private::FileSpec & file_spec)1282 bool Platform::GetFileExists(const lldb_private::FileSpec &file_spec) {
1283 return false;
1284 }
1285
Unlink(const FileSpec & path)1286 Status Platform::Unlink(const FileSpec &path) {
1287 Status error("unimplemented");
1288 return error;
1289 }
1290
GetMmapArgumentList(const ArchSpec & arch,addr_t addr,addr_t length,unsigned prot,unsigned flags,addr_t fd,addr_t offset)1291 MmapArgList Platform::GetMmapArgumentList(const ArchSpec &arch, addr_t addr,
1292 addr_t length, unsigned prot,
1293 unsigned flags, addr_t fd,
1294 addr_t offset) {
1295 uint64_t flags_platform = 0;
1296 if (flags & eMmapFlagsPrivate)
1297 flags_platform |= MAP_PRIVATE;
1298 if (flags & eMmapFlagsAnon)
1299 flags_platform |= MAP_ANON;
1300
1301 MmapArgList args({addr, length, prot, flags_platform, fd, offset});
1302 return args;
1303 }
1304
RunShellCommand(llvm::StringRef command,const FileSpec & working_dir,int * status_ptr,int * signo_ptr,std::string * command_output,const Timeout<std::micro> & timeout)1305 lldb_private::Status Platform::RunShellCommand(
1306 llvm::StringRef command,
1307 const FileSpec &
1308 working_dir, // Pass empty FileSpec to use the current working directory
1309 int *status_ptr, // Pass nullptr if you don't want the process exit status
1310 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1311 // process to exit
1312 std::string
1313 *command_output, // Pass nullptr if you don't want the command output
1314 const Timeout<std::micro> &timeout) {
1315 return RunShellCommand(llvm::StringRef(), command, working_dir, status_ptr,
1316 signo_ptr, command_output, timeout);
1317 }
1318
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)1319 lldb_private::Status Platform::RunShellCommand(
1320 llvm::StringRef shell, // Pass empty if you want to use the default
1321 // shell interpreter
1322 llvm::StringRef command, // Shouldn't be empty
1323 const FileSpec &
1324 working_dir, // Pass empty FileSpec to use the current working directory
1325 int *status_ptr, // Pass nullptr if you don't want the process exit status
1326 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1327 // process to exit
1328 std::string
1329 *command_output, // Pass nullptr if you don't want the command output
1330 const Timeout<std::micro> &timeout) {
1331 if (IsHost())
1332 return Host::RunShellCommand(shell, command, working_dir, status_ptr,
1333 signo_ptr, command_output, timeout);
1334 else
1335 return Status("unimplemented");
1336 }
1337
CalculateMD5(const FileSpec & file_spec,uint64_t & low,uint64_t & high)1338 bool Platform::CalculateMD5(const FileSpec &file_spec, uint64_t &low,
1339 uint64_t &high) {
1340 if (!IsHost())
1341 return false;
1342 auto Result = llvm::sys::fs::md5_contents(file_spec.GetPath());
1343 if (!Result)
1344 return false;
1345 std::tie(high, low) = Result->words();
1346 return true;
1347 }
1348
SetLocalCacheDirectory(const char * local)1349 void Platform::SetLocalCacheDirectory(const char *local) {
1350 m_local_cache_directory.assign(local);
1351 }
1352
GetLocalCacheDirectory()1353 const char *Platform::GetLocalCacheDirectory() {
1354 return m_local_cache_directory.c_str();
1355 }
1356
1357 static constexpr OptionDefinition g_rsync_option_table[] = {
1358 {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
1359 {}, 0, eArgTypeNone, "Enable rsync."},
1360 {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
1361 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1362 "Platform-specific options required for rsync to work."},
1363 {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P',
1364 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypeCommandName,
1365 "Platform-specific rsync prefix put before the remote path."},
1366 {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i',
1367 OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
1368 "Do not automatically fill in the remote hostname when composing the "
1369 "rsync command."},
1370 };
1371
1372 static constexpr OptionDefinition g_ssh_option_table[] = {
1373 {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
1374 {}, 0, eArgTypeNone, "Enable SSH."},
1375 {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
1376 nullptr, {}, 0, eArgTypeCommandName,
1377 "Platform-specific options required for SSH to work."},
1378 };
1379
1380 static constexpr OptionDefinition g_caching_option_table[] = {
1381 {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
1382 OptionParser::eRequiredArgument, nullptr, {}, 0, eArgTypePath,
1383 "Path in which to store local copies of files."},
1384 };
1385
GetDefinitions()1386 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
1387 return llvm::makeArrayRef(g_rsync_option_table);
1388 }
1389
OptionParsingStarting(ExecutionContext * execution_context)1390 void OptionGroupPlatformRSync::OptionParsingStarting(
1391 ExecutionContext *execution_context) {
1392 m_rsync = false;
1393 m_rsync_opts.clear();
1394 m_rsync_prefix.clear();
1395 m_ignores_remote_hostname = false;
1396 }
1397
1398 lldb_private::Status
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)1399 OptionGroupPlatformRSync::SetOptionValue(uint32_t option_idx,
1400 llvm::StringRef option_arg,
1401 ExecutionContext *execution_context) {
1402 Status error;
1403 char short_option = (char)GetDefinitions()[option_idx].short_option;
1404 switch (short_option) {
1405 case 'r':
1406 m_rsync = true;
1407 break;
1408
1409 case 'R':
1410 m_rsync_opts.assign(std::string(option_arg));
1411 break;
1412
1413 case 'P':
1414 m_rsync_prefix.assign(std::string(option_arg));
1415 break;
1416
1417 case 'i':
1418 m_ignores_remote_hostname = true;
1419 break;
1420
1421 default:
1422 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1423 break;
1424 }
1425
1426 return error;
1427 }
1428
1429 lldb::BreakpointSP
SetThreadCreationBreakpoint(lldb_private::Target & target)1430 Platform::SetThreadCreationBreakpoint(lldb_private::Target &target) {
1431 return lldb::BreakpointSP();
1432 }
1433
GetDefinitions()1434 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
1435 return llvm::makeArrayRef(g_ssh_option_table);
1436 }
1437
OptionParsingStarting(ExecutionContext * execution_context)1438 void OptionGroupPlatformSSH::OptionParsingStarting(
1439 ExecutionContext *execution_context) {
1440 m_ssh = false;
1441 m_ssh_opts.clear();
1442 }
1443
1444 lldb_private::Status
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)1445 OptionGroupPlatformSSH::SetOptionValue(uint32_t option_idx,
1446 llvm::StringRef option_arg,
1447 ExecutionContext *execution_context) {
1448 Status error;
1449 char short_option = (char)GetDefinitions()[option_idx].short_option;
1450 switch (short_option) {
1451 case 's':
1452 m_ssh = true;
1453 break;
1454
1455 case 'S':
1456 m_ssh_opts.assign(std::string(option_arg));
1457 break;
1458
1459 default:
1460 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1461 break;
1462 }
1463
1464 return error;
1465 }
1466
GetDefinitions()1467 llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
1468 return llvm::makeArrayRef(g_caching_option_table);
1469 }
1470
OptionParsingStarting(ExecutionContext * execution_context)1471 void OptionGroupPlatformCaching::OptionParsingStarting(
1472 ExecutionContext *execution_context) {
1473 m_cache_dir.clear();
1474 }
1475
SetOptionValue(uint32_t option_idx,llvm::StringRef option_arg,ExecutionContext * execution_context)1476 lldb_private::Status OptionGroupPlatformCaching::SetOptionValue(
1477 uint32_t option_idx, llvm::StringRef option_arg,
1478 ExecutionContext *execution_context) {
1479 Status error;
1480 char short_option = (char)GetDefinitions()[option_idx].short_option;
1481 switch (short_option) {
1482 case 'c':
1483 m_cache_dir.assign(std::string(option_arg));
1484 break;
1485
1486 default:
1487 error.SetErrorStringWithFormat("unrecognized option '%c'", short_option);
1488 break;
1489 }
1490
1491 return error;
1492 }
1493
GetEnvironment()1494 Environment Platform::GetEnvironment() { return Environment(); }
1495
GetTrapHandlerSymbolNames()1496 const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1497 if (!m_calculated_trap_handlers) {
1498 std::lock_guard<std::mutex> guard(m_mutex);
1499 if (!m_calculated_trap_handlers) {
1500 CalculateTrapHandlerSymbolNames();
1501 m_calculated_trap_handlers = true;
1502 }
1503 }
1504 return m_trap_handlers;
1505 }
1506
GetCachedExecutable(ModuleSpec & module_spec,lldb::ModuleSP & module_sp,const FileSpecList * module_search_paths_ptr,Platform & remote_platform)1507 Status Platform::GetCachedExecutable(
1508 ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1509 const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1510 const auto platform_spec = module_spec.GetFileSpec();
1511 const auto error = LoadCachedExecutable(
1512 module_spec, module_sp, module_search_paths_ptr, remote_platform);
1513 if (error.Success()) {
1514 module_spec.GetFileSpec() = module_sp->GetFileSpec();
1515 module_spec.GetPlatformFileSpec() = platform_spec;
1516 }
1517
1518 return error;
1519 }
1520
LoadCachedExecutable(const ModuleSpec & module_spec,lldb::ModuleSP & module_sp,const FileSpecList * module_search_paths_ptr,Platform & remote_platform)1521 Status Platform::LoadCachedExecutable(
1522 const ModuleSpec &module_spec, lldb::ModuleSP &module_sp,
1523 const FileSpecList *module_search_paths_ptr, Platform &remote_platform) {
1524 return GetRemoteSharedModule(module_spec, nullptr, module_sp,
1525 [&](const ModuleSpec &spec) {
1526 return remote_platform.ResolveExecutable(
1527 spec, module_sp, module_search_paths_ptr);
1528 },
1529 nullptr);
1530 }
1531
GetRemoteSharedModule(const ModuleSpec & module_spec,Process * process,lldb::ModuleSP & module_sp,const ModuleResolver & module_resolver,bool * did_create_ptr)1532 Status Platform::GetRemoteSharedModule(const ModuleSpec &module_spec,
1533 Process *process,
1534 lldb::ModuleSP &module_sp,
1535 const ModuleResolver &module_resolver,
1536 bool *did_create_ptr) {
1537 // Get module information from a target.
1538 ModuleSpec resolved_module_spec;
1539 bool got_module_spec = false;
1540 if (process) {
1541 // Try to get module information from the process
1542 if (process->GetModuleSpec(module_spec.GetFileSpec(),
1543 module_spec.GetArchitecture(),
1544 resolved_module_spec)) {
1545 if (!module_spec.GetUUID().IsValid() ||
1546 module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1547 got_module_spec = true;
1548 }
1549 }
1550 }
1551
1552 if (!module_spec.GetArchitecture().IsValid()) {
1553 Status error;
1554 // No valid architecture was specified, ask the platform for the
1555 // architectures that we should be using (in the correct order) and see if
1556 // we can find a match that way
1557 ModuleSpec arch_module_spec(module_spec);
1558 for (uint32_t idx = 0; GetSupportedArchitectureAtIndex(
1559 idx, arch_module_spec.GetArchitecture());
1560 ++idx) {
1561 error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
1562 nullptr, nullptr);
1563 // Did we find an executable using one of the
1564 if (error.Success() && module_sp)
1565 break;
1566 }
1567 if (module_sp) {
1568 resolved_module_spec = arch_module_spec;
1569 got_module_spec = true;
1570 }
1571 }
1572
1573 if (!got_module_spec) {
1574 // Get module information from a target.
1575 if (GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1576 resolved_module_spec)) {
1577 if (!module_spec.GetUUID().IsValid() ||
1578 module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1579 got_module_spec = true;
1580 }
1581 }
1582 }
1583
1584 if (!got_module_spec) {
1585 // Fall back to the given module resolver, which may have its own
1586 // search logic.
1587 return module_resolver(module_spec);
1588 }
1589
1590 // If we are looking for a specific UUID, make sure resolved_module_spec has
1591 // the same one before we search.
1592 if (module_spec.GetUUID().IsValid()) {
1593 resolved_module_spec.GetUUID() = module_spec.GetUUID();
1594 }
1595
1596 // Trying to find a module by UUID on local file system.
1597 const auto error = module_resolver(resolved_module_spec);
1598 if (error.Fail()) {
1599 if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr))
1600 return Status();
1601 }
1602
1603 return error;
1604 }
1605
GetCachedSharedModule(const ModuleSpec & module_spec,lldb::ModuleSP & module_sp,bool * did_create_ptr)1606 bool Platform::GetCachedSharedModule(const ModuleSpec &module_spec,
1607 lldb::ModuleSP &module_sp,
1608 bool *did_create_ptr) {
1609 if (IsHost() || !GetGlobalPlatformProperties().GetUseModuleCache() ||
1610 !GetGlobalPlatformProperties().GetModuleCacheDirectory())
1611 return false;
1612
1613 Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM);
1614
1615 // Check local cache for a module.
1616 auto error = m_module_cache->GetAndPut(
1617 GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1618 [this](const ModuleSpec &module_spec,
1619 const FileSpec &tmp_download_file_spec) {
1620 return DownloadModuleSlice(
1621 module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1622 module_spec.GetObjectSize(), tmp_download_file_spec);
1623
1624 },
1625 [this](const ModuleSP &module_sp,
1626 const FileSpec &tmp_download_file_spec) {
1627 return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1628 },
1629 module_sp, did_create_ptr);
1630 if (error.Success())
1631 return true;
1632
1633 LLDB_LOGF(log, "Platform::%s - module %s not found in local cache: %s",
1634 __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1635 error.AsCString());
1636 return false;
1637 }
1638
DownloadModuleSlice(const FileSpec & src_file_spec,const uint64_t src_offset,const uint64_t src_size,const FileSpec & dst_file_spec)1639 Status Platform::DownloadModuleSlice(const FileSpec &src_file_spec,
1640 const uint64_t src_offset,
1641 const uint64_t src_size,
1642 const FileSpec &dst_file_spec) {
1643 Status error;
1644
1645 std::error_code EC;
1646 llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::OF_None);
1647 if (EC) {
1648 error.SetErrorStringWithFormat("unable to open destination file: %s",
1649 dst_file_spec.GetPath().c_str());
1650 return error;
1651 }
1652
1653 auto src_fd = OpenFile(src_file_spec, File::eOpenOptionReadOnly,
1654 lldb::eFilePermissionsFileDefault, error);
1655
1656 if (error.Fail()) {
1657 error.SetErrorStringWithFormat("unable to open source file: %s",
1658 error.AsCString());
1659 return error;
1660 }
1661
1662 std::vector<char> buffer(1024);
1663 auto offset = src_offset;
1664 uint64_t total_bytes_read = 0;
1665 while (total_bytes_read < src_size) {
1666 const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1667 src_size - total_bytes_read);
1668 const uint64_t n_read =
1669 ReadFile(src_fd, offset, &buffer[0], to_read, error);
1670 if (error.Fail())
1671 break;
1672 if (n_read == 0) {
1673 error.SetErrorString("read 0 bytes");
1674 break;
1675 }
1676 offset += n_read;
1677 total_bytes_read += n_read;
1678 dst.write(&buffer[0], n_read);
1679 }
1680
1681 Status close_error;
1682 CloseFile(src_fd, close_error); // Ignoring close error.
1683
1684 return error;
1685 }
1686
DownloadSymbolFile(const lldb::ModuleSP & module_sp,const FileSpec & dst_file_spec)1687 Status Platform::DownloadSymbolFile(const lldb::ModuleSP &module_sp,
1688 const FileSpec &dst_file_spec) {
1689 return Status(
1690 "Symbol file downloading not supported by the default platform.");
1691 }
1692
GetModuleCacheRoot()1693 FileSpec Platform::GetModuleCacheRoot() {
1694 auto dir_spec = GetGlobalPlatformProperties().GetModuleCacheDirectory();
1695 dir_spec.AppendPathComponent(GetName().AsCString());
1696 return dir_spec;
1697 }
1698
GetCacheHostname()1699 const char *Platform::GetCacheHostname() { return GetHostname(); }
1700
GetRemoteUnixSignals()1701 const UnixSignalsSP &Platform::GetRemoteUnixSignals() {
1702 static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1703 return s_default_unix_signals_sp;
1704 }
1705
GetUnixSignals()1706 UnixSignalsSP Platform::GetUnixSignals() {
1707 if (IsHost())
1708 return UnixSignals::CreateForHost();
1709 return GetRemoteUnixSignals();
1710 }
1711
LoadImage(lldb_private::Process * process,const lldb_private::FileSpec & local_file,const lldb_private::FileSpec & remote_file,lldb_private::Status & error)1712 uint32_t Platform::LoadImage(lldb_private::Process *process,
1713 const lldb_private::FileSpec &local_file,
1714 const lldb_private::FileSpec &remote_file,
1715 lldb_private::Status &error) {
1716 if (local_file && remote_file) {
1717 // Both local and remote file was specified. Install the local file to the
1718 // given location.
1719 if (IsRemote() || local_file != remote_file) {
1720 error = Install(local_file, remote_file);
1721 if (error.Fail())
1722 return LLDB_INVALID_IMAGE_TOKEN;
1723 }
1724 return DoLoadImage(process, remote_file, nullptr, error);
1725 }
1726
1727 if (local_file) {
1728 // Only local file was specified. Install it to the current working
1729 // directory.
1730 FileSpec target_file = GetWorkingDirectory();
1731 target_file.AppendPathComponent(local_file.GetFilename().AsCString());
1732 if (IsRemote() || local_file != target_file) {
1733 error = Install(local_file, target_file);
1734 if (error.Fail())
1735 return LLDB_INVALID_IMAGE_TOKEN;
1736 }
1737 return DoLoadImage(process, target_file, nullptr, error);
1738 }
1739
1740 if (remote_file) {
1741 // Only remote file was specified so we don't have to do any copying
1742 return DoLoadImage(process, remote_file, nullptr, error);
1743 }
1744
1745 error.SetErrorString("Neither local nor remote file was specified");
1746 return LLDB_INVALID_IMAGE_TOKEN;
1747 }
1748
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)1749 uint32_t Platform::DoLoadImage(lldb_private::Process *process,
1750 const lldb_private::FileSpec &remote_file,
1751 const std::vector<std::string> *paths,
1752 lldb_private::Status &error,
1753 lldb_private::FileSpec *loaded_image) {
1754 error.SetErrorString("LoadImage is not supported on the current platform");
1755 return LLDB_INVALID_IMAGE_TOKEN;
1756 }
1757
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)1758 uint32_t Platform::LoadImageUsingPaths(lldb_private::Process *process,
1759 const lldb_private::FileSpec &remote_filename,
1760 const std::vector<std::string> &paths,
1761 lldb_private::Status &error,
1762 lldb_private::FileSpec *loaded_path)
1763 {
1764 FileSpec file_to_use;
1765 if (remote_filename.IsAbsolute())
1766 file_to_use = FileSpec(remote_filename.GetFilename().GetStringRef(),
1767
1768 remote_filename.GetPathStyle());
1769 else
1770 file_to_use = remote_filename;
1771
1772 return DoLoadImage(process, file_to_use, &paths, error, loaded_path);
1773 }
1774
UnloadImage(lldb_private::Process * process,uint32_t image_token)1775 Status Platform::UnloadImage(lldb_private::Process *process,
1776 uint32_t image_token) {
1777 return Status("UnloadImage is not supported on the current platform");
1778 }
1779
ConnectProcess(llvm::StringRef connect_url,llvm::StringRef plugin_name,Debugger & debugger,Target * target,Status & error)1780 lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
1781 llvm::StringRef plugin_name,
1782 Debugger &debugger, Target *target,
1783 Status &error) {
1784 return DoConnectProcess(connect_url, plugin_name, debugger, nullptr, target,
1785 error);
1786 }
1787
ConnectProcessSynchronous(llvm::StringRef connect_url,llvm::StringRef plugin_name,Debugger & debugger,Stream & stream,Target * target,Status & error)1788 lldb::ProcessSP Platform::ConnectProcessSynchronous(
1789 llvm::StringRef connect_url, llvm::StringRef plugin_name,
1790 Debugger &debugger, Stream &stream, Target *target, Status &error) {
1791 return DoConnectProcess(connect_url, plugin_name, debugger, &stream, target,
1792 error);
1793 }
1794
DoConnectProcess(llvm::StringRef connect_url,llvm::StringRef plugin_name,Debugger & debugger,Stream * stream,Target * target,Status & error)1795 lldb::ProcessSP Platform::DoConnectProcess(llvm::StringRef connect_url,
1796 llvm::StringRef plugin_name,
1797 Debugger &debugger, Stream *stream,
1798 Target *target, Status &error) {
1799 error.Clear();
1800
1801 if (!target) {
1802 ArchSpec arch;
1803 if (target && target->GetArchitecture().IsValid())
1804 arch = target->GetArchitecture();
1805 else
1806 arch = Target::GetDefaultArchitecture();
1807
1808 const char *triple = "";
1809 if (arch.IsValid())
1810 triple = arch.GetTriple().getTriple().c_str();
1811
1812 TargetSP new_target_sp;
1813 error = debugger.GetTargetList().CreateTarget(
1814 debugger, "", triple, eLoadDependentsNo, nullptr, new_target_sp);
1815 target = new_target_sp.get();
1816 }
1817
1818 if (!target || error.Fail())
1819 return nullptr;
1820
1821 lldb::ProcessSP process_sp =
1822 target->CreateProcess(debugger.GetListener(), plugin_name, nullptr, true);
1823
1824 if (!process_sp)
1825 return nullptr;
1826
1827 // If this private method is called with a stream we are synchronous.
1828 const bool synchronous = stream != nullptr;
1829
1830 ListenerSP listener_sp(
1831 Listener::MakeListener("lldb.Process.ConnectProcess.hijack"));
1832 if (synchronous)
1833 process_sp->HijackProcessEvents(listener_sp);
1834
1835 error = process_sp->ConnectRemote(connect_url);
1836 if (error.Fail()) {
1837 if (synchronous)
1838 process_sp->RestoreProcessEvents();
1839 return nullptr;
1840 }
1841
1842 if (synchronous) {
1843 EventSP event_sp;
1844 process_sp->WaitForProcessToStop(llvm::None, &event_sp, true, listener_sp,
1845 nullptr);
1846 process_sp->RestoreProcessEvents();
1847 bool pop_process_io_handler = false;
1848 Process::HandleProcessStateChangedEvent(event_sp, stream,
1849 pop_process_io_handler);
1850 }
1851
1852 return process_sp;
1853 }
1854
ConnectToWaitingProcesses(lldb_private::Debugger & debugger,lldb_private::Status & error)1855 size_t Platform::ConnectToWaitingProcesses(lldb_private::Debugger &debugger,
1856 lldb_private::Status &error) {
1857 error.Clear();
1858 return 0;
1859 }
1860
GetSoftwareBreakpointTrapOpcode(Target & target,BreakpointSite * bp_site)1861 size_t Platform::GetSoftwareBreakpointTrapOpcode(Target &target,
1862 BreakpointSite *bp_site) {
1863 ArchSpec arch = target.GetArchitecture();
1864 assert(arch.IsValid());
1865 const uint8_t *trap_opcode = nullptr;
1866 size_t trap_opcode_size = 0;
1867
1868 switch (arch.GetMachine()) {
1869 case llvm::Triple::aarch64_32:
1870 case llvm::Triple::aarch64: {
1871 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
1872 trap_opcode = g_aarch64_opcode;
1873 trap_opcode_size = sizeof(g_aarch64_opcode);
1874 } break;
1875
1876 case llvm::Triple::arc: {
1877 static const uint8_t g_hex_opcode[] = { 0xff, 0x7f };
1878 trap_opcode = g_hex_opcode;
1879 trap_opcode_size = sizeof(g_hex_opcode);
1880 } break;
1881
1882 // TODO: support big-endian arm and thumb trap codes.
1883 case llvm::Triple::arm: {
1884 // The ARM reference recommends the use of 0xe7fddefe and 0xdefe but the
1885 // linux kernel does otherwise.
1886 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
1887 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
1888
1889 lldb::BreakpointLocationSP bp_loc_sp(bp_site->GetOwnerAtIndex(0));
1890 AddressClass addr_class = AddressClass::eUnknown;
1891
1892 if (bp_loc_sp) {
1893 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
1894 if (addr_class == AddressClass::eUnknown &&
1895 (bp_loc_sp->GetAddress().GetFileAddress() & 1))
1896 addr_class = AddressClass::eCodeAlternateISA;
1897 }
1898
1899 if (addr_class == AddressClass::eCodeAlternateISA) {
1900 trap_opcode = g_thumb_breakpoint_opcode;
1901 trap_opcode_size = sizeof(g_thumb_breakpoint_opcode);
1902 } else {
1903 trap_opcode = g_arm_breakpoint_opcode;
1904 trap_opcode_size = sizeof(g_arm_breakpoint_opcode);
1905 }
1906 } break;
1907
1908 case llvm::Triple::avr: {
1909 static const uint8_t g_hex_opcode[] = {0x98, 0x95};
1910 trap_opcode = g_hex_opcode;
1911 trap_opcode_size = sizeof(g_hex_opcode);
1912 } break;
1913
1914 case llvm::Triple::mips:
1915 case llvm::Triple::mips64: {
1916 static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
1917 trap_opcode = g_hex_opcode;
1918 trap_opcode_size = sizeof(g_hex_opcode);
1919 } break;
1920
1921 case llvm::Triple::mipsel:
1922 case llvm::Triple::mips64el: {
1923 static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
1924 trap_opcode = g_hex_opcode;
1925 trap_opcode_size = sizeof(g_hex_opcode);
1926 } break;
1927
1928 case llvm::Triple::systemz: {
1929 static const uint8_t g_hex_opcode[] = {0x00, 0x01};
1930 trap_opcode = g_hex_opcode;
1931 trap_opcode_size = sizeof(g_hex_opcode);
1932 } break;
1933
1934 case llvm::Triple::hexagon: {
1935 static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
1936 trap_opcode = g_hex_opcode;
1937 trap_opcode_size = sizeof(g_hex_opcode);
1938 } break;
1939
1940 case llvm::Triple::ppc:
1941 case llvm::Triple::ppc64: {
1942 static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
1943 trap_opcode = g_ppc_opcode;
1944 trap_opcode_size = sizeof(g_ppc_opcode);
1945 } break;
1946
1947 case llvm::Triple::ppc64le: {
1948 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
1949 trap_opcode = g_ppc64le_opcode;
1950 trap_opcode_size = sizeof(g_ppc64le_opcode);
1951 } break;
1952
1953 case llvm::Triple::x86:
1954 case llvm::Triple::x86_64: {
1955 static const uint8_t g_i386_opcode[] = {0xCC};
1956 trap_opcode = g_i386_opcode;
1957 trap_opcode_size = sizeof(g_i386_opcode);
1958 } break;
1959
1960 default:
1961 return 0;
1962 }
1963
1964 assert(bp_site);
1965 if (bp_site->SetTrapOpcode(trap_opcode, trap_opcode_size))
1966 return trap_opcode_size;
1967
1968 return 0;
1969 }
1970