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