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