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