LLDB mainline
Platform.cpp
Go to the documentation of this file.
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
18#include "lldb/Core/Debugger.h"
19#include "lldb/Core/Module.h"
22#include "lldb/Host/FileCache.h"
24#include "lldb/Host/Host.h"
25#include "lldb/Host/HostInfo.h"
37#include "lldb/Target/Process.h"
38#include "lldb/Target/Target.h"
43#include "lldb/Utility/Log.h"
44#include "lldb/Utility/Status.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/STLExtras.h"
49#include "llvm/Support/FileSystem.h"
50#include "llvm/Support/FormatVariadic.h"
51#include "llvm/Support/Path.h"
52
53// Define these constants from POSIX mman.h rather than include the file so
54// that they will be correct even when compiled on Linux.
55#define MAP_PRIVATE 2
56#define MAP_ANON 0x1000
57
58using namespace lldb;
59using namespace lldb_private;
60
61// Use a singleton function for g_local_platform_sp to avoid init constructors
62// since LLDB is often part of a shared library
64 static PlatformSP g_platform_sp;
65 return g_platform_sp;
66}
67
68const char *Platform::GetHostPlatformName() { return "host"; }
69
70namespace {
71
72#define LLDB_PROPERTIES_platform
73#include "TargetProperties.inc"
74
75enum {
76#define LLDB_PROPERTIES_platform
77#include "TargetPropertiesEnum.inc"
78};
79
80} // namespace
81
83 static constexpr llvm::StringLiteral g_setting_name("platform");
84 return g_setting_name;
86
88 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
89 m_collection_sp->Initialize(g_platform_properties_def);
90
91 auto module_cache_dir = GetModuleCacheDirectory();
92 if (module_cache_dir)
93 return;
94
95 llvm::SmallString<64> user_home_dir;
96 if (!FileSystem::Instance().GetHomeDirectory(user_home_dir))
97 return;
98
99 module_cache_dir = FileSpec(user_home_dir.c_str());
100 module_cache_dir.AppendPathComponent(".lldb");
101 module_cache_dir.AppendPathComponent("module_cache");
102 SetDefaultModuleCacheDirectory(module_cache_dir);
103 SetModuleCacheDirectory(module_cache_dir);
104}
105
107 const auto idx = ePropertyUseModuleCache;
109 idx, g_platform_properties[idx].default_uint_value != 0);
110}
111
112bool PlatformProperties::SetUseModuleCache(bool use_module_cache) {
113 return SetPropertyAtIndex(ePropertyUseModuleCache, use_module_cache);
114}
115
117 return GetPropertyAtIndexAs<FileSpec>(ePropertyModuleCacheDirectory, {});
118}
119
121 return m_collection_sp->SetPropertyAtIndex(ePropertyModuleCacheDirectory,
122 dir_spec);
123}
124
126 const auto idx = ePropertyShellExpandTimeout;
127 uint64_t seconds = GetPropertyAtIndexAs<uint64_t>(
128 idx, g_platform_properties[idx].default_uint_value);
129 if (seconds == 0)
130 return std::nullopt;
131 return std::chrono::seconds(seconds);
132}
133
135 const FileSpec &dir_spec) {
136 auto f_spec_opt = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(
137 ePropertyModuleCacheDirectory);
138 assert(f_spec_opt);
139 f_spec_opt->SetDefaultValue(dir_spec);
140}
141
142/// Get the native host platform plug-in.
143///
144/// There should only be one of these for each host that LLDB runs
145/// upon that should be statically compiled in and registered using
146/// preprocessor macros or other similar build mechanisms.
147///
148/// This platform will be used as the default platform when launching
149/// or attaching to processes unless another platform is specified.
151
153
155
157 static PlatformProperties g_settings;
158 return g_settings;
159}
160
162 // The native platform should use its static void Platform::Initialize()
163 // function to register itself as the native platform.
164 GetHostPlatformSP() = platform_sp;
165}
166
168 const UUID *uuid_ptr, FileSpec &local_file) {
169 // Default to the local case
170 local_file = platform_file;
171 return Status();
172}
173
174bool Platform::IsSymbolFileTrusted(Module &module) { return false; }
175
178 const Target &target) {
179 LoadScriptFromSymFile default_load_style =
181
182 return target
184 .value_or(default_load_style);
185}
186
187llvm::SmallDenseMap<FileSpec, LoadScriptFromSymFile>
189 Stream &feedback_stream, FileSpec module_spec, const Target &target) {
190 assert(module_spec);
191 assert(target.GetDebugger().GetScriptInterpreter());
192
193 llvm::SmallDenseMap<FileSpec, LoadScriptFromSymFile> file_specs;
194
195 // For now only Python scripts supported for auto-loading.
197 return file_specs;
198
200 target.GetDebugger()
203 module_spec.GetFileNameStrippingExtension());
204
205 FileSpecList paths = target.GetSafeAutoLoadPaths();
206
207 // Iterate in reverse so we consider the latest appended path first.
208 for (FileSpec path : llvm::reverse(paths)) {
209 path.AppendPathComponent(sanitized_name.GetOriginalName());
210
211 // Resolve relative paths and '~'.
213
214 if (!FileSystem::Instance().Exists(path))
215 continue;
216
217 FileSpec script_fspec = path;
218 script_fspec.AppendPathComponent(
219 llvm::formatv("{0}.py", sanitized_name.GetSanitizedName()).str());
220
221 FileSpec orig_script_fspec = path;
222 orig_script_fspec.AppendPathComponent(
223 llvm::formatv("{0}.py", sanitized_name.GetOriginalName()).str());
224
225 WarnIfInvalidUnsanitizedScriptExists(feedback_stream, sanitized_name,
226 orig_script_fspec, script_fspec);
227
228 if (FileSystem::Instance().Exists(script_fspec)) {
229 LoadScriptFromSymFile load_style =
230 Platform::GetScriptLoadStyleForModule(module_spec, target);
231 file_specs.try_emplace(std::move(script_fspec), load_style);
232 }
233
234 // If we successfully found a directory in a safe auto-load path
235 // stop looking at any other paths.
236 break;
237 }
238
239 return file_specs;
240}
241
242llvm::SmallDenseMap<FileSpec, LoadScriptFromSymFile>
244 Target *target, Module &module, Stream &feedback_stream) {
245 llvm::SmallDenseMap<FileSpec, LoadScriptFromSymFile> empty;
246 return empty;
247}
248
249llvm::SmallDenseMap<FileSpec, LoadScriptFromSymFile>
251 Stream &feedback_stream) {
252 llvm::SmallDenseMap<FileSpec, LoadScriptFromSymFile> empty;
253 if (!target)
254 return empty;
255
256 // Give derived platforms a chance to locate scripting resources.
258 target, module, feedback_stream);
259 !fspecs.empty())
260 return fspecs;
261
262 const FileSpec &module_spec = module.GetFileSpec();
263 if (!module_spec)
264 return empty;
265
267 module_spec, *target);
268}
269
271 const ModuleSpec &module_spec, Target &target, ModuleSP &module_sp,
272 llvm::SmallVectorImpl<lldb::ModuleSP> *old_modules, bool *did_create_ptr) {
273 if (IsHost())
274 // Note: module_search_paths_ptr functionality is now handled internally
275 // by getting target from module_spec and calling
276 // target->GetExecutableSearchPaths()
277 return ModuleList::GetSharedModule(module_spec, module_sp, old_modules,
278 did_create_ptr);
279
280 // Module resolver lambda.
281 auto resolver = [&](const ModuleSpec &spec) {
283 ModuleSpec resolved_spec;
284 // Check if we have sysroot set.
285 if (!m_sdk_sysroot.empty()) {
286 // Prepend sysroot to module spec.
287 resolved_spec = spec;
289 // Try to get shared module with resolved spec.
290 error = ModuleList::GetSharedModule(resolved_spec, module_sp, old_modules,
291 did_create_ptr,
292 /*invoke_locate_callback=*/false);
293 }
294 // If we don't have sysroot or it didn't work then
295 // try original module spec.
296 if (!error.Success()) {
297 resolved_spec = spec;
298 error = ModuleList::GetSharedModule(resolved_spec, module_sp, old_modules,
299 did_create_ptr,
300 /*invoke_locate_callback=*/false);
301 }
302 if (error.Success() && module_sp)
303 module_sp->SetPlatformFileSpec(resolved_spec.GetFileSpec());
304 return error;
305 };
306
307 return GetRemoteSharedModule(module_spec, &target, module_sp, resolver,
308 did_create_ptr);
309}
310
311bool Platform::GetModuleSpec(const FileSpec &module_file_spec,
312 const ArchSpec &arch, ModuleSpec &module_spec) {
313 ModuleSpecList module_specs =
314 ObjectFile::GetModuleSpecifications(module_file_spec, 0, 0);
315
316 ModuleSpec matched_module_spec;
317 return module_specs.FindMatchingModuleSpec(ModuleSpec(module_file_spec, arch),
318 module_spec);
319}
320
321PlatformSP Platform::Create(llvm::StringRef name) {
322 lldb::PlatformSP platform_sp;
323 if (name == GetHostPlatformName())
324 return GetHostPlatform();
325
326 if (PlatformCreateInstance create_callback =
328 return create_callback(true, nullptr);
329 return nullptr;
330}
331
332ArchSpec Platform::GetAugmentedArchSpec(Platform *platform, llvm::StringRef triple) {
333 if (platform)
334 return platform->GetAugmentedArchSpec(triple);
335 return HostInfo::GetAugmentedArchSpec(triple);
336}
337
338/// Default Constructor
346 m_module_cache(std::make_unique<ModuleCache>()) {
347 Log *log = GetLog(LLDBLog::Object);
348 LLDB_LOGF(log, "%p Platform::Platform()", static_cast<void *>(this));
349}
350
351Platform::~Platform() = default;
352
354 strm.Format(" Platform: {0}\n", GetPluginName());
355
357 if (arch.IsValid()) {
358 if (!arch.GetTriple().str().empty()) {
359 strm.PutCString(" Triple: ");
360 arch.DumpTriple(strm.AsRawOstream());
361 strm.EOL();
362 }
363 }
364
365 llvm::VersionTuple os_version = GetOSVersion();
366 if (!os_version.empty()) {
367 strm.Format("OS Version: {0}", os_version.getAsString());
368
369 if (std::optional<std::string> s = GetOSBuildString())
370 strm.Format(" ({0})", *s);
371
372 strm.EOL();
373 }
374
375 if (IsHost()) {
376 strm.Printf(" Hostname: %s\n", GetHostname());
377 } else {
378 const bool is_connected = IsConnected();
379 if (is_connected)
380 strm.Printf(" Hostname: %s\n", GetHostname());
381 strm.Printf(" Connected: %s\n", is_connected ? "yes" : "no");
382 }
383
384 if (const std::string &sdk_root = GetSDKRootDirectory(); !sdk_root.empty())
385 strm.Format(" Sysroot: {0}\n", sdk_root);
386
387 if (GetWorkingDirectory()) {
388 strm.Printf("WorkingDir: %s\n", GetWorkingDirectory().GetPath().c_str());
389 }
390 if (!IsConnected())
391 return;
392
393 std::string specific_info(GetPlatformSpecificConnectionInformation());
394
395 if (!specific_info.empty())
396 strm.Printf("Platform-specific connection: %s\n", specific_info.c_str());
397
398 if (std::optional<std::string> s = GetOSKernelDescription())
399 strm.Format(" Kernel: {0}\n", *s);
400}
401
402llvm::VersionTuple Platform::GetOSVersion(Process *process) {
403 std::lock_guard<std::mutex> guard(m_mutex);
404
405 if (IsHost()) {
406 if (m_os_version.empty()) {
407 // We have a local host platform
408 m_os_version = HostInfo::GetOSVersion();
410 }
411 } else {
412 // We have a remote platform. We can only fetch the remote
413 // OS version if we are connected, and we don't want to do it
414 // more than once.
415
416 const bool is_connected = IsConnected();
417
418 bool fetch = false;
419 if (!m_os_version.empty()) {
420 // We have valid OS version info, check to make sure it wasn't manually
421 // set prior to connecting. If it was manually set prior to connecting,
422 // then lets fetch the actual OS version info if we are now connected.
423 if (is_connected && !m_os_version_set_while_connected)
424 fetch = true;
425 } else {
426 // We don't have valid OS version info, fetch it if we are connected
427 fetch = is_connected;
428 }
429
430 if (fetch)
432 }
433
434 if (!m_os_version.empty())
435 return m_os_version;
436 if (process) {
437 // Check with the process in case it can answer the question if a process
438 // was provided
439 return process->GetHostOSVersion();
440 }
441 return llvm::VersionTuple();
442}
443
444std::optional<std::string> Platform::GetOSBuildString() {
445 if (IsHost())
446 return HostInfo::GetOSBuildString();
447 return GetRemoteOSBuildString();
448}
449
450std::optional<std::string> Platform::GetOSKernelDescription() {
451 if (IsHost())
452 return HostInfo::GetOSKernelDescription();
454}
455
457 Target *target, std::vector<std::string> &options) {
458 std::vector<std::string> default_compilation_options = {
459 "-x", "c++", "-Xclang", "-nostdsysteminc", "-Xclang", "-nostdsysteminc"};
460
461 options.insert(options.end(), default_compilation_options.begin(),
462 default_compilation_options.end());
463}
464
466 if (IsHost()) {
467 llvm::SmallString<64> cwd;
468 if (llvm::sys::fs::current_path(cwd))
469 return {};
470 else {
471 FileSpec file_spec(cwd);
472 FileSystem::Instance().Resolve(file_spec);
473 return file_spec;
474 }
475 } else {
476 if (!m_working_dir)
478 return m_working_dir;
479 }
480}
481
487
489RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft,
490 llvm::StringRef path) {
491 RecurseCopyBaton *rc_baton = (RecurseCopyBaton *)baton;
492 FileSpec src(path);
493 namespace fs = llvm::sys::fs;
494 switch (ft) {
495 case fs::file_type::fifo_file:
496 case fs::file_type::socket_file:
497 // we have no way to copy pipes and sockets - ignore them and continue
499 break;
500
501 case fs::file_type::directory_file: {
502 // make the new directory and get in there
503 FileSpec dst_dir = rc_baton->dst;
504 if (dst_dir.GetFilename().empty())
505 dst_dir.SetFilename(src.GetFilename());
507 dst_dir, lldb::eFilePermissionsDirectoryDefault);
508 if (error.Fail()) {
510 "unable to setup directory {0} on remote end", dst_dir.GetPath());
511 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
512 }
513
514 // now recurse
515 std::string src_dir_path(src.GetPath());
516
517 // Make a filespec that only fills in the directory of a FileSpec so when
518 // we enumerate we can quickly fill in the filename for dst copies
519 FileSpec recurse_dst;
520 recurse_dst.SetDirectory(dst_dir.GetPath());
521 RecurseCopyBaton rc_baton2 = {recurse_dst, rc_baton->platform_ptr,
522 Status()};
523 FileSystem::Instance().EnumerateDirectory(src_dir_path, true, true, true,
524 RecurseCopy_Callback, &rc_baton2);
525 if (rc_baton2.error.Fail()) {
526 rc_baton->error = Status::FromErrorString(rc_baton2.error.AsCString());
527 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
528 }
530 } break;
531
532 case fs::file_type::symlink_file: {
533 // copy the file and keep going
534 FileSpec dst_file = rc_baton->dst;
535 if (dst_file.GetFilename().empty())
536 dst_file.SetFilename(src.GetFilename());
537
538 FileSpec src_resolved;
539
540 rc_baton->error = FileSystem::Instance().Readlink(src, src_resolved);
541
542 if (rc_baton->error.Fail())
543 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
545 rc_baton->error =
546 rc_baton->platform_ptr->CreateSymlink(dst_file, src_resolved);
547
548 if (rc_baton->error.Fail())
549 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
550
552 } break;
553
554 case fs::file_type::regular_file: {
555 // copy the file and keep going
556 FileSpec dst_file = rc_baton->dst;
557 if (dst_file.GetFilename().empty())
558 dst_file.SetFilename(src.GetFilename());
559 Status err = rc_baton->platform_ptr->PutFile(src, dst_file);
560 if (err.Fail()) {
561 rc_baton->error = Status::FromErrorString(err.AsCString());
562 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
563 }
565 } break;
566
567 default:
569 "invalid file detected during copy: %s", src.GetPath().c_str());
570 return FileSystem::eEnumerateDirectoryResultQuit; // got an error, bail out
571 break;
572 }
573 llvm_unreachable("Unhandled file_type!");
574}
575
576Status Platform::Install(const FileSpec &src, const FileSpec &dst) {
578
580 LLDB_LOGF(log, "Platform::Install (src='%s', dst='%s')",
581 src.GetPath().c_str(), dst.GetPath().c_str());
582 FileSpec fixed_dst(dst);
583
584 if (fixed_dst.GetFilename().empty())
585 fixed_dst.SetFilename(src.GetFilename());
586
587 FileSpec working_dir = GetWorkingDirectory();
588
589 if (dst) {
590 if (!dst.GetDirectory().empty()) {
591 const char first_dst_dir_char = dst.GetDirectory().front();
592 if (first_dst_dir_char == '/' || first_dst_dir_char == '\\') {
593 fixed_dst.SetDirectory(dst.GetDirectory());
594 }
595 // If the fixed destination file doesn't have a directory yet, then we
596 // must have a relative path. We will resolve this relative path against
597 // the platform's working directory
598 if (fixed_dst.GetDirectory().empty()) {
599 FileSpec relative_spec;
600 if (working_dir) {
601 relative_spec = working_dir;
602 relative_spec.AppendPathComponent(dst.GetPath());
603 fixed_dst.SetDirectory(relative_spec.GetDirectory());
604 } else {
606 "platform working directory must be valid for relative path '%s'",
607 dst.GetPath().c_str());
608 return error;
609 }
610 }
611 } else {
612 if (working_dir) {
613 fixed_dst.SetDirectory(working_dir.GetPath());
614 } else {
616 "platform working directory must be valid for relative path '%s'",
617 dst.GetPath().c_str());
618 return error;
619 }
620 }
621 } else {
622 if (working_dir) {
623 fixed_dst.SetDirectory(working_dir.GetPath());
624 } else {
625 error =
626 Status::FromErrorString("platform working directory must be valid "
627 "when destination directory is empty");
628 return error;
629 }
630 }
631
632 LLDB_LOGF(log, "Platform::Install (src='%s', dst='%s') fixed_dst='%s'",
633 src.GetPath().c_str(), dst.GetPath().c_str(),
634 fixed_dst.GetPath().c_str());
635
636 if (GetSupportsRSync()) {
637 error = PutFile(src, dst);
638 } else {
639 namespace fs = llvm::sys::fs;
640 switch (fs::get_file_type(src.GetPath(), false)) {
641 case fs::file_type::directory_file: {
642 llvm::sys::fs::remove(fixed_dst.GetPath());
643 uint32_t permissions = FileSystem::Instance().GetPermissions(src);
644 if (permissions == 0)
645 permissions = eFilePermissionsDirectoryDefault;
646 error = MakeDirectory(fixed_dst, permissions);
647 if (error.Success()) {
648 // Make a filespec that only fills in the directory of a FileSpec so
649 // when we enumerate we can quickly fill in the filename for dst copies
650 FileSpec recurse_dst;
651 recurse_dst.SetDirectory(fixed_dst.GetPath());
652 std::string src_dir_path(src.GetPath());
653 RecurseCopyBaton baton = {recurse_dst, this, Status()};
655 src_dir_path, true, true, true, RecurseCopy_Callback, &baton);
656 return std::move(baton.error);
657 }
658 } break;
659
660 case fs::file_type::regular_file:
661 llvm::sys::fs::remove(fixed_dst.GetPath());
662 error = PutFile(src, fixed_dst);
663 break;
664
665 case fs::file_type::symlink_file: {
666 llvm::sys::fs::remove(fixed_dst.GetPath());
667 FileSpec src_resolved;
668 error = FileSystem::Instance().Readlink(src, src_resolved);
669 if (error.Success())
670 error = CreateSymlink(dst, src_resolved);
671 } break;
672 case fs::file_type::fifo_file:
673 error = Status::FromErrorString("platform install doesn't handle pipes");
674 break;
675 case fs::file_type::socket_file:
676 error =
677 Status::FromErrorString("platform install doesn't handle sockets");
678 break;
679 default:
681 "platform install doesn't handle non file or directory items");
682 break;
683 }
684 }
685 return error;
686}
687
689 if (IsHost()) {
691 LLDB_LOG(log, "{0}", file_spec);
692 if (std::error_code ec = llvm::sys::fs::set_current_path(file_spec.GetPath())) {
693 LLDB_LOG(log, "error: {0}", ec.message());
694 return false;
695 }
696 return true;
697 } else {
698 m_working_dir.Clear();
699 return SetRemoteWorkingDirectory(file_spec);
700 }
701}
702
704 uint32_t permissions) {
705 if (IsHost())
706 return llvm::sys::fs::create_directory(file_spec.GetPath(), permissions);
707 else {
710 "remote platform {0} doesn't support {1}", GetPluginName(),
711 LLVM_PRETTY_FUNCTION);
712 return error;
713 }
714}
715
717 uint32_t &file_permissions) {
718 if (IsHost()) {
719 auto Value = llvm::sys::fs::getPermissions(file_spec.GetPath());
720 if (Value)
721 file_permissions = Value.get();
722 return Status(Value.getError());
723 } else {
726 "remote platform {0} doesn't support {1}", GetPluginName(),
727 LLVM_PRETTY_FUNCTION);
728 return error;
729 }
730}
731
733 uint32_t file_permissions) {
734 if (IsHost()) {
735 auto Perms = static_cast<llvm::sys::fs::perms>(file_permissions);
736 return llvm::sys::fs::setPermissions(file_spec.GetPath(), Perms);
737 } else {
740 "remote platform {0} doesn't support {1}", GetPluginName(),
741 LLVM_PRETTY_FUNCTION);
742 return error;
743 }
744}
745
747 File::OpenOptions flags, uint32_t mode,
748 Status &error) {
749 if (IsHost())
750 return FileCache::GetInstance().OpenFile(file_spec, flags, mode, error);
751 return UINT64_MAX;
752}
753
755 if (IsHost())
757 return false;
758}
759
761 if (!IsHost())
762 return UINT64_MAX;
763
764 uint64_t Size;
765 if (llvm::sys::fs::file_size(file_spec.GetPath(), Size))
766 return 0;
767 return Size;
768}
769
770uint64_t Platform::ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst,
771 uint64_t dst_len, Status &error) {
772 if (IsHost())
773 return FileCache::GetInstance().ReadFile(fd, offset, dst, dst_len, error);
775 "Platform::ReadFile() is not supported in the {0} platform",
776 GetPluginName());
777 return -1;
778}
779
780uint64_t Platform::WriteFile(lldb::user_id_t fd, uint64_t offset,
781 const void *src, uint64_t src_len, Status &error) {
782 if (IsHost())
783 return FileCache::GetInstance().WriteFile(fd, offset, src, src_len, error);
785 "Platform::WriteFile() is not supported in the {0} platform",
786 GetPluginName());
787 return -1;
788}
789
791 if (IsHost())
792 return HostInfo::GetUserIDResolver();
794}
795
797 if (IsHost())
798 return "127.0.0.1";
799
800 if (m_hostname.empty())
801 return nullptr;
802 return m_hostname.c_str();
803}
804
805std::string Platform::GetFullNameForDylib(llvm::StringRef basename) {
806 return basename.str();
807}
808
811 LLDB_LOGF(log, "Platform::SetRemoteWorkingDirectory('%s')",
812 working_dir.GetPath().c_str());
813 m_working_dir = working_dir;
814 return true;
815}
816
817bool Platform::SetOSVersion(llvm::VersionTuple version) {
818 if (IsHost()) {
819 // We don't need anyone setting the OS version for the host platform, we
820 // should be able to figure it out by calling HostInfo::GetOSVersion(...).
821 return false;
822 } else {
823 // We have a remote platform, allow setting the target OS version if we
824 // aren't connected, since if we are connected, we should be able to
825 // request the remote OS version from the connected platform.
826 if (IsConnected())
827 return false;
828 else {
829 // We aren't connected and we might want to set the OS version ahead of
830 // time before we connect so we can peruse files and use a local SDK or
831 // PDK cache of support files to disassemble or do other things.
832 m_os_version = version;
833 return true;
834 }
835 }
836 return false;
837}
838
840 lldb::ModuleSP &exe_module_sp) {
841
842 // We may connect to a process and use the provided executable (Don't use
843 // local $PATH).
844 ModuleSpec resolved_module_spec(module_spec);
845
846 // Resolve any executable within a bundle on MacOSX
847 Host::ResolveExecutableInBundle(resolved_module_spec.GetFileSpec());
848
849 if (!FileSystem::Instance().Exists(resolved_module_spec.GetFileSpec()) &&
850 !module_spec.GetUUID().IsValid())
852 "'{0}' does not exist", resolved_module_spec.GetFileSpec());
853
854 if (resolved_module_spec.GetArchitecture().IsValid() ||
855 resolved_module_spec.GetUUID().IsValid()) {
856 Status error = ModuleList::GetSharedModule(resolved_module_spec,
857 exe_module_sp, nullptr, nullptr);
858
859 if (exe_module_sp && exe_module_sp->GetObjectFile())
860 return error;
861 exe_module_sp.reset();
862 }
863 // No valid architecture was specified or the exact arch wasn't found.
864 // Ask the platform for the architectures that we should be using (in the
865 // correct order) and see if we can find a match that way.
866 StreamString arch_names;
867 llvm::ListSeparator LS;
868 ArchSpec process_host_arch;
870 for (const ArchSpec &arch : GetSupportedArchitectures(process_host_arch)) {
871 resolved_module_spec.GetArchitecture() = arch;
872
873 error = ModuleList::GetSharedModule(resolved_module_spec, exe_module_sp,
874 nullptr, nullptr);
875 if (error.Success()) {
876 if (exe_module_sp && exe_module_sp->GetObjectFile())
877 break;
878 error = Status::FromErrorString("no exe object file");
879 }
880
881 arch_names << LS << arch.GetArchitectureName();
882 }
883
884 if (exe_module_sp && error.Success())
885 return {};
886
887 if (!FileSystem::Instance().Readable(resolved_module_spec.GetFileSpec()))
889 "'{0}' is not readable", resolved_module_spec.GetFileSpec());
890
891 if (!ObjectFile::IsObjectFile(resolved_module_spec.GetFileSpec()))
893 "'{0}' is not a valid executable", resolved_module_spec.GetFileSpec());
894
896 "'{0}' doesn't contain any '{1}' platform architectures: {2}",
897 resolved_module_spec.GetFileSpec(), GetPluginName(),
898 arch_names.GetData());
899}
900
902 FileSpec &sym_file) {
904 if (FileSystem::Instance().Exists(sym_spec.GetSymbolFileSpec()))
905 sym_file = sym_spec.GetSymbolFileSpec();
906 else
907 error = Status::FromErrorString("unable to resolve symbol file");
908 return error;
909}
910
911bool Platform::ResolveRemotePath(const FileSpec &platform_path,
912 FileSpec &resolved_platform_path) {
913 resolved_platform_path = platform_path;
914 FileSystem::Instance().Resolve(resolved_platform_path);
915 return true;
916}
917
919 if (IsHost()) {
920 if (!m_system_arch.IsValid()) {
921 // We have a local host platform
922 m_system_arch = HostInfo::GetArchitecture();
924 }
925 } else {
926 // We have a remote platform. We can only fetch the remote system
927 // architecture if we are connected, and we don't want to do it more than
928 // once.
929
930 const bool is_connected = IsConnected();
931
932 bool fetch = false;
933 if (m_system_arch.IsValid()) {
934 // We have valid OS version info, check to make sure it wasn't manually
935 // set prior to connecting. If it was manually set prior to connecting,
936 // then lets fetch the actual OS version info if we are now connected.
937 if (is_connected && !m_system_arch_set_while_connected)
938 fetch = true;
939 } else {
940 // We don't have valid OS version info, fetch it if we are connected
941 fetch = is_connected;
942 }
943
944 if (fetch) {
947 }
948 }
949 return m_system_arch;
950}
951
953 if (triple.empty())
954 return ArchSpec();
955 llvm::Triple normalized_triple(llvm::Triple::normalize(triple));
956 if (!ArchSpec::ContainsOnlyArch(normalized_triple))
957 return ArchSpec(triple);
958
959 if (auto kind = HostInfo::ParseArchitectureKind(triple))
960 return HostInfo::GetArchitecture(*kind);
961
962 ArchSpec compatible_arch;
963 ArchSpec raw_arch(triple);
965 &compatible_arch))
966 return raw_arch;
967
968 if (!compatible_arch.IsValid())
969 return ArchSpec(normalized_triple);
970
971 const llvm::Triple &compatible_triple = compatible_arch.GetTriple();
972 if (normalized_triple.getVendorName().empty())
973 normalized_triple.setVendor(compatible_triple.getVendor());
974 if (normalized_triple.getOSName().empty())
975 normalized_triple.setOS(compatible_triple.getOS());
976 if (normalized_triple.getEnvironmentName().empty())
977 normalized_triple.setEnvironment(compatible_triple.getEnvironment());
978 return ArchSpec(normalized_triple);
979}
980
983 if (IsHost())
985 "The currently selected platform ({0}) is "
986 "the host platform and is always connected.",
987 GetPluginName());
988 else
990 "Platform::ConnectRemote() is not supported by {0}", GetPluginName());
991 return error;
992}
993
996 if (IsHost())
998 "The currently selected platform ({0}) is "
999 "the host platform and is always connected.",
1000 GetPluginName());
1001 else
1003 "Platform::DisconnectRemote() is not supported by {0}",
1004 GetPluginName());
1005 return error;
1006}
1007
1009 ProcessInstanceInfo &process_info) {
1010 // Take care of the host case so that each subclass can just call this
1011 // function to get the host functionality.
1012 if (IsHost())
1013 return Host::GetProcessInfo(pid, process_info);
1014 return false;
1015}
1016
1018 ProcessInstanceInfoList &process_infos) {
1019 // Take care of the host case so that each subclass can just call this
1020 // function to get the host functionality.
1021 uint32_t match_count = 0;
1022 if (IsHost())
1023 match_count = Host::FindProcesses(match_info, process_infos);
1024 return match_count;
1025}
1026
1028 ProcessInstanceInfoList processes;
1030 assert(match.MatchAllProcesses());
1031 FindProcesses(match, processes);
1032 return processes;
1033}
1034
1036 Status error;
1038 LLDB_LOGF(log, "Platform::%s()", __FUNCTION__);
1039
1040 // Take care of the host case so that each subclass can just call this
1041 // function to get the host functionality.
1042 if (IsHost()) {
1043 if (::getenv("LLDB_LAUNCH_FLAG_LAUNCH_IN_TTY"))
1044 launch_info.GetFlags().Set(eLaunchFlagLaunchInTTY);
1045
1046 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInShell)) {
1047 const bool will_debug = launch_info.GetFlags().Test(eLaunchFlagDebug);
1048 const bool first_arg_is_full_shell_command = false;
1049 uint32_t num_resumes = GetResumeCountForLaunchInfo(launch_info);
1050 if (log) {
1051 const FileSpec &shell = launch_info.GetShell();
1052 std::string shell_str = (shell) ? shell.GetPath() : "<null>";
1053 LLDB_LOGF(log,
1054 "Platform::%s GetResumeCountForLaunchInfo() returned %" PRIu32
1055 ", shell is '%s'",
1056 __FUNCTION__, num_resumes, shell_str.c_str());
1057 }
1058
1059 if (!launch_info.ConvertArgumentsForLaunchingInShell(
1060 error, will_debug, first_arg_is_full_shell_command, num_resumes))
1061 return error;
1062 } else if (launch_info.GetFlags().Test(eLaunchFlagShellExpandArguments)) {
1063 error = ShellExpandArguments(launch_info);
1064 if (error.Fail()) {
1066 "shell expansion failed (reason: %s). "
1067 "consider launching with 'process "
1068 "launch'.",
1069 error.AsCString("unknown"));
1070 return error;
1071 }
1072 }
1073
1074 LLDB_LOGF(log, "Platform::%s final launch_info resume count: %" PRIu32,
1075 __FUNCTION__, launch_info.GetResumeCount());
1076
1077 error = Host::LaunchProcess(launch_info);
1078 } else
1080 "base lldb_private::Platform class can't launch remote processes");
1081 return error;
1082}
1083
1085 if (IsHost())
1087 launch_info, GetGlobalPlatformProperties().GetShellExpandTimeout());
1089 "base lldb_private::Platform class can't expand arguments");
1090}
1091
1094 LLDB_LOGF(log, "Platform::%s, pid %" PRIu64, __FUNCTION__, pid);
1095
1096 if (!IsHost()) {
1098 "base lldb_private::Platform class can't kill remote processes");
1099 }
1100 Host::Kill(pid, SIGKILL);
1101 return Status();
1102}
1103
1105 Debugger &debugger, Target &target,
1106 Status &error) {
1108 LLDB_LOG(log, "target = {0}", &target);
1109
1110 ProcessSP process_sp;
1111 // Make sure we stop at the entry point
1112 launch_info.GetFlags().Set(eLaunchFlagDebug);
1113 // We always launch the process we are going to debug in a separate process
1114 // group, since then we can handle ^C interrupts ourselves w/o having to
1115 // worry about the target getting them as well.
1116 launch_info.SetLaunchInSeparateProcessGroup(true);
1117
1118 // Allow any StructuredData process-bound plugins to adjust the launch info
1119 // if needed
1121 if (cbs.filter_callback) {
1122 // Give this ProcessLaunchInfo filter a chance to adjust the launch info.
1123 error = (*cbs.filter_callback)(launch_info, &target);
1124 if (!error.Success()) {
1125 LLDB_LOGF(log,
1126 "Platform::%s() StructuredDataPlugin launch "
1127 "filter failed.",
1128 __FUNCTION__);
1129 return process_sp;
1130 }
1131 }
1132 }
1133
1134 error = LaunchProcess(launch_info);
1135 if (error.Success()) {
1136 LLDB_LOGF(log,
1137 "Platform::%s LaunchProcess() call succeeded (pid=%" PRIu64 ")",
1138 __FUNCTION__, launch_info.GetProcessID());
1139 if (launch_info.GetProcessID() != LLDB_INVALID_PROCESS_ID) {
1140 ProcessAttachInfo attach_info(launch_info);
1141 process_sp = Attach(attach_info, debugger, &target, error);
1142 if (process_sp) {
1143 LLDB_LOG(log, "Attach() succeeded, Process plugin: {0}",
1144 process_sp->GetPluginName());
1145 launch_info.SetHijackListener(attach_info.GetHijackListener());
1146
1147 // Since we attached to the process, it will think it needs to detach
1148 // if the process object just goes away without an explicit call to
1149 // Process::Kill() or Process::Detach(), so let it know to kill the
1150 // process if this happens.
1151 process_sp->SetShouldDetach(false);
1152
1153 // If we didn't have any file actions, the pseudo terminal might have
1154 // been used where the secondary side was given as the file to open for
1155 // stdin/out/err after we have already opened the primary so we can
1156 // read/write stdin/out/err.
1157#ifndef _WIN32
1158 int pty_fd = launch_info.GetPTY().ReleasePrimaryFileDescriptor();
1159 if (pty_fd != PseudoTerminal::invalid_fd) {
1160 process_sp->SetSTDIOFileDescriptor(pty_fd);
1161 }
1162#endif
1163 } else {
1164 LLDB_LOGF(log, "Platform::%s Attach() failed: %s", __FUNCTION__,
1165 error.AsCString());
1166 }
1167 } else {
1168 LLDB_LOGF(log,
1169 "Platform::%s LaunchProcess() returned launch_info with "
1170 "invalid process id",
1171 __FUNCTION__);
1172 }
1173 } else {
1174 LLDB_LOGF(log, "Platform::%s LaunchProcess() failed: %s", __FUNCTION__,
1175 error.AsCString());
1176 }
1177
1178 return process_sp;
1179}
1180
1181std::vector<ArchSpec>
1182Platform::CreateArchList(llvm::ArrayRef<llvm::Triple::ArchType> archs,
1183 llvm::Triple::OSType os) {
1184 std::vector<ArchSpec> list;
1185 for(auto arch : archs) {
1186 llvm::Triple triple;
1187 triple.setArch(arch);
1188 triple.setOS(os);
1189 list.push_back(ArchSpec(triple));
1190 }
1191 return list;
1192}
1193
1194/// Lets a platform answer if it is compatible with a given
1195/// architecture and the target triple contained within.
1197 const ArchSpec &process_host_arch,
1198 ArchSpec::MatchType match,
1199 ArchSpec *compatible_arch_ptr) {
1200 // If the architecture is invalid, we must answer true...
1201 if (arch.IsValid()) {
1202 ArchSpec platform_arch;
1203 for (const ArchSpec &platform_arch :
1204 GetSupportedArchitectures(process_host_arch)) {
1205 if (arch.IsMatch(platform_arch, match)) {
1206 if (compatible_arch_ptr)
1207 *compatible_arch_ptr = platform_arch;
1208 return true;
1209 }
1210 }
1211 }
1212 if (compatible_arch_ptr)
1213 compatible_arch_ptr->Clear();
1214 return false;
1215}
1216
1217Status Platform::PutFile(const FileSpec &source, const FileSpec &destination,
1218 uint32_t uid, uint32_t gid) {
1220 LLDB_LOGF(log, "[PutFile] Using block by block transfer....\n");
1221
1222 auto source_open_options =
1224 namespace fs = llvm::sys::fs;
1225 if (fs::is_symlink_file(source.GetPath()))
1226 source_open_options |= File::eOpenOptionDontFollowSymlinks;
1227
1228 auto source_file = FileSystem::Instance().Open(source, source_open_options,
1229 lldb::eFilePermissionsUserRW);
1230 if (!source_file)
1231 return Status::FromError(source_file.takeError());
1232 Status error;
1233
1234 bool requires_upload = true;
1235 llvm::ErrorOr<llvm::MD5::MD5Result> remote_md5 = CalculateMD5(destination);
1236 if (std::error_code ec = remote_md5.getError()) {
1237 LLDB_LOG(log, "[PutFile] couldn't get md5 sum of destination: {0}",
1238 ec.message());
1239 } else {
1240 llvm::ErrorOr<llvm::MD5::MD5Result> local_md5 =
1241 llvm::sys::fs::md5_contents(source.GetPath());
1242 if (std::error_code ec = local_md5.getError()) {
1243 LLDB_LOG(log, "[PutFile] couldn't get md5 sum of source: {0}",
1244 ec.message());
1245 } else {
1246 LLDB_LOGF(log, "[PutFile] destination md5: %016" PRIx64 "%016" PRIx64,
1247 remote_md5->high(), remote_md5->low());
1248 LLDB_LOGF(log, "[PutFile] local md5: %016" PRIx64 "%016" PRIx64,
1249 local_md5->high(), local_md5->low());
1250 requires_upload = *remote_md5 != *local_md5;
1251 }
1252 }
1253
1254 if (!requires_upload) {
1255 LLDB_LOGF(log, "[PutFile] skipping PutFile because md5sums match");
1256 return error;
1257 }
1258
1259 uint32_t permissions = source_file.get()->GetPermissions(error);
1260 if (permissions == 0)
1261 permissions = lldb::eFilePermissionsUserRWX;
1262
1263 lldb::user_id_t dest_file = OpenFile(
1266 permissions, error);
1267 LLDB_LOGF(log, "dest_file = %" PRIu64 "\n", dest_file);
1268
1269 if (error.Fail())
1270 return error;
1271 if (dest_file == UINT64_MAX)
1272 return Status::FromErrorString("unable to open target file");
1273 lldb::WritableDataBufferSP buffer_sp(new DataBufferHeap(1024 * 16, 0));
1274 uint64_t offset = 0;
1275 for (;;) {
1276 size_t bytes_read = buffer_sp->GetByteSize();
1277 error = source_file.get()->Read(buffer_sp->GetBytes(), bytes_read);
1278 if (error.Fail() || bytes_read == 0)
1279 break;
1280
1281 const uint64_t bytes_written =
1282 WriteFile(dest_file, offset, buffer_sp->GetBytes(), bytes_read, error);
1283 if (error.Fail())
1284 break;
1285
1286 offset += bytes_written;
1287 if (bytes_written != bytes_read) {
1288 // We didn't write the correct number of bytes, so adjust the file
1289 // position in the source file we are reading from...
1290 source_file.get()->SeekFromStart(offset);
1291 }
1292 }
1293 CloseFile(dest_file, error);
1294
1295 if (uid == UINT32_MAX && gid == UINT32_MAX)
1296 return error;
1297
1298 // TODO: ChownFile?
1299
1300 return error;
1301}
1302
1303Status Platform::GetFile(const FileSpec &source, const FileSpec &destination) {
1304 return Status::FromErrorString("unimplemented");
1305}
1306
1307Status
1308Platform::CreateSymlink(const FileSpec &src, // The name of the link is in src
1309 const FileSpec &dst) // The symlink points to dst
1310{
1311 if (IsHost())
1312 return FileSystem::Instance().Symlink(src, dst);
1313 return Status::FromErrorString("unimplemented");
1314}
1315
1317 if (IsHost())
1318 return FileSystem::Instance().Exists(file_spec);
1319 return false;
1320}
1321
1323 if (IsHost())
1324 return llvm::sys::fs::remove(path.GetPath());
1325 return Status::FromErrorString("unimplemented");
1326}
1327
1329 addr_t length, unsigned prot,
1330 unsigned flags, addr_t fd,
1331 addr_t offset) {
1332 uint64_t flags_platform = 0;
1333 if (flags & eMmapFlagsPrivate)
1334 flags_platform |= MAP_PRIVATE;
1335 if (flags & eMmapFlagsAnon)
1336 flags_platform |= MAP_ANON;
1337
1338 MmapArgList args({addr, length, prot, flags_platform, fd, offset});
1339 return args;
1340}
1341
1343 llvm::StringRef command,
1344 const FileSpec &
1345 working_dir, // Pass empty FileSpec to use the current working directory
1346 int *status_ptr, // Pass nullptr if you don't want the process exit status
1347 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1348 // process to exit
1349 std::string
1350 *command_output, // Pass nullptr if you don't want the command output
1351 std::string *separated_error_output, // Pass nullptr if you don't want the
1352 // command error output
1353 const Timeout<std::micro> &timeout) {
1354 return RunShellCommand(llvm::StringRef(), command, working_dir, status_ptr,
1355 signo_ptr, command_output, separated_error_output,
1356 timeout);
1357}
1358
1360 llvm::StringRef shell, // Pass empty if you want to use the default
1361 // shell interpreter
1362 llvm::StringRef command, // Shouldn't be empty
1363 const FileSpec &
1364 working_dir, // Pass empty FileSpec to use the current working directory
1365 int *status_ptr, // Pass nullptr if you don't want the process exit status
1366 int *signo_ptr, // Pass nullptr if you don't want the signal that caused the
1367 // process to exit
1368 std::string
1369 *command_output, // Pass nullptr if you don't want the command output
1370 std::string *separated_error_output, // Pass nullptr if you don't want the
1371 // command error output
1372 const Timeout<std::micro> &timeout) {
1373 if (IsHost())
1374 return Host::RunShellCommand(shell, command, working_dir, status_ptr,
1375 signo_ptr, command_output,
1376 separated_error_output, timeout);
1378 "unable to run a remote command without a platform");
1379}
1380
1381llvm::ErrorOr<llvm::MD5::MD5Result>
1383 if (!IsHost())
1384 return std::make_error_code(std::errc::not_supported);
1385 return llvm::sys::fs::md5_contents(file_spec.GetPath());
1386}
1387
1388void Platform::SetLocalCacheDirectory(const char *local) {
1389 m_local_cache_directory.assign(local);
1390}
1391
1393 return m_local_cache_directory.c_str();
1394}
1395
1397 {LLDB_OPT_SET_ALL, false, "rsync", 'r', OptionParser::eNoArgument, nullptr,
1398 {}, 0, eArgTypeNone, "Enable rsync."},
1399 {LLDB_OPT_SET_ALL, false, "rsync-opts", 'R',
1401 "Platform-specific options required for rsync to work."},
1402 {LLDB_OPT_SET_ALL, false, "rsync-prefix", 'P',
1404 "Platform-specific rsync prefix put before the remote path."},
1405 {LLDB_OPT_SET_ALL, false, "ignore-remote-hostname", 'i',
1406 OptionParser::eNoArgument, nullptr, {}, 0, eArgTypeNone,
1407 "Do not automatically fill in the remote hostname when composing the "
1408 "rsync command."},
1409};
1410
1412 {LLDB_OPT_SET_ALL, false, "ssh", 's', OptionParser::eNoArgument, nullptr,
1413 {}, 0, eArgTypeNone, "Enable SSH."},
1414 {LLDB_OPT_SET_ALL, false, "ssh-opts", 'S', OptionParser::eRequiredArgument,
1415 nullptr, {}, 0, eArgTypeCommandName,
1416 "Platform-specific options required for SSH to work."},
1417};
1418
1420 {LLDB_OPT_SET_ALL, false, "local-cache-dir", 'c',
1422 "Path in which to store local copies of files."},
1423};
1424
1425llvm::ArrayRef<OptionDefinition> OptionGroupPlatformRSync::GetDefinitions() {
1426 return llvm::ArrayRef(g_rsync_option_table);
1427}
1428
1430 ExecutionContext *execution_context) {
1431 m_rsync = false;
1432 m_rsync_opts.clear();
1433 m_rsync_prefix.clear();
1435}
1436
1439 llvm::StringRef option_arg,
1440 ExecutionContext *execution_context) {
1441 Status error;
1442 char short_option = (char)GetDefinitions()[option_idx].short_option;
1443 switch (short_option) {
1444 case 'r':
1445 m_rsync = true;
1446 break;
1447
1448 case 'R':
1449 m_rsync_opts.assign(std::string(option_arg));
1450 break;
1451
1452 case 'P':
1453 m_rsync_prefix.assign(std::string(option_arg));
1454 break;
1455
1456 case 'i':
1458 break;
1459
1460 default:
1461 error = Status::FromErrorStringWithFormat("unrecognized option '%c'",
1462 short_option);
1463 break;
1464 }
1465
1466 return error;
1467}
1468
1473
1474llvm::ArrayRef<OptionDefinition> OptionGroupPlatformSSH::GetDefinitions() {
1475 return llvm::ArrayRef(g_ssh_option_table);
1476}
1477
1479 ExecutionContext *execution_context) {
1480 m_ssh = false;
1481 m_ssh_opts.clear();
1482}
1483
1486 llvm::StringRef option_arg,
1487 ExecutionContext *execution_context) {
1488 Status error;
1489 char short_option = (char)GetDefinitions()[option_idx].short_option;
1490 switch (short_option) {
1491 case 's':
1492 m_ssh = true;
1493 break;
1494
1495 case 'S':
1496 m_ssh_opts.assign(std::string(option_arg));
1497 break;
1498
1499 default:
1500 error = Status::FromErrorStringWithFormat("unrecognized option '%c'",
1501 short_option);
1502 break;
1503 }
1504
1505 return error;
1506}
1507
1508llvm::ArrayRef<OptionDefinition> OptionGroupPlatformCaching::GetDefinitions() {
1509 return llvm::ArrayRef(g_caching_option_table);
1510}
1511
1513 ExecutionContext *execution_context) {
1514 m_cache_dir.clear();
1515}
1516
1518 uint32_t option_idx, llvm::StringRef option_arg,
1519 ExecutionContext *execution_context) {
1520 Status error;
1521 char short_option = (char)GetDefinitions()[option_idx].short_option;
1522 switch (short_option) {
1523 case 'c':
1524 m_cache_dir.assign(std::string(option_arg));
1525 break;
1526
1527 default:
1528 error = Status::FromErrorStringWithFormat("unrecognized option '%c'",
1529 short_option);
1530 break;
1531 }
1532
1533 return error;
1534}
1535
1537 if (IsHost())
1538 return Host::GetEnvironment();
1539 return Environment();
1540}
1541
1542const std::vector<ConstString> &Platform::GetTrapHandlerSymbolNames() {
1544 std::lock_guard<std::mutex> guard(m_mutex);
1548 }
1549 }
1550 return m_trap_handlers;
1551}
1552
1554 lldb::ModuleSP &module_sp) {
1555 FileSpec platform_spec = module_spec.GetFileSpec();
1557 module_spec, /*target=*/nullptr, module_sp,
1558 [&](const ModuleSpec &spec) {
1559 return Platform::ResolveExecutable(spec, module_sp);
1560 },
1561 nullptr);
1562 if (error.Success()) {
1563 module_spec.GetFileSpec() = module_sp->GetFileSpec();
1564 module_spec.GetPlatformFileSpec() = platform_spec;
1565 }
1566
1567 return error;
1568}
1569
1571 Target *target,
1572 lldb::ModuleSP &module_sp,
1573 const ModuleResolver &module_resolver,
1574 bool *did_create_ptr) {
1575 // Get module information from a target.
1576 ModuleSpec resolved_module_spec;
1577 ArchSpec process_host_arch;
1578 bool got_module_spec = false;
1579 if (Process *process = target ? target->GetProcessSP().get() : nullptr) {
1580 process_host_arch = process->GetSystemArchitecture();
1581 // Try to get module information from the process
1582 if (process->GetModuleSpec(module_spec.GetFileSpec(),
1583 module_spec.GetArchitecture(),
1584 resolved_module_spec)) {
1585 if (!module_spec.GetUUID().IsValid() ||
1586 module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1587 got_module_spec = true;
1588 }
1589 }
1590 }
1591
1592 if (!module_spec.GetArchitecture().IsValid()) {
1593 Status error;
1594 // No valid architecture was specified, ask the platform for the
1595 // architectures that we should be using (in the correct order) and see if
1596 // we can find a match that way
1597 ModuleSpec arch_module_spec(module_spec);
1598 for (const ArchSpec &arch : GetSupportedArchitectures(process_host_arch)) {
1599 arch_module_spec.GetArchitecture() = arch;
1600 error = ModuleList::GetSharedModule(arch_module_spec, module_sp, nullptr,
1601 nullptr);
1602 // Did we find an executable using one of the
1603 if (error.Success() && module_sp)
1604 break;
1605 }
1606 if (module_sp) {
1607 resolved_module_spec = arch_module_spec;
1608 got_module_spec = true;
1609 }
1610 }
1611
1612 if (!got_module_spec) {
1613 // Get module information from a target.
1614 if (GetModuleSpec(module_spec.GetFileSpec(), module_spec.GetArchitecture(),
1615 resolved_module_spec)) {
1616 if (!module_spec.GetUUID().IsValid() ||
1617 module_spec.GetUUID() == resolved_module_spec.GetUUID()) {
1618 got_module_spec = true;
1619 }
1620 }
1621 }
1622
1623 if (!got_module_spec) {
1624 // Fall back to the given module resolver, which may have its own
1625 // search logic.
1626 return module_resolver(module_spec);
1627 }
1628
1629 // If we are looking for a specific UUID, make sure resolved_module_spec has
1630 // the same one before we search.
1631 if (module_spec.GetUUID().IsValid()) {
1632 resolved_module_spec.GetUUID() = module_spec.GetUUID();
1633 }
1634
1635 // Retain the target context from the original module_spec since
1636 // process->GetModuleSpec might have cleared it.
1637 resolved_module_spec.SetTarget(module_spec.GetTargetSP());
1638
1639 // Call locate module callback if set. This allows users to implement their
1640 // own module cache system. For example, to leverage build system artifacts,
1641 // to bypass pulling files from remote platform, or to search symbol files
1642 // from symbol servers.
1643 FileSpec symbol_file_spec;
1644 CallLocateModuleCallbackIfSet(resolved_module_spec, module_sp,
1645 symbol_file_spec, did_create_ptr);
1646 if (module_sp) {
1647 // The module is loaded.
1648 if (symbol_file_spec) {
1649 // 1. module_sp:loaded, symbol_file_spec:set
1650 // The callback found a module file and a symbol file for this
1651 // resolved_module_spec. Set the symbol file to the module.
1652 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
1653 } else {
1654 // 2. module_sp:loaded, symbol_file_spec:empty
1655 // The callback only found a module file for this
1656 // resolved_module_spec.
1657 }
1658 return Status();
1659 }
1660
1661 // The module is not loaded by CallLocateModuleCallbackIfSet.
1662 // 3. module_sp:empty, symbol_file_spec:set
1663 // The callback only found a symbol file for the module. We continue to
1664 // find a module file for this resolved_module_spec. and we will call
1665 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
1666 // 4. module_sp:empty, symbol_file_spec:empty
1667 // The callback is not set. Or the callback did not find any module
1668 // files nor any symbol files. Or the callback failed, or something
1669 // went wrong. We continue to find a module file for this
1670 // resolved_module_spec.
1671
1672 // Trying to find a module by UUID on local file system.
1673 Status error = module_resolver(resolved_module_spec);
1674 if (error.Success()) {
1675 if (module_sp && symbol_file_spec) {
1676 // Set the symbol file to the module if the locate modudle callback was
1677 // called and returned only a symbol file.
1678 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
1679 }
1680 return error;
1681 }
1682
1683 // Fallback to call GetCachedSharedModule on failure.
1684 if (GetCachedSharedModule(resolved_module_spec, module_sp, did_create_ptr)) {
1685 if (module_sp && symbol_file_spec) {
1686 // Set the symbol file to the module if the locate modudle callback was
1687 // called and returned only a symbol file.
1688 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
1689 }
1690 return Status();
1691 }
1692
1694 "Failed to call GetCachedSharedModule");
1695}
1696
1698 lldb::ModuleSP &module_sp,
1699 FileSpec &symbol_file_spec,
1700 bool *did_create_ptr) {
1702 // Locate module callback is not set.
1703 return;
1704 }
1705
1706 FileSpec module_file_spec;
1707 Status error =
1708 m_locate_module_callback(module_spec, module_file_spec, symbol_file_spec);
1709
1710 // Locate module callback is set and called. Check the error.
1712 if (error.Fail()) {
1713 LLDB_LOGF(log, "%s: locate module callback failed: %s",
1714 LLVM_PRETTY_FUNCTION, error.AsCString());
1715 return;
1716 }
1717
1718 // The locate module callback was succeeded.
1719 // Check the module_file_spec and symbol_file_spec values.
1720 // 1. module:empty symbol:empty -> Failure
1721 // - The callback did not return any files.
1722 // 2. module:exists symbol:exists -> Success
1723 // - The callback returned a module file and a symbol file.
1724 // 3. module:exists symbol:empty -> Success
1725 // - The callback returned only a module file.
1726 // 4. module:empty symbol:exists -> Success
1727 // - The callback returned only a symbol file.
1728 // For example, a breakpad symbol text file.
1729 if (!module_file_spec && !symbol_file_spec) {
1730 // This is '1. module:empty symbol:empty -> Failure'
1731 // The callback did not return any files.
1732 LLDB_LOGF(log,
1733 "%s: locate module callback did not set both "
1734 "module_file_spec and symbol_file_spec",
1735 LLVM_PRETTY_FUNCTION);
1736 return;
1737 }
1738
1739 // If the callback returned a module file, it should exist.
1740 if (module_file_spec && !FileSystem::Instance().Exists(module_file_spec)) {
1741 LLDB_LOGF(log,
1742 "%s: locate module callback set a non-existent file to "
1743 "module_file_spec: %s",
1744 LLVM_PRETTY_FUNCTION, module_file_spec.GetPath().c_str());
1745 // Clear symbol_file_spec for the error.
1746 symbol_file_spec.Clear();
1747 return;
1748 }
1749
1750 // If the callback returned a symbol file, it should exist.
1751 if (symbol_file_spec && !FileSystem::Instance().Exists(symbol_file_spec)) {
1752 LLDB_LOGF(log,
1753 "%s: locate module callback set a non-existent file to "
1754 "symbol_file_spec: %s",
1755 LLVM_PRETTY_FUNCTION, symbol_file_spec.GetPath().c_str());
1756 // Clear symbol_file_spec for the error.
1757 symbol_file_spec.Clear();
1758 return;
1759 }
1760
1761 if (!module_file_spec && symbol_file_spec) {
1762 // This is '4. module:empty symbol:exists -> Success'
1763 // The locate module callback returned only a symbol file. For example,
1764 // a breakpad symbol text file. GetRemoteSharedModule will use this returned
1765 // symbol_file_spec.
1766 LLDB_LOGF(log, "%s: locate module callback succeeded: symbol=%s",
1767 LLVM_PRETTY_FUNCTION, symbol_file_spec.GetPath().c_str());
1768 return;
1769 }
1770
1771 // This is one of the following.
1772 // - 2. module:exists symbol:exists -> Success
1773 // - The callback returned a module file and a symbol file.
1774 // - 3. module:exists symbol:empty -> Success
1775 // - The callback returned Only a module file.
1776 // Load the module file.
1777 auto cached_module_spec(module_spec);
1778 cached_module_spec.GetUUID().Clear(); // Clear UUID since it may contain md5
1779 // content hash instead of real UUID.
1780 cached_module_spec.GetFileSpec() = module_file_spec;
1781 cached_module_spec.GetSymbolFileSpec() = symbol_file_spec;
1782 cached_module_spec.GetPlatformFileSpec() = module_spec.GetFileSpec();
1783 cached_module_spec.SetObjectOffset(0);
1784
1785 error = ModuleList::GetSharedModule(cached_module_spec, module_sp, nullptr,
1786 did_create_ptr, false);
1787 if (error.Success() && module_sp) {
1788 // Succeeded to load the module file.
1789 LLDB_LOGF(log, "%s: locate module callback succeeded: module=%s symbol=%s",
1790 LLVM_PRETTY_FUNCTION, module_file_spec.GetPath().c_str(),
1791 symbol_file_spec.GetPath().c_str());
1792 } else {
1793 LLDB_LOGF(log,
1794 "%s: locate module callback succeeded but failed to load: "
1795 "module=%s symbol=%s",
1796 LLVM_PRETTY_FUNCTION, module_file_spec.GetPath().c_str(),
1797 symbol_file_spec.GetPath().c_str());
1798 // Clear module_sp and symbol_file_spec for the error.
1799 module_sp.reset();
1800 symbol_file_spec.Clear();
1801 }
1802}
1803
1805 lldb::ModuleSP &module_sp,
1806 bool *did_create_ptr) {
1807 if (IsHost() || !GetGlobalPlatformProperties().GetUseModuleCache() ||
1808 !GetGlobalPlatformProperties().GetModuleCacheDirectory())
1809 return false;
1810
1812
1813 // Check local cache for a module.
1814 auto error = m_module_cache->GetAndPut(
1815 GetModuleCacheRoot(), GetCacheHostname(), module_spec,
1816 [this](const ModuleSpec &module_spec,
1817 const FileSpec &tmp_download_file_spec) {
1818 return DownloadModuleSlice(
1819 module_spec.GetFileSpec(), module_spec.GetObjectOffset(),
1820 module_spec.GetObjectSize(), tmp_download_file_spec);
1821
1822 },
1823 [this](const ModuleSP &module_sp,
1824 const FileSpec &tmp_download_file_spec) {
1825 return DownloadSymbolFile(module_sp, tmp_download_file_spec);
1826 },
1827 module_sp, did_create_ptr);
1828 if (error.Success())
1829 return true;
1830
1831 LLDB_LOGF(log, "Platform::%s - module %s not found in local cache: %s",
1832 __FUNCTION__, module_spec.GetUUID().GetAsString().c_str(),
1833 error.AsCString());
1834 return false;
1835}
1836
1838 const uint64_t src_offset,
1839 const uint64_t src_size,
1840 const FileSpec &dst_file_spec) {
1841 Status error;
1842
1843 std::error_code EC;
1844 llvm::raw_fd_ostream dst(dst_file_spec.GetPath(), EC, llvm::sys::fs::OF_None);
1845 if (EC) {
1847 "unable to open destination file: %s", dst_file_spec.GetPath().c_str());
1848 return error;
1849 }
1850
1851 auto src_fd = OpenFile(src_file_spec, File::eOpenOptionReadOnly,
1852 lldb::eFilePermissionsFileDefault, error);
1853
1854 if (error.Fail()) {
1855 error = Status::FromErrorStringWithFormat("unable to open source file: %s",
1856 error.AsCString());
1857 return error;
1858 }
1859
1860 std::vector<char> buffer(512 * 1024);
1861 auto offset = src_offset;
1862 uint64_t total_bytes_read = 0;
1863 while (total_bytes_read < src_size) {
1864 const auto to_read = std::min(static_cast<uint64_t>(buffer.size()),
1865 src_size - total_bytes_read);
1866 const uint64_t n_read =
1867 ReadFile(src_fd, offset, &buffer[0], to_read, error);
1868 if (error.Fail())
1869 break;
1870 if (n_read == 0) {
1871 error = Status::FromErrorString("read 0 bytes");
1872 break;
1873 }
1874 offset += n_read;
1875 total_bytes_read += n_read;
1876 dst.write(&buffer[0], n_read);
1877 }
1878
1879 Status close_error;
1880 CloseFile(src_fd, close_error); // Ignoring close error.
1881
1882 return error;
1883}
1884
1886 const FileSpec &dst_file_spec) {
1888 "Symbol file downloading not supported by the default platform.");
1889}
1890
1894 return dir_spec;
1895}
1896
1897const char *Platform::GetCacheHostname() { return GetHostname(); }
1898
1900 static const auto s_default_unix_signals_sp = std::make_shared<UnixSignals>();
1901 return s_default_unix_signals_sp;
1902}
1903
1909
1911 const lldb_private::FileSpec &local_file,
1912 const lldb_private::FileSpec &remote_file,
1914 if (local_file && remote_file) {
1915 // Both local and remote file was specified. Install the local file to the
1916 // given location.
1917 if (IsRemote() || local_file != remote_file) {
1918 error = Install(local_file, remote_file);
1919 if (error.Fail())
1921 }
1922 return DoLoadImage(process, remote_file, nullptr, error);
1923 }
1924
1925 if (local_file) {
1926 // Only local file was specified. Install it to the current working
1927 // directory.
1928 FileSpec target_file = GetWorkingDirectory();
1929 target_file.AppendPathComponent(local_file.GetFilename());
1930 if (IsRemote() || local_file != target_file) {
1931 error = Install(local_file, target_file);
1932 if (error.Fail())
1934 }
1935 return DoLoadImage(process, target_file, nullptr, error);
1936 }
1937
1938 if (remote_file) {
1939 // Only remote file was specified so we don't have to do any copying
1940 return DoLoadImage(process, remote_file, nullptr, error);
1941 }
1942
1943 error =
1944 Status::FromErrorString("Neither local nor remote file was specified");
1946}
1947
1949 const lldb_private::FileSpec &remote_file,
1950 const std::vector<std::string> *paths,
1952 lldb_private::FileSpec *loaded_image) {
1954 "LoadImage is not supported on the current platform");
1956}
1957
1959 const lldb_private::FileSpec &remote_filename,
1960 const std::vector<std::string> &paths,
1962 lldb_private::FileSpec *loaded_path)
1963{
1964 FileSpec file_to_use;
1965 if (remote_filename.IsAbsolute())
1966 file_to_use =
1967 FileSpec(remote_filename.GetFilename(), remote_filename.GetPathStyle());
1968 else
1969 file_to_use = remote_filename;
1970
1971 return DoLoadImage(process, file_to_use, &paths, error, loaded_path);
1972}
1973
1975 uint32_t image_token) {
1977 "UnloadImage is not supported on the current platform");
1978}
1979
1980lldb::ProcessSP Platform::ConnectProcess(llvm::StringRef connect_url,
1981 llvm::StringRef plugin_name,
1982 Debugger &debugger, Target *target,
1983 Status &error) {
1984 return DoConnectProcess(connect_url, plugin_name, debugger, nullptr, target,
1985 error);
1986}
1987
1989 llvm::StringRef connect_url, llvm::StringRef plugin_name,
1990 Debugger &debugger, Stream &stream, Target *target, Status &error) {
1991 return DoConnectProcess(connect_url, plugin_name, debugger, &stream, target,
1992 error);
1993}
1994
1996 llvm::StringRef plugin_name,
1997 Debugger &debugger, Stream *stream,
1998 Target *target, Status &error) {
1999 error.Clear();
2000
2001 if (!target) {
2003
2004 const char *triple =
2005 arch.IsValid() ? arch.GetTriple().getTriple().c_str() : "";
2006
2007 TargetSP new_target_sp;
2008 error = debugger.GetTargetList().CreateTarget(
2009 debugger, "", triple, eLoadDependentsNo, nullptr, new_target_sp);
2010
2011 target = new_target_sp.get();
2012 if (!target || error.Fail()) {
2013 return nullptr;
2014 }
2015 }
2016
2017 lldb::ProcessSP process_sp =
2018 target->CreateProcess(debugger.GetListener(), plugin_name, nullptr, true);
2019
2020 if (!process_sp)
2021 return nullptr;
2022
2023 // If this private method is called with a stream we are synchronous.
2024 const bool synchronous = stream != nullptr;
2025
2026 ListenerSP listener_sp(
2027 Listener::MakeListener("lldb.Process.ConnectProcess.hijack"));
2028 if (synchronous)
2029 process_sp->HijackProcessEvents(listener_sp);
2030
2031 error = process_sp->ConnectRemote(connect_url);
2032 if (error.Fail()) {
2033 if (synchronous)
2034 process_sp->RestoreProcessEvents();
2035 return nullptr;
2036 }
2037
2038 if (synchronous) {
2039 EventSP event_sp;
2040 process_sp->WaitForProcessToStop(std::nullopt, &event_sp, true, listener_sp,
2041 nullptr);
2042 process_sp->RestoreProcessEvents();
2043 bool pop_process_io_handler = false;
2044 // This is a user-level stop, so we allow recognizers to select frames.
2046 event_sp, stream, SelectMostRelevantFrame, pop_process_io_handler);
2047 }
2048
2049 return process_sp;
2050}
2051
2054 error.Clear();
2055 return 0;
2056}
2057
2058llvm::ArrayRef<uint8_t> Platform::SoftwareTrapOpcodeBytes(const ArchSpec &arch,
2059 size_t size_hint) {
2060 llvm::ArrayRef<uint8_t> trap_opcode;
2061
2062 switch (arch.GetMachine()) {
2063 case llvm::Triple::aarch64_32:
2064 case llvm::Triple::aarch64: {
2065 static const uint8_t g_aarch64_opcode[] = {0x00, 0x00, 0x20, 0xd4};
2066 trap_opcode =
2067 llvm::ArrayRef<uint8_t>(g_aarch64_opcode, sizeof(g_aarch64_opcode));
2068 } break;
2069
2070 case llvm::Triple::arc: {
2071 static const uint8_t g_hex_opcode[] = {0xff, 0x7f};
2072 trap_opcode = llvm::ArrayRef<uint8_t>(g_hex_opcode, sizeof(g_hex_opcode));
2073 } break;
2074
2075 case llvm::Triple::arm: {
2076 // ARM CPUs have dedicated BKPT instructions: 0xe7fddefe and 0xdefe.
2077 // However, the linux kernel recognizes two different sequences based on
2078 // undefined instruction encodings (linux/arch/arm/kernel/ptrace.c)
2079 static const uint8_t g_arm_breakpoint_opcode[] = {0xf0, 0x01, 0xf0, 0xe7};
2080 static const uint8_t g_thumb_breakpoint_opcode[] = {0x01, 0xde};
2081
2082 if (size_hint == 2) {
2083 trap_opcode = llvm::ArrayRef<uint8_t>(g_thumb_breakpoint_opcode,
2084 sizeof(g_thumb_breakpoint_opcode));
2085 } else {
2086 trap_opcode = llvm::ArrayRef<uint8_t>(g_arm_breakpoint_opcode,
2087 sizeof(g_arm_breakpoint_opcode));
2088 }
2089 } break;
2090
2091 case llvm::Triple::avr: {
2092 static const uint8_t g_hex_opcode[] = {0x98, 0x95};
2093 trap_opcode = llvm::ArrayRef<uint8_t>(g_hex_opcode, sizeof(g_hex_opcode));
2094 } break;
2095
2096 case llvm::Triple::mips:
2097 case llvm::Triple::mips64: {
2098 static const uint8_t g_hex_opcode[] = {0x00, 0x00, 0x00, 0x0d};
2099 trap_opcode = llvm::ArrayRef<uint8_t>(g_hex_opcode, sizeof(g_hex_opcode));
2100 } break;
2101
2102 case llvm::Triple::mipsel:
2103 case llvm::Triple::mips64el: {
2104 static const uint8_t g_hex_opcode[] = {0x0d, 0x00, 0x00, 0x00};
2105 trap_opcode = llvm::ArrayRef<uint8_t>(g_hex_opcode, sizeof(g_hex_opcode));
2106 } break;
2107
2108 case llvm::Triple::msp430: {
2109 static const uint8_t g_msp430_opcode[] = {0x43, 0x43};
2110 trap_opcode =
2111 llvm::ArrayRef<uint8_t>(g_msp430_opcode, sizeof(g_msp430_opcode));
2112 } break;
2113
2114 case llvm::Triple::systemz: {
2115 static const uint8_t g_hex_opcode[] = {0x00, 0x01};
2116 trap_opcode = llvm::ArrayRef<uint8_t>(g_hex_opcode, sizeof(g_hex_opcode));
2117 } break;
2118
2119 case llvm::Triple::hexagon: {
2120 static const uint8_t g_hex_opcode[] = {0x0c, 0xdb, 0x00, 0x54};
2121 trap_opcode = llvm::ArrayRef<uint8_t>(g_hex_opcode, sizeof(g_hex_opcode));
2122 } break;
2123
2124 case llvm::Triple::ppc:
2125 case llvm::Triple::ppc64: {
2126 static const uint8_t g_ppc_opcode[] = {0x7f, 0xe0, 0x00, 0x08};
2127 trap_opcode = llvm::ArrayRef<uint8_t>(g_ppc_opcode, sizeof(g_ppc_opcode));
2128 } break;
2129
2130 case llvm::Triple::ppc64le: {
2131 static const uint8_t g_ppc64le_opcode[] = {0x08, 0x00, 0xe0, 0x7f}; // trap
2132 trap_opcode =
2133 llvm::ArrayRef<uint8_t>(g_ppc64le_opcode, sizeof(g_ppc64le_opcode));
2134 } break;
2135
2136 case llvm::Triple::x86:
2137 case llvm::Triple::x86_64: {
2138 static const uint8_t g_i386_opcode[] = {0xCC};
2139 trap_opcode = llvm::ArrayRef<uint8_t>(g_i386_opcode, sizeof(g_i386_opcode));
2140 } break;
2141
2142 case llvm::Triple::riscv32:
2143 case llvm::Triple::riscv64: {
2144 static const uint8_t g_riscv_opcode[] = {0x73, 0x00, 0x10, 0x00}; // ebreak
2145 static const uint8_t g_riscv_opcode_c[] = {0x02, 0x90}; // c.ebreak
2146 if (size_hint == 2) {
2147 trap_opcode = g_riscv_opcode_c;
2148 } else {
2149 trap_opcode =
2150 llvm::ArrayRef<uint8_t>(g_riscv_opcode, sizeof(g_riscv_opcode));
2151 }
2152 } break;
2153
2154 case llvm::Triple::loongarch32:
2155 case llvm::Triple::loongarch64: {
2156 static const uint8_t g_loongarch_opcode[] = {0x05, 0x00, 0x2a,
2157 0x00}; // break 0x5
2158 trap_opcode =
2159 llvm::ArrayRef<uint8_t>(g_loongarch_opcode, sizeof(g_loongarch_opcode));
2160 } break;
2161
2162 // Unreachable (0x00) triggers an unconditional trap.
2163 case llvm::Triple::wasm32: {
2164 static const uint8_t g_wasm_opcode[] = {0x00};
2165 trap_opcode = llvm::ArrayRef<uint8_t>(g_wasm_opcode, sizeof(g_wasm_opcode));
2166 } break;
2167 // The default case should not match against anything, so return empty Array.
2168 default: {
2169 trap_opcode = llvm::ArrayRef<uint8_t>{};
2170 };
2171 }
2172 return trap_opcode;
2173}
2174
2176 llvm::ArrayRef<uint8_t> bytes) {
2177 ArchSpec arch = target.GetArchitecture();
2178 assert(arch.IsValid());
2179 const auto &triple = arch.GetTriple();
2180
2181 if (bytes.size() && triple.isRISCV()) {
2182 // RISC-V instructions have the two LSB as 0b11 if they are four-byte.
2183 return (bytes[0] & 0b11) == 0b11 ? 4 : 2;
2184 }
2185
2186 if (triple.isARM()) {
2187 if (auto addr_class = addr.GetAddressClass();
2188 addr_class == AddressClass::eCodeAlternateISA) {
2189 return 2;
2190 } else {
2191 return 4;
2192 }
2193 }
2194 return 0;
2195}
2196
2198 BreakpointSite *bp_site) {
2199 ArchSpec arch = target.GetArchitecture();
2200 assert(arch.IsValid());
2202 if (bp_site) {
2203 // TODO: support big-endian arm and thumb trap codes.
2205 if (bp_loc_sp)
2206 addr_class = bp_loc_sp->GetAddress().GetAddressClass();
2207 }
2208
2209 size_t size_hint = 0;
2210 // Check for either ARM or RISC-V short instruction conditions.
2211 if (addr_class == AddressClass::eCodeAlternateISA ||
2212 (arch.GetFlags() & ArchSpec::eRISCV_rvc))
2213 size_hint = 2;
2214 auto trap_opcode = SoftwareTrapOpcodeBytes(arch, size_hint);
2215
2216 if (bp_site &&
2217 bp_site->SetTrapOpcode(trap_opcode.begin(), trap_opcode.size()))
2218 return trap_opcode.size();
2219
2220 return 0;
2221}
2222
2223CompilerType Platform::GetSiginfoType(const llvm::Triple& triple) {
2224 return CompilerType();
2225}
2226
2228 return {};
2229}
2230
2234
2238
2240 Stream &os,
2242 const FileSpec &original_fspec, const FileSpec &fspec) {
2243 if (!sanitized_name.RequiredSanitization())
2244 return;
2245
2246 // Path to unsanitized script name doesn't exist. Nothing to warn about.
2247 if (!FileSystem::Instance().Exists(original_fspec))
2248 return;
2249
2250 std::string reason_for_complaint =
2251 sanitized_name.IsKeyword()
2252 ? llvm::formatv("conflicts with the keyword '{0}'",
2253 sanitized_name.GetConflictingKeyword())
2254 .str()
2255 : "contains reserved characters";
2256
2257 if (FileSystem::Instance().Exists(fspec))
2258 os.Format("debug script '{0}' cannot be loaded because '{1}' {2}. "
2259 "Ignoring '{1}' and loading '{3}' instead.\n",
2260 original_fspec.GetPath(), original_fspec.GetFilename(),
2261 std::move(reason_for_complaint), fspec.GetFilename());
2262 else
2263 os.Format("debug script '{0}' cannot be loaded because '{1}' {2}. "
2264 "If you intend to have this script loaded, please rename it to "
2265 "'{3}' and retry.\n",
2266 original_fspec.GetPath(), original_fspec.GetFilename(),
2267 std::move(reason_for_complaint), fspec.GetFilename());
2268}
2269
2270llvm::Expected<std::pair<XcodeSDKAndSysroot, bool>>
2272 SymbolFile *sym_file = module.GetSymbolFile();
2273 if (!sym_file)
2274 return llvm::createStringError(
2275 llvm::formatv("No symbol file available for module '{0}'",
2276 module.GetFileSpec().GetFilename()));
2277
2278 if (sym_file->GetNumCompileUnits() == 0)
2279 return llvm::createStringError(
2280 llvm::formatv("Could not resolve SDK for module '{0}'. Symbol file has "
2281 "no compile units.",
2282 module.GetFileSpec()));
2283
2284 XcodeSDKAndSysroot merged_sdk;
2285 for (unsigned i = 0; i < sym_file->GetNumCompileUnits(); ++i)
2286 if (auto cu_sp = sym_file->GetCompileUnitAtIndex(i))
2287 merged_sdk.Merge(sym_file->ParseXcodeSDK(*cu_sp));
2288
2289 // Only Darwin SDKs come in public and internal flavors, so a generic
2290 // platform can never see the two conflict.
2291 return std::pair{std::move(merged_sdk), /*found_mismatch=*/false};
2292}
2293
2294llvm::Expected<std::string>
2296 auto sdk_or_err = GetSDKPathFromDebugInfo(module);
2297 if (!sdk_or_err)
2298 return llvm::joinErrors(
2299 llvm::createStringError("could not parse SDK path from debug-info"),
2300 sdk_or_err.takeError());
2301
2302 return sdk_or_err->first.GetSysroot().GetPath();
2303}
2304
2305llvm::Expected<XcodeSDKAndSysroot>
2307 ModuleSP module_sp = unit.CalculateSymbolContextModule();
2308 if (!module_sp)
2309 return llvm::createStringError("compile unit has no module");
2310
2311 SymbolFile *sym_file = module_sp->GetSymbolFile();
2312 if (!sym_file)
2313 return llvm::createStringError(
2314 llvm::formatv("No symbol file available for module '{0}'",
2315 module_sp->GetFileSpec().GetFilename()));
2316
2317 return sym_file->ParseXcodeSDK(unit);
2318}
2319
2320llvm::Expected<std::string>
2322 auto sdk_or_err = GetSDKPathFromDebugInfo(unit);
2323 if (!sdk_or_err)
2324 return llvm::joinErrors(
2325 llvm::createStringError("could not parse SDK path from debug-info"),
2326 sdk_or_err.takeError());
2327
2328 return sdk_or_err->GetSysroot().GetPath();
2329}
2330
2332 std::lock_guard<std::recursive_mutex> guard(m_mutex);
2333 for (const PlatformSP &platform_sp : m_platforms) {
2334 if (platform_sp->GetName() == name)
2335 return platform_sp;
2336 }
2337 return Create(name);
2338}
2339
2341 const ArchSpec &process_host_arch,
2342 ArchSpec *platform_arch_ptr,
2343 Status &error) {
2344 std::lock_guard<std::recursive_mutex> guard(m_mutex);
2345 // First try exact arch matches across all platforms already created
2346 for (const auto &platform_sp : m_platforms) {
2347 if (platform_sp->IsCompatibleArchitecture(
2348 arch, process_host_arch, ArchSpec::ExactMatch, platform_arch_ptr))
2349 return platform_sp;
2350 }
2351
2352 // Next try compatible arch matches across all platforms already created
2353 for (const auto &platform_sp : m_platforms) {
2354 if (platform_sp->IsCompatibleArchitecture(arch, process_host_arch,
2356 platform_arch_ptr))
2357 return platform_sp;
2358 }
2359
2360 // First try exact arch matches across all platform plug-ins
2361 for (auto create_callback : PluginManager::GetPlatformCreateCallbacks()) {
2362 PlatformSP platform_sp = create_callback(false, &arch);
2363 if (platform_sp &&
2364 platform_sp->IsCompatibleArchitecture(
2365 arch, process_host_arch, ArchSpec::ExactMatch, platform_arch_ptr)) {
2366 m_platforms.push_back(platform_sp);
2367 return platform_sp;
2368 }
2369 }
2370 // Next try compatible arch matches across all platform plug-ins
2371 for (auto create_callback : PluginManager::GetPlatformCreateCallbacks()) {
2372 PlatformSP platform_sp = create_callback(false, &arch);
2373 if (platform_sp && platform_sp->IsCompatibleArchitecture(
2374 arch, process_host_arch, ArchSpec::CompatibleMatch,
2375 platform_arch_ptr)) {
2376 m_platforms.push_back(platform_sp);
2377 return platform_sp;
2378 }
2379 }
2380 if (platform_arch_ptr)
2381 platform_arch_ptr->Clear();
2382 return nullptr;
2383}
2384
2386 const ArchSpec &process_host_arch,
2387 ArchSpec *platform_arch_ptr) {
2388 Status error;
2389 if (arch.IsValid())
2390 return GetOrCreate(arch, process_host_arch, platform_arch_ptr, error);
2391 return nullptr;
2392}
2393
2394PlatformSP PlatformList::GetOrCreate(llvm::ArrayRef<ArchSpec> archs,
2395 const ArchSpec &process_host_arch,
2396 std::vector<PlatformSP> &candidates) {
2397 candidates.clear();
2398 candidates.reserve(archs.size());
2399
2400 if (archs.empty())
2401 return nullptr;
2402
2403 PlatformSP host_platform_sp = Platform::GetHostPlatform();
2404
2405 // Prefer the selected platform if it matches at least one architecture.
2407 for (const ArchSpec &arch : archs) {
2408 if (m_selected_platform_sp->IsCompatibleArchitecture(
2409 arch, process_host_arch, ArchSpec::CompatibleMatch, nullptr))
2411 }
2412 }
2413
2414 // Prefer the host platform if it matches at least one architecture.
2415 if (host_platform_sp) {
2416 for (const ArchSpec &arch : archs) {
2417 if (host_platform_sp->IsCompatibleArchitecture(
2418 arch, process_host_arch, ArchSpec::CompatibleMatch, nullptr))
2419 return host_platform_sp;
2420 }
2421 }
2422
2423 // Collect a list of candidate platforms for the architectures.
2424 for (const ArchSpec &arch : archs) {
2425 if (PlatformSP platform = GetOrCreate(arch, process_host_arch, nullptr))
2426 candidates.push_back(platform);
2427 }
2428
2429 // The selected or host platform didn't match any of the architectures. If
2430 // the same platform supports all architectures then that's the obvious next
2431 // best thing.
2432 if (candidates.size() == archs.size()) {
2433 if (llvm::all_of(candidates, [&](const PlatformSP &p) -> bool {
2434 return p->GetName() == candidates.front()->GetName();
2435 })) {
2436 return candidates.front();
2437 }
2438 }
2439
2440 // At this point we either have no platforms that match the given
2441 // architectures or multiple platforms with no good way to disambiguate
2442 // between them.
2443 return nullptr;
2444}
2445
2446PlatformSP PlatformList::Create(llvm::StringRef name) {
2447 std::lock_guard<std::recursive_mutex> guard(m_mutex);
2448 PlatformSP platform_sp = Platform::Create(name);
2449 if (platform_sp)
2450 m_platforms.push_back(platform_sp);
2451 return platform_sp;
2452}
2453
2455 lldb::addr_t addr, bool notify) {
2456 std::lock_guard<std::recursive_mutex> guard(m_mutex);
2457
2458 for (auto create_callback : PluginManager::GetPlatformCreateCallbacks()) {
2459 ArchSpec arch;
2460 PlatformSP platform_sp = create_callback(true, &arch);
2461 if (platform_sp) {
2462 if (platform_sp->LoadPlatformBinaryAndSetup(process, addr, notify))
2463 return true;
2464 }
2465 }
2466 return false;
2467}
static llvm::raw_ostream & error(Stream &strm)
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define MAP_ANON
#define MAP_PRIVATE
static FileSystem::EnumerateDirectoryResult RecurseCopy_Callback(void *baton, llvm::sys::fs::file_type ft, llvm::StringRef path)
Definition Platform.cpp:489
static PlatformSP & GetHostPlatformSP()
Definition Platform.cpp:63
static constexpr OptionDefinition g_rsync_option_table[]
static constexpr OptionDefinition g_ssh_option_table[]
static constexpr OptionDefinition g_caching_option_table[]
A section + offset based address class.
Definition Address.h:62
AddressClass GetAddressClass() const
Definition Address.cpp:1015
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:453
void Clear()
Clears the object state.
Definition ArchSpec.cpp:732
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:545
bool IsMatch(const ArchSpec &rhs, MatchType match) const
Compare this ArchSpec to another ArchSpec.
void DumpTriple(llvm::raw_ostream &s) const
uint32_t GetFlags() const
Definition ArchSpec.h:616
llvm::Triple::ArchType GetMachine() const
Returns a machine family for the current architecture.
Definition ArchSpec.cpp:883
static bool ContainsOnlyArch(const llvm::Triple &normalized_triple)
Returns true if the OS, vendor and environment fields of the triple are unset.
A command line argument class.
Definition Args.h:33
Class that manages the actual breakpoint that will be inserted into the running program.
bool SetTrapOpcode(const uint8_t *trap_opcode, uint32_t trap_opcode_size)
Sets the trap opcode.
lldb::BreakpointLocationSP GetConstituentAtIndex(size_t idx)
This method returns the breakpoint location at index index located at this breakpoint site.
A class that describes a compilation unit.
Definition CompileUnit.h:43
lldb::ModuleSP CalculateSymbolContextModule() override
Generic representation of a type in a programming language.
A subclass of DataBuffer that stores a data buffer on the heap.
A class to manage flag bits.
Definition Debugger.h:100
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:220
lldb::ScriptLanguage GetScriptLanguage() const
Definition Debugger.cpp:458
lldb::ListenerSP GetListener()
Definition Debugger.h:191
ScriptInterpreter * GetScriptInterpreter(bool can_create=true, std::optional< lldb::ScriptLanguage > language={})
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
bool CloseFile(lldb::user_id_t fd, Status &error)
Definition FileCache.cpp:43
uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t dst_len, Status &error)
Definition FileCache.cpp:92
lldb::user_id_t OpenFile(const FileSpec &file_spec, File::OpenOptions flags, uint32_t mode, Status &error)
Definition FileCache.cpp:26
uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, Status &error)
Definition FileCache.cpp:64
static FileCache & GetInstance()
Definition FileCache.cpp:19
A file collection class.
A file utility class.
Definition FileSpec.h:56
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
llvm::StringRef GetFileNameStrippingExtension() const
Return the filename without the extension part.
Definition FileSpec.cpp:414
void SetFilename(llvm::StringRef filename)
Filename string set accessor.
Definition FileSpec.cpp:363
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
bool IsAbsolute() const
Returns true if the filespec represents an absolute path.
Definition FileSpec.cpp:518
Style GetPathStyle() const
Definition FileSpec.cpp:356
void PrependPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:440
llvm::StringRef GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:233
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void Clear()
Clears the object state.
Definition FileSpec.cpp:265
void SetDirectory(llvm::StringRef directory)
Directory string set accessor.
Definition FileSpec.cpp:358
void EnumerateDirectory(llvm::Twine path, bool find_directories, bool find_files, bool find_other, EnumerateDirectoryCallbackType callback, void *callback_baton)
@ eEnumerateDirectoryResultNext
Enumerate next entry in the current directory.
Definition FileSystem.h:182
@ eEnumerateDirectoryResultQuit
Stop directory enumerations at any level.
Definition FileSystem.h:187
Status Symlink(const FileSpec &src, const FileSpec &dst)
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
int Open(const char *path, int flags, int mode=0600)
Wraps open in a platform-independent way.
Status Readlink(const FileSpec &src, FileSpec &dst)
uint32_t GetPermissions(const FileSpec &file_spec) const
Return the current permissions of the given file.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
@ eOpenOptionDontFollowSymlinks
Definition FileBase.h:60
bool Test(ValueType bit) const
Test a single flag bit.
Definition Flags.h:96
ValueType Set(ValueType mask)
Set one or more flags by logical OR'ing mask with the current flags.
Definition Flags.h:73
static Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch the process specified in launch_info.
static bool ResolveExecutableInBundle(FileSpec &file)
When executable files may live within a directory, where the directory represents an executable bundl...
static Status ShellExpandArguments(ProcessLaunchInfo &launch_info, const Timeout< std::micro > &timeout)
Perform expansion of the command-line for this launch info This can potentially involve wildcard expa...
Definition aix/Host.cpp:216
static Environment GetEnvironment()
static Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *error_output, const Timeout< std::micro > &timeout, bool run_in_shell=true)
Run a shell command.
static bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
Definition aix/Host.cpp:211
static uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos)
static void Kill(lldb::pid_t pid, int signo)
static lldb::ListenerSP MakeListener(llvm::StringRef name)
Definition Listener.cpp:373
A module cache class.
Definition ModuleCache.h:47
static Status GetSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr, bool invoke_locate_callback=true, bool invoke_symbol_locators=true)
bool FindMatchingModuleSpec(const ModuleSpec &module_spec, ModuleSpec &match_module_spec) const
Definition ModuleSpec.h:396
uint64_t GetObjectOffset() const
Definition ModuleSpec.h:111
FileSpec & GetPlatformFileSpec()
Definition ModuleSpec.h:69
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:81
void SetTarget(lldb::TargetSP target)
Set the target to be used when resolving a module.
Definition ModuleSpec.h:150
uint64_t GetObjectSize() const
Definition ModuleSpec.h:117
lldb::TargetSP GetTargetSP() const
Definition ModuleSpec.h:142
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:91
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:447
static bool IsObjectFile(lldb_private::FileSpec file_spec)
static ModuleSpecList GetModuleSpecifications(const FileSpec &file, lldb::offset_t file_offset, lldb::offset_t file_size, lldb::DataExtractorSP=lldb::DataExtractorSP())
lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
void OptionParsingStarting(ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
lldb_private::Status SetOptionValue(uint32_t option_idx, llvm::StringRef option_value, ExecutionContext *execution_context) override
llvm::ArrayRef< OptionDefinition > GetDefinitions() override
void OptionParsingStarting(ExecutionContext *execution_context) override
lldb::PlatformSP m_selected_platform_sp
Definition Platform.h:1267
std::recursive_mutex m_mutex
Definition Platform.h:1265
lldb::PlatformSP Create(llvm::StringRef name)
bool LoadPlatformBinaryAndSetup(Process *process, lldb::addr_t addr, bool notify)
Detect a binary in memory that will determine which Platform and DynamicLoader should be used in this...
lldb::PlatformSP GetOrCreate(llvm::StringRef name)
FileSpec GetModuleCacheDirectory() const
Definition Platform.cpp:116
bool SetUseModuleCache(bool use_module_cache)
Definition Platform.cpp:112
void SetDefaultModuleCacheDirectory(const FileSpec &dir_spec)
Definition Platform.cpp:134
bool SetModuleCacheDirectory(const FileSpec &dir_spec)
Definition Platform.cpp:120
Timeout< std::micro > GetShellExpandTimeout() const
The timeout to use when expanding launch arguments via the shell.
Definition Platform.cpp:125
static llvm::StringRef GetSettingName()
Definition Platform.cpp:82
A plug-in interface definition class for debug platform that includes many platform abilities such as...
Definition Platform.h:82
virtual std::optional< std::string > GetRemoteOSBuildString()
Definition Platform.h:229
virtual Status Install(const FileSpec &src, const FileSpec &dst)
Install a file or directory to the remote system.
Definition Platform.cpp:576
virtual Status GetFileWithUUID(const FileSpec &platform_file, const UUID *uuid_ptr, FileSpec &local_file)
Locate a file for a platform.
Definition Platform.cpp:167
size_t GetTrapOpcodeSizeHint(Target &target, Address addr, llvm::ArrayRef< uint8_t > bytes)
Get the suggested size hint for a trap instruction on the given target.
bool GetCachedSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, bool *did_create_ptr)
virtual llvm::Expected< std::pair< XcodeSDKAndSysroot, bool > > GetSDKPathFromDebugInfo(Module &module)
Search each CU associated with the specified 'module' for the SDK paths the CUs were compiled against...
virtual FileSpec GetRemoteWorkingDirectory()
Definition Platform.h:242
virtual Status ResolveSymbolFile(Target &target, const ModuleSpec &sym_spec, FileSpec &sym_file)
Find a symbol file given a symbol file module specification.
Definition Platform.cpp:901
ProcessInstanceInfoList GetAllProcesses()
virtual bool GetFileExists(const lldb_private::FileSpec &file_spec)
virtual bool CloseFile(lldb::user_id_t fd, Status &error)
Definition Platform.cpp:754
virtual bool IsConnected() const
Definition Platform.h:563
void SetLocateModuleCallback(LocateModuleCallback callback)
Set locate module callback.
virtual lldb::user_id_t OpenFile(const FileSpec &file_spec, File::OpenOptions flags, uint32_t mode, Status &error)
Definition Platform.cpp:746
virtual const char * GetHostname()
Definition Platform.cpp:796
std::vector< ConstString > m_trap_handlers
Definition Platform.h:1091
virtual MmapArgList GetMmapArgumentList(const ArchSpec &arch, lldb::addr_t addr, lldb::addr_t length, unsigned prot, unsigned flags, lldb::addr_t fd, lldb::addr_t offset)
virtual uint32_t FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &proc_infos)
Attach to an existing process by process name.
virtual size_t GetSoftwareBreakpointTrapOpcode(Target &target, BreakpointSite *bp_site)
virtual lldb::ProcessSP DebugProcess(ProcessLaunchInfo &launch_info, Debugger &debugger, Target &target, Status &error)
Subclasses do not need to implement this function as it uses the Platform::LaunchProcess() followed b...
static void Terminate()
Definition Platform.cpp:154
virtual void CalculateTrapHandlerSymbolNames()=0
Ask the Platform subclass to fill in the list of trap handler names.
virtual bool IsSymbolFileTrusted(Module &module)
Returns true if the module's symbol file (e.g.
Definition Platform.cpp:174
std::string m_rsync_prefix
Definition Platform.h:1086
llvm::VersionTuple m_os_version
Definition Platform.h:1075
virtual Status ResolveExecutable(const ModuleSpec &module_spec, lldb::ModuleSP &exe_module_sp)
Set the target's executable based off of the existing architecture information in target given a path...
Definition Platform.cpp:839
const std::string & GetSDKRootDirectory() const
Definition Platform.h:587
virtual Status GetFilePermissions(const FileSpec &file_spec, uint32_t &file_permissions)
Definition Platform.cpp:716
llvm::ArrayRef< uint8_t > SoftwareTrapOpcodeBytes(const ArchSpec &arch, size_t size_hint=0)
Get the bytes of the platform's software interrupt instruction.
virtual Status MakeDirectory(const FileSpec &file_spec, uint32_t permissions)
Definition Platform.cpp:703
FileSpec GetWorkingDirectory()
Definition Platform.cpp:465
virtual void AddClangModuleCompilationOptions(Target *target, std::vector< std::string > &options)
Definition Platform.cpp:456
virtual UserIDResolver & GetUserIDResolver()
Definition Platform.cpp:790
virtual Status PutFile(const FileSpec &source, const FileSpec &destination, uint32_t uid=UINT32_MAX, uint32_t gid=UINT32_MAX)
virtual std::string GetFullNameForDylib(llvm::StringRef basename)
Definition Platform.cpp:805
virtual const std::vector< ConstString > & GetTrapHandlerSymbolNames()
Provide a list of trap handler function names for this platform.
static ArchSpec GetAugmentedArchSpec(Platform *platform, llvm::StringRef triple)
Augments the triple either with information from platform or the host system (if platform is null).
Definition Platform.cpp:332
~Platform() override
The destructor is virtual since this class is designed to be inherited from by the plug-in instance.
bool m_system_arch_set_while_connected
Definition Platform.h:1068
Platform(bool is_host_platform)
Default Constructor.
Definition Platform.cpp:339
static lldb::PlatformSP Create(llvm::StringRef name)
Definition Platform.cpp:321
virtual Status DisconnectRemote()
Definition Platform.cpp:994
static lldb::PlatformSP GetHostPlatform()
Get the native host platform plug-in.
Definition Platform.cpp:150
std::string m_local_cache_directory
Definition Platform.h:1090
virtual lldb::BreakpointSP SetThreadCreationBreakpoint(Target &target)
lldb::UnixSignalsSP GetUnixSignals()
virtual lldb::user_id_t GetFileSize(const FileSpec &file_spec)
Definition Platform.cpp:760
bool SetWorkingDirectory(const FileSpec &working_dir)
Definition Platform.cpp:688
static void SetHostPlatform(const lldb::PlatformSP &platform_sp)
Definition Platform.cpp:161
virtual llvm::Expected< std::string > ResolveSDKPathFromDebugInfo(Module &module)
Returns the full path of the most appropriate SDK for the specified 'module'.
const ArchSpec & GetSystemArchitecture()
Definition Platform.cpp:918
virtual lldb::ProcessSP Attach(ProcessAttachInfo &attach_info, Debugger &debugger, Target *target, Status &error)=0
Attach to an existing process using a process ID.
virtual const char * GetLocalCacheDirectory()
llvm::SmallDenseMap< FileSpec, LoadScriptFromSymFile > LocateExecutableScriptingResources(Target *target, Module &module, Stream &feedback_stream)
Locate the scripting resource given a module specification.
Definition Platform.cpp:250
static void WarnIfInvalidUnsanitizedScriptExists(Stream &os, const ScriptInterpreter::SanitizedScriptingModuleName &sanitized_name, const FileSpec &original_fspec, const FileSpec &fspec)
If we did some replacements of reserved characters, and a file with the untampered name exists,...
virtual Status Unlink(const FileSpec &file_spec)
uint32_t LoadImage(lldb_private::Process *process, const lldb_private::FileSpec &local_file, const lldb_private::FileSpec &remote_file, lldb_private::Status &error)
Load a shared library into this process.
virtual bool SetRemoteWorkingDirectory(const FileSpec &working_dir)
Definition Platform.cpp:809
virtual std::optional< std::string > GetRemoteOSKernelDescription()
Definition Platform.h:233
LocateModuleCallback m_locate_module_callback
Definition Platform.h:1094
Status GetCachedExecutable(ModuleSpec &module_spec, lldb::ModuleSP &module_sp)
virtual void SetLocalCacheDirectory(const char *local)
virtual CompilerType GetSiginfoType(const llvm::Triple &triple)
virtual Status DownloadModuleSlice(const FileSpec &src_file_spec, const uint64_t src_offset, const uint64_t src_size, const FileSpec &dst_file_spec)
virtual ArchSpec GetRemoteSystemArchitecture()
Definition Platform.h:238
virtual llvm::VersionTuple GetOSVersion(Process *process=nullptr)
Get the OS version from a connected platform.
Definition Platform.cpp:402
virtual void GetStatus(Stream &strm)
Report the current status for this platform.
Definition Platform.cpp:353
virtual lldb::ProcessSP ConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, Debugger &debugger, Target *target, Status &error)
virtual Status DownloadSymbolFile(const lldb::ModuleSP &module_sp, const FileSpec &dst_file_spec)
bool SetOSVersion(llvm::VersionTuple os_version)
Definition Platform.cpp:817
virtual Status LaunchProcess(ProcessLaunchInfo &launch_info)
Launch a new process on a platform, not necessarily for debugging, it could be just for running the p...
virtual Status KillProcess(const lldb::pid_t pid)
Kill process on a platform.
virtual Status CreateSymlink(const FileSpec &src, const FileSpec &dst)
static void Initialize()
Definition Platform.cpp:152
std::optional< std::string > GetOSBuildString()
Definition Platform.cpp:444
virtual size_t ConnectToWaitingProcesses(lldb_private::Debugger &debugger, lldb_private::Status &error)
Connect to all processes waiting for a debugger to attach.
virtual uint32_t 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_path=nullptr)
virtual Status UnloadImage(lldb_private::Process *process, uint32_t image_token)
virtual bool IsCompatibleArchitecture(const ArchSpec &arch, const ArchSpec &process_host_arch, ArchSpec::MatchType match, ArchSpec *compatible_arch_ptr)
Lets a platform answer if it is compatible with a given architecture and the target triple contained ...
virtual bool GetRemoteOSVersion()
Definition Platform.h:227
static std::vector< ArchSpec > CreateArchList(llvm::ArrayRef< llvm::Triple::ArchType > archs, llvm::Triple::OSType os)
Create a list of ArchSpecs with the given OS and a architectures.
std::string m_hostname
Definition Platform.h:1074
static PlatformProperties & GetGlobalPlatformProperties()
Definition Platform.cpp:156
virtual Status GetSharedModule(const ModuleSpec &module_spec, Target &target, lldb::ModuleSP &module_sp, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr)
Definition Platform.cpp:270
virtual uint64_t WriteFile(lldb::user_id_t fd, uint64_t offset, const void *src, uint64_t src_len, Status &error)
Definition Platform.cpp:780
void CallLocateModuleCallbackIfSet(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, FileSpec &symbol_file_spec, bool *did_create_ptr)
lldb::ProcessSP DoConnectProcess(llvm::StringRef connect_url, llvm::StringRef plugin_name, Debugger &debugger, Stream *stream, Target *target, Status &error)
Private implementation of connecting to a process.
const std::unique_ptr< ModuleCache > m_module_cache
Definition Platform.h:1093
virtual std::string GetPlatformSpecificConnectionInformation()
Definition Platform.h:757
LocateModuleCallback GetLocateModuleCallback() const
bool IsRemote() const
Definition Platform.h:561
bool m_os_version_set_while_connected
Definition Platform.h:1067
virtual Status GetFile(const FileSpec &source, const FileSpec &destination)
virtual bool GetSupportsRSync()
Definition Platform.h:692
FileSpec GetModuleCacheRoot()
virtual uint32_t GetResumeCountForLaunchInfo(ProcessLaunchInfo &launch_info)
Definition Platform.h:762
virtual const char * GetCacheHostname()
virtual Status SetFilePermissions(const FileSpec &file_spec, uint32_t file_permissions)
Definition Platform.cpp:732
virtual bool GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &proc_info)
bool IsHost() const
Definition Platform.h:557
virtual llvm::SmallDenseMap< FileSpec, LoadScriptFromSymFile > LocateExecutableScriptingResourcesForPlatform(Target *target, Module &module, Stream &feedback_stream)
Locate the platform-specific scripting resource given a module specification.
Definition Platform.cpp:243
std::function< Status(const ModuleSpec &)> ModuleResolver
Definition Platform.h:1138
Status GetRemoteSharedModule(const ModuleSpec &module_spec, Target *target, lldb::ModuleSP &module_sp, const ModuleResolver &module_resolver, bool *did_create_ptr)
static LoadScriptFromSymFile GetScriptLoadStyleForModule(const FileSpec &module_fspec, const Target &target)
Returns the LoadScriptFromSymFile of scripting resource associated with the specified module FileSpec...
Definition Platform.cpp:177
virtual Environment GetEnvironment()
virtual const lldb::UnixSignalsSP & GetRemoteUnixSignals()
std::string m_rsync_opts
Definition Platform.h:1085
virtual Status ConnectRemote(Args &args)
Definition Platform.cpp:981
uint32_t LoadImageUsingPaths(lldb_private::Process *process, const lldb_private::FileSpec &library_name, const std::vector< std::string > &paths, lldb_private::Status &error, lldb_private::FileSpec *loaded_path)
Load a shared library specified by base name into this process, looking by hand along a set of paths.
virtual std::vector< ArchSpec > GetSupportedArchitectures(const ArchSpec &process_host_arch)=0
Get the platform's supported architectures in the order in which they should be searched.
virtual Args GetExtraStartupCommands()
virtual bool ResolveRemotePath(const FileSpec &platform_path, FileSpec &resolved_platform_path)
Resolves the FileSpec to a (possibly) remote path.
Definition Platform.cpp:911
virtual lldb_private::Status RunShellCommand(llvm::StringRef command, const FileSpec &working_dir, int *status_ptr, int *signo_ptr, std::string *command_output, std::string *separated_error_output, const Timeout< std::micro > &timeout)
std::function< Status(const ModuleSpec &module_spec, FileSpec &module_file_spec, FileSpec &symbol_file_spec)> LocateModuleCallback
Definition Platform.h:1031
std::string m_sdk_sysroot
Definition Platform.h:1070
std::string m_ssh_opts
Definition Platform.h:1088
virtual llvm::ErrorOr< llvm::MD5::MD5Result > CalculateMD5(const FileSpec &file_spec)
virtual Status ShellExpandArguments(ProcessLaunchInfo &launch_info)
Perform expansion of the command-line for this launch info This can potentially involve wildcard expa...
virtual lldb::ProcessSP ConnectProcessSynchronous(llvm::StringRef connect_url, llvm::StringRef plugin_name, Debugger &debugger, Stream &stream, Target *target, Status &error)
static const char * GetHostPlatformName()
Definition Platform.cpp:68
virtual uint64_t ReadFile(lldb::user_id_t fd, uint64_t offset, void *dst, uint64_t dst_len, Status &error)
Definition Platform.cpp:770
virtual bool GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec)
Definition Platform.cpp:311
std::optional< std::string > GetOSKernelDescription()
Definition Platform.cpp:450
static llvm::SmallDenseMap< FileSpec, LoadScriptFromSymFile > LocateExecutableScriptingResourcesFromSafePaths(Stream &feedback_stream, FileSpec module_spec, const Target &target)
Helper function for LocateExecutableScriptingResources which gathers FileSpecs for executable scripts...
Definition Platform.cpp:188
virtual llvm::StringRef GetPluginName()=0
static PlatformCreateInstance GetPlatformCreateCallbackForPluginName(llvm::StringRef name)
static llvm::SmallVector< StructuredDataPluginCallbacks > GetStructuredDataPluginCallbacks()
static llvm::SmallVector< PlatformCreateInstance > GetPlatformCreateCallbacks()
void SetHijackListener(const lldb::ListenerSP &listener_sp)
lldb::ListenerSP GetHijackListener() const
lldb::pid_t GetProcessID() const
Definition ProcessInfo.h:66
const FileSpec & GetShell() const
bool ConvertArgumentsForLaunchingInShell(Status &error, bool will_debug, bool first_arg_is_full_shell_command, uint32_t num_resumes)
void SetLaunchInSeparateProcessGroup(bool separate)
A plug-in interface definition class for debugging a process.
Definition Process.h:368
static bool HandleProcessStateChangedEvent(const lldb::EventSP &event_sp, Stream *stream, SelectMostRelevant select_most_relevant, bool &pop_process_io_handler)
Centralize the code that handles and prints descriptions for process state changes.
Definition Process.cpp:792
virtual llvm::VersionTuple GetHostOSVersion()
Sometimes the connection to a process can detect the host OS version that the process is running on.
Definition Process.h:1257
lldb::OptionValuePropertiesSP m_collection_sp
T GetPropertyAtIndexAs(uint32_t idx, T default_value, const ExecutionContext *exe_ctx=nullptr) const
bool SetPropertyAtIndex(uint32_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
@ invalid_fd
Invalid file descriptor value.
int ReleasePrimaryFileDescriptor()
Release the primary file descriptor.
Holds an lldb_private::Module name and a "sanitized" version of it for the purposes of loading a scri...
bool RequiredSanitization() const
Returns true if the original name has been sanitized (i.e., required changes).
bool IsKeyword() const
Returns true if this name is a keyword in the associated scripting language.
virtual SanitizedScriptingModuleName GetSanitizedScriptingModuleName(llvm::StringRef name)
An error handling class.
Definition Status.h:118
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
const char * GetData() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t EOL()
Output and End of Line character to the stream.
Definition Stream.cpp:155
Provides public interface for all SymbolFiles.
Definition SymbolFile.h:51
virtual uint32_t GetNumCompileUnits()=0
virtual lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx)=0
virtual XcodeSDKAndSysroot ParseXcodeSDK(CompileUnit &comp_unit)
Return the Xcode SDK comp_unit was compiled against.
Definition SymbolFile.h:152
Status CreateTarget(Debugger &debugger, llvm::StringRef user_exe_path, llvm::StringRef triple_str, LoadDependentFiles get_dependent_modules, const OptionGroupPlatform *platform_options, lldb::TargetSP &target_sp)
Create a new Target.
std::optional< LoadScriptFromSymFile > GetAutoLoadScriptsForModule(llvm::StringRef module_name) const
Definition Target.cpp:6006
LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const
Definition Target.cpp:5811
Debugger & GetDebugger() const
Definition Target.h:1356
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:330
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition Target.cpp:318
FileSpecList GetSafeAutoLoadPaths() const
Get the list of paths that LLDB will consider automatically loading scripting resources from.
Definition Target.cpp:6145
static ArchSpec GetDefaultArchitecture()
Definition Target.cpp:2929
const ArchSpec & GetArchitecture() const
Definition Target.h:1315
Represents UUID's of various sizes.
Definition UUID.h:27
std::string GetAsString(llvm::StringRef separator="-") const
Definition UUID.cpp:54
bool IsValid() const
Definition UUID.h:69
static lldb::UnixSignalsSP CreateForHost()
An abstract interface for things that know how to map numeric user/group IDs into names.
static UserIDResolver & GetNoopResolver()
Returns a resolver which returns a failure value for each query.
An abstraction which groups an XcodeSDK with the sysroot it was used from.
Definition XcodeSDK.h:101
void Merge(const XcodeSDKAndSysroot &other)
Definition XcodeSDK.cpp:312
#define UINT64_MAX
#define LLDB_OPT_SET_ALL
#define LLDB_INVALID_IMAGE_TOKEN
#define UINT32_MAX
#define LLDB_INVALID_PROCESS_ID
@ SelectMostRelevantFrame
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
LoadScriptFromSymFile
Definition Target.h:61
llvm::SmallVector< lldb::addr_t, 6 > MmapArgList
Definition Platform.h:69
lldb::PlatformSP(* PlatformCreateInstance)(bool force, const ArchSpec *arch)
@ eMmapFlagsPrivate
Definition Platform.h:47
std::vector< ProcessInstanceInfo > ProcessInstanceInfoList
Definition Host.h:32
@ eScriptLanguagePython
std::shared_ptr< lldb_private::BreakpointLocation > BreakpointLocationSP
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
std::shared_ptr< lldb_private::Platform > PlatformSP
@ eErrorTypeGeneric
Generic errors that can be any value.
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::Event > EventSP
uint64_t pid_t
Definition lldb-types.h:84
@ eArgTypeCommandName
std::shared_ptr< lldb_private::Listener > ListenerSP
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
std::shared_ptr< lldb_private::Module > ModuleSP
const FileSpec & dst
Definition Platform.cpp:483
Platform * platform_ptr
Definition Platform.cpp:484
#define SIGKILL