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

source code of lldb/source/Target/Platform.cpp