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