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