[Go to site: main page, start]

LLDB mainline
Target.cpp
Go to the documentation of this file.
1//===-- Target.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
21#include "lldb/Core/Debugger.h"
22#include "lldb/Core/Module.h"
26#include "lldb/Core/Section.h"
29#include "lldb/Core/Telemetry.h"
36#include "lldb/Host/Host.h"
37#include "lldb/Host/PosixApi.h"
49#include "lldb/Symbol/Symbol.h"
50#include "lldb/Target/ABI.h"
54#include "lldb/Target/Process.h"
60#include "lldb/Target/Thread.h"
64#include "lldb/Utility/Event.h"
68#include "lldb/Utility/Log.h"
70#include "lldb/Utility/State.h"
72#include "lldb/Utility/Timer.h"
73
74#include "llvm/ADT/STLExtras.h"
75#include "llvm/ADT/ScopeExit.h"
76#include "llvm/ADT/SetVector.h"
77#include "llvm/Support/ErrorExtras.h"
78#include "llvm/Support/ThreadPool.h"
79
80#include <memory>
81#include <mutex>
82#include <optional>
83#include <sstream>
84
85using namespace lldb;
86using namespace lldb_private;
87
88namespace {
89
90struct ExecutableInstaller {
91
92 ExecutableInstaller(PlatformSP platform, ModuleSP module)
93 : m_platform{platform}, m_module{module},
94 m_local_file{m_module->GetFileSpec()},
95 m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
96
97 void setupRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
98
99 PlatformSP m_platform;
100 ModuleSP m_module;
101 const FileSpec m_local_file;
102 const FileSpec m_remote_file;
103};
104
105struct MainExecutableInstaller {
106
107 MainExecutableInstaller(PlatformSP platform, ModuleSP module, TargetSP target,
108 ProcessLaunchInfo &launch_info)
109 : m_platform{platform}, m_module{module},
110 m_local_file{m_module->GetFileSpec()},
111 m_remote_file{
112 getRemoteFileSpec(m_platform, target, m_module, m_local_file)},
113 m_launch_info{launch_info} {}
114
115 void setupRemoteFile() const {
116 m_module->SetPlatformFileSpec(m_remote_file);
117 m_launch_info.SetExecutableFile(m_remote_file,
118 /*add_exe_file_as_first_arg=*/false);
119 m_platform->SetFilePermissions(m_remote_file, 0700 /*-rwx------*/);
120 }
121
122 PlatformSP m_platform;
123 ModuleSP m_module;
124 const FileSpec m_local_file;
125 const FileSpec m_remote_file;
126
127private:
128 static FileSpec getRemoteFileSpec(PlatformSP platform, TargetSP target,
129 ModuleSP module,
130 const FileSpec &local_file) {
131 FileSpec remote_file = module->GetRemoteInstallFileSpec();
132 if (remote_file || !target->GetAutoInstallMainExecutable())
133 return remote_file;
134
135 if (!local_file)
136 return {};
137
138 remote_file = platform->GetRemoteWorkingDirectory();
139 remote_file.AppendPathComponent(local_file.GetFilename());
140
141 return remote_file;
142 }
143
144 ProcessLaunchInfo &m_launch_info;
145};
146} // namespace
147
148static std::atomic<lldb::user_id_t> g_target_unique_id{1};
149
150template <typename Installer>
151static Status installExecutable(const Installer &installer) {
152 if (!installer.m_local_file || !installer.m_remote_file)
153 return Status();
154
155 Status error = installer.m_platform->Install(installer.m_local_file,
156 installer.m_remote_file);
157 if (error.Fail())
158 return error;
159
160 installer.setupRemoteFile();
161 return Status();
162}
163
165 : m_spec(spec),
166 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
167
169 m_spec = spec;
171 return *this;
172}
173
175 static constexpr llvm::StringLiteral class_name("lldb.target");
176 return class_name;
177}
178
179Target::Target(Debugger &debugger, const ArchSpec &target_arch,
180 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
181 : TargetProperties(this),
182 Broadcaster(debugger.GetBroadcasterManager(),
184 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
185 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
191 m_suppress_stop_hooks(false), m_is_dummy_target(is_dummy_target),
194 llvm::formatv("Session {0}", m_target_unique_id).str()),
196 std::make_unique<StackFrameRecognizerManager>()) {
197 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
198 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
199 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
200 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
201 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
202 SetEventName(eBroadcastBitNewTargetCreated, "new-target-created");
203
205
206 LLDB_LOG(GetLog(LLDBLog::Object), "{0} Target::Target()",
207 static_cast<void *>(this));
208 if (target_arch.IsValid()) {
210 "Target::Target created with architecture {0} ({1})",
211 target_arch.GetArchitectureName(),
212 target_arch.GetTriple().getTriple().c_str());
213 }
214
216}
217
219 Log *log = GetLog(LLDBLog::Object);
220 LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this));
222}
223
225 m_stop_hooks = target.m_stop_hooks;
228 m_hooks = target.m_hooks;
230
231 for (const auto &breakpoint_sp : target.m_breakpoint_list.Breakpoints()) {
232 if (breakpoint_sp->IsInternal())
233 continue;
234
235 BreakpointSP new_bp(
236 Breakpoint::CopyFromBreakpoint(shared_from_this(), *breakpoint_sp));
237 AddBreakpoint(std::move(new_bp), false);
238 }
239
240 for (const auto &bp_name_entry : target.m_breakpoint_names) {
241 AddBreakpointName(std::make_unique<BreakpointName>(*bp_name_entry.second));
242 }
243
244 for (auto const &elem : target.m_breakpoint_overrides) {
245 BreakpointResolverOverrideUP new_override_up =
246 elem.second->CopyIntoNewTarget(*this);
247 if (new_override_up->Validate())
248 AddBreakpointResolverOverride(std::move(new_override_up));
249 }
250
251 m_frame_recognizer_manager_up = std::make_unique<StackFrameRecognizerManager>(
253
255}
256
257void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
258 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
259 if (description_level != lldb::eDescriptionLevelBrief) {
260 s->Indent();
261 s->PutCString("Target\n");
262 s->IndentMore();
263 m_images.Dump(s);
264 m_breakpoint_list.Dump(s);
266 s->IndentLess();
267 } else {
268 Module *exe_module = GetExecutableModulePointer();
269 if (exe_module)
270 s->PutCString(exe_module->GetFileSpec().GetFilename());
271 else
272 s->PutCString("No executable module.");
273 }
274}
275
277 // Do any cleanup of the target we need to do between process instances.
278 // NB It is better to do this before destroying the process in case the
279 // clean up needs some help from the process.
280 m_breakpoint_list.ClearAllBreakpointSites();
281 m_internal_breakpoint_list.ClearAllBreakpointSites();
283 llvm::consumeError(m_process_sp->FlushDelayedBreakpoints());
284 // Disable watchpoints just on the debugger side.
285 std::unique_lock<std::recursive_mutex> lock;
286 this->GetWatchpointList().GetListMutex(lock);
291}
292
294 if (m_process_sp) {
295 // We dispose any active tracing sessions on the current process
296 m_trace_sp.reset();
297
298 if (m_process_sp->IsAlive())
299 m_process_sp->Destroy(false);
300
301 m_process_sp->Finalize(false /* not destructing */);
302
303 // Let the process finalize itself first, then clear the section load
304 // history. Some objects owned by the process might end up calling
305 // SectionLoadHistory::SetSectionUnloaded() which can create entries in
306 // the section load history that can mess up subsequent processes.
308
310
311 m_process_sp.reset();
312 }
313}
314
316 llvm::StringRef plugin_name,
317 const FileSpec *crash_file,
318 bool can_connect) {
319 if (!listener_sp)
320 listener_sp = GetDebugger().GetListener();
322 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
323 listener_sp, crash_file, can_connect);
324 return m_process_sp;
325}
326
328
330 const char *repl_options, bool can_create) {
331 if (language == eLanguageTypeUnknown)
332 language = m_debugger.GetREPLLanguage();
333
334 if (language == eLanguageTypeUnknown) {
336
337 if (auto single_lang = repl_languages.GetSingularLanguage()) {
338 language = *single_lang;
339 } else if (repl_languages.Empty()) {
341 "LLDB isn't configured with REPL support for any languages.");
342 return REPLSP();
343 } else {
345 "Multiple possible REPL languages. Please specify a language.");
346 return REPLSP();
347 }
348 }
349
350 REPLMap::iterator pos = m_repl_map.find(language);
351
352 if (pos != m_repl_map.end()) {
353 return pos->second;
354 }
355
356 if (!can_create) {
358 "Couldn't find an existing REPL for %s, and can't create a new one",
360 return lldb::REPLSP();
361 }
362
363 Debugger *const debugger = nullptr;
364 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
365
366 if (ret) {
367 m_repl_map[language] = ret;
368 return m_repl_map[language];
369 }
370
371 if (err.Success()) {
373 "Couldn't create a REPL for %s",
375 }
376
377 return lldb::REPLSP();
378}
379
381 lldbassert(!m_repl_map.count(language));
382
383 m_repl_map[language] = repl_sp;
384}
385
387 std::lock_guard<std::recursive_mutex> guard(m_mutex);
388 m_valid = false;
390 m_platform_sp.reset();
391 m_arch = ArchSpec();
392 ClearModules(true);
394 const bool notify = false;
395 m_breakpoint_list.RemoveAll(notify);
396 m_internal_breakpoint_list.RemoveAll(notify);
398 m_watchpoint_list.RemoveAll(notify);
400 m_search_filter_sp.reset();
401 m_image_search_paths.Clear(notify);
402 m_stop_hooks.clear();
404 m_internal_stop_hooks.clear();
405 m_suppress_stop_hooks = false;
406 m_repl_map.clear();
407 Args signal_args;
408 ClearDummySignals(signal_args);
409}
410
411llvm::StringRef Target::GetABIName() const {
412 lldb::ABISP abi_sp;
413 if (m_process_sp)
414 abi_sp = m_process_sp->GetABI();
415 if (!abi_sp)
417 if (abi_sp)
418 return abi_sp->GetPluginName();
419 return {};
420}
421
423 if (internal)
425 else
426 return m_breakpoint_list;
427}
428
429const BreakpointList &Target::GetBreakpointList(bool internal) const {
430 if (internal)
432 else
433 return m_breakpoint_list;
434}
435
437 BreakpointSP bp_sp;
438
439 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
440 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
441 else
442 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
443
444 return bp_sp;
445}
446
449 ModuleSP main_module_sp = GetExecutableModule();
450 FileSpecList shared_lib_filter;
451 shared_lib_filter.Append(main_module_sp->GetFileSpec());
452 llvm::SetVector<std::string, std::vector<std::string>,
453 std::unordered_set<std::string>>
454 entryPointNamesSet;
456 Language *lang = Language::FindPlugin(lang_type);
457 if (!lang) {
458 error = Status::FromErrorString("Language not found\n");
459 return lldb::BreakpointSP();
460 }
461 std::string entryPointName = lang->GetUserEntryPointName().str();
462 if (!entryPointName.empty())
463 entryPointNamesSet.insert(entryPointName);
464 }
465 if (entryPointNamesSet.empty()) {
466 error = Status::FromErrorString("No entry point name found\n");
467 return lldb::BreakpointSP();
468 }
470 &shared_lib_filter,
471 /*containingSourceFiles=*/nullptr, entryPointNamesSet.takeVector(),
472 /*func_name_type_mask=*/eFunctionNameTypeFull,
473 /*language=*/eLanguageTypeUnknown,
474 /*offset=*/0,
475 /*skip_prologue=*/eLazyBoolNo,
476 /*internal=*/false,
477 /*hardware=*/false);
478 if (!bp_sp) {
479 error = Status::FromErrorString("Breakpoint creation failed.\n");
480 return lldb::BreakpointSP();
481 }
482 bp_sp->SetOneShot(true);
483 return bp_sp;
484}
485
487 const FileSpecList *containingModules,
488 const FileSpecList *source_file_spec_list,
489 const std::unordered_set<std::string> &function_names,
490 RegularExpression source_regex, bool internal, bool hardware,
491 LazyBool move_to_nearest_code) {
493 containingModules, source_file_spec_list));
494 if (move_to_nearest_code == eLazyBoolCalculate)
495 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
497 nullptr, std::move(source_regex), function_names,
498 !static_cast<bool>(move_to_nearest_code)));
499
500 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
501}
502
504 const FileSpec &file, uint32_t line_no,
505 uint32_t column, lldb::addr_t offset,
506 LazyBool check_inlines,
507 LazyBool skip_prologue, bool internal,
508 bool hardware,
509 LazyBool move_to_nearest_code) {
510 FileSpec remapped_file;
511 std::optional<llvm::StringRef> removed_prefix_opt =
512 GetSourcePathMap().ReverseRemapPath(file, remapped_file);
513 if (!removed_prefix_opt)
514 remapped_file = file;
515
516 if (check_inlines == eLazyBoolCalculate) {
517 const InlineStrategy inline_strategy = GetInlineStrategy();
518 switch (inline_strategy) {
520 check_inlines = eLazyBoolNo;
521 break;
522
524 if (remapped_file.IsSourceImplementationFile())
525 check_inlines = eLazyBoolNo;
526 else
527 check_inlines = eLazyBoolYes;
528 break;
529
531 check_inlines = eLazyBoolYes;
532 break;
533 }
534 }
535 SearchFilterSP filter_sp;
536 if (check_inlines == eLazyBoolNo) {
537 // Not checking for inlines, we are looking only for matching compile units
538 FileSpecList compile_unit_list;
539 compile_unit_list.Append(remapped_file);
540 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
541 &compile_unit_list);
542 } else {
543 filter_sp = GetSearchFilterForModuleList(containingModules);
544 }
545 if (skip_prologue == eLazyBoolCalculate)
546 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
547 if (move_to_nearest_code == eLazyBoolCalculate)
548 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
549
550 SourceLocationSpec location_spec(remapped_file, line_no, column,
551 check_inlines,
552 !static_cast<bool>(move_to_nearest_code));
553 if (!location_spec)
554 return nullptr;
555
557 nullptr, offset, skip_prologue, location_spec, removed_prefix_opt));
558 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
559}
560
562 bool hardware) {
563 Address so_addr;
564
565 // Check for any reason we want to move this breakpoint to other address.
566 addr = GetBreakableLoadAddress(addr);
567
568 // Attempt to resolve our load address if possible, though it is ok if it
569 // doesn't resolve to section/offset.
570
571 // Try and resolve as a load address if possible
572 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
573 if (!so_addr.IsValid()) {
574 // The address didn't resolve, so just set this as an absolute address
575 so_addr.SetOffset(addr);
576 }
577 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
578 return bp_sp;
579}
580
582 bool hardware) {
583 SearchFilterSP filter_sp =
584 std::make_shared<SearchFilterForUnconstrainedSearches>(
585 shared_from_this());
586 BreakpointResolverSP resolver_sp =
587 std::make_shared<BreakpointResolverAddress>(nullptr, addr);
588 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
589}
590
593 const FileSpec &file_spec,
594 bool request_hardware) {
595 SearchFilterSP filter_sp =
596 std::make_shared<SearchFilterForUnconstrainedSearches>(
597 shared_from_this());
598 BreakpointResolverSP resolver_sp =
599 std::make_shared<BreakpointResolverAddress>(nullptr, Address(file_addr),
600 file_spec);
601 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
602 false);
603}
604
606 const FileSpecList *containingModules,
607 const FileSpecList *containingSourceFiles, const char *func_name,
608 FunctionNameType func_name_type_mask, LanguageType language,
609 lldb::addr_t offset, bool offset_is_insn_count, LazyBool skip_prologue,
610 bool internal, bool hardware) {
611 BreakpointSP bp_sp;
612 if (func_name) {
614 containingModules, containingSourceFiles));
615
616 if (skip_prologue == eLazyBoolCalculate)
617 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
618 if (language == lldb::eLanguageTypeUnknown)
619 language = GetLanguage().AsLanguageType();
620
622 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
623 offset, offset_is_insn_count, skip_prologue));
624 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
625 }
626 return bp_sp;
627}
628
630Target::CreateBreakpoint(const FileSpecList *containingModules,
631 const FileSpecList *containingSourceFiles,
632 const std::vector<std::string> &func_names,
633 FunctionNameType func_name_type_mask,
634 LanguageType language, lldb::addr_t offset,
635 LazyBool skip_prologue, bool internal, bool hardware) {
636 BreakpointSP bp_sp;
637 size_t num_names = func_names.size();
638 if (num_names > 0) {
640 containingModules, containingSourceFiles));
641
642 if (skip_prologue == eLazyBoolCalculate)
643 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
644 if (language == lldb::eLanguageTypeUnknown)
645 language = GetLanguage().AsLanguageType();
646
647 BreakpointResolverSP resolver_sp(
648 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
649 language, offset, skip_prologue));
650 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
651 }
652 return bp_sp;
653}
654
656Target::CreateBreakpoint(const FileSpecList *containingModules,
657 const FileSpecList *containingSourceFiles,
658 const char *func_names[], size_t num_names,
659 FunctionNameType func_name_type_mask,
660 LanguageType language, lldb::addr_t offset,
661 LazyBool skip_prologue, bool internal, bool hardware) {
662 BreakpointSP bp_sp;
663 if (num_names > 0) {
665 containingModules, containingSourceFiles));
666
667 if (skip_prologue == eLazyBoolCalculate) {
668 if (offset == 0)
669 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
670 else
671 skip_prologue = eLazyBoolNo;
672 }
673 if (language == lldb::eLanguageTypeUnknown)
674 language = GetLanguage().AsLanguageType();
675
676 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
677 nullptr, func_names, num_names, func_name_type_mask, language, offset,
678 skip_prologue));
679 resolver_sp->SetOffset(offset);
680 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
681 }
682 return bp_sp;
683}
684
687 SearchFilterSP filter_sp;
688 if (containingModule != nullptr) {
689 // TODO: We should look into sharing module based search filters
690 // across many breakpoints like we do for the simple target based one
691 filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(),
692 *containingModule);
693 } else {
696 std::make_shared<SearchFilterForUnconstrainedSearches>(
697 shared_from_this());
698 filter_sp = m_search_filter_sp;
699 }
700 return filter_sp;
701}
702
705 SearchFilterSP filter_sp;
706 if (containingModules && containingModules->GetSize() != 0) {
707 // TODO: We should look into sharing module based search filters
708 // across many breakpoints like we do for the simple target based one
709 filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(),
710 *containingModules);
711 } else {
714 std::make_shared<SearchFilterForUnconstrainedSearches>(
715 shared_from_this());
716 filter_sp = m_search_filter_sp;
717 }
718 return filter_sp;
719}
720
722 const FileSpecList *containingModules,
723 const FileSpecList *containingSourceFiles) {
724 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
725 return GetSearchFilterForModuleList(containingModules);
726
727 SearchFilterSP filter_sp;
728 if (containingModules == nullptr) {
729 // We could make a special "CU List only SearchFilter". Better yet was if
730 // these could be composable, but that will take a little reworking.
731
732 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
733 shared_from_this(), FileSpecList(), *containingSourceFiles);
734 } else {
735 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
736 shared_from_this(), *containingModules, *containingSourceFiles);
737 }
738 return filter_sp;
739}
740
742 const FileSpecList *containingModules,
743 const FileSpecList *containingSourceFiles, RegularExpression func_regex,
744 lldb::LanguageType requested_language, LazyBool skip_prologue,
745 bool internal, bool hardware) {
747 containingModules, containingSourceFiles));
748 bool skip = (skip_prologue == eLazyBoolCalculate)
750 : static_cast<bool>(skip_prologue);
752 nullptr, std::move(func_regex), requested_language, 0, skip));
753
754 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
755}
756
759 bool catch_bp, bool throw_bp, bool internal,
760 Args *additional_args, Status *error) {
762 *this, language, catch_bp, throw_bp, internal);
763 if (exc_bkpt_sp && additional_args) {
764 BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
765 if (precondition_sp && additional_args) {
766 if (error)
767 *error = precondition_sp->ConfigurePrecondition(*additional_args);
768 else
769 precondition_sp->ConfigurePrecondition(*additional_args);
770 }
771 }
772 return exc_bkpt_sp;
773}
774
776 const llvm::StringRef class_name, const FileSpecList *containingModules,
777 const FileSpecList *containingSourceFiles, bool internal,
778 bool request_hardware, StructuredData::ObjectSP extra_args_sp,
779 Status *creation_error) {
780 SearchFilterSP filter_sp;
781
783 bool has_files =
784 containingSourceFiles && containingSourceFiles->GetSize() > 0;
785 bool has_modules = containingModules && containingModules->GetSize() > 0;
786
787 if (has_files && has_modules) {
788 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
789 containingSourceFiles);
790 } else if (has_files) {
791 filter_sp =
792 GetSearchFilterForModuleAndCUList(nullptr, containingSourceFiles);
793 } else if (has_modules) {
794 filter_sp = GetSearchFilterForModuleList(containingModules);
795 } else {
796 filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
797 shared_from_this());
798 }
799
801 nullptr, class_name, depth, StructuredDataImpl(extra_args_sp)));
802 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
803}
804
806 BreakpointResolverSP &resolver_sp,
807 bool internal, bool request_hardware,
808 bool resolve_indirect_symbols) {
809 BreakpointSP bp_sp;
810 if (filter_sp && resolver_sp) {
811 // Now check whether there are any "Breakpoint Overrides" registered, and
812 // if there are see if one of them want to handle this request instead.
813 // But we don't allow overrides for internal breakpoints:
814 if (!internal) {
815 BreakpointResolverSP overridden_sp =
816 CheckBreakpointOverrides(resolver_sp);
817 if (overridden_sp)
818 resolver_sp = overridden_sp;
819 }
820 const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
821 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
822 resolve_indirect_symbols));
823 resolver_sp->SetBreakpoint(bp_sp);
824 AddBreakpoint(bp_sp, internal);
825 }
826 return bp_sp;
827}
828
829void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
830 if (!bp_sp)
831 return;
832 if (internal)
833 m_internal_breakpoint_list.Add(bp_sp, false);
834 else
835 m_breakpoint_list.Add(bp_sp, true);
836
838 if (log) {
839 StreamString s;
840 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
841 LLDB_LOGF(log, "Target::%s (internal = %s) => break_id = %s\n",
842 __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
843 }
844
845 bp_sp->ResolveBreakpoint();
846
847 if (!internal) {
849 }
850}
851
852void Target::AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name,
853 Status &error) {
854 BreakpointSP bp_sp =
855 m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
856 if (!bp_sp) {
857 StreamString s;
858 id.GetDescription(&s, eDescriptionLevelBrief);
859 error = Status::FromErrorStringWithFormat("Could not find breakpoint %s",
860 s.GetData());
861 return;
862 }
863 AddNameToBreakpoint(bp_sp, name, error);
864}
865
866void Target::AddNameToBreakpoint(BreakpointSP &bp_sp, llvm::StringRef name,
867 Status &error) {
868 if (!bp_sp)
869 return;
870
871 BreakpointName *bp_name = FindBreakpointName(name, true, error);
872 if (!bp_name)
873 return;
874
875 bp_name->ConfigureBreakpoint(bp_sp);
876 bp_sp->AddName(name);
877}
878
879void Target::AddBreakpointName(std::unique_ptr<BreakpointName> bp_name) {
880 m_breakpoint_names.insert(
881 std::make_pair(bp_name->GetName(), std::move(bp_name)));
882}
883
885 bool can_create, Status &error) {
887 if (!error.Success())
888 return nullptr;
889
890 BreakpointNameMap::iterator iter = m_breakpoint_names.find(name);
891 if (iter != m_breakpoint_names.end()) {
892 return iter->second.get();
893 }
894
895 if (!can_create) {
897 "Breakpoint name \"{0}\" doesn't exist and can_create is false.", name);
898 return nullptr;
899 }
900
901 return m_breakpoint_names
902 .insert(
903 std::make_pair(name, std::make_unique<BreakpointName>(name.str())))
904 .first->second.get();
905}
906
907void Target::DeleteBreakpointName(llvm::StringRef name) {
908 BreakpointNameMap::iterator iter = m_breakpoint_names.find(name);
909
910 if (iter != m_breakpoint_names.end()) {
911 m_breakpoint_names.erase(iter);
912 for (auto bp_sp : m_breakpoint_list.Breakpoints())
913 bp_sp->RemoveName(name);
914 }
915}
916
918 llvm::StringRef name) {
919 bp_sp->RemoveName(name);
920}
921
923 BreakpointName &bp_name, const BreakpointOptions &new_options,
924 const BreakpointName::Permissions &new_permissions) {
925 bp_name.GetOptions().CopyOverSetOptions(new_options);
926 bp_name.GetPermissions().MergeInto(new_permissions);
927 ApplyNameToBreakpoints(bp_name);
928}
929
931 llvm::Expected<std::vector<BreakpointSP>> expected_vector =
932 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName());
933
934 if (!expected_vector) {
935 LLDB_LOG(GetLog(LLDBLog::Breakpoints), "invalid breakpoint name: {}",
936 llvm::toString(expected_vector.takeError()));
937 return;
938 }
939
940 for (auto bp_sp : *expected_vector)
941 bp_name.ConfigureBreakpoint(bp_sp);
942}
943
944void Target::GetBreakpointNames(std::vector<std::string> &names) {
945 names.clear();
946 for (const auto &bp_name_entry : m_breakpoint_names) {
947 names.push_back(bp_name_entry.first().str());
948 }
949 llvm::sort(names);
950}
951
952llvm::Expected<lldb::user_id_t> Target::AddBreakpointResolverOverride(
953 llvm::StringRef class_name, uint64_t type_mask,
954 StructuredData::DictionarySP args_data_sp, llvm::StringRef description) {
955 if (class_name.empty())
956 return llvm::createStringError(llvm::inconvertibleErrorCode(),
957 "empty class name");
958
960 return llvm::createStringErrorV(
961 llvm::inconvertibleErrorCode(),
962 "invalid breakpoint type mask: {0}, should be composed of the "
963 "elements of the BreakpointResolverType enum.",
964 type_mask);
965
967 impl.SetObjectSP(args_data_sp);
968
969 BreakpointResolverOverrideUP new_override_up(
970 new ScriptedBreakpointResolverOverride(*this, std::string(description),
971 type_mask, std::string(class_name),
972 impl));
973 llvm::Error error = new_override_up->Validate();
974 if (error)
975 return error;
976
977 return AddBreakpointResolverOverride(std::move(new_override_up));
978}
979
983
985 std::vector<lldb::user_id_t> &idxs,
986 uint32_t output_width,
987 bool use_color) {
988 if (m_breakpoint_overrides.size() == 0) {
989 stream << "No overrides.\n";
990 return;
991 }
992
993 bool empty = idxs.empty();
994 bool print_first = true;
995 for (auto const &elem : m_breakpoint_overrides) {
996 auto idx_pos = llvm::find(idxs, elem.first);
997 if (empty || idx_pos != idxs.end()) {
998 if (print_first) {
999
1000 ansi::OutputWordWrappedLines(stream, "ID Mask Description\n",
1001 output_width, use_color);
1002 ansi::OutputWordWrappedLines(stream, "---- ------ -----------\n",
1003 output_width, use_color);
1004 print_first = false;
1005 }
1006 auto content = llvm::formatv("{0,4} {1,6} {2}\n", elem.first,
1007 elem.second->DescribeTypeMask(),
1008 elem.second->GetDescription())
1009 .str();
1010 ansi::OutputWordWrappedLines(stream, content, output_width, use_color);
1011 if (!empty)
1012 idxs.erase(idx_pos);
1013 }
1014 }
1015}
1016
1018 return (m_process_sp && m_process_sp->IsAlive());
1019}
1020
1023 for (auto const &elem : m_breakpoint_overrides) {
1024 if (!original_sp->ResolverTyInMask(elem.second->GetTypeMask()))
1025 continue;
1026 if (lldb::BreakpointResolverSP overriden_sp =
1027 elem.second->CheckForOverride(*this, original_sp))
1028 return overriden_sp;
1029 }
1030 return {};
1031}
1032
1034 std::optional<uint32_t> num_supported_hardware_watchpoints =
1035 target->GetProcessSP()->GetWatchpointSlotCount();
1036
1037 // If unable to determine the # of watchpoints available,
1038 // assume they are supported.
1039 if (!num_supported_hardware_watchpoints)
1040 return true;
1041
1042 if (*num_supported_hardware_watchpoints == 0) {
1044 "Target supports (%u) hardware watchpoint slots.\n",
1045 *num_supported_hardware_watchpoints);
1046 return false;
1047 }
1048 return true;
1049}
1050
1051// See also Watchpoint::SetWatchpointType(uint32_t type) and the
1052// OptionGroupWatchpoint::WatchType enum type.
1054 const CompilerType *type, uint32_t kind,
1055 Status &error) {
1057 LLDB_LOGF(log,
1058 "Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
1059 " type = %u)\n",
1060 __FUNCTION__, addr, (uint64_t)size, kind);
1061
1062 WatchpointSP wp_sp;
1063 if (!ProcessIsValid()) {
1064 error = Status::FromErrorString("process is not alive");
1065 return wp_sp;
1066 }
1067
1068 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
1069 if (size == 0)
1071 "cannot set a watchpoint with watch_size of 0");
1072 else
1074 "invalid watch address: %" PRIu64, addr);
1075 return wp_sp;
1076 }
1077
1078 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
1079 error =
1080 Status::FromErrorStringWithFormat("invalid watchpoint type: %d", kind);
1081 }
1082
1084 return wp_sp;
1085
1086 // Currently we only support one watchpoint per address, with total number of
1087 // watchpoints limited by the hardware which the inferior is running on.
1088
1089 // Grab the list mutex while doing operations.
1090 const bool notify = false; // Don't notify about all the state changes we do
1091 // on creating the watchpoint.
1092
1093 // Mask off ignored bits from watchpoint address.
1094 if (ABISP abi = m_process_sp->GetABI())
1095 addr = abi->FixDataAddress(addr);
1096
1097 // LWP_TODO this sequence is looking for an existing watchpoint
1098 // at the exact same user-specified address, disables the new one
1099 // if addr/size/type match. If type/size differ, disable old one.
1100 // This isn't correct, we need both watchpoints to use a shared
1101 // WatchpointResource in the target, and expand the WatchpointResource
1102 // to handle the needs of both Watchpoints.
1103 // Also, even if the addresses don't match, they may need to be
1104 // supported by the same WatchpointResource, e.g. a watchpoint
1105 // watching 1 byte at 0x102 and a watchpoint watching 1 byte at 0x103.
1106 // They're in the same word and must be watched by a single hardware
1107 // watchpoint register.
1108
1109 std::unique_lock<std::recursive_mutex> lock;
1110 this->GetWatchpointList().GetListMutex(lock);
1111 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
1112 if (matched_sp) {
1113 size_t old_size = matched_sp->GetByteSize();
1114 uint32_t old_type =
1115 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
1116 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0) |
1117 (matched_sp->WatchpointModify() ? LLDB_WATCH_TYPE_MODIFY : 0);
1118 // Return the existing watchpoint if both size and type match.
1119 if (size == old_size && kind == old_type) {
1120 wp_sp = matched_sp;
1121 wp_sp->SetEnabled(false, notify);
1122 } else {
1123 // Nil the matched watchpoint; we will be creating a new one.
1124 m_process_sp->DisableWatchpoint(matched_sp, notify);
1125 m_watchpoint_list.Remove(matched_sp->GetID(), true);
1126 }
1127 }
1128
1129 if (!wp_sp) {
1130 wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type);
1131 wp_sp->SetWatchpointType(kind, notify);
1132 m_watchpoint_list.Add(wp_sp, true);
1133 }
1134
1135 error = m_process_sp->EnableWatchpoint(wp_sp, notify);
1136 LLDB_LOGF(log, "Target::%s (creation of watchpoint %s with id = %u)\n",
1137 __FUNCTION__, error.Success() ? "succeeded" : "failed",
1138 wp_sp->GetID());
1139
1140 if (error.Fail()) {
1141 // Enabling the watchpoint on the device side failed. Remove the said
1142 // watchpoint from the list maintained by the target instance.
1143 m_watchpoint_list.Remove(wp_sp->GetID(), true);
1144 wp_sp.reset();
1145 } else
1147 return wp_sp;
1148}
1149
1152 LLDB_LOGF(log, "Target::%s \n", __FUNCTION__);
1153
1154 m_breakpoint_list.RemoveAllowed(true);
1155
1157}
1158
1159void Target::RemoveAllBreakpoints(bool internal_also) {
1161 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1162 internal_also ? "yes" : "no");
1163
1164 m_breakpoint_list.RemoveAll(true);
1165 if (internal_also)
1166 m_internal_breakpoint_list.RemoveAll(false);
1167
1169}
1170
1171void Target::DisableAllBreakpoints(bool internal_also) {
1173 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1174 internal_also ? "yes" : "no");
1175
1176 m_breakpoint_list.SetEnabledAll(false);
1177 if (internal_also)
1178 m_internal_breakpoint_list.SetEnabledAll(false);
1179}
1180
1183 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
1184
1185 m_breakpoint_list.SetEnabledAllowed(false);
1186}
1187
1188void Target::EnableAllBreakpoints(bool internal_also) {
1190 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1191 internal_also ? "yes" : "no");
1192
1193 m_breakpoint_list.SetEnabledAll(true);
1194 if (internal_also)
1195 m_internal_breakpoint_list.SetEnabledAll(true);
1196}
1197
1200 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
1201
1202 m_breakpoint_list.SetEnabledAllowed(true);
1203}
1204
1207 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1208 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1209
1210 if (DisableBreakpointByID(break_id)) {
1211 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1212 m_internal_breakpoint_list.Remove(break_id, false);
1213 else {
1215 if (m_last_created_breakpoint->GetID() == break_id)
1217 }
1218 m_breakpoint_list.Remove(break_id, true);
1219 }
1220 return true;
1221 }
1222 return false;
1223}
1224
1227 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1228 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1229
1230 BreakpointSP bp_sp;
1231
1232 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1233 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
1234 else
1235 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1236 if (bp_sp) {
1237 bp_sp->SetEnabled(false);
1238 return true;
1239 }
1240 return false;
1241}
1242
1245 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1246 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1247
1248 BreakpointSP bp_sp;
1249
1250 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1251 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
1252 else
1253 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1254
1255 if (bp_sp) {
1256 bp_sp->SetEnabled(true);
1257 return true;
1258 }
1259 return false;
1260}
1261
1265
1267 const BreakpointIDList &bp_ids,
1268 bool append) {
1269 Status error;
1270
1271 if (!file) {
1272 error = Status::FromErrorString("Invalid FileSpec.");
1273 return error;
1274 }
1275
1276 std::string path(file.GetPath());
1277 StructuredData::ObjectSP input_data_sp;
1278
1279 StructuredData::ArraySP break_store_sp;
1280 StructuredData::Array *break_store_ptr = nullptr;
1281
1282 if (append) {
1283 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1284 if (error.Success()) {
1285 break_store_ptr = input_data_sp->GetAsArray();
1286 if (!break_store_ptr) {
1288 "Tried to append to invalid input file %s", path.c_str());
1289 return error;
1290 }
1291 }
1292 }
1293
1294 if (!break_store_ptr) {
1295 break_store_sp = std::make_shared<StructuredData::Array>();
1296 break_store_ptr = break_store_sp.get();
1297 }
1298
1299 StreamFile out_file(path.c_str(),
1303 lldb::eFilePermissionsFileDefault);
1304 if (!out_file.GetFile().IsValid()) {
1305 error = Status::FromErrorStringWithFormat("Unable to open output file: %s.",
1306 path.c_str());
1307 return error;
1308 }
1309
1310 std::unique_lock<std::recursive_mutex> lock;
1312
1313 if (bp_ids.GetSize() == 0) {
1314 const BreakpointList &breakpoints = GetBreakpointList();
1315
1316 size_t num_breakpoints = breakpoints.GetSize();
1317 for (size_t i = 0; i < num_breakpoints; i++) {
1318 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1320 // If a breakpoint can't serialize it, just ignore it for now:
1321 if (bkpt_save_sp)
1322 break_store_ptr->AddItem(bkpt_save_sp);
1323 }
1324 } else {
1325
1326 std::unordered_set<lldb::break_id_t> processed_bkpts;
1327 const size_t count = bp_ids.GetSize();
1328 for (size_t i = 0; i < count; ++i) {
1329 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1330 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1331
1332 if (bp_id != LLDB_INVALID_BREAK_ID) {
1333 // Only do each breakpoint once:
1334 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1335 insert_result = processed_bkpts.insert(bp_id);
1336 if (!insert_result.second)
1337 continue;
1338
1339 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1341 // If the user explicitly asked to serialize a breakpoint, and we
1342 // can't, then raise an error:
1343 if (!bkpt_save_sp) {
1345 "Unable to serialize breakpoint %d", bp_id);
1346 return error;
1347 }
1348 break_store_ptr->AddItem(bkpt_save_sp);
1349 }
1350 }
1351 }
1352
1353 break_store_ptr->Dump(out_file, false);
1354 out_file.PutChar('\n');
1355 return error;
1356}
1357
1359 BreakpointIDList &new_bps) {
1360 std::vector<std::string> no_names;
1361 return CreateBreakpointsFromFile(file, no_names, new_bps);
1362}
1363
1365 std::vector<std::string> &names,
1366 BreakpointIDList &new_bps) {
1367 std::unique_lock<std::recursive_mutex> lock;
1369
1370 Status error;
1371 StructuredData::ObjectSP input_data_sp =
1373 if (!error.Success()) {
1374 return error;
1375 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1377 "Invalid JSON from input file: %s.", file.GetPath().c_str());
1378 return error;
1379 }
1380
1381 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1382 if (!bkpt_array) {
1384 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1385 return error;
1386 }
1387
1388 size_t num_bkpts = bkpt_array->GetSize();
1389 size_t num_names = names.size();
1390
1391 for (size_t i = 0; i < num_bkpts; i++) {
1392 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1393 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1394 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1395 if (!bkpt_dict) {
1397 "Invalid breakpoint data for element %zu from input file: %s.", i,
1398 file.GetPath().c_str());
1399 return error;
1400 }
1401 StructuredData::ObjectSP bkpt_data_sp =
1403 if (num_names &&
1405 continue;
1406
1408 shared_from_this(), bkpt_data_sp, error);
1409 if (!error.Success()) {
1411 "Error restoring breakpoint %zu from %s: %s.", i,
1412 file.GetPath().c_str(), error.AsCString());
1413 return error;
1414 }
1415 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1416 }
1417 return error;
1418}
1419
1420// The flag 'end_to_end', default to true, signifies that the operation is
1421// performed end to end, for both the debugger and the debuggee.
1422
1423// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1424// to end operations.
1425bool Target::RemoveAllWatchpoints(bool end_to_end) {
1427 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1428
1429 if (!end_to_end) {
1430 m_watchpoint_list.RemoveAll(true);
1431 return true;
1432 }
1433
1434 // Otherwise, it's an end to end operation.
1435
1436 if (!ProcessIsValid())
1437 return false;
1438
1439 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1440 if (!wp_sp)
1441 return false;
1442
1443 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1444 if (rc.Fail())
1445 return false;
1446 }
1447 m_watchpoint_list.RemoveAll(true);
1449 return true; // Success!
1450}
1451
1452// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1453// to end operations.
1454bool Target::DisableAllWatchpoints(bool end_to_end) {
1456 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1457
1458 if (!end_to_end) {
1459 m_watchpoint_list.SetEnabledAll(false);
1460 return true;
1461 }
1462
1463 // Otherwise, it's an end to end operation.
1464
1465 if (!ProcessIsValid())
1466 return false;
1467
1468 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1469 if (!wp_sp)
1470 return false;
1471
1472 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1473 if (rc.Fail())
1474 return false;
1475 }
1476 return true; // Success!
1477}
1478
1479// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1480// to end operations.
1481bool Target::EnableAllWatchpoints(bool end_to_end) {
1483 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1484
1485 if (!end_to_end) {
1486 m_watchpoint_list.SetEnabledAll(true);
1487 return true;
1488 }
1489
1490 // Otherwise, it's an end to end operation.
1491
1492 if (!ProcessIsValid())
1493 return false;
1494
1495 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1496 if (!wp_sp)
1497 return false;
1498
1499 Status rc = m_process_sp->EnableWatchpoint(wp_sp);
1500 if (rc.Fail())
1501 return false;
1502 }
1503 return true; // Success!
1504}
1505
1506// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1509 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1510
1511 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1512 if (!wp_sp)
1513 return false;
1514
1515 wp_sp->ResetHitCount();
1516 }
1517 return true; // Success!
1518}
1519
1520// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1523 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1524
1525 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1526 if (!wp_sp)
1527 return false;
1528
1529 wp_sp->ResetHistoricValues();
1530 }
1531 return true; // Success!
1532}
1533
1534// Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1535// these operations.
1536bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1538 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1539
1540 if (!ProcessIsValid())
1541 return false;
1542
1543 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1544 if (!wp_sp)
1545 return false;
1546
1547 wp_sp->SetIgnoreCount(ignore_count);
1548 }
1549 return true; // Success!
1550}
1551
1552// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1555 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1556
1557 if (!ProcessIsValid())
1558 return false;
1559
1560 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1561 if (wp_sp) {
1562 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1563 if (rc.Success())
1564 return true;
1565
1566 // Else, fallthrough.
1567 }
1568 return false;
1569}
1570
1571// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1574 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1575
1576 if (!ProcessIsValid())
1577 return false;
1578
1579 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1580 if (wp_sp) {
1581 Status rc = m_process_sp->EnableWatchpoint(wp_sp);
1582 if (rc.Success())
1583 return true;
1584
1585 // Else, fallthrough.
1586 }
1587 return false;
1588}
1589
1590// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1593 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1594
1595 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1596 if (watch_to_remove_sp == m_last_created_watchpoint)
1598
1599 if (DisableWatchpointByID(watch_id)) {
1600 m_watchpoint_list.Remove(watch_id, true);
1601 return true;
1602 }
1603 return false;
1604}
1605
1606// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1608 uint32_t ignore_count) {
1610 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1611
1612 if (!ProcessIsValid())
1613 return false;
1614
1615 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1616 if (wp_sp) {
1617 wp_sp->SetIgnoreCount(ignore_count);
1618 return true;
1619 }
1620 return false;
1621}
1622
1624 std::lock_guard<std::recursive_mutex> lock(m_images.GetMutex());
1625
1626 // Search for the first executable in the module list.
1627 for (ModuleSP module_sp : m_images.ModulesNoLocking()) {
1628 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1629 if (obj == nullptr)
1630 continue;
1632 return module_sp;
1633 }
1634
1635 // If there is none, fall back return the first module loaded.
1636 return m_images.GetModuleAtIndex(0);
1637}
1638
1642
1643void Target::ClearModules(bool delete_locations) {
1644 ModulesDidUnload(m_images, delete_locations);
1645 m_section_load_history.Clear();
1646 m_images.Clear();
1648}
1649
1651 // When a process exec's we need to know about it so we can do some cleanup.
1652 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1653 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1654}
1655
1657 LoadDependentFiles load_dependent_files) {
1659 &m_debugger);
1660 Log *log = GetLog(LLDBLog::Target);
1661 ClearModules(false);
1662
1663 if (executable_sp) {
1665 if (ProcessSP proc = GetProcessSP())
1666 pid = proc->GetID();
1667
1669 info->exec_mod = executable_sp;
1670 info->uuid = executable_sp->GetUUID();
1671 info->pid = pid;
1672 info->triple = executable_sp->GetArchitecture().GetTriple().getTriple();
1673 info->is_start_entry = true;
1674 });
1675
1676 helper.DispatchOnExit([&, pid](telemetry::ExecutableModuleInfo *info) {
1677 info->exec_mod = executable_sp;
1678 info->uuid = executable_sp->GetUUID();
1679 info->pid = pid;
1680 });
1681
1682 ElapsedTime elapsed(m_stats.GetCreateTime());
1683 LLDB_SCOPED_TIMERF("Target::SetExecutableModule (executable = '%s')",
1684 executable_sp->GetFileSpec().GetPath().c_str());
1685
1686 const bool notify = true;
1687 m_images.Append(executable_sp,
1688 notify); // The first image is our executable file
1689
1690 // If we haven't set an architecture yet, reset our architecture based on
1691 // what we found in the executable module.
1692 if (!m_arch.GetSpec().IsValid()) {
1693 m_arch = executable_sp->GetArchitecture();
1694 LLDB_LOG(log,
1695 "Target::SetExecutableModule setting architecture to {0} ({1}) "
1696 "based on executable file",
1697 m_arch.GetSpec().GetArchitectureName(),
1698 m_arch.GetSpec().GetTriple().getTriple());
1699 }
1700
1701 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1702 bool load_dependents = true;
1703 switch (load_dependent_files) {
1705 load_dependents = executable_sp->IsExecutable();
1706 break;
1707 case eLoadDependentsYes:
1708 load_dependents = true;
1709 break;
1710 case eLoadDependentsNo:
1711 load_dependents = false;
1712 break;
1713 }
1714
1715 if (executable_objfile && load_dependents) {
1716 // FileSpecList is not thread safe and needs to be synchronized.
1717 FileSpecList dependent_files;
1718 std::mutex dependent_files_mutex;
1719
1720 // ModuleList is thread safe.
1721 ModuleList added_modules;
1722
1723 auto GetDependentModules = [&](FileSpec dependent_file_spec) {
1724 FileSpec platform_dependent_file_spec;
1725 if (m_platform_sp)
1726 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1727 platform_dependent_file_spec);
1728 else
1729 platform_dependent_file_spec = dependent_file_spec;
1730
1731 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1732 ModuleSP image_module_sp(
1733 GetOrCreateModule(module_spec, false /* notify */));
1734 if (image_module_sp) {
1735 added_modules.AppendIfNeeded(image_module_sp, false);
1736 ObjectFile *objfile = image_module_sp->GetObjectFile();
1737 if (objfile) {
1738 // Create a local copy of the dependent file list so we don't have
1739 // to lock for the whole duration of GetDependentModules.
1740 FileSpecList dependent_files_copy;
1741 {
1742 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1743 dependent_files_copy = dependent_files;
1744 }
1745
1746 // Remember the size of the local copy so we can append only the
1747 // modules that have been added by GetDependentModules.
1748 const size_t previous_dependent_files =
1749 dependent_files_copy.GetSize();
1750
1751 objfile->GetDependentModules(dependent_files_copy);
1752
1753 {
1754 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1755 for (size_t i = previous_dependent_files;
1756 i < dependent_files_copy.GetSize(); ++i)
1757 dependent_files.AppendIfUnique(
1758 dependent_files_copy.GetFileSpecAtIndex(i));
1759 }
1760 }
1761 }
1762 };
1763
1764 executable_objfile->GetDependentModules(dependent_files);
1765
1766 llvm::ThreadPoolTaskGroup task_group(Debugger::GetThreadPool());
1767 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1768 // Process all currently known dependencies in parallel in the innermost
1769 // loop. This may create newly discovered dependencies to be appended to
1770 // dependent_files. We'll deal with these files during the next
1771 // iteration of the outermost loop.
1772 {
1773 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1774 for (; i < dependent_files.GetSize(); i++)
1775 task_group.async(GetDependentModules,
1776 dependent_files.GetFileSpecAtIndex(i));
1777 }
1778 task_group.wait();
1779 }
1780 ModulesDidLoad(added_modules);
1781 }
1782 }
1783}
1784
1785bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform,
1786 bool merge) {
1787 Log *log = GetLog(LLDBLog::Target);
1788 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1789 bool replace_local_arch = true;
1790 bool compatible_local_arch = false;
1791 ArchSpec other(arch_spec);
1792
1793 // Changing the architecture might mean that the currently selected platform
1794 // isn't compatible. Set the platform correctly if we are asked to do so,
1795 // otherwise assume the user will set the platform manually.
1796 if (set_platform) {
1797 if (other.IsValid()) {
1798 auto platform_sp = GetPlatform();
1799 if (!platform_sp || !platform_sp->IsCompatibleArchitecture(
1800 other, {}, ArchSpec::CompatibleMatch, nullptr)) {
1801 ArchSpec platform_arch;
1802 if (PlatformSP arch_platform_sp =
1803 GetDebugger().GetPlatformList().GetOrCreate(other, {},
1804 &platform_arch)) {
1805 arch_platform_sp->SetLocateModuleCallback(
1806 platform_sp->GetLocateModuleCallback());
1807 SetPlatform(arch_platform_sp);
1808 if (platform_arch.IsValid())
1809 other = platform_arch;
1810 }
1811 }
1812 }
1813 }
1814
1815 if (!missing_local_arch) {
1816 if (merge && m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1817 other.MergeFrom(m_arch.GetSpec());
1818
1819 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1820 compatible_local_arch = true;
1821
1822 if (m_arch.GetSpec().GetTriple() == other.GetTriple())
1823 replace_local_arch = false;
1824 }
1825 }
1826 }
1827
1828 if (compatible_local_arch || missing_local_arch) {
1829 // If we haven't got a valid arch spec, or the architectures are compatible
1830 // update the architecture, unless the one we already have is more
1831 // specified
1832 if (replace_local_arch)
1833 m_arch = other;
1834 LLDB_LOG(log,
1835 "Target::SetArchitecture merging compatible arch; arch "
1836 "is now {0} ({1})",
1837 m_arch.GetSpec().GetArchitectureName(),
1838 m_arch.GetSpec().GetTriple().getTriple());
1839 return true;
1840 }
1841
1842 // If we have an executable file, try to reset the executable to the desired
1843 // architecture
1844 LLDB_LOGF(
1845 log,
1846 "Target::SetArchitecture changing architecture to %s (%s) from %s (%s)",
1847 arch_spec.GetArchitectureName(),
1848 arch_spec.GetTriple().getTriple().c_str(),
1849 m_arch.GetSpec().GetArchitectureName(),
1850 m_arch.GetSpec().GetTriple().getTriple().c_str());
1851 m_arch = other;
1852 ModuleSP executable_sp = GetExecutableModule();
1853
1854 ClearModules(true);
1855 // Need to do something about unsetting breakpoints.
1856
1857 if (executable_sp) {
1858 LLDB_LOGF(log,
1859 "Target::SetArchitecture Trying to select executable file "
1860 "architecture %s (%s)",
1861 arch_spec.GetArchitectureName(),
1862 arch_spec.GetTriple().getTriple().c_str());
1863 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1864 module_spec.SetTarget(shared_from_this());
1865 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1866 nullptr, nullptr);
1867
1868 if (!error.Fail() && executable_sp) {
1870 return true;
1871 }
1872 }
1873 return false;
1874}
1875
1876bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1877 Log *log = GetLog(LLDBLog::Target);
1878 if (arch_spec.IsValid()) {
1879 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1880 // The current target arch is compatible with "arch_spec", see if we can
1881 // improve our current architecture using bits from "arch_spec"
1882
1883 LLDB_LOGF(log,
1884 "Target::MergeArchitecture target has arch %s, merging with "
1885 "arch %s",
1886 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1887 arch_spec.GetTriple().getTriple().c_str());
1888
1889 // Merge bits from arch_spec into "merged_arch" and set our architecture
1890 ArchSpec merged_arch(m_arch.GetSpec());
1891 merged_arch.MergeFrom(arch_spec);
1892 return SetArchitecture(merged_arch);
1893 } else {
1894 // The new architecture is different, we just need to replace it
1895 return SetArchitecture(arch_spec);
1896 }
1897 }
1898 return false;
1899}
1900
1901void Target::NotifyWillClearList(const ModuleList &module_list) {}
1902
1904 const ModuleSP &module_sp) {
1905 // A module is being added to this target for the first time
1906 if (m_valid) {
1907 ModuleList my_module_list;
1908 my_module_list.Append(module_sp);
1909 ModulesDidLoad(my_module_list);
1910 }
1911}
1912
1914 const ModuleSP &module_sp) {
1915 // A module is being removed from this target.
1916 if (m_valid) {
1917 ModuleList my_module_list;
1918 my_module_list.Append(module_sp);
1919 ModulesDidUnload(my_module_list, false);
1920 }
1921}
1922
1924 const ModuleSP &old_module_sp,
1925 const ModuleSP &new_module_sp) {
1926 // A module is replacing an already added module
1927 if (m_valid) {
1928 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1929 new_module_sp);
1930 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1931 old_module_sp, new_module_sp);
1932 }
1933}
1934
1936 ModulesDidUnload(module_list, false);
1937}
1938
1940 if (GetPreloadSymbols())
1942
1943 const size_t num_images = module_list.GetSize();
1944 if (m_valid && num_images) {
1945 std::list<Status> errors;
1946 module_list.LoadScriptingResourcesInTarget(this, errors);
1947 for (const auto &err : errors)
1948 GetDebugger().GetAsyncErrorStream()->PutCString(err.AsCString());
1949
1950 for (size_t idx = 0; idx < num_images; ++idx) {
1951 ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1952 LoadTypeSummariesForModule(module_sp);
1953 LoadFormattersForModule(module_sp);
1954 }
1955 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1956 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1957 if (m_process_sp) {
1958 m_process_sp->ModulesDidLoad(module_list);
1959 }
1960 RunModuleHooks(/*is_load=*/true);
1961 auto data_sp =
1962 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1964 }
1965}
1966
1968 if (m_valid && module_list.GetSize()) {
1969 if (m_process_sp) {
1970 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1971 runtime->SymbolsDidLoad(module_list);
1972 }
1973 }
1974
1975 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1976 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1977 auto data_sp =
1978 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1980 }
1981}
1982
1983void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1984 if (m_valid && module_list.GetSize()) {
1985 UnloadModuleSections(module_list);
1986 auto data_sp =
1987 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1989 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1990 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1991 delete_locations);
1992
1993 // If a module was torn down it will have torn down the 'TypeSystemClang's
1994 // that we used as source 'ASTContext's for the persistent variables in
1995 // the current target. Those would now be unsafe to access because the
1996 // 'DeclOrigin' are now possibly stale. Thus clear all persistent
1997 // variables. We only want to flush 'TypeSystem's if the module being
1998 // unloaded was capable of describing a source type. JITted module unloads
1999 // happen frequently for Objective-C utility functions or the REPL and rely
2000 // on the persistent variables to stick around.
2001 const bool should_flush_type_systems =
2002 module_list.AnyOf([](lldb_private::Module &module) {
2003 auto *object_file = module.GetObjectFile();
2004
2005 if (!object_file)
2006 return false;
2007
2008 auto type = object_file->GetType();
2009
2010 // eTypeExecutable: when debugged binary was rebuilt
2011 // eTypeSharedLibrary: if dylib was re-loaded
2012 return module.FileHasChanged() &&
2013 (type == ObjectFile::eTypeObjectFile ||
2014 type == ObjectFile::eTypeExecutable ||
2015 type == ObjectFile::eTypeSharedLibrary);
2016 });
2017
2018 if (should_flush_type_systems)
2020
2021 RunModuleHooks(/*is_load=*/false);
2022 }
2023}
2024
2026 const FileSpec &module_file_spec) {
2028 ModuleList matchingModules;
2029 ModuleSpec module_spec(module_file_spec);
2030 GetImages().FindModules(module_spec, matchingModules);
2031 size_t num_modules = matchingModules.GetSize();
2032
2033 // If there is more than one module for this file spec, only
2034 // return true if ALL the modules are on the black list.
2035 if (num_modules > 0) {
2036 for (size_t i = 0; i < num_modules; i++) {
2038 matchingModules.GetModuleAtIndex(i)))
2039 return false;
2040 }
2041 return true;
2042 }
2043 }
2044 return false;
2045}
2046
2048 const lldb::ModuleSP &module_sp) {
2050 if (m_platform_sp)
2051 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
2052 module_sp);
2053 }
2054 return false;
2055}
2056
2057size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
2058 size_t dst_len, Status &error) {
2059 SectionSP section_sp(addr.GetSection());
2060 if (section_sp) {
2061 // If the contents of this section are encrypted, the on-disk file is
2062 // unusable. Read only from live memory.
2063 if (section_sp->IsEncrypted()) {
2064 error = Status::FromErrorString("section is encrypted");
2065 return 0;
2066 }
2067 ModuleSP module_sp(section_sp->GetModule());
2068 if (module_sp) {
2069 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
2070 if (objfile) {
2071 size_t bytes_read = objfile->ReadSectionData(
2072 section_sp.get(), addr.GetOffset(), dst, dst_len);
2073 if (bytes_read > 0)
2074 return bytes_read;
2075 else
2077 "error reading data from section {0}", section_sp->GetName());
2078 } else
2079 error = Status::FromErrorString("address isn't from a object file");
2080 } else
2081 error = Status::FromErrorString("address isn't in a module");
2082 } else
2084 "address doesn't contain a section that points to a "
2085 "section in a object file");
2086
2087 return 0;
2088}
2089
2090size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len,
2091 Status &error, bool force_live_memory,
2092 lldb::addr_t *load_addr_ptr,
2093 bool *did_read_live_memory) {
2094 error.Clear();
2095 if (did_read_live_memory)
2096 *did_read_live_memory = false;
2097
2098 Address fixed_addr = addr;
2099 if (ProcessIsValid())
2100 if (const ABISP &abi = m_process_sp->GetABI())
2101 fixed_addr.SetLoadAddress(abi->FixAnyAddress(addr.GetLoadAddress(this)),
2102 this);
2103
2104 // if we end up reading this from process memory, we will fill this with the
2105 // actual load address
2106 if (load_addr_ptr)
2107 *load_addr_ptr = LLDB_INVALID_ADDRESS;
2108
2109 size_t bytes_read = 0;
2110
2111 addr_t load_addr = LLDB_INVALID_ADDRESS;
2112 addr_t file_addr = LLDB_INVALID_ADDRESS;
2113 Address resolved_addr;
2114 if (!fixed_addr.IsSectionOffset()) {
2115 SectionLoadList &section_load_list = GetSectionLoadList();
2116 if (section_load_list.IsEmpty()) {
2117 // No sections are loaded, so we must assume we are not running yet and
2118 // anything we are given is a file address.
2119 file_addr =
2120 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
2121 // its offset is the file address
2122 m_images.ResolveFileAddress(file_addr, resolved_addr);
2123 } else {
2124 // We have at least one section loaded. This can be because we have
2125 // manually loaded some sections with "target modules load ..." or
2126 // because we have a live process that has sections loaded through
2127 // the dynamic loader
2128 load_addr =
2129 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
2130 // its offset is the load address
2131 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
2132 }
2133 }
2134 if (!resolved_addr.IsValid())
2135 resolved_addr = fixed_addr;
2136
2137 // If we read from the file cache but can't get as many bytes as requested,
2138 // we keep the result around in this buffer, in case this result is the
2139 // best we can do.
2140 std::unique_ptr<uint8_t[]> file_cache_read_buffer;
2141 size_t file_cache_bytes_read = 0;
2142
2143 // Read from file cache if read-only section.
2144 if (!force_live_memory && resolved_addr.IsSectionOffset()) {
2145 SectionSP section_sp(resolved_addr.GetSection());
2146 if (section_sp) {
2147 auto permissions = Flags(section_sp->GetPermissions());
2148 bool is_readonly = !permissions.Test(ePermissionsWritable) &&
2149 permissions.Test(ePermissionsReadable);
2150 if (is_readonly) {
2151 file_cache_bytes_read =
2152 ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2153 if (file_cache_bytes_read == dst_len)
2154 return file_cache_bytes_read;
2155 else if (file_cache_bytes_read > 0) {
2156 file_cache_read_buffer =
2157 std::make_unique<uint8_t[]>(file_cache_bytes_read);
2158 std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read);
2159 }
2160 }
2161 }
2162 }
2163
2164 if (ProcessIsValid()) {
2165 if (load_addr == LLDB_INVALID_ADDRESS)
2166 load_addr = resolved_addr.GetLoadAddress(this);
2167
2168 if (load_addr == LLDB_INVALID_ADDRESS) {
2169 ModuleSP addr_module_sp(resolved_addr.GetModule());
2170 if (addr_module_sp && addr_module_sp->GetFileSpec())
2172 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
2173 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
2174 else
2176 "0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
2177 } else {
2178 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
2179 if (bytes_read != dst_len) {
2180 if (error.Success()) {
2181 if (bytes_read == 0)
2183 "read memory from 0x%" PRIx64 " failed", load_addr);
2184 else
2186 "only %" PRIu64 " of %" PRIu64
2187 " bytes were read from memory at 0x%" PRIx64,
2188 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
2189 }
2190 }
2191 if (bytes_read) {
2192 if (load_addr_ptr)
2193 *load_addr_ptr = load_addr;
2194 if (did_read_live_memory)
2195 *did_read_live_memory = true;
2196 return bytes_read;
2197 }
2198 }
2199 }
2200
2201 if (file_cache_read_buffer && file_cache_bytes_read > 0) {
2202 // Reading from the process failed. If we've previously succeeded in reading
2203 // something from the file cache, then copy that over and return that.
2204 std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read);
2205 return file_cache_bytes_read;
2206 }
2207
2208 if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) {
2209 // If we didn't already try and read from the object file cache, then try
2210 // it after failing to read from the process.
2211 error.Clear();
2212 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2213 // A short read here is only a failure if a live read already failed too.
2214 // Reaching this point with a valid process means the process contributed
2215 // nothing.
2216 if (bytes_read > 0 && bytes_read != dst_len && error.Success() &&
2219 "only {0} of {1} bytes were read from the object file cache",
2220 bytes_read, dst_len);
2221 return bytes_read;
2222 }
2223 return 0;
2224}
2225
2226size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
2227 Status &error, bool force_live_memory) {
2228 char buf[256];
2229 out_str.clear();
2230 addr_t curr_addr = addr.GetLoadAddress(this);
2231 Address address(addr);
2232 while (true) {
2233 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error,
2234 force_live_memory);
2235 if (length == 0)
2236 break;
2237 out_str.append(buf, length);
2238 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2239 // to read some more characters
2240 if (length == sizeof(buf) - 1)
2241 curr_addr += length;
2242 else
2243 break;
2244 address = Address(curr_addr);
2245 }
2246 return out_str.size();
2247}
2248
2249size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
2250 size_t dst_max_len, Status &result_error,
2251 bool force_live_memory) {
2252 size_t total_cstr_len = 0;
2253 if (dst && dst_max_len) {
2254 result_error.Clear();
2255 // NULL out everything just to be safe
2256 memset(dst, 0, dst_max_len);
2257 addr_t curr_addr = addr.GetLoadAddress(this);
2258 Address address(addr);
2259
2260 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
2261 // this really needs to be tied to the memory cache subsystem's cache line
2262 // size, so leave this as a fixed constant.
2263 const size_t cache_line_size = 512;
2264
2265 size_t bytes_left = dst_max_len - 1;
2266 char *curr_dst = dst;
2267
2268 while (bytes_left > 0) {
2269 addr_t cache_line_bytes_left =
2270 cache_line_size - (curr_addr % cache_line_size);
2271 addr_t bytes_to_read =
2272 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2273 Status error;
2274 size_t bytes_read = ReadMemory(address, curr_dst, bytes_to_read, error,
2275 force_live_memory);
2276
2277 if (bytes_read == 0) {
2278 result_error = std::move(error);
2279 dst[total_cstr_len] = '\0';
2280 break;
2281 }
2282 const size_t len = strlen(curr_dst);
2283
2284 total_cstr_len += len;
2285
2286 if (len < bytes_to_read)
2287 break;
2288
2289 curr_dst += bytes_read;
2290 curr_addr += bytes_read;
2291 bytes_left -= bytes_read;
2292 address = Address(curr_addr);
2293 }
2294 } else {
2295 if (dst == nullptr)
2296 result_error = Status::FromErrorString("invalid arguments");
2297 else
2298 result_error.Clear();
2299 }
2300 return total_cstr_len;
2301}
2302
2304 addr_t load_addr = addr.GetLoadAddress(this);
2305 if (load_addr != LLDB_INVALID_ADDRESS && m_process_sp) {
2306 // Avoid crossing cache line boundaries.
2307 addr_t cache_line_size = m_process_sp->GetMemoryCacheLineSize();
2308 return cache_line_size - (load_addr % cache_line_size);
2309 }
2310
2311 // The read is going to go to the file cache, so we can just pick a largish
2312 // value.
2313 return 0x1000;
2314}
2315
2316size_t Target::ReadStringFromMemory(const Address &addr, char *dst,
2317 size_t max_bytes, Status &error,
2318 size_t type_width, bool force_live_memory) {
2319 if (!dst || !max_bytes || !type_width || max_bytes < type_width)
2320 return 0;
2321
2322 size_t total_bytes_read = 0;
2323
2324 // Ensure a null terminator independent of the number of bytes that is
2325 // read.
2326 memset(dst, 0, max_bytes);
2327 size_t bytes_left = max_bytes - type_width;
2328
2329 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2330 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2331 "string with more than 4 bytes "
2332 "per character!");
2333
2334 Address address = addr;
2335 char *curr_dst = dst;
2336
2337 error.Clear();
2338 while (bytes_left > 0 && error.Success()) {
2339 addr_t bytes_to_read =
2340 std::min<addr_t>(bytes_left, GetReasonableReadSize(address));
2341 size_t bytes_read =
2342 ReadMemory(address, curr_dst, bytes_to_read, error, force_live_memory);
2343
2344 if (bytes_read == 0)
2345 break;
2346
2347 // Search for a null terminator of correct size and alignment in
2348 // bytes_read
2349 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2350 for (size_t i = aligned_start;
2351 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2352 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2353 error.Clear();
2354 return i;
2355 }
2356
2357 total_bytes_read += bytes_read;
2358 curr_dst += bytes_read;
2359 address.Slide(bytes_read);
2360 bytes_left -= bytes_read;
2361 }
2362 return total_bytes_read;
2363}
2364
2365size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
2366 bool is_signed, Scalar &scalar,
2367 Status &error,
2368 bool force_live_memory) {
2369 uint64_t uval;
2370
2371 if (byte_size <= sizeof(uval)) {
2372 size_t bytes_read =
2373 ReadMemory(addr, &uval, byte_size, error, force_live_memory);
2374 if (bytes_read == byte_size) {
2375 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
2376 m_arch.GetSpec().GetAddressByteSize());
2377 lldb::offset_t offset = 0;
2378 if (byte_size <= 4)
2379 scalar = data.GetMaxU32(&offset, byte_size);
2380 else
2381 scalar = data.GetMaxU64(&offset, byte_size);
2382
2383 if (is_signed) {
2384 scalar.MakeSigned();
2385 scalar.SignExtend(byte_size * 8);
2386 }
2387 return bytes_read;
2388 }
2389 } else {
2391 "byte size of %u is too large for integer scalar type", byte_size);
2392 }
2393 return 0;
2394}
2395
2397 size_t integer_byte_size,
2398 int64_t fail_value, Status &error,
2399 bool force_live_memory) {
2400 Scalar scalar;
2401 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, true, scalar, error,
2402 force_live_memory))
2403 return scalar.SLongLong(fail_value);
2404 return fail_value;
2405}
2406
2408 size_t integer_byte_size,
2409 uint64_t fail_value, Status &error,
2410 bool force_live_memory) {
2411 Scalar scalar;
2412 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
2413 force_live_memory))
2414 return scalar.ULongLong(fail_value);
2415 return fail_value;
2416}
2417
2419 Address &pointer_addr,
2420 bool force_live_memory) {
2421 Scalar scalar;
2422 if (ReadScalarIntegerFromMemory(addr, m_arch.GetSpec().GetAddressByteSize(),
2423 false, scalar, error, force_live_memory)) {
2424 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
2425 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
2426 SectionLoadList &section_load_list = GetSectionLoadList();
2427 if (section_load_list.IsEmpty()) {
2428 // No sections are loaded, so we must assume we are not running yet and
2429 // anything we are given is a file address.
2430 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
2431 } else {
2432 // We have at least one section loaded. This can be because we have
2433 // manually loaded some sections with "target modules load ..." or
2434 // because we have a live process that has sections loaded through
2435 // the dynamic loader
2436 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
2437 }
2438 // We weren't able to resolve the pointer value, so just return an
2439 // address with no section
2440 if (!pointer_addr.IsValid())
2441 pointer_addr.SetOffset(pointer_vm_addr);
2442 return true;
2443 }
2444 }
2445 return false;
2446}
2447
2449 bool notify, Status *error_ptr) {
2450 ModuleSP module_sp;
2451
2452 Status error;
2453
2454 // Apply any remappings specified in target.object-map:
2455 ModuleSpec module_spec(orig_module_spec);
2456 module_spec.SetTarget(shared_from_this());
2457 PathMappingList &obj_mapping = GetObjectPathMap();
2458 if (std::optional<FileSpec> remapped_obj_file =
2459 obj_mapping.RemapPath(orig_module_spec.GetFileSpec().GetPath(),
2460 true /* only_if_exists */)) {
2461 module_spec.GetFileSpec().SetPath(remapped_obj_file->GetPath());
2462 }
2463
2464 // First see if we already have this module in our module list. If we do,
2465 // then we're done, we don't need to consult the shared modules list. But
2466 // only do this if we are passed a UUID.
2467
2468 if (module_spec.GetUUID().IsValid())
2469 module_sp = m_images.FindFirstModule(module_spec);
2470
2471 if (!module_sp) {
2472 llvm::SmallVector<ModuleSP, 1>
2473 old_modules; // This will get filled in if we have a new version
2474 // of the library
2475 bool did_create_module = false;
2476 FileSpecList search_paths = GetExecutableSearchPaths();
2477 FileSpec symbol_file_spec;
2478
2479 // Call locate module callback if set. This allows users to implement their
2480 // own module cache system. For example, to leverage build system artifacts,
2481 // to bypass pulling files from remote platform, or to search symbol files
2482 // from symbol servers.
2483 if (m_platform_sp)
2484 m_platform_sp->CallLocateModuleCallbackIfSet(
2485 module_spec, module_sp, symbol_file_spec, &did_create_module);
2486
2487 // The result of this CallLocateModuleCallbackIfSet is one of the following.
2488 // 1. module_sp:loaded, symbol_file_spec:set
2489 // The callback found a module file and a symbol file for the
2490 // module_spec. We will call module_sp->SetSymbolFileFileSpec with
2491 // the symbol_file_spec later.
2492 // 2. module_sp:loaded, symbol_file_spec:empty
2493 // The callback only found a module file for the module_spec.
2494 // 3. module_sp:empty, symbol_file_spec:set
2495 // The callback only found a symbol file for the module. We continue
2496 // to find a module file for this module_spec and we will call
2497 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
2498 // 4. module_sp:empty, symbol_file_spec:empty
2499 // Platform does not exist, the callback is not set, the callback did
2500 // not find any module files nor any symbol files, the callback failed,
2501 // or something went wrong. We continue to find a module file for this
2502 // module_spec.
2503
2504 if (!module_sp) {
2505 // If there are image search path entries, try to use them to acquire a
2506 // suitable image.
2507 if (m_image_search_paths.GetSize()) {
2508 ModuleSpec transformed_spec(module_spec);
2509 ConstString transformed_dir;
2510 if (m_image_search_paths.RemapPath(
2511 ConstString(module_spec.GetFileSpec().GetDirectory()),
2512 transformed_dir)) {
2513 transformed_spec.GetFileSpec().SetDirectory(transformed_dir);
2514 transformed_spec.GetFileSpec().SetFilename(
2515 module_spec.GetFileSpec().GetFilename());
2516 transformed_spec.SetTarget(shared_from_this());
2517 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2518 &old_modules, &did_create_module);
2519 }
2520 }
2521 }
2522
2523 if (!module_sp) {
2524 // If we have a UUID, we can check our global shared module list in case
2525 // we already have it. If we don't have a valid UUID, then we can't since
2526 // the path in "module_spec" will be a platform path, and we will need to
2527 // let the platform find that file. For example, we could be asking for
2528 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2529 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2530 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2531 // cache.
2532 if (module_spec.GetUUID().IsValid()) {
2533 // We have a UUID, it is OK to check the global module list...
2534 error = ModuleList::GetSharedModule(module_spec, module_sp,
2535 &old_modules, &did_create_module);
2536 }
2537
2538 if (!module_sp) {
2539 // The platform is responsible for finding and caching an appropriate
2540 // module in the shared module cache.
2541 if (m_platform_sp) {
2542 error = m_platform_sp->GetSharedModule(
2543 module_spec, *this, module_sp, &old_modules, &did_create_module);
2544 } else {
2545 error = Status::FromErrorString("no platform is currently set");
2546 }
2547 }
2548 }
2549
2550 // We found a module that wasn't in our target list. Let's make sure that
2551 // there wasn't an equivalent module in the list already, and if there was,
2552 // let's remove it.
2553 if (module_sp) {
2554 ObjectFile *objfile = module_sp->GetObjectFile();
2555 if (objfile) {
2556 switch (objfile->GetType()) {
2557 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2558 /// a program's execution state
2559 case ObjectFile::eTypeExecutable: /// A normal executable
2560 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2561 /// executable
2562 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2563 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2564 /// used during execution
2565 break;
2566 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2567 /// debug information
2568 if (error_ptr)
2569 *error_ptr = Status::FromErrorString(
2570 "debug info files aren't valid target "
2571 "modules, please specify an executable");
2572 return ModuleSP();
2573 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2574 /// against but not used for
2575 /// execution
2576 if (error_ptr)
2577 *error_ptr = Status::FromErrorString(
2578 "stub libraries aren't valid target "
2579 "modules, please specify an executable");
2580 return ModuleSP();
2581 default:
2582 if (error_ptr)
2583 *error_ptr = Status::FromErrorString(
2584 "unsupported file type, please specify an executable");
2585 return ModuleSP();
2586 }
2587 // GetSharedModule is not guaranteed to find the old shared module, for
2588 // instance in the common case where you pass in the UUID, it is only
2589 // going to find the one module matching the UUID. In fact, it has no
2590 // good way to know what the "old module" relevant to this target is,
2591 // since there might be many copies of a module with this file spec in
2592 // various running debug sessions, but only one of them will belong to
2593 // this target. So let's remove the UUID from the module list, and look
2594 // in the target's module list. Only do this if there is SOMETHING else
2595 // in the module spec...
2596 if (module_spec.GetUUID().IsValid() &&
2597 !module_spec.GetFileSpec().GetFilename().empty() &&
2598 !module_spec.GetFileSpec().GetDirectory().empty()) {
2599 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2600 module_spec_copy.GetUUID().Clear();
2601
2602 ModuleList found_modules;
2603 m_images.FindModules(module_spec_copy, found_modules);
2604 found_modules.ForEach([&](const ModuleSP &found_module) {
2605 old_modules.push_back(found_module);
2607 });
2608 }
2609
2610 // If the locate module callback had found a symbol file, set it to the
2611 // module_sp before preloading symbols.
2612 if (symbol_file_spec)
2613 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
2614
2615 llvm::SmallVector<ModuleSP, 1> replaced_modules;
2616 for (ModuleSP &old_module_sp : old_modules) {
2617 if (m_images.GetIndexForModule(old_module_sp.get()) !=
2619 if (replaced_modules.empty())
2620 m_images.ReplaceModule(old_module_sp, module_sp);
2621 else
2622 m_images.Remove(old_module_sp);
2623
2624 replaced_modules.push_back(std::move(old_module_sp));
2625 }
2626 }
2627
2628 if (replaced_modules.size() > 1) {
2629 // The same new module replaced multiple old modules
2630 // simultaneously. It's not clear this should ever
2631 // happen (if we always replace old modules as we add
2632 // new ones, presumably we should never have more than
2633 // one old one). If there are legitimate cases where
2634 // this happens, then the ModuleList::Notifier interface
2635 // may need to be adjusted to allow reporting this.
2636 // In the meantime, just log that this has happened; just
2637 // above we called ReplaceModule on the first one, and Remove
2638 // on the rest.
2640 StreamString message;
2641 auto dump = [&message](Module &dump_module) -> void {
2642 UUID dump_uuid = dump_module.GetUUID();
2643
2644 message << '[';
2645 dump_module.GetDescription(message.AsRawOstream());
2646 message << " (uuid ";
2647
2648 if (dump_uuid.IsValid())
2649 dump_uuid.Dump(message);
2650 else
2651 message << "not specified";
2652
2653 message << ")]";
2654 };
2655
2656 message << "New module ";
2657 dump(*module_sp);
2658 message.AsRawOstream()
2659 << llvm::formatv(" simultaneously replaced {0} old modules: ",
2660 replaced_modules.size());
2661 for (ModuleSP &replaced_module_sp : replaced_modules)
2662 dump(*replaced_module_sp);
2663
2664 log->PutString(message.GetString());
2665 }
2666 }
2667
2668 if (replaced_modules.empty()) {
2669 if (!m_images.AppendIfNeeded(module_sp, notify) && notify)
2670 NotifyModuleAdded(m_images, module_sp);
2671 }
2672
2673 for (ModuleSP &old_module_sp : replaced_modules) {
2674 auto old_module_wp = old_module_sp->weak_from_this();
2675 old_module_sp.reset();
2677 }
2678 } else
2679 module_sp.reset();
2680 }
2681 }
2682 if (error_ptr)
2683 *error_ptr = std::move(error);
2684 return module_sp;
2685}
2686
2687TargetSP Target::CalculateTarget() { return shared_from_this(); }
2688
2690
2692
2694
2696 exe_ctx.Clear();
2697 exe_ctx.SetTargetPtr(this);
2698}
2699
2703
2705 void *baton) {
2706 Target *target = (Target *)baton;
2707 ModuleSP exe_module_sp(target->GetExecutableModule());
2708 if (exe_module_sp)
2709 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2710}
2711
2712llvm::Expected<lldb::TypeSystemSP>
2714 bool create_on_demand) {
2715 if (!m_valid)
2716 return llvm::createStringError("invalid target");
2717
2718 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2719 // assembly code
2720 || language == eLanguageTypeAssembly ||
2721 language == eLanguageTypeUnknown) {
2722 LanguageSet languages_for_expressions =
2724
2725 if (languages_for_expressions[eLanguageTypeC]) {
2726 language = eLanguageTypeC; // LLDB's default. Override by setting the
2727 // target language.
2728 } else {
2729 if (languages_for_expressions.Empty())
2730 return llvm::createStringError(
2731 "No expression support for any languages");
2732 language = (LanguageType)languages_for_expressions.bitvector.find_first();
2733 }
2734 }
2735
2736 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2737 create_on_demand);
2738}
2739
2746
2747std::vector<lldb::TypeSystemSP>
2748Target::GetScratchTypeSystems(bool create_on_demand) {
2749 if (!m_valid)
2750 return {};
2751
2752 // Some TypeSystem instances are associated with several LanguageTypes so
2753 // they will show up several times in the loop below. The SetVector filters
2754 // out all duplicates as they serve no use for the caller.
2755 std::vector<lldb::TypeSystemSP> scratch_type_systems;
2756
2757 LanguageSet languages_for_expressions =
2759
2760 for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2761 auto language = (LanguageType)bit;
2762 auto type_system_or_err =
2763 GetScratchTypeSystemForLanguage(language, create_on_demand);
2764 if (!type_system_or_err)
2766 GetLog(LLDBLog::Target), type_system_or_err.takeError(),
2767 "Language '{1}' has expression support but no scratch type "
2768 "system available: {0}",
2770 else
2771 if (auto ts = *type_system_or_err)
2772 scratch_type_systems.push_back(ts);
2773 }
2774
2775 std::sort(scratch_type_systems.begin(), scratch_type_systems.end());
2776 scratch_type_systems.erase(llvm::unique(scratch_type_systems),
2777 scratch_type_systems.end());
2778 return scratch_type_systems;
2779}
2780
2783 auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2784
2785 if (auto err = type_system_or_err.takeError()) {
2787 GetLog(LLDBLog::Target), std::move(err),
2788 "Unable to get persistent expression state for language {1}: {0}",
2790 return nullptr;
2791 }
2792
2793 if (auto ts = *type_system_or_err)
2794 return ts->GetPersistentExpressionState();
2795
2797 "Unable to get persistent expression state for language {}:",
2799 return nullptr;
2800}
2801
2803 llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language,
2804 Expression::ResultType desired_type,
2805 const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2806 Status &error) {
2807 auto type_system_or_err =
2809 if (auto err = type_system_or_err.takeError()) {
2811 "Could not find type system for language %s: %s",
2813 llvm::toString(std::move(err)).c_str());
2814 return nullptr;
2815 }
2816
2817 auto ts = *type_system_or_err;
2818 if (!ts) {
2820 "Type system for language %s is no longer live",
2821 language.GetDescription().data());
2822 return nullptr;
2823 }
2824
2825 auto *user_expr = ts->GetUserExpression(expr, prefix, language, desired_type,
2826 options, ctx_obj);
2827 if (!user_expr)
2829 "Could not create an expression for language %s",
2830 language.GetDescription().data());
2831
2832 return user_expr;
2833}
2834
2836 lldb::LanguageType language, const CompilerType &return_type,
2837 const Address &function_address, const ValueList &arg_value_list,
2838 const char *name, Status &error) {
2839 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2840 if (auto err = type_system_or_err.takeError()) {
2842 "Could not find type system for language %s: %s",
2844 llvm::toString(std::move(err)).c_str());
2845 return nullptr;
2846 }
2847 auto ts = *type_system_or_err;
2848 if (!ts) {
2850 "Type system for language %s is no longer live",
2852 return nullptr;
2853 }
2854 auto *persistent_fn = ts->GetFunctionCaller(return_type, function_address,
2855 arg_value_list, name);
2856 if (!persistent_fn)
2858 "Could not create an expression for language %s",
2860
2861 return persistent_fn;
2862}
2863
2864llvm::Expected<std::unique_ptr<UtilityFunction>>
2865Target::CreateUtilityFunction(std::string expression, std::string name,
2866 lldb::LanguageType language,
2867 ExecutionContext &exe_ctx) {
2868 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2869 if (!type_system_or_err)
2870 return type_system_or_err.takeError();
2871 auto ts = *type_system_or_err;
2872 if (!ts)
2873 return llvm::createStringError(
2874 llvm::StringRef("Type system for language ") +
2876 llvm::StringRef(" is no longer live"));
2877 std::unique_ptr<UtilityFunction> utility_fn =
2878 ts->CreateUtilityFunction(std::move(expression), std::move(name));
2879 if (!utility_fn)
2880 return llvm::createStringError(
2881 llvm::StringRef("Could not create an expression for language") +
2883
2884 DiagnosticManager diagnostics;
2885 if (!utility_fn->Install(diagnostics, exe_ctx))
2886 return diagnostics.GetAsError(lldb::eExpressionSetupError,
2887 "Could not install utility function:");
2888
2889 return std::move(utility_fn);
2890}
2891
2893
2895
2899
2903
2907
2910 "setting target's default architecture to {0} ({1})",
2911 arch.GetArchitectureName(), arch.GetTriple().getTriple());
2913}
2914
2915llvm::Error Target::SetLabel(llvm::StringRef label) {
2916 size_t n = LLDB_INVALID_INDEX32;
2917 if (llvm::to_integer(label, n))
2918 return llvm::createStringError("cannot use integer as target label");
2919 TargetList &targets = GetDebugger().GetTargetList();
2920 for (size_t i = 0; i < targets.GetNumTargets(); i++) {
2921 TargetSP target_sp = targets.GetTargetAtIndex(i);
2922 if (target_sp && target_sp->GetLabel() == label) {
2923 return llvm::createStringErrorV(
2924 "Cannot use label '{0}' since it's set in target #{1}.", label, i);
2925 }
2926 }
2927
2928 m_label = label.str();
2929 return llvm::Error::success();
2930}
2931
2933 const SymbolContext *sc_ptr) {
2934 // The target can either exist in the "process" of ExecutionContext, or in
2935 // the "target_sp" member of SymbolContext. This accessor helper function
2936 // will get the target from one of these locations.
2937
2938 Target *target = nullptr;
2939 if (sc_ptr != nullptr)
2940 target = sc_ptr->target_sp.get();
2941 if (target == nullptr && exe_ctx_ptr)
2942 target = exe_ctx_ptr->GetTargetPtr();
2943 return target;
2944}
2945
2947 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2948 lldb::ValueObjectSP &result_valobj_sp,
2949 const EvaluateExpressionOptions &options, std::string *fixed_expression,
2950 ValueObject *ctx_obj) {
2951 result_valobj_sp.reset();
2952
2953 ExpressionResults execution_results = eExpressionSetupError;
2954
2955 if (expr.empty()) {
2956 m_stats.GetExpressionStats().NotifyFailure();
2957 return execution_results;
2958 }
2959
2960 // We shouldn't run stop hooks in expressions.
2961 bool old_suppress_value = m_suppress_stop_hooks;
2962 m_suppress_stop_hooks = true;
2963 llvm::scope_exit on_exit([this, old_suppress_value]() {
2964 m_suppress_stop_hooks = old_suppress_value;
2965 });
2966
2967 ExecutionContext exe_ctx;
2968
2969 if (exe_scope) {
2970 exe_scope->CalculateExecutionContext(exe_ctx);
2971 } else if (m_process_sp) {
2972 m_process_sp->CalculateExecutionContext(exe_ctx);
2973 } else {
2975 }
2976
2977 // Make sure we aren't just trying to see the value of a persistent variable
2978 // (something like "$0")
2979 // Only check for persistent variables the expression starts with a '$'
2980 lldb::ExpressionVariableSP persistent_var_sp;
2981 if (expr[0] == '$') {
2982 auto type_system_or_err =
2984 if (auto err = type_system_or_err.takeError()) {
2985 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2986 "Unable to get scratch type system: {0}");
2987 } else {
2988 auto ts = *type_system_or_err;
2989 if (!ts)
2990 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2991 "Scratch type system is no longer live: {0}");
2992 else
2993 persistent_var_sp =
2994 ts->GetPersistentExpressionState()->GetVariable(expr);
2995 }
2996 }
2997 if (persistent_var_sp) {
2998 result_valobj_sp = persistent_var_sp->GetValueObject();
2999 execution_results = eExpressionCompleted;
3000 } else {
3001 // If this expression is being evaluated from inside a frame provider,
3002 // force single-thread execution. Resuming all threads while a provider
3003 // is mid-construction could cause unwanted process state changes.
3004 EvaluateExpressionOptions effective_options = options;
3005 if (ThreadSP thread_sp = exe_ctx.GetThreadSP()) {
3006 if (thread_sp->IsAnyProviderActive()) {
3007 effective_options.SetStopOthers(true);
3008 effective_options.SetTryAllThreads(false);
3009 }
3010 }
3011 llvm::StringRef prefix = GetExpressionPrefixContents();
3012 execution_results =
3013 UserExpression::Evaluate(exe_ctx, effective_options, expr, prefix,
3014 result_valobj_sp, fixed_expression, ctx_obj);
3015 }
3016
3017 if (execution_results == eExpressionCompleted)
3018 m_stats.GetExpressionStats().NotifySuccess();
3019 else
3020 m_stats.GetExpressionStats().NotifyFailure();
3021 return execution_results;
3022}
3023
3025 lldb::ExpressionVariableSP variable_sp;
3027 [name, &variable_sp](TypeSystemSP type_system) -> bool {
3028 auto ts = type_system.get();
3029 if (!ts)
3030 return true;
3031 if (PersistentExpressionState *persistent_state =
3032 ts->GetPersistentExpressionState()) {
3033 variable_sp = persistent_state->GetVariable(name);
3034
3035 if (variable_sp)
3036 return false; // Stop iterating the ForEach
3037 }
3038 return true; // Keep iterating the ForEach
3039 });
3040 return variable_sp;
3041}
3042
3045
3047 [name, &address](lldb::TypeSystemSP type_system) -> bool {
3048 auto ts = type_system.get();
3049 if (!ts)
3050 return true;
3051
3052 if (PersistentExpressionState *persistent_state =
3053 ts->GetPersistentExpressionState()) {
3054 address = persistent_state->LookupSymbol(name);
3055 if (address != LLDB_INVALID_ADDRESS)
3056 return false; // Stop iterating the ForEach
3057 }
3058 return true; // Keep iterating the ForEach
3059 });
3060 return address;
3061}
3062
3063llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
3064 Module *exe_module = GetExecutableModulePointer();
3065
3066 // Try to find the entry point address in the primary executable.
3067 const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
3068 if (has_primary_executable) {
3069 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
3070 if (entry_addr.IsValid())
3071 return entry_addr;
3072 }
3073
3074 const ModuleList &modules = GetImages();
3075 const size_t num_images = modules.GetSize();
3076 for (size_t idx = 0; idx < num_images; ++idx) {
3077 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
3078 if (!module_sp || !module_sp->GetObjectFile())
3079 continue;
3080
3081 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
3082 if (entry_addr.IsValid())
3083 return entry_addr;
3084 }
3085
3086 // We haven't found the entry point address. Return an appropriate error.
3087 if (!has_primary_executable)
3088 return llvm::createStringError(
3089 "No primary executable found and could not find entry point address in "
3090 "any executable module");
3091
3092 return llvm::createStringError(
3093 "Could not find entry point address for primary executable module \"" +
3094 exe_module->GetFileSpec().GetFilename() + "\"");
3095}
3096
3098 AddressClass addr_class) const {
3099 auto arch_plugin = GetArchitecturePlugin();
3100 return arch_plugin
3101 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
3102 : load_addr;
3103}
3104
3106 AddressClass addr_class) const {
3107 auto arch_plugin = GetArchitecturePlugin();
3108 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
3109 : load_addr;
3110}
3111
3113 auto arch_plugin = GetArchitecturePlugin();
3114 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
3115}
3116
3117llvm::Expected<lldb::DisassemblerSP>
3118Target::ReadInstructions(const Address &start_addr, uint32_t count,
3119 const char *flavor_string) {
3120 DataBufferHeap data(GetArchitecture().GetMaximumOpcodeByteSize() * count, 0);
3121 bool force_live_memory = true;
3124 const size_t bytes_read =
3125 ReadMemory(start_addr, data.GetBytes(), data.GetByteSize(), error,
3126 force_live_memory, &load_addr);
3127
3128 if (error.Fail()) {
3129 return llvm::joinErrors(
3130 llvm::createStringErrorV(
3131 "Target::ReadInstructions failed to read memory at {:x}: ",
3132 start_addr.GetLoadAddress(this)),
3133 error.takeError());
3134 }
3135
3136 const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
3137 if (!flavor_string || flavor_string[0] == '\0') {
3138 // FIXME - we don't have the mechanism in place to do per-architecture
3139 // settings. But since we know that for now we only support flavors on
3140 // x86 & x86_64,
3141 const llvm::Triple::ArchType arch = GetArchitecture().GetTriple().getArch();
3142 if (arch == llvm::Triple::x86 || arch == llvm::Triple::x86_64)
3143 flavor_string = GetDisassemblyFlavor();
3144 }
3145
3147 GetArchitecture(), nullptr, flavor_string, GetDisassemblyCPU(),
3148 GetDisassemblyFeatures(), start_addr, data.GetBytes(), bytes_read, count,
3149 data_from_file);
3150}
3151
3154 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
3155 return *m_source_manager_up;
3156}
3157
3159 bool internal) {
3160 user_id_t new_uid = (internal ? LLDB_INVALID_UID : ++m_stop_hook_next_id);
3161 Target::StopHookSP stop_hook_sp;
3162 switch (kind) {
3164 stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
3165 break;
3167 stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
3168 break;
3170 stop_hook_sp.reset(new StopHookCoded(shared_from_this(), new_uid));
3171 break;
3172 }
3173 if (internal)
3174 m_internal_stop_hooks.push_back(stop_hook_sp);
3175 else
3176 m_stop_hooks[new_uid] = stop_hook_sp;
3177 return stop_hook_sp;
3178}
3179
3181 if (!RemoveStopHookByID(user_id))
3182 return;
3183 if (user_id == m_stop_hook_next_id)
3185}
3186
3188 size_t num_removed = m_stop_hooks.erase(user_id);
3189 return (num_removed != 0);
3190}
3191
3193
3195 StopHookSP found_hook;
3196
3197 StopHookCollection::iterator specified_hook_iter;
3198 specified_hook_iter = m_stop_hooks.find(user_id);
3199 if (specified_hook_iter != m_stop_hooks.end())
3200 found_hook = (*specified_hook_iter).second;
3201 return found_hook;
3202}
3203
3205 bool active_state) {
3206 StopHookCollection::iterator specified_hook_iter;
3207 specified_hook_iter = m_stop_hooks.find(user_id);
3208 if (specified_hook_iter == m_stop_hooks.end())
3209 return false;
3210
3211 (*specified_hook_iter).second->SetIsActive(active_state);
3212 return true;
3213}
3214
3215void Target::SetAllStopHooksActiveState(bool active_state) {
3216 StopHookCollection::iterator pos, end = m_stop_hooks.end();
3217 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
3218 (*pos).second->SetIsActive(active_state);
3219 }
3220}
3221
3222// FIXME: Ideally we would like to return a `const &` (const reference) instead
3223// of creating copy here, but that is not possible due to different container
3224// types. In C++20, we should be able to use `std::ranges::views::values` to
3225// adapt the key-pair entries in the `std::map` (behind `StopHookCollection`)
3226// to avoid creating the copy.
3227const std::vector<Target::StopHookSP>
3228Target::GetStopHooks(bool internal) const {
3229 if (internal)
3230 return m_internal_stop_hooks;
3231
3232 std::vector<StopHookSP> stop_hooks;
3233 for (auto &[_, hook] : m_stop_hooks)
3234 stop_hooks.push_back(hook);
3235
3236 return stop_hooks;
3237}
3238
3239bool Target::RunStopHooks(bool at_initial_stop) {
3241 return false;
3242
3243 if (!m_process_sp)
3244 return false;
3245
3246 // Somebody might have restarted the process:
3247 // Still return false, the return value is about US restarting the target.
3248 lldb::StateType state = m_process_sp->GetState();
3249 if (!(state == eStateStopped || state == eStateAttaching))
3250 return false;
3251
3252 auto is_active = [at_initial_stop](StopHookSP hook) {
3253 bool should_run_now = (!at_initial_stop || hook->GetRunAtInitialStop());
3254 return hook->IsActive() && should_run_now;
3255 };
3256
3257 // Create list of active internal and user stop hooks.
3258 std::vector<StopHookSP> active_hooks;
3259 llvm::copy_if(m_internal_stop_hooks, std::back_inserter(active_hooks),
3260 is_active);
3261 for (auto &[_, hook] : m_stop_hooks) {
3262 if (is_active(hook))
3263 active_hooks.push_back(hook);
3264 }
3265
3266 // Also collect unified hooks that fire on process stop.
3267 std::vector<HookSP> active_unified_hooks;
3268 for (auto &[_, hook] : m_hooks) {
3269 if (hook->IsEnabled() && hook->FiresOn(Hook::kProcessStop) &&
3270 (!at_initial_stop || hook->GetRunAtInitialStop()))
3271 active_unified_hooks.push_back(hook);
3272 }
3273
3274 if (active_hooks.empty() && active_unified_hooks.empty())
3275 return false;
3276
3277 // Make sure we check that we are not stopped because of us running a user
3278 // expression since in that case we do not want to run the stop-hooks. Note,
3279 // you can't just check whether the last stop was for a User Expression,
3280 // because breakpoint commands get run before stop hooks, and one of them
3281 // might have run an expression. You have to ensure you run the stop hooks
3282 // once per natural stop.
3283 uint32_t last_natural_stop = m_process_sp->GetModIDRef().GetLastNaturalStopID();
3284 if (last_natural_stop != 0 && m_latest_stop_hook_id == last_natural_stop)
3285 return false;
3286
3287 std::vector<ExecutionContext> exc_ctx_with_reasons;
3288
3289 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
3290 size_t num_threads = cur_threadlist.GetSize();
3291 for (size_t i = 0; i < num_threads; i++) {
3292 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
3293 if (cur_thread_sp->ThreadStoppedForAReason()) {
3294 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
3295 exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
3296 cur_frame_sp.get());
3297 }
3298 }
3299
3300 // If no threads stopped for a reason, don't run the stop-hooks.
3301 // However, if this is the FIRST stop for this process, then we are in the
3302 // state where an attach or a core file load was completed without designating
3303 // a particular thread as responsible for the stop. In that case, we do
3304 // want to run the stop hooks, but do so just on one thread.
3305 size_t num_exe_ctx = exc_ctx_with_reasons.size();
3306 if (num_exe_ctx == 0) {
3307 if (at_initial_stop && num_threads > 0) {
3308 lldb::ThreadSP thread_to_use_sp = cur_threadlist.GetThreadAtIndex(0);
3309 exc_ctx_with_reasons.emplace_back(
3310 m_process_sp.get(), thread_to_use_sp.get(),
3311 thread_to_use_sp->GetStackFrameAtIndex(0).get());
3312 num_exe_ctx = 1;
3313 } else {
3314 return false;
3315 }
3316 }
3317
3318 m_latest_stop_hook_id = last_natural_stop;
3319
3320 StreamSP output_sp = m_debugger.GetAsyncOutputStream();
3321 llvm::scope_exit on_exit([output_sp] { output_sp->Flush(); });
3322
3323 size_t num_hooks_with_output = llvm::count_if(
3324 active_hooks, [](auto h) { return !h->GetSuppressOutput(); });
3325 num_hooks_with_output += llvm::count_if(
3326 active_unified_hooks, [](auto h) { return !h->GetSuppressOutput(); });
3327 bool print_hook_header = (num_hooks_with_output > 1);
3328 bool print_thread_header = (num_exe_ctx > 1);
3329 bool should_stop = false;
3330 bool requested_continue = false;
3331
3332 // A stop hook might get deleted while running stop hooks.
3333 // We have to decide what that means. We will follow the rule that deleting
3334 // a stop hook while processing these stop hooks will delete it for FUTURE
3335 // stops but not this stop. Fortunately, copying the m_stop_hooks to the
3336 // active_hooks list before iterating over the hooks has this effect.
3337 for (auto cur_hook_sp : active_hooks) {
3338 bool any_thread_matched = false;
3339 for (auto exc_ctx : exc_ctx_with_reasons) {
3340 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
3341 continue;
3342
3343 bool suppress_output = cur_hook_sp->GetSuppressOutput();
3344 if (print_hook_header && !any_thread_matched && !suppress_output) {
3345 StreamString s;
3346 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
3347 if (s.GetSize() != 0)
3348 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
3349 s.GetData());
3350 else
3351 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
3352 any_thread_matched = true;
3353 }
3354
3355 if (print_thread_header && !suppress_output)
3356 output_sp->Printf("-- Thread %d\n",
3357 exc_ctx.GetThreadPtr()->GetIndexID());
3358
3359 auto result = cur_hook_sp->HandleStop(exc_ctx, output_sp);
3360 switch (result) {
3362 if (cur_hook_sp->GetAutoContinue())
3363 requested_continue = true;
3364 else
3365 should_stop = true;
3366 break;
3368 requested_continue = true;
3369 break;
3371 // Do nothing
3372 break;
3374 // We don't have a good way to prohibit people from restarting the
3375 // target willy nilly in a stop hook. If the hook did so, give a
3376 // gentle suggestion here and back out of the hook processing.
3377 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3378 " set the program running.\n"
3379 " Consider using '-G true' to make "
3380 "stop hooks auto-continue.\n",
3381 cur_hook_sp->GetID());
3382 // FIXME: if we are doing non-stop mode for real, we would have to
3383 // check that OUR thread was restarted, otherwise we should keep
3384 // processing stop hooks.
3385 return true;
3386 }
3387 }
3388 }
3389
3390 // Run unified hooks that fire on process stop.
3391 for (auto cur_hook_sp : active_unified_hooks) {
3392 bool any_thread_matched = false;
3393 for (auto exc_ctx : exc_ctx_with_reasons) {
3394 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
3395 continue;
3396
3397 bool suppress_output = cur_hook_sp->GetSuppressOutput();
3398 if (print_hook_header && !any_thread_matched && !suppress_output) {
3399 StreamString s;
3400 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
3401 if (s.GetSize() != 0)
3402 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
3403 s.GetData());
3404 else
3405 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
3406 any_thread_matched = true;
3407 }
3408
3409 if (print_thread_header && !suppress_output)
3410 output_sp->Printf("-- Thread %d\n",
3411 exc_ctx.GetThreadPtr()->GetIndexID());
3412
3413 auto result = cur_hook_sp->HandleStop(exc_ctx, output_sp);
3414 switch (result) {
3416 if (cur_hook_sp->GetAutoContinue())
3417 requested_continue = true;
3418 else
3419 should_stop = true;
3420 break;
3422 requested_continue = true;
3423 break;
3425 break;
3427 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3428 " set the program running.\n"
3429 " Consider using '-G true' to make "
3430 "stop hooks auto-continue.\n",
3431 cur_hook_sp->GetID());
3432 return true;
3433 }
3434 }
3435 }
3436
3437 // Resume iff at least one hook requested to continue and no hook asked to
3438 // stop.
3439 if (requested_continue && !should_stop) {
3440 Log *log = GetLog(LLDBLog::Process);
3441 Status error = m_process_sp->PrivateResume();
3442 if (error.Success()) {
3443 LLDB_LOG(log, "Resuming from RunStopHooks");
3444 return true;
3445 } else {
3446 LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
3447 return false;
3448 }
3449 }
3450
3451 return false;
3452}
3453
3455 // NOTE: intentional leak so we don't crash if global destructor chain gets
3456 // called as other threads still use the result of this function
3457 static TargetProperties *g_settings_ptr =
3458 new TargetProperties(nullptr);
3459 return *g_settings_ptr;
3460}
3461
3463 Status error;
3464 PlatformSP platform_sp(GetPlatform());
3465 if (!platform_sp || !platform_sp->IsRemote() || !platform_sp->IsConnected())
3466 return error;
3467
3468 // Install all files that have an install path when connected to a
3469 // remote platform. If target.auto-install-main-executable is set then
3470 // also install the main executable even if it does not have an explicit
3471 // install path specified.
3472
3473 for (auto module_sp : GetImages().Modules()) {
3474 if (module_sp == GetExecutableModule()) {
3475 MainExecutableInstaller installer{platform_sp, module_sp,
3476 shared_from_this(), *launch_info};
3477 error = installExecutable(installer);
3478 } else {
3479 ExecutableInstaller installer{platform_sp, module_sp};
3480 error = installExecutable(installer);
3481 }
3482
3483 if (error.Fail())
3484 return error;
3485 }
3486
3487 return error;
3488}
3489
3491 uint32_t stop_id, bool allow_section_end) {
3492 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr,
3493 allow_section_end);
3494}
3495
3497 Address &resolved_addr) {
3498 return m_images.ResolveFileAddress(file_addr, resolved_addr);
3499}
3500
3502 addr_t new_section_load_addr,
3503 bool warn_multiple) {
3504 const addr_t old_section_load_addr =
3505 m_section_load_history.GetSectionLoadAddress(
3506 SectionLoadHistory::eStopIDNow, section_sp);
3507 if (old_section_load_addr != new_section_load_addr) {
3508 uint32_t stop_id = 0;
3509 ProcessSP process_sp(GetProcessSP());
3510 if (process_sp)
3511 stop_id = process_sp->GetStopID();
3512 else
3513 stop_id = m_section_load_history.GetLastStopID();
3514 if (m_section_load_history.SetSectionLoadAddress(
3515 stop_id, section_sp, new_section_load_addr, warn_multiple))
3516 return true; // Return true if the section load address was changed...
3517 }
3518 return false; // Return false to indicate nothing changed
3519}
3520
3521size_t Target::UnloadModuleSections(const ModuleList &module_list) {
3522 size_t section_unload_count = 0;
3523 size_t num_modules = module_list.GetSize();
3524 for (size_t i = 0; i < num_modules; ++i) {
3525 section_unload_count +=
3526 UnloadModuleSections(module_list.GetModuleAtIndex(i));
3527 }
3528 return section_unload_count;
3529}
3530
3532 uint32_t stop_id = 0;
3533 ProcessSP process_sp(GetProcessSP());
3534 if (process_sp)
3535 stop_id = process_sp->GetStopID();
3536 else
3537 stop_id = m_section_load_history.GetLastStopID();
3538 SectionList *sections = module_sp->GetSectionList();
3539 size_t section_unload_count = 0;
3540 if (sections) {
3541 const uint32_t num_sections = sections->GetNumSections(0);
3542 for (uint32_t i = 0; i < num_sections; ++i) {
3543 section_unload_count += m_section_load_history.SetSectionUnloaded(
3544 stop_id, sections->GetSectionAtIndex(i));
3545 }
3546 }
3547 return section_unload_count;
3548}
3549
3551 uint32_t stop_id = 0;
3552 ProcessSP process_sp(GetProcessSP());
3553 if (process_sp)
3554 stop_id = process_sp->GetStopID();
3555 else
3556 stop_id = m_section_load_history.GetLastStopID();
3557 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
3558}
3559
3561 addr_t load_addr) {
3562 uint32_t stop_id = 0;
3563 ProcessSP process_sp(GetProcessSP());
3564 if (process_sp)
3565 stop_id = process_sp->GetStopID();
3566 else
3567 stop_id = m_section_load_history.GetLastStopID();
3568 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
3569 load_addr);
3570}
3571
3573
3575 lldb_private::TypeSummaryImpl &summary_provider) {
3576 return m_summary_statistics_cache.GetSummaryStatisticsForProvider(
3577 summary_provider);
3578}
3579
3583
3585 if (process_info.IsScriptedProcess()) {
3586 // Only copy scripted process launch options.
3587 ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>(
3589 default_launch_info.SetProcessPluginName("ScriptedProcess");
3590 default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata());
3591 SetProcessLaunchInfo(default_launch_info);
3592 }
3593}
3594
3596 m_stats.SetLaunchOrAttachTime();
3597 Status error;
3598 Log *log = GetLog(LLDBLog::Target);
3599
3600 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
3601 launch_info.GetExecutableFile().GetPath().c_str());
3602
3603 StateType state = eStateInvalid;
3604
3605 // Scope to temporarily get the process state in case someone has manually
3606 // remotely connected already to a process and we can skip the platform
3607 // launching.
3608 {
3609 ProcessSP process_sp(GetProcessSP());
3610
3611 if (process_sp) {
3612 state = process_sp->GetState();
3613 LLDB_LOGF(log,
3614 "Target::%s the process exists, and its current state is %s",
3615 __FUNCTION__, StateAsCString(state));
3616 } else {
3617 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
3618 __FUNCTION__);
3619 }
3620 }
3621
3622 launch_info.GetFlags().Set(eLaunchFlagDebug);
3623
3624 SaveScriptedLaunchInfo(launch_info);
3625
3626 // Get the value of synchronous execution here. If you wait till after you
3627 // have started to run, then you could have hit a breakpoint, whose command
3628 // might switch the value, and then you'll pick up that incorrect value.
3629 Debugger &debugger = GetDebugger();
3630 const bool synchronous_execution =
3632
3633 PlatformSP platform_sp(GetPlatform());
3634
3635 FinalizeFileActions(launch_info);
3636
3637 if (state == eStateConnected) {
3638 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY))
3640 "can't launch in tty when launching through a remote connection");
3641 }
3642
3643 if (!launch_info.GetArchitecture().IsValid())
3644 launch_info.GetArchitecture() = GetArchitecture();
3645
3646 // Hijacking events of the process to be created to be sure that all events
3647 // until the first stop are intercepted (in case if platform doesn't define
3648 // its own hijacking listener or if the process is created by the target
3649 // manually, without the platform).
3650 if (!launch_info.GetHijackListener())
3651 launch_info.SetHijackListener(
3653
3654 // If we're not already connected to the process, and if we have a platform
3655 // that can launch a process for debugging, go ahead and do that here.
3656 if (state != eStateConnected && platform_sp &&
3657 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) {
3658 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
3659 __FUNCTION__);
3660
3661 // If there was a previous process, delete it before we make the new one.
3662 // One subtle point, we delete the process before we release the reference
3663 // to m_process_sp. That way even if we are the last owner, the process
3664 // will get Finalized before it gets destroyed.
3666
3667 m_process_sp =
3668 GetPlatform()->DebugProcess(launch_info, debugger, *this, error);
3669
3670 } else {
3671 LLDB_LOGF(log,
3672 "Target::%s the platform doesn't know how to debug a "
3673 "process, getting a process plugin to do this for us.",
3674 __FUNCTION__);
3675
3676 if (state == eStateConnected) {
3677 assert(m_process_sp);
3678 } else {
3679 // Use a Process plugin to construct the process.
3680 CreateProcess(launch_info.GetListener(),
3681 launch_info.GetProcessPluginName(), nullptr, false);
3682 }
3683
3684 // Since we didn't have a platform launch the process, launch it here.
3685 if (m_process_sp) {
3686 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener());
3687 m_process_sp->SetShadowListener(launch_info.GetShadowListener());
3688 error = m_process_sp->Launch(launch_info);
3689 }
3690 }
3691
3692 if (!error.Success())
3693 return error;
3694
3695 if (!m_process_sp)
3696 return Status::FromErrorString("failed to launch or debug process");
3697
3698 bool rebroadcast_first_stop =
3699 !synchronous_execution &&
3700 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry);
3701
3702 assert(launch_info.GetHijackListener());
3703
3704 EventSP first_stop_event_sp;
3705 state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp,
3706 rebroadcast_first_stop,
3707 launch_info.GetHijackListener());
3708 m_process_sp->RestoreProcessEvents();
3709
3710 if (rebroadcast_first_stop) {
3711 // We don't need to run the stop hooks by hand here, they will get
3712 // triggered when this rebroadcast event gets fetched.
3713 assert(first_stop_event_sp);
3714 m_process_sp->BroadcastEvent(first_stop_event_sp);
3715 return error;
3716 }
3717 // Run the stop hooks that want to run at entry.
3718 RunStopHooks(true /* at entry point */);
3719
3720 switch (state) {
3721 case eStateStopped: {
3722 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3723 break;
3724 if (synchronous_execution)
3725 // Now we have handled the stop-from-attach, and we are just
3726 // switching to a synchronous resume. So we should switch to the
3727 // SyncResume hijacker.
3728 m_process_sp->ResumeSynchronous(stream);
3729 else
3730 error = m_process_sp->Resume();
3731 if (!error.Success()) {
3733 "process resume at entry point failed: %s", error.AsCString());
3734 }
3735 } break;
3736 case eStateExited: {
3737 bool with_shell = !!launch_info.GetShell();
3738 const int exit_status = m_process_sp->GetExitStatus();
3739 const char *exit_desc = m_process_sp->GetExitDescription();
3740 std::string desc;
3741 if (exit_desc && exit_desc[0])
3742 desc = " (" + std::string(exit_desc) + ')';
3743 if (with_shell)
3745 "process exited with status %i%s\n"
3746 "'r' and 'run' are aliases that default to launching through a "
3747 "shell.\n"
3748 "Try launching without going through a shell by using "
3749 "'process launch'.",
3750 exit_status, desc.c_str());
3751 else
3753 "process exited with status %i%s", exit_status, desc.c_str());
3754 } break;
3755 default:
3757 "initial process state wasn't stopped: %s", StateAsCString(state));
3758 break;
3759 }
3760 return error;
3761}
3762
3763void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3764
3766
3767llvm::Expected<TraceSP> Target::CreateTrace() {
3768 if (!m_process_sp)
3769 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3770 "A process is required for tracing");
3771 if (m_trace_sp)
3772 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3773 "A trace already exists for the target");
3774
3775 llvm::Expected<TraceSupportedResponse> trace_type =
3776 m_process_sp->TraceSupported();
3777 if (!trace_type)
3778 return llvm::createStringError(
3779 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3780 llvm::toString(trace_type.takeError()).c_str());
3781 if (llvm::Expected<TraceSP> trace_sp =
3783 m_trace_sp = *trace_sp;
3784 else
3785 return llvm::createStringError(
3786 llvm::inconvertibleErrorCode(),
3787 "Couldn't create a Trace object for the process. %s",
3788 llvm::toString(trace_sp.takeError()).c_str());
3789 return m_trace_sp;
3790}
3791
3792llvm::Expected<TraceSP> Target::GetTraceOrCreate() {
3793 if (m_trace_sp)
3794 return m_trace_sp;
3795 return CreateTrace();
3796}
3797
3799 Progress attach_progress("Waiting to attach to process");
3800 m_stats.SetLaunchOrAttachTime();
3801 auto state = eStateInvalid;
3802 auto process_sp = GetProcessSP();
3803 if (process_sp) {
3804 state = process_sp->GetState();
3805 if (process_sp->IsAlive() && state != eStateConnected) {
3806 if (state == eStateAttaching)
3807 return Status::FromErrorString("process attach is in progress");
3808 return Status::FromErrorString("a process is already being debugged");
3809 }
3810 }
3811
3812 const ModuleSP old_exec_module_sp = GetExecutableModule();
3813
3814 // If no process info was specified, then use the target executable name as
3815 // the process to attach to by default
3816 if (!attach_info.ProcessInfoSpecified()) {
3817 if (old_exec_module_sp)
3818 attach_info.GetExecutableFile().SetFilename(
3819 old_exec_module_sp->GetPlatformFileSpec().GetFilename());
3820
3821 if (!attach_info.ProcessInfoSpecified()) {
3823 "no process specified, create a target with a file, or "
3824 "specify the --pid or --name");
3825 }
3826 }
3827
3828 const auto platform_sp =
3830 ListenerSP hijack_listener_sp;
3831 const bool async = attach_info.GetAsync();
3832 if (!async) {
3833 hijack_listener_sp =
3835 attach_info.SetHijackListener(hijack_listener_sp);
3836 }
3837
3838 Status error;
3839 if (state != eStateConnected && platform_sp != nullptr &&
3840 platform_sp->CanDebugProcess() && !attach_info.IsScriptedProcess()) {
3841 SetPlatform(platform_sp);
3842 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3843 } else {
3844 if (state != eStateConnected) {
3845 SaveScriptedLaunchInfo(attach_info);
3846 llvm::StringRef plugin_name = attach_info.GetProcessPluginName();
3847 process_sp =
3849 plugin_name, nullptr, false);
3850 if (!process_sp) {
3852 "failed to create process using plugin '{0}'",
3853 plugin_name.empty() ? "<empty>" : plugin_name);
3854 return error;
3855 }
3856 }
3857 if (hijack_listener_sp)
3858 process_sp->HijackProcessEvents(hijack_listener_sp);
3859 error = process_sp->Attach(attach_info);
3860 }
3861
3862 if (error.Success() && process_sp) {
3863 if (async) {
3864 process_sp->RestoreProcessEvents();
3865 } else {
3866 // We are stopping all the way out to the user, so update selected frames.
3867 state = process_sp->WaitForProcessToStop(
3868 std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
3870 process_sp->RestoreProcessEvents();
3871
3872 // Run the stop hooks here. Since we were hijacking the events, they
3873 // wouldn't have gotten run as part of event delivery.
3874 RunStopHooks(/* at_initial_stop= */ true);
3875
3876 if (state != eStateStopped) {
3877 const char *exit_desc = process_sp->GetExitDescription();
3878 if (exit_desc)
3879 error = Status::FromErrorStringWithFormat("%s", exit_desc);
3880 else
3882 "process did not stop (no such process or permission problem?)");
3883 process_sp->Destroy(false);
3884 }
3885 }
3886 }
3887 return error;
3888}
3889
3891 const ScriptedFrameProviderDescriptor &descriptor) {
3892 if (!descriptor.IsValid())
3893 return llvm::createStringError("invalid frame provider descriptor");
3894
3895 llvm::StringRef name = descriptor.GetName();
3896 if (name.empty())
3897 return llvm::createStringError(
3898 "frame provider descriptor has no class name");
3899
3900 {
3901 std::unique_lock<std::recursive_mutex> guard(
3903
3904 // Check for duplicate: same class name and args (content hash).
3905 uint32_t descriptor_hash = descriptor.GetHash();
3906 for (const auto &entry : m_frame_provider_descriptors) {
3907 if (entry.second.GetHash() == descriptor_hash)
3909 llvm::formatv("frame provider idx={0} with the same class name and "
3910 "arguments is already registered",
3911 entry.second.GetID())
3912 .str());
3913 }
3914
3915 uint32_t descriptor_id = m_next_frame_provider_id++;
3916 ScriptedFrameProviderDescriptor new_descriptor = descriptor;
3917 new_descriptor.SetID(descriptor_id);
3918 m_frame_provider_descriptors[descriptor_id] = new_descriptor;
3919
3921
3922 return descriptor_id;
3923 }
3924}
3925
3927 bool removed = false;
3928 {
3929 std::lock_guard<std::recursive_mutex> guard(
3931 removed = m_frame_provider_descriptors.erase(id);
3932 }
3933
3934 if (removed)
3936 return removed;
3937}
3938
3940 {
3941 std::lock_guard<std::recursive_mutex> guard(
3945 }
3946
3948}
3949
3950const llvm::MapVector<uint32_t, ScriptedFrameProviderDescriptor> &
3952 std::lock_guard<std::recursive_mutex> guard(
3955}
3956
3958 ProcessSP process_sp = GetProcessSP();
3959 if (!process_sp)
3960 return;
3961 for (ThreadSP thread_sp : process_sp->Threads()) {
3962 // Clear frame providers on existing threads so they reload with new config.
3963 thread_sp->ClearScriptedFrameProvider();
3964 // Notify threads that the stack traces might have changed.
3965 if (thread_sp->EventTypeHasListeners(Thread::eBroadcastBitStackChanged)) {
3966 auto data_sp = std::make_shared<Thread::ThreadEventData>(thread_sp);
3967 thread_sp->BroadcastEvent(Thread::eBroadcastBitStackChanged, data_sp);
3968 }
3969 }
3970}
3971
3973 Log *log = GetLog(LLDBLog::Process);
3974
3975 // Finalize the file actions, and if none were given, default to opening up a
3976 // pseudo terminal
3977 PlatformSP platform_sp = GetPlatform();
3978 const bool default_to_use_pty =
3979 m_platform_sp ? m_platform_sp->IsHost() : false;
3980 LLDB_LOG(
3981 log,
3982 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3983 bool(platform_sp),
3984 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3985 default_to_use_pty);
3986
3987 // If nothing for stdin or stdout or stderr was specified, then check the
3988 // process for any default settings that were set with "settings set"
3989 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3990 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3991 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3992 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3993 "default handling");
3994
3995 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3996 // Do nothing, if we are launching in a remote terminal no file actions
3997 // should be done at all.
3998 return;
3999 }
4000
4001 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
4002 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
4003 "for stdin, stdout and stderr");
4004 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
4005 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
4006 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
4007 } else {
4008 // Check for any values that might have gotten set with any of: (lldb)
4009 // settings set target.input-path (lldb) settings set target.output-path
4010 // (lldb) settings set target.error-path
4011 FileSpec in_file_spec;
4012 FileSpec out_file_spec;
4013 FileSpec err_file_spec;
4014 // Only override with the target settings if we don't already have an
4015 // action for in, out or error
4016 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
4017 in_file_spec = GetStandardInputPath();
4018 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
4019 out_file_spec = GetStandardOutputPath();
4020 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
4021 err_file_spec = GetStandardErrorPath();
4022
4023 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{2}'",
4024 in_file_spec, out_file_spec, err_file_spec);
4025
4026 if (in_file_spec) {
4027 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
4028 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
4029 }
4030
4031 if (out_file_spec) {
4032 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
4033 LLDB_LOG(log, "appended stdout open file action for {0}",
4034 out_file_spec);
4035 }
4036
4037 if (err_file_spec) {
4038 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
4039 LLDB_LOG(log, "appended stderr open file action for {0}",
4040 err_file_spec);
4041 }
4042
4043 if (default_to_use_pty) {
4044#ifdef _WIN32
4045 if (info.GetFlags().Test(eLaunchFlagUsePipes) ||
4046 ::getenv("LLDB_LAUNCH_FLAG_USE_PIPES")) {
4047 llvm::Error Err = info.SetUpPipeRedirection();
4048 LLDB_LOG_ERROR(log, std::move(Err),
4049 "SetUpPipeRedirection failed: {0}");
4050 } else {
4051#endif
4052 llvm::Error Err = info.SetUpPtyRedirection();
4053 LLDB_LOG_ERROR(log, std::move(Err),
4054 "SetUpPtyRedirection failed: {0}");
4055#ifdef _WIN32
4056 }
4057#endif
4058 }
4059 }
4060 }
4061}
4062
4063void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify,
4064 LazyBool stop) {
4065 if (name.empty())
4066 return;
4067 // Don't add a signal if all the actions are trivial:
4068 if (pass == eLazyBoolCalculate && notify == eLazyBoolCalculate
4069 && stop == eLazyBoolCalculate)
4070 return;
4071
4072 auto& elem = m_dummy_signals[name];
4073 elem.pass = pass;
4074 elem.notify = notify;
4075 elem.stop = stop;
4076}
4077
4079 const DummySignalElement &elem) {
4080 if (!signals_sp)
4081 return false;
4082
4083 int32_t signo
4084 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
4085 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
4086 return false;
4087
4088 if (elem.second.pass == eLazyBoolYes)
4089 signals_sp->SetShouldSuppress(signo, false);
4090 else if (elem.second.pass == eLazyBoolNo)
4091 signals_sp->SetShouldSuppress(signo, true);
4092
4093 if (elem.second.notify == eLazyBoolYes)
4094 signals_sp->SetShouldNotify(signo, true);
4095 else if (elem.second.notify == eLazyBoolNo)
4096 signals_sp->SetShouldNotify(signo, false);
4097
4098 if (elem.second.stop == eLazyBoolYes)
4099 signals_sp->SetShouldStop(signo, true);
4100 else if (elem.second.stop == eLazyBoolNo)
4101 signals_sp->SetShouldStop(signo, false);
4102 return true;
4103}
4104
4106 const DummySignalElement &elem) {
4107 if (!signals_sp)
4108 return false;
4109 int32_t signo
4110 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
4111 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
4112 return false;
4113 bool do_pass = elem.second.pass != eLazyBoolCalculate;
4114 bool do_stop = elem.second.stop != eLazyBoolCalculate;
4115 bool do_notify = elem.second.notify != eLazyBoolCalculate;
4116 signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass);
4117 return true;
4118}
4119
4121 StreamSP warning_stream_sp) {
4122 if (!signals_sp)
4123 return;
4124
4125 for (const auto &elem : m_dummy_signals) {
4126 if (!UpdateSignalFromDummy(signals_sp, elem))
4127 warning_stream_sp->Printf("Target signal '%s' not found in process\n",
4128 elem.first().str().c_str());
4129 }
4130}
4131
4132void Target::ClearDummySignals(Args &signal_names) {
4133 ProcessSP process_sp = GetProcessSP();
4134 // The simplest case, delete them all with no process to update.
4135 if (signal_names.GetArgumentCount() == 0 && !process_sp) {
4136 m_dummy_signals.clear();
4137 return;
4138 }
4139 UnixSignalsSP signals_sp;
4140 if (process_sp)
4141 signals_sp = process_sp->GetUnixSignals();
4142
4143 for (const Args::ArgEntry &entry : signal_names) {
4144 const char *signal_name = entry.c_str();
4145 auto elem = m_dummy_signals.find(signal_name);
4146 // If we didn't find it go on.
4147 // FIXME: Should I pipe error handling through here?
4148 if (elem == m_dummy_signals.end()) {
4149 continue;
4150 }
4151 if (signals_sp)
4152 ResetSignalFromDummy(signals_sp, *elem);
4153 m_dummy_signals.erase(elem);
4154 }
4155}
4156
4157void Target::PrintDummySignals(Stream &strm, Args &signal_args) {
4158 strm.PutCString("NAME PASS STOP NOTIFY\n");
4159 strm.PutCString("=========== ======= ======= =======\n");
4160
4161 auto str_for_lazy = [] (LazyBool lazy) -> const char * {
4162 switch (lazy) {
4163 case eLazyBoolCalculate: return "not set";
4164 case eLazyBoolYes: return "true ";
4165 case eLazyBoolNo: return "false ";
4166 }
4167 llvm_unreachable("Fully covered switch above!");
4168 };
4169 size_t num_args = signal_args.GetArgumentCount();
4170 for (const auto &elem : m_dummy_signals) {
4171 bool print_it = false;
4172 for (size_t idx = 0; idx < num_args; idx++) {
4173 if (elem.first() == signal_args.GetArgumentAtIndex(idx)) {
4174 print_it = true;
4175 break;
4176 }
4177 }
4178 if (print_it) {
4179 strm.Printf("%-11s ", elem.first().str().c_str());
4180 strm.Printf("%s %s %s\n", str_for_lazy(elem.second.pass),
4181 str_for_lazy(elem.second.stop),
4182 str_for_lazy(elem.second.notify));
4183 }
4184 }
4185}
4186
4187// Target::StopHook
4191
4193 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
4196 if (rhs.m_thread_spec_up)
4197 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
4198}
4199
4201 m_specifier_sp.reset(specifier);
4202}
4203
4205 m_thread_spec_up.reset(specifier);
4206}
4207
4209 SymbolContextSpecifier *specifier = GetSpecifier();
4210 if (!specifier)
4211 return true;
4212
4213 bool will_run = true;
4214 if (exc_ctx.GetFramePtr())
4215 will_run = GetSpecifier()->SymbolContextMatches(
4216 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
4217 if (will_run && GetThreadSpecifier() != nullptr)
4218 will_run =
4219 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
4220
4221 return will_run;
4222}
4223
4225 lldb::DescriptionLevel level) const {
4226
4227 // For brief descriptions, only print the subclass description:
4228 if (level == eDescriptionLevelBrief) {
4229 GetSubclassDescription(s, level);
4230 return;
4231 }
4232
4233 auto indent_scope = s.MakeIndentScope();
4234
4235 s.Printf("Hook: %" PRIu64 "\n", GetID());
4236 if (m_active)
4237 s.Indent("State: enabled\n");
4238 else
4239 s.Indent("State: disabled\n");
4240
4241 if (m_auto_continue)
4242 s.Indent("AutoContinue on\n");
4243
4244 if (m_specifier_sp) {
4245 s.Indent();
4246 s.PutCString("Specifier:\n");
4247 auto indent_scope = s.MakeIndentScope();
4248 m_specifier_sp->GetDescription(&s, level);
4249 }
4250
4251 if (m_thread_spec_up) {
4252 StreamString tmp;
4253 s.Indent("Thread:\n");
4254 m_thread_spec_up->GetDescription(&tmp, level);
4255 auto indent_scope = s.MakeIndentScope();
4256 s.Indent(tmp.GetString());
4257 s.PutCString("\n");
4258 }
4259 GetSubclassDescription(s, level);
4260}
4261
4263 Stream &s, lldb::DescriptionLevel level) const {
4264 // The brief description just prints the first command.
4265 if (level == eDescriptionLevelBrief) {
4266 if (m_commands.GetSize() == 1)
4267 s.PutCString(m_commands.GetStringAtIndex(0));
4268 return;
4269 }
4270 s.Indent("Commands:\n");
4271 auto indent_scope = s.MakeIndentScope(4);
4272 uint32_t num_commands = m_commands.GetSize();
4273 for (uint32_t i = 0; i < num_commands; i++) {
4274 s.Indent(m_commands.GetStringAtIndex(i));
4275 s.PutCString("\n");
4276 }
4277}
4278
4279// Target::StopHookCommandLine
4281 GetCommands().SplitIntoLines(string);
4282}
4283
4285 const std::vector<std::string> &strings) {
4286 for (auto string : strings)
4287 GetCommands().AppendString(string.c_str());
4288}
4289
4292 StreamSP output_sp) {
4293 assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
4294 "with no target");
4295
4296 if (!m_commands.GetSize())
4298
4299 CommandReturnObject result(false);
4300 result.SetImmediateOutputStream(output_sp);
4301 result.SetImmediateErrorStream(output_sp);
4302 result.SetInteractive(false);
4303 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
4305 options.SetStopOnContinue(true);
4306 options.SetStopOnError(true);
4307 options.SetEchoCommands(false);
4308 options.SetPrintResults(true);
4309 options.SetPrintErrors(true);
4310 options.SetAddToHistory(false);
4311
4312 // Force Async:
4313 bool old_async = debugger.GetAsyncExecution();
4314 debugger.SetAsyncExecution(true);
4315 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
4316 options, result);
4317 debugger.SetAsyncExecution(old_async);
4318 lldb::ReturnStatus status = result.GetStatus();
4323}
4324
4325// Target::StopHookScripted
4327 const ScriptedMetadata &scripted_metadata) {
4328 Status error;
4329
4330 ScriptInterpreter *script_interp =
4331 GetTarget()->GetDebugger().GetScriptInterpreter();
4332 if (!script_interp) {
4333 error = Status::FromErrorString("No script interpreter installed.");
4334 return error;
4335 }
4336
4338 if (!m_interface_sp) {
4340 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__,
4341 "Script interpreter couldn't create Scripted Stop Hook Interface");
4342 return error;
4343 }
4344
4345 auto obj_or_err =
4346 m_interface_sp->CreatePluginObject(scripted_metadata, GetTarget());
4347 if (!obj_or_err) {
4348 return Status::FromError(obj_or_err.takeError());
4349 }
4350
4351 StructuredData::ObjectSP object_sp = *obj_or_err;
4352 if (!object_sp || !object_sp->IsValid()) {
4354 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__,
4355 "Failed to create valid script object");
4356 return error;
4357 }
4358
4359 return {};
4360}
4361
4364 StreamSP output_sp) {
4365 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
4366 "with no target");
4367
4368 if (!m_interface_sp)
4370
4371 lldb::StreamSP stream = std::make_shared<lldb_private::StreamString>();
4372 auto should_stop_or_err = m_interface_sp->HandleStop(exc_ctx, stream);
4373 output_sp->PutCString(
4374 reinterpret_cast<StreamString *>(stream.get())->GetData());
4375 if (!should_stop_or_err) {
4376 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), should_stop_or_err.takeError(),
4377 "scripted stop hook HandleStop failed: {0}");
4379 }
4380
4381 return *should_stop_or_err ? StopHookResult::KeepStopped
4383}
4384
4386 if (m_interface_sp && m_interface_sp->GetScriptedMetadata())
4387 return m_interface_sp->GetScriptedMetadata()->GetClassName();
4388 return "<unknown>";
4389}
4390
4392 Stream &s, lldb::DescriptionLevel level) const {
4393 llvm::StringRef class_name = GetScriptClassName();
4394 if (level == eDescriptionLevelBrief) {
4395 s.PutCString(class_name);
4396 return;
4397 }
4398 s.Indent("Class:");
4399 s.Format("{0}\n", class_name);
4400
4401 // Now print the extra args:
4402 // FIXME: We should use StructuredData.GetDescription on the args dict
4403 // but that seems to rely on some printing plugin that doesn't exist.
4405 (m_interface_sp && m_interface_sp->GetScriptedMetadata())
4406 ? m_interface_sp->GetScriptedMetadata()->GetArgsSP()
4407 : nullptr;
4408 if (!as_dict || !as_dict->IsValid())
4409 return;
4410
4411 uint32_t num_keys = as_dict->GetSize();
4412 if (num_keys == 0)
4413 return;
4414
4415 s.Indent("Args:\n");
4416 auto indent_scope = s.MakeIndentScope(4);
4417
4418 auto print_one_element = [&s](llvm::StringRef key,
4419 StructuredData::Object *object) {
4420 s.Indent();
4421 s.Format("{0} : {1}\n", key, object->GetStringValue());
4422 return true;
4423 };
4424
4425 as_dict->ForEach(print_one_element);
4426}
4427
4428// Hook
4429
4431 : UserID(uid), m_target_sp(std::move(target_sp)), m_kind(kind) {}
4432
4443
4445 m_sc_specifier_sp.reset(specifier);
4446}
4447
4449 m_thread_spec_up.reset(specifier);
4450}
4451
4454 if (!specifier)
4455 return true;
4456
4457 bool will_run = true;
4458 if (exc_ctx.GetFramePtr())
4459 will_run = specifier->SymbolContextMatches(
4460 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
4461 if (will_run && GetThreadSpecifier() != nullptr)
4462 will_run =
4463 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
4464
4465 return will_run;
4466}
4467
4469 lldb::DescriptionLevel level) const {
4470 s.Printf("Hook: %" PRIu64 "\n", GetID());
4471 if (level == eDescriptionLevelBrief)
4472 return;
4473 s.IndentMore();
4474 s.Indent();
4475 s.Printf("State: %s\n", m_enabled ? "enabled" : "disabled");
4476
4477 {
4478 std::string fires_on;
4480 fires_on += "load";
4482 if (!fires_on.empty())
4483 fires_on += ", ";
4484 fires_on += "unload";
4485 }
4487 if (!fires_on.empty())
4488 fires_on += ", ";
4489 fires_on += "stop";
4490 }
4491 if (!fires_on.empty()) {
4492 s.Indent();
4493 s.Printf("Triggers: %s\n", fires_on.c_str());
4494 }
4495 }
4496 // Subclasses add their content (commands or class) then call
4497 // GetFilterDescription to print filters.
4498 s.IndentLess();
4499}
4500
4502 lldb::DescriptionLevel level) const {
4503 s.IndentMore();
4504
4505 if (m_auto_continue)
4506 s.Indent("AutoContinue on\n");
4507
4508 if (m_sc_specifier_sp) {
4509 s.Indent();
4510 s.PutCString("Specifier:\n");
4511 s.IndentMore();
4512 m_sc_specifier_sp->GetDescription(&s, level);
4513 s.IndentLess();
4514 }
4515
4516 if (m_thread_spec_up) {
4517 StreamString tmp;
4518 s.Indent("Thread:\n");
4519 m_thread_spec_up->GetDescription(&tmp, level);
4520 s.IndentMore();
4521 s.Indent(tmp.GetString());
4522 s.PutCString("\n");
4523 s.IndentLess();
4524 }
4525
4526 s.IndentLess();
4527}
4528
4530 Stream &s, lldb::DescriptionLevel level) const {
4531 Hook::GetDescription(s, level);
4532 if (level == eDescriptionLevelBrief) {
4533 if (m_commands.GetSize() == 1)
4534 s.PutCString(m_commands.GetStringAtIndex(0));
4535 else
4536 s.Printf("%" PRIu64 " commands", (uint64_t)m_commands.GetSize());
4537 return;
4538 }
4539
4540 // Commands come after the header (ID, State, Triggers) but before filters.
4541 s.IndentMore();
4542 s.Indent("Commands: \n");
4543 s.IndentMore();
4544 for (uint32_t i = 0; i < m_commands.GetSize(); i++) {
4545 s.Indent(m_commands.GetStringAtIndex(i));
4546 s.PutCString("\n");
4547 }
4548 s.IndentLess();
4549 s.IndentLess();
4550
4551 GetFilterDescription(s, level);
4552}
4553
4554// HookCommandLine
4555
4556void Target::HookCommandLine::SetActionFromString(const std::string &string) {
4557 GetCommands().SplitIntoLines(string);
4558}
4559
4561 const std::vector<std::string> &strings) {
4562 for (const auto &string : strings)
4563 GetCommands().AppendString(string.c_str());
4564}
4565
4567 if (!m_commands.GetSize())
4568 return;
4569
4570 TargetSP target_sp = GetTarget();
4571 if (!target_sp)
4572 return;
4573
4574 CommandReturnObject result(false);
4575 result.SetImmediateOutputStream(output_sp);
4576 result.SetInteractive(false);
4577 Debugger &debugger = target_sp->GetDebugger();
4578
4579 ExecutionContext exe_ctx;
4580 if (target_sp->GetProcessSP())
4581 exe_ctx.SetContext(target_sp->GetProcessSP());
4582 else
4583 exe_ctx.SetContext(target_sp, false);
4584
4586 options.SetStopOnContinue(true);
4587 options.SetStopOnError(true);
4588 options.SetEchoCommands(false);
4589 options.SetPrintResults(true);
4590 options.SetPrintErrors(true);
4591 options.SetAddToHistory(false);
4592
4593 bool old_async = debugger.GetAsyncExecution();
4594 debugger.SetAsyncExecution(true);
4595 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exe_ctx,
4596 options, result);
4597 debugger.SetAsyncExecution(old_async);
4598}
4599
4601 // Command-based hooks run the same commands on unload as on load.
4602 HandleModuleLoaded(output_sp);
4603}
4604
4607 StreamSP output_sp) {
4608 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
4609 "with no target");
4610
4611 if (!m_commands.GetSize())
4613
4614 CommandReturnObject result(false);
4615 result.SetImmediateOutputStream(output_sp);
4616 result.SetImmediateErrorStream(output_sp);
4617 result.SetInteractive(false);
4618 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
4620 options.SetStopOnContinue(true);
4621 options.SetStopOnError(true);
4622 options.SetEchoCommands(false);
4623 options.SetPrintResults(true);
4624 options.SetPrintErrors(true);
4625 options.SetAddToHistory(false);
4626
4627 bool old_async = debugger.GetAsyncExecution();
4628 debugger.SetAsyncExecution(true);
4629 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
4630 options, result);
4631 debugger.SetAsyncExecution(old_async);
4632 lldb::ReturnStatus status = result.GetStatus();
4637}
4638
4639// HookScripted
4640
4642 const ScriptedMetadata &scripted_metadata) {
4643 ScriptInterpreter *script_interp =
4644 GetTarget()->GetDebugger().GetScriptInterpreter();
4645 if (!script_interp)
4646 return Status::FromErrorString("No script interpreter installed.");
4647
4649 if (!m_interface_sp)
4651 "ScriptedHook::%s () - ERROR: %s", __FUNCTION__,
4652 "Script interpreter couldn't create Scripted Hook Interface");
4653
4654 auto obj_or_err =
4655 m_interface_sp->CreatePluginObject(scripted_metadata, GetTarget());
4656 if (!obj_or_err)
4657 return Status::FromError(obj_or_err.takeError());
4658
4659 StructuredData::ObjectSP object_sp = *obj_or_err;
4660 if (!object_sp || !object_sp->IsValid())
4662 "ScriptedHook::%s () - ERROR: %s", __FUNCTION__,
4663 "Failed to create valid script object");
4664
4665 // Determine which triggers the class supports by checking which callback
4666 // methods it implements.
4667 auto methods = m_interface_sp->GetSupportedMethods();
4668 if (!methods.any())
4670 "hook class implements none of the expected methods "
4671 "(handle_module_loaded, handle_module_unloaded, handle_stop)");
4672
4673 if (methods.handle_module_loaded)
4675 if (methods.handle_module_unloaded)
4677 if (methods.handle_stop)
4679
4680 return {};
4681}
4682
4684 if (!m_interface_sp)
4685 return;
4686
4687 StreamSP stream = std::make_shared<StreamString>();
4688 m_interface_sp->HandleModuleLoaded(stream);
4689 output_sp->PutCString(static_cast<StreamString *>(stream.get())->GetData());
4690}
4691
4693 if (!m_interface_sp)
4694 return;
4695
4696 StreamSP stream = std::make_shared<StreamString>();
4697 m_interface_sp->HandleModuleUnloaded(stream);
4698 output_sp->PutCString(static_cast<StreamString *>(stream.get())->GetData());
4699}
4700
4703 StreamSP output_sp) {
4704 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
4705 "with no target");
4706
4707 if (!m_interface_sp)
4709
4710 lldb::StreamSP stream = std::make_shared<lldb_private::StreamString>();
4711 auto should_stop_or_err = m_interface_sp->HandleStop(exc_ctx, stream);
4712 output_sp->PutCString(static_cast<StreamString *>(stream.get())->GetData());
4713 if (!should_stop_or_err)
4715
4716 return *should_stop_or_err ? StopHook::StopHookResult::KeepStopped
4718}
4719
4721 if (m_interface_sp && m_interface_sp->GetScriptedMetadata())
4722 return m_interface_sp->GetScriptedMetadata()->GetClassName();
4723 return "<unknown>";
4724}
4725
4727 lldb::DescriptionLevel level) const {
4728 Hook::GetDescription(s, level);
4729 llvm::StringRef class_name = GetScriptClassName();
4730 if (level == eDescriptionLevelBrief) {
4731 s.PutCString(class_name);
4732 return;
4733 }
4734
4735 // Class and args come after the header (ID, State, Triggers) but before
4736 // filters.
4737 s.IndentMore();
4738 s.Indent("Class: ");
4739 s.Format("{0}\n", class_name);
4740
4742 (m_interface_sp && m_interface_sp->GetScriptedMetadata())
4743 ? m_interface_sp->GetScriptedMetadata()->GetArgsSP()
4744 : nullptr;
4745 if (as_dict && as_dict->IsValid() && as_dict->GetSize() > 0) {
4746 s.Indent("Args:\n");
4747 s.IndentMore();
4748
4749 auto print_one_element = [&s](llvm::StringRef key,
4750 StructuredData::Object *object) {
4751 s.Indent();
4752 s.Format("{0} : {1}\n", key, object->GetStringValue());
4753 return true;
4754 };
4755
4756 as_dict->ForEach(print_one_element);
4757 s.IndentLess();
4758 }
4759 s.IndentLess();
4760
4761 GetFilterDescription(s, level);
4762}
4763
4764// Hook management methods
4765
4767 lldb::user_id_t new_uid = ++m_hook_next_id;
4768 HookSP hook_sp;
4769 switch (kind) {
4771 hook_sp.reset(new HookCommandLine(shared_from_this(), new_uid));
4772 break;
4774 hook_sp.reset(new HookScripted(shared_from_this(), new_uid));
4775 break;
4776 }
4777 m_hooks[new_uid] = hook_sp;
4778 return hook_sp;
4779}
4780
4782 if (!RemoveHookByID(uid))
4783 return;
4784 if (uid > 0)
4786}
4787
4789 size_t num_removed = m_hooks.erase(uid);
4790 return (num_removed != 0);
4791}
4792
4794
4796 auto iter = m_hooks.find(uid);
4797 if (iter == m_hooks.end())
4798 return {};
4799 return iter->second;
4800}
4801
4803 if (index >= m_hooks.size())
4804 return {};
4805 auto iter = m_hooks.begin();
4806 std::advance(iter, index);
4807 return iter->second;
4808}
4809
4811 auto iter = m_hooks.find(uid);
4812 if (iter == m_hooks.end())
4813 return false;
4814 iter->second->SetIsEnabled(enabled);
4815 return true;
4816}
4817
4819 for (auto &[_, hook] : m_hooks)
4820 hook->SetIsEnabled(enabled);
4821}
4822
4824 if (m_hooks.empty())
4825 return;
4826
4828
4829 // Copy active hooks into a local vector before iterating, in case a
4830 // callback modifies m_hooks (same pattern as RunStopHooks).
4831 std::vector<HookSP> active_hooks;
4832 for (auto &[_, hook_sp] : m_hooks) {
4833 if (hook_sp->IsEnabled() && hook_sp->FiresOn(trigger))
4834 active_hooks.push_back(hook_sp);
4835 }
4836
4837 if (active_hooks.empty())
4838 return;
4839
4840 StreamSP output_sp = m_debugger.GetAsyncOutputStream();
4841
4842 for (auto &hook_sp : active_hooks) {
4843 if (is_load)
4844 hook_sp->HandleModuleLoaded(output_sp);
4845 else
4846 hook_sp->HandleModuleUnloaded(output_sp);
4847 }
4848
4849 output_sp->Flush();
4850}
4851
4853 {
4855 "no-dynamic-values",
4856 "Don't calculate the dynamic type of values",
4857 },
4858 {
4860 "run-target",
4861 "Calculate the dynamic type of values "
4862 "even if you have to run the target.",
4863 },
4864 {
4866 "no-run-target",
4867 "Calculate the dynamic type of values, but don't run the target.",
4868 },
4869};
4870
4874
4876 {
4878 "never",
4879 "Never look for inline breakpoint locations (fastest). This setting "
4880 "should only be used if you know that no inlining occurs in your"
4881 "programs.",
4882 },
4883 {
4885 "headers",
4886 "Only check for inline breakpoint locations when setting breakpoints "
4887 "in header files, but not when setting breakpoint in implementation "
4888 "source files (default).",
4889 },
4890 {
4892 "always",
4893 "Always look for inline breakpoint locations when setting file and "
4894 "line breakpoints (slower but most accurate).",
4895 },
4896};
4897
4903
4905 {
4907 "default",
4908 "Disassembler default (currently att).",
4909 },
4910 {
4912 "intel",
4913 "Intel disassembler flavor.",
4914 },
4915 {
4917 "att",
4918 "AT&T disassembler flavor.",
4919 },
4920};
4921
4923 {
4925 "mcjit",
4926 "Use LLVM's MCJIT execution engine.",
4927 },
4928 {
4930 "orc",
4931 "Use LLVM's ORC execution engine.",
4932 },
4933};
4934
4936 {
4938 "false",
4939 "Never import the 'std' C++ module in the expression parser.",
4940 },
4941 {
4943 "fallback",
4944 "Retry evaluating expressions with an imported 'std' C++ module if they"
4945 " failed to parse without the module. This allows evaluating more "
4946 "complex expressions involving C++ standard library types."
4947 },
4948 {
4950 "true",
4951 "Always import the 'std' C++ module. This allows evaluating more "
4952 "complex expressions involving C++ standard library types. This feature"
4953 " is experimental."
4954 },
4955};
4956
4957static constexpr OptionEnumValueElement
4959 {
4961 "auto",
4962 "Automatically determine the most appropriate method for the "
4963 "target OS.",
4964 },
4965 {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct",
4966 "Prefer using the realized classes struct."},
4967 {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList",
4968 "Prefer using the CopyRealizedClassList API."},
4969 {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList",
4970 "Prefer using the GetRealizedClassList API."},
4971};
4972
4974 {
4976 "c",
4977 "C-style (0xffff).",
4978 },
4979 {
4981 "asm",
4982 "Asm-style (0ffffh).",
4983 },
4984};
4985
4987 {
4989 "true",
4990 "Load debug scripts inside symbol files",
4991 },
4992 {
4994 "false",
4995 "Do not load debug scripts inside symbol files.",
4996 },
4997 {
4999 "warn",
5000 "Warn about debug scripts inside symbol files but do not load them.",
5001 },
5002 {
5004 "trusted",
5005 "Load debug scripts inside trusted symbol files, and warn about "
5006 "scripts from untrusted symbol files.",
5007 },
5008};
5009
5011 {
5013 "true",
5014 "Load .lldbinit files from current directory",
5015 },
5016 {
5018 "false",
5019 "Do not load .lldbinit files from current directory",
5020 },
5021 {
5023 "warn",
5024 "Warn about loading .lldbinit files from current directory",
5025 },
5026};
5027
5029 {
5031 "minimal",
5032 "Load minimal information when loading modules from memory. Currently "
5033 "this setting loads sections only.",
5034 },
5035 {
5037 "partial",
5038 "Load partial information when loading modules from memory. Currently "
5039 "this setting loads sections and function bounds.",
5040 },
5041 {
5043 "complete",
5044 "Load complete information when loading modules from memory. Currently "
5045 "this setting loads sections and all symbols.",
5046 },
5047};
5048
5049#define LLDB_PROPERTIES_target
5050#include "TargetProperties.inc"
5051
5052enum {
5053#define LLDB_PROPERTIES_target
5054#include "TargetPropertiesEnum.inc"
5056};
5057
5059 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
5060public:
5061 TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
5062
5063 const Property *
5065 const ExecutionContext *exe_ctx = nullptr) const override {
5066 // When getting the value for a key from the target options, we will always
5067 // try and grab the setting from the current target if there is one. Else
5068 // we just use the one from this instance.
5069 if (exe_ctx) {
5070 Target *target = exe_ctx->GetTargetPtr();
5071 if (target && !target->IsDummyTarget()) {
5072 TargetOptionValueProperties *target_properties =
5073 static_cast<TargetOptionValueProperties *>(
5074 target->GetValueProperties().get());
5075 if (this != target_properties)
5076 return target_properties->ProtectedGetPropertyAtIndex(idx);
5077 }
5078 }
5079 return ProtectedGetPropertyAtIndex(idx);
5080 }
5081};
5082
5083// TargetProperties
5084#define LLDB_PROPERTIES_target_experimental
5085#include "TargetProperties.inc"
5086
5087enum {
5088#define LLDB_PROPERTIES_target_experimental
5089#include "TargetPropertiesEnum.inc"
5090};
5091
5093 : public Cloneable<TargetExperimentalOptionValueProperties,
5094 OptionValueProperties> {
5095public:
5097 : Cloneable(Properties::GetExperimentalSettingsName()) {}
5098};
5099
5105
5106// TargetProperties
5108 : Properties(), m_launch_info(), m_target(target) {
5109 if (target) {
5112
5113 // Set callbacks to update launch_info whenever "settins set" updated any
5114 // of these properties
5115 m_collection_sp->SetValueChangedCallback(
5116 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
5117 m_collection_sp->SetValueChangedCallback(
5118 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
5119 m_collection_sp->SetValueChangedCallback(
5120 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
5121 m_collection_sp->SetValueChangedCallback(
5122 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
5123 m_collection_sp->SetValueChangedCallback(
5124 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
5125 m_collection_sp->SetValueChangedCallback(
5126 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
5127 m_collection_sp->SetValueChangedCallback(
5128 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
5129 m_collection_sp->SetValueChangedCallback(
5130 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
5131 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
5133 });
5134 m_collection_sp->SetValueChangedCallback(
5135 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
5136 m_collection_sp->SetValueChangedCallback(
5137 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
5138 m_collection_sp->SetValueChangedCallback(
5139 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
5140
5141 m_collection_sp->SetValueChangedCallback(
5142 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
5144 std::make_unique<TargetExperimentalProperties>();
5145 m_collection_sp->AppendProperty(
5147 "Experimental settings - setting these won't produce "
5148 "errors if the setting is not present.",
5149 true, m_experimental_properties_up->GetValueProperties());
5150 } else {
5151 m_collection_sp = std::make_shared<TargetOptionValueProperties>("target");
5152 m_collection_sp->Initialize(g_target_properties_def);
5154 std::make_unique<TargetExperimentalProperties>();
5155 m_collection_sp->AppendProperty(
5157 "Experimental settings - setting these won't produce "
5158 "errors if the setting is not present.",
5159 true, m_experimental_properties_up->GetValueProperties());
5160 m_collection_sp->AppendProperty(
5161 "process", "Settings specific to processes.", true,
5163 m_collection_sp->SetValueChangedCallback(
5164 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
5165 }
5166}
5167
5169
5182
5184 size_t prop_idx, ExecutionContext *exe_ctx) const {
5185 const Property *exp_property =
5186 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
5187 OptionValueProperties *exp_values =
5188 exp_property->GetValue()->GetAsProperties();
5189 if (exp_values)
5190 return exp_values->GetPropertyAtIndexAs<bool>(prop_idx, exe_ctx);
5191 return std::nullopt;
5192}
5193
5195 ExecutionContext *exe_ctx) const {
5196 return GetExperimentalPropertyValue(ePropertyInjectLocalVars, exe_ctx)
5197 .value_or(true);
5198}
5199
5201 const Property *exp_property =
5202 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
5203 OptionValueProperties *exp_values =
5204 exp_property->GetValue()->GetAsProperties();
5205 if (exp_values)
5206 return exp_values->GetPropertyAtIndexAs<bool>(ePropertyUseDIL, exe_ctx)
5207 .value_or(false);
5208 else
5209 return true;
5210}
5211
5213 const Property *exp_property =
5214 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
5215 OptionValueProperties *exp_values =
5216 exp_property->GetValue()->GetAsProperties();
5217 if (exp_values)
5218 exp_values->SetPropertyAtIndex(ePropertyUseDIL, true, exe_ctx);
5219}
5220
5222 const uint32_t idx = ePropertyDefaultArch;
5223 return GetPropertyAtIndexAs<ArchSpec>(idx, {});
5224}
5225
5227 const uint32_t idx = ePropertyDefaultArch;
5228 SetPropertyAtIndex(idx, arch);
5229}
5230
5232 const uint32_t idx = ePropertyMoveToNearestCode;
5234 idx, g_target_properties[idx].default_uint_value != 0);
5235}
5236
5238 const uint32_t idx = ePropertyPreferDynamic;
5240 idx, static_cast<lldb::DynamicValueType>(
5241 g_target_properties[idx].default_uint_value));
5242}
5243
5245 const uint32_t idx = ePropertyPreferDynamic;
5246 return SetPropertyAtIndex(idx, d);
5247}
5248
5250 if (INTERRUPT_REQUESTED(m_target->GetDebugger(),
5251 "Interrupted checking preload symbols")) {
5252 return false;
5253 }
5254 const uint32_t idx = ePropertyPreloadSymbols;
5256 idx, g_target_properties[idx].default_uint_value != 0);
5257}
5258
5260 const uint32_t idx = ePropertyPreloadSymbols;
5261 SetPropertyAtIndex(idx, b);
5262}
5263
5265 const uint32_t idx = ePropertyDisableASLR;
5267 idx, g_target_properties[idx].default_uint_value != 0);
5268}
5269
5271 const uint32_t idx = ePropertyDisableASLR;
5272 SetPropertyAtIndex(idx, b);
5273}
5274
5276 const uint32_t idx = ePropertyInheritTCC;
5278 idx, g_target_properties[idx].default_uint_value != 0);
5279}
5280
5282 const uint32_t idx = ePropertyInheritTCC;
5283 SetPropertyAtIndex(idx, b);
5284}
5285
5287 const uint32_t idx = ePropertyDetachOnError;
5289 idx, g_target_properties[idx].default_uint_value != 0);
5290}
5291
5293 const uint32_t idx = ePropertyDetachOnError;
5294 SetPropertyAtIndex(idx, b);
5295}
5296
5298 const uint32_t idx = ePropertyDisableSTDIO;
5300 idx, g_target_properties[idx].default_uint_value != 0);
5301}
5302
5304 const uint32_t idx = ePropertyDisableSTDIO;
5305 SetPropertyAtIndex(idx, b);
5306}
5308 const uint32_t idx = ePropertyLaunchWorkingDir;
5310 idx, g_target_properties[idx].default_cstr_value);
5311}
5312
5314 const uint32_t idx = ePropertyParallelModuleLoad;
5316 idx, g_target_properties[idx].default_uint_value != 0);
5317}
5318
5320 const uint32_t idx = ePropertyDisassemblyFlavor;
5321 const char *return_value;
5322
5323 x86DisassemblyFlavor flavor_value =
5325 idx, static_cast<x86DisassemblyFlavor>(
5326 g_target_properties[idx].default_uint_value));
5327
5328 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
5329 return return_value;
5330}
5331
5333 const uint32_t idx = ePropertyDisassemblyCPU;
5334 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
5335 idx, g_target_properties[idx].default_cstr_value);
5336 return str.empty() ? nullptr : str.data();
5337}
5338
5340 const uint32_t idx = ePropertyDisassemblyFeatures;
5341 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
5342 idx, g_target_properties[idx].default_cstr_value);
5343 return str.empty() ? nullptr : str.data();
5344}
5345
5347 const uint32_t idx = ePropertyInlineStrategy;
5349 idx,
5350 static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value));
5351}
5352
5353// Returning RealpathPrefixes, but the setting's type is FileSpecList. We do
5354// this because we want the FileSpecList to normalize the file paths for us.
5356 const uint32_t idx = ePropertySourceRealpathPrefixes;
5358}
5359
5360llvm::StringRef TargetProperties::GetArg0() const {
5361 const uint32_t idx = ePropertyArg0;
5363 idx, g_target_properties[idx].default_cstr_value);
5364}
5365
5366void TargetProperties::SetArg0(llvm::StringRef arg) {
5367 const uint32_t idx = ePropertyArg0;
5368 SetPropertyAtIndex(idx, arg);
5369 m_launch_info.SetArg0(arg);
5370}
5371
5373 const uint32_t idx = ePropertyRunArgs;
5374 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
5375}
5376
5378 const uint32_t idx = ePropertyRunArgs;
5379 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
5380 m_launch_info.GetArguments() = args;
5381}
5382
5384 Environment env;
5385
5386 if (m_target &&
5388 ePropertyInheritEnv,
5389 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
5390 if (auto platform_sp = m_target->GetPlatform()) {
5391 Environment platform_env = platform_sp->GetEnvironment();
5392 for (const auto &KV : platform_env)
5393 env[KV.first()] = KV.second;
5394 }
5395 }
5396
5397 Args property_unset_env;
5398 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
5399 property_unset_env);
5400 for (const auto &var : property_unset_env)
5401 env.erase(var.ref());
5402
5403 Args property_env;
5404 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env);
5405 for (const auto &KV : Environment(property_env))
5406 env[KV.first()] = KV.second;
5407
5408 return env;
5409}
5410
5414
5416 Environment environment;
5417
5418 if (m_target == nullptr)
5419 return environment;
5420
5422 ePropertyInheritEnv,
5423 g_target_properties[ePropertyInheritEnv].default_uint_value != 0))
5424 return environment;
5425
5426 PlatformSP platform_sp = m_target->GetPlatform();
5427 if (platform_sp == nullptr)
5428 return environment;
5429
5430 Environment platform_environment = platform_sp->GetEnvironment();
5431 for (const auto &KV : platform_environment)
5432 environment[KV.first()] = KV.second;
5433
5434 Args property_unset_environment;
5435 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
5436 property_unset_environment);
5437 for (const auto &var : property_unset_environment)
5438 environment.erase(var.ref());
5439
5440 return environment;
5441}
5442
5444 Args property_environment;
5445 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars,
5446 property_environment);
5447 Environment environment;
5448 for (const auto &KV : Environment(property_environment))
5449 environment[KV.first()] = KV.second;
5450
5451 return environment;
5452}
5453
5455 // TODO: Get rid of the Args intermediate step
5456 const uint32_t idx = ePropertyEnvVars;
5457 m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env));
5458}
5459
5461 const uint32_t idx = ePropertySkipPrologue;
5463 idx, g_target_properties[idx].default_uint_value != 0);
5464}
5465
5467 const uint32_t idx = ePropertySourceMap;
5468 OptionValuePathMappings *option_value =
5469 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
5470 assert(option_value);
5471 return option_value->GetCurrentValue();
5472}
5473
5475 const uint32_t idx = ePropertyObjectMap;
5476 OptionValuePathMappings *option_value =
5477 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
5478 assert(option_value);
5479 return option_value->GetCurrentValue();
5480}
5481
5483 const uint32_t idx = ePropertyAutoSourceMapRelative;
5485 idx, g_target_properties[idx].default_uint_value != 0);
5486}
5487
5489 const uint32_t idx = ePropertyExecutableSearchPaths;
5490 OptionValueFileSpecList *option_value =
5491 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
5492 assert(option_value);
5493 option_value->AppendCurrentValue(dir);
5494}
5495
5497 const uint32_t idx = ePropertyExecutableSearchPaths;
5498 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
5499}
5500
5502 const uint32_t idx = ePropertyDebugFileSearchPaths;
5503 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
5504}
5505
5507 const uint32_t idx = ePropertyClangModuleSearchPaths;
5508 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
5509}
5510
5512 const uint32_t idx = ePropertyAutoImportClangModules;
5514 idx, g_target_properties[idx].default_uint_value != 0);
5515}
5516
5518 const uint32_t idx = ePropertyImportStdModule;
5520 idx, static_cast<ImportStdModule>(
5521 g_target_properties[idx].default_uint_value));
5522}
5523
5525 const uint32_t idx = ePropertyDynamicClassInfoHelper;
5527 idx, static_cast<DynamicClassInfoHelper>(
5528 g_target_properties[idx].default_uint_value));
5529}
5530
5532 const uint32_t idx = ePropertyAutoApplyFixIts;
5534 idx, g_target_properties[idx].default_uint_value != 0);
5535}
5536
5538 const uint32_t idx = ePropertyRetriesWithFixIts;
5540 idx, g_target_properties[idx].default_uint_value);
5541}
5542
5544 const uint32_t idx = ePropertyNotifyAboutFixIts;
5546 idx, g_target_properties[idx].default_uint_value != 0);
5547}
5548
5550 const uint32_t idx = ePropertySaveObjectsDir;
5551 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5552}
5553
5555 const uint32_t idx = ePropertyJITEngine;
5557 idx, static_cast<JITEngine>(g_target_properties[idx].default_uint_value));
5558}
5559
5561 FileSpec new_dir = GetSaveJITObjectsDir();
5562 if (!new_dir)
5563 return;
5564
5565 const FileSystem &instance = FileSystem::Instance();
5566 bool exists = instance.Exists(new_dir);
5567 bool is_directory = instance.IsDirectory(new_dir);
5568 std::string path = new_dir.GetPath(true);
5569 bool writable = llvm::sys::fs::can_write(path);
5570 if (exists && is_directory && writable)
5571 return;
5572
5573 m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir)
5574 ->GetValue()
5575 ->Clear();
5576
5577 std::string buffer;
5578 llvm::raw_string_ostream os(buffer);
5579 os << "JIT object dir '" << path << "' ";
5580 if (!exists)
5581 os << "does not exist";
5582 else if (!is_directory)
5583 os << "is not a directory";
5584 else if (!writable)
5585 os << "is not writable";
5586
5587 std::optional<lldb::user_id_t> debugger_id;
5588 if (m_target)
5589 debugger_id = m_target->GetDebugger().GetID();
5590 Debugger::ReportError(buffer, debugger_id);
5591}
5592
5594 const uint32_t idx = ePropertyEnableSynthetic;
5596 idx, g_target_properties[idx].default_uint_value != 0);
5597}
5598
5600 const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes;
5602 idx, g_target_properties[idx].default_uint_value != 0);
5603}
5604
5606 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
5608 idx, g_target_properties[idx].default_uint_value);
5609}
5610
5612 const uint32_t idx = ePropertyMaxChildrenCount;
5614 idx, g_target_properties[idx].default_uint_value);
5615}
5616
5617std::pair<uint32_t, bool>
5619 const uint32_t idx = ePropertyMaxChildrenDepth;
5620 auto *option_value =
5621 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx);
5622 bool is_default = !option_value->OptionWasSet();
5623 return {option_value->GetCurrentValue(), is_default};
5624}
5625
5627 const uint32_t idx = ePropertyMaxSummaryLength;
5629 idx, g_target_properties[idx].default_uint_value);
5630}
5631
5633 const uint32_t idx = ePropertyMaxMemReadSize;
5635 idx, g_target_properties[idx].default_uint_value);
5636}
5637
5639 const uint32_t idx = ePropertyInputPath;
5640 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5641}
5642
5643void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
5644 const uint32_t idx = ePropertyInputPath;
5645 SetPropertyAtIndex(idx, path);
5646}
5647
5649 const uint32_t idx = ePropertyOutputPath;
5650 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5651}
5652
5654 const uint32_t idx = ePropertyOutputPath;
5655 SetPropertyAtIndex(idx, path);
5656}
5657
5659 const uint32_t idx = ePropertyErrorPath;
5660 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5661}
5662
5663void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
5664 const uint32_t idx = ePropertyErrorPath;
5665 SetPropertyAtIndex(idx, path);
5666}
5667
5669 const uint32_t idx = ePropertyLanguage;
5671}
5672
5674 const uint32_t idx = ePropertyExprPrefix;
5675 OptionValueFileSpec *file =
5676 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx);
5677 if (file) {
5678 DataBufferSP data_sp(file->GetFileContents());
5679 if (data_sp)
5680 return llvm::StringRef(
5681 reinterpret_cast<const char *>(data_sp->GetBytes()),
5682 data_sp->GetByteSize());
5683 }
5684 return "";
5685}
5686
5688 const uint32_t idx = ePropertyExprErrorLimit;
5690 idx, g_target_properties[idx].default_uint_value);
5691}
5692
5694 const uint32_t idx = ePropertyExprAllocAddress;
5696 idx, g_target_properties[idx].default_uint_value);
5697}
5698
5700 const uint32_t idx = ePropertyExprAllocSize;
5702 idx, g_target_properties[idx].default_uint_value);
5703}
5704
5706 const uint32_t idx = ePropertyExprAllocAlign;
5708 idx, g_target_properties[idx].default_uint_value);
5709}
5710
5712 const uint32_t idx = ePropertyBreakpointUseAvoidList;
5714 idx, g_target_properties[idx].default_uint_value != 0);
5715}
5716
5718 const uint32_t idx = ePropertyUseHexImmediates;
5720 idx, g_target_properties[idx].default_uint_value != 0);
5721}
5722
5724 const uint32_t idx = ePropertyUseFastStepping;
5726 idx, g_target_properties[idx].default_uint_value != 0);
5727}
5728
5730 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
5732 idx, g_target_properties[idx].default_uint_value != 0);
5733}
5734
5736 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
5738 idx, static_cast<LoadScriptFromSymFile>(
5739 g_target_properties[idx].default_uint_value));
5740}
5741
5743 LoadScriptFromSymFile load_style) {
5744 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
5745 SetPropertyAtIndex(idx, load_style);
5746}
5747
5749 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
5751 idx, static_cast<LoadCWDlldbinitFile>(
5752 g_target_properties[idx].default_uint_value));
5753}
5754
5756 const uint32_t idx = ePropertyHexImmediateStyle;
5758 idx, static_cast<Disassembler::HexImmediateStyle>(
5759 g_target_properties[idx].default_uint_value));
5760}
5761
5763 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
5765 idx, static_cast<MemoryModuleLoadLevel>(
5766 g_target_properties[idx].default_uint_value));
5767}
5768
5770 const uint32_t idx = ePropertyTrapHandlerNames;
5771 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
5772}
5773
5775 const uint32_t idx = ePropertyTrapHandlerNames;
5776 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
5777}
5778
5780 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
5782 idx, g_target_properties[idx].default_uint_value != 0);
5783}
5784
5786 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
5787 SetPropertyAtIndex(idx, b);
5788}
5789
5791 const uint32_t idx = ePropertyDisplayRecognizedArguments;
5793 idx, g_target_properties[idx].default_uint_value != 0);
5794}
5795
5797 const uint32_t idx = ePropertyDisplayRecognizedArguments;
5798 SetPropertyAtIndex(idx, b);
5799}
5800
5804
5806 const ProcessLaunchInfo &launch_info) {
5807 m_launch_info = launch_info;
5808 SetArg0(launch_info.GetArg0());
5809 SetRunArguments(launch_info.GetArguments());
5810 SetEnvironment(launch_info.GetEnvironment());
5811 const FileAction *input_file_action =
5812 launch_info.GetFileActionForFD(STDIN_FILENO);
5813 if (input_file_action) {
5814 SetStandardInputPath(input_file_action->GetFileSpec().GetPath());
5815 }
5816 const FileAction *output_file_action =
5817 launch_info.GetFileActionForFD(STDOUT_FILENO);
5818 if (output_file_action) {
5819 SetStandardOutputPath(output_file_action->GetFileSpec().GetPath());
5820 }
5821 const FileAction *error_file_action =
5822 launch_info.GetFileActionForFD(STDERR_FILENO);
5823 if (error_file_action) {
5824 SetStandardErrorPath(error_file_action->GetFileSpec().GetPath());
5825 }
5826 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
5827 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
5829 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
5830 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
5831}
5832
5834 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5836 idx, g_target_properties[idx].default_uint_value != 0);
5837}
5838
5840 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5841 m_collection_sp->SetPropertyAtIndex(idx, b);
5842}
5843
5845 const uint32_t idx = ePropertyAutoInstallMainExecutable;
5847 idx, g_target_properties[idx].default_uint_value != 0);
5848}
5849
5853
5855 Args args;
5856 if (GetRunArguments(args))
5857 m_launch_info.GetArguments() = args;
5858}
5859
5863
5865 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
5866 false);
5867}
5868
5870 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
5871 false, true);
5872}
5873
5875 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
5876 false, true);
5877}
5878
5880 if (GetDetachOnError())
5881 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
5882 else
5883 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
5884}
5885
5887 if (GetDisableASLR())
5888 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
5889 else
5890 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
5891}
5892
5894 if (GetInheritTCC())
5895 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
5896 else
5897 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
5898}
5899
5901 if (GetDisableSTDIO())
5902 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
5903 else
5904 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
5905}
5906
5908 const uint32_t idx = ePropertyDebugUtilityExpression;
5910 idx, g_target_properties[idx].default_uint_value != 0);
5911}
5912
5914 const uint32_t idx = ePropertyDebugUtilityExpression;
5915 SetPropertyAtIndex(idx, debug);
5916}
5917
5919 const uint32_t idx = ePropertyCheckValueObjectOwnership;
5921 idx, g_target_properties[idx].default_uint_value != 0);
5922}
5923
5925 const uint32_t idx = ePropertyCheckValueObjectOwnership;
5926 SetPropertyAtIndex(idx, check);
5927}
5928
5929std::optional<LoadScriptFromSymFile>
5931 llvm::StringRef module_name) const {
5932 auto *dict = m_collection_sp->GetPropertyAtIndexAsOptionValueDictionary(
5933 ePropertyAutoLoadScriptsForModules);
5934 if (!dict)
5935 return std::nullopt;
5936
5937 OptionValueSP value_sp = dict->GetValueForKey(module_name);
5938 if (!value_sp)
5939 return std::nullopt;
5940
5941 return value_sp->GetValueAs<LoadScriptFromSymFile>();
5942}
5943
5945 llvm::StringRef module_name, LoadScriptFromSymFile load_style) {
5946 auto *dict = m_collection_sp->GetPropertyAtIndexAsOptionValueDictionary(
5947 ePropertyAutoLoadScriptsForModules);
5948 if (!dict)
5949 return;
5950
5951 dict->SetValueForKey(module_name,
5952 std::make_shared<OptionValueEnumeration>(
5954}
5955
5956// Target::TargetEventData
5957
5960
5962 const ModuleList &module_list)
5963 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
5964
5966 const lldb::TargetSP &target_sp, const lldb::TargetSP &created_target_sp)
5967 : EventData(), m_target_sp(target_sp),
5968 m_created_target_sp(created_target_sp), m_module_list() {}
5969
5971
5973 return "Target::TargetEventData";
5974}
5975
5977 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
5978 if (i != 0)
5979 *s << ", ";
5980 m_module_list.GetModuleAtIndex(i)->GetDescription(
5982 }
5983}
5984
5987 if (event_ptr) {
5988 const EventData *event_data = event_ptr->GetData();
5989 if (event_data &&
5991 return static_cast<const TargetEventData *>(event_ptr->GetData());
5992 }
5993 return nullptr;
5994}
5995
5997 TargetSP target_sp;
5998 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
5999 if (event_data)
6000 target_sp = event_data->m_target_sp;
6001 return target_sp;
6002}
6003
6006 TargetSP created_target_sp;
6007 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
6008 if (event_data)
6009 created_target_sp = event_data->m_created_target_sp;
6010 return created_target_sp;
6011}
6012
6015 ModuleList module_list;
6016 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
6017 if (event_data)
6018 module_list = event_data->m_module_list;
6019 return module_list;
6020}
6021
6023 return TargetAPIMutex(shared_from_this());
6024}
6025
6026/// Get metrics associated with this target in JSON format.
6027llvm::json::Value
6029 return m_stats.ToJSON(*this, options);
6030}
6031
6032void Target::ResetStatistics() { m_stats.Reset(*this); }
6033
6035
6039
6041
6045
6047 lldb::BreakpointEventType eventKind) {
6049 std::shared_ptr<Breakpoint::BreakpointEventData> data_sp =
6050 std::make_shared<Breakpoint::BreakpointEventData>(
6051 eventKind, bp.shared_from_this());
6053 }
6054}
6055
6061
6064
6065 // Add platform-specific safe-paths.
6066 if (m_platform_sp) {
6067 if (auto platform_fspecs_or_err =
6068 m_platform_sp->GetSafeAutoLoadPaths(*this))
6069 fspecs.Append(*platform_fspecs_or_err);
6070 else
6072 platform_fspecs_or_err.takeError(),
6073 "Skipping safe auto-load: {0}");
6074 }
6075
6076 // Properties for testing get added last so they take priority.
6077#ifndef NDEBUG
6078 for (const auto &fspec :
6080 fspecs.Append(fspec);
6081#endif
6082
6083 return fspecs;
6084}
6085
6086// FIXME: the language plugin should expression options dynamically and
6087// we should validate here (by asking the language plugin) that the options
6088// being set/retrieved are actually valid options.
6089
6090llvm::Error
6092 bool value) {
6093 if (option_name.empty())
6094 return llvm::createStringError("can't set an option with an empty name");
6095
6096 if (StructuredData::ObjectSP existing_sp =
6097 GetLanguageOptions().GetValueForKey(option_name);
6098 existing_sp && existing_sp->GetType() != eStructuredDataTypeBoolean)
6099 return llvm::createStringErrorV("trying to override existing option '{0}' "
6100 "of type '{1}' with a boolean value",
6101 option_name, existing_sp->GetType());
6102
6103 GetLanguageOptions().AddBooleanItem(option_name, value);
6104
6105 return llvm::Error::success();
6106}
6107
6109 llvm::StringRef option_name) const {
6111
6112 if (!opts.HasKey(option_name))
6113 return llvm::createStringErrorV("option '{0}' does not exist", option_name);
6114
6115 bool result;
6116 if (!opts.GetValueForKeyAsBoolean(option_name, result))
6117 return llvm::createStringErrorV("failed to get option '{0}' as boolean",
6118 option_name);
6119
6120 return result;
6121}
6122
6129
6135
6136// FIXME: this option is C++ plugin specific and should be registered by it,
6137// instead of hard-coding it here.
6138constexpr llvm::StringLiteral s_cpp_ignore_context_qualifiers_option =
6139 "c++-ignore-context-qualifiers";
6140
6145
6150
static void dump(const StructuredData::Array &array, Stream &s)
static llvm::raw_ostream & error(Stream &strm)
#define INTERRUPT_REQUESTED(debugger,...)
This handy define will keep you from having to generate a report for the interruption by hand.
Definition Debugger.h:502
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
@ ePropertyExperimental
Definition Process.cpp:143
static void skip(TSLexer *lexer)
static double elapsed(const StatsTimepoint &start, const StatsTimepoint &end)
static Status installExecutable(const Installer &installer)
Definition Target.cpp:151
constexpr llvm::StringLiteral s_cpp_ignore_context_qualifiers_option
Definition Target.cpp:6138
static constexpr OptionEnumValueElement g_dynamic_class_info_helper_value_types[]
Definition Target.cpp:4958
static bool CheckIfWatchpointsSupported(Target *target, Status &error)
Definition Target.cpp:1033
static constexpr OptionEnumValueElement g_jit_engine_value_types[]
Definition Target.cpp:4922
static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[]
Definition Target.cpp:5010
x86DisassemblyFlavor
Definition Target.cpp:4898
@ eX86DisFlavorDefault
Definition Target.cpp:4899
@ eX86DisFlavorIntel
Definition Target.cpp:4900
@ eX86DisFlavorATT
Definition Target.cpp:4901
static constexpr OptionEnumValueElement g_dynamic_value_types[]
Definition Target.cpp:4852
static constexpr OptionEnumValueElement g_memory_module_load_level_values[]
Definition Target.cpp:5028
static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[]
Definition Target.cpp:4986
static std::atomic< lldb::user_id_t > g_target_unique_id
Definition Target.cpp:148
static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[]
Definition Target.cpp:4904
static constexpr OptionEnumValueElement g_hex_immediate_style_values[]
Definition Target.cpp:4973
static constexpr OptionEnumValueElement g_inline_breakpoint_enums[]
Definition Target.cpp:4875
static constexpr OptionEnumValueElement g_import_std_module_value_types[]
Definition Target.cpp:4935
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:86
const Property * GetPropertyAtIndex(size_t idx, const ExecutionContext *exe_ctx=nullptr) const override
Definition Target.cpp:5064
TargetOptionValueProperties(llvm::StringRef name)
Definition Target.cpp:5061
static lldb::ABISP FindPlugin(lldb::ProcessSP process_sp, const ArchSpec &arch)
Definition ABI.cpp:27
A section + offset based address class.
Definition Address.h:62
lldb::addr_t GetLoadAddress(Target *target) const
Get the load address.
Definition Address.cpp:301
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition Address.cpp:1028
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition Address.h:426
bool Slide(int64_t offset)
Definition Address.h:446
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition Address.cpp:273
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:281
lldb::addr_t GetOffset() const
Get the section relative offset value.
Definition Address.h:329
bool IsValid() const
Check if the object state is valid.
Definition Address.h:355
bool IsSectionOffset() const
Check if an address is section offset.
Definition Address.h:342
bool SetOffset(lldb::addr_t offset)
Set accessor for the offset.
Definition Address.h:435
An architecture specification class.
Definition ArchSpec.h:32
bool IsValid() const
Tests if this ArchSpec is valid.
Definition ArchSpec.h:452
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:544
void MergeFrom(const ArchSpec &other)
Merges fields from another ArchSpec into this ArchSpec.
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:740
A command line argument class.
Definition Args.h:33
size_t GetArgumentCount() const
Gets the number of arguments left in this command object.
Definition Args.h:120
const char * GetArgumentAtIndex(size_t idx) const
Gets the NULL terminated C string argument pointer for the argument at index idx.
Definition Args.cpp:273
bool AddBreakpointID(BreakpointID bp_id)
BreakpointID GetBreakpointIDAtIndex(size_t index) const
lldb::break_id_t GetBreakpointID() const
static bool StringIsBreakpointName(llvm::StringRef str, Status &error)
Takes an input string and checks to see whether it is a breakpoint name.
General Outline: Allows adding and removing breakpoints and find by ID and index.
BreakpointIterable Breakpoints()
void GetListMutex(std::unique_lock< std::recursive_mutex > &lock)
Sets the passed in Locker to hold the Breakpoint List mutex.
void ResetHitCounts()
Resets the hit count of all breakpoints.
size_t GetSize() const
Returns the number of elements in this breakpoint list.
lldb::BreakpointSP GetBreakpointAtIndex(size_t i) const
Returns a shared pointer to the breakpoint with index i.
void MergeInto(const Permissions &incoming)
llvm::StringRef GetName() const
BreakpointOptions & GetOptions()
void ConfigureBreakpoint(lldb::BreakpointSP bp_sp)
"lldb/Breakpoint/BreakpointOptions.h" Class that manages the options on a breakpoint or breakpoint lo...
void CopyOverSetOptions(const BreakpointOptions &rhs)
Copy over only the options set in the incoming BreakpointOptions.
"lldb/Breakpoint/BreakpointResolverFileLine.h" This class sets breakpoints by file and line.
"lldb/Breakpoint/BreakpointResolverFileRegex.h" This class sets breakpoints by file and line.
"lldb/Breakpoint/BreakpointResolverName.h" This class sets breakpoints on a given function name,...
"lldb/Breakpoint/BreakpointResolverScripted.h" This class sets breakpoints on a given Address.
static bool TypeMaskIsValid(uint64_t mask)
static std::string DescribeMask(uint64_t mask)
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition Breakpoint.h:83
virtual StructuredData::ObjectSP SerializeToStructuredData()
static lldb::BreakpointSP CreateFromStructuredData(lldb::TargetSP target_sp, StructuredData::ObjectSP &data_object_sp, Status &error)
static lldb::BreakpointSP CopyFromBreakpoint(lldb::TargetSP new_target, const Breakpoint &bp_to_copy_from)
static const char * GetSerializationKey()
Definition Breakpoint.h:162
static bool SerializedBreakpointMatchesNames(StructuredData::ObjectSP &bkpt_object_sp, std::vector< std::string > &names)
bool EventTypeHasListeners(uint32_t event_type)
Broadcaster(lldb::BroadcasterManagerSP manager_sp, std::string name)
Construct with a broadcaster with a name.
void SetEventName(uint32_t event_mask, const char *name)
Set the name for an event bit.
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
A class that implements CRTP-based "virtual constructor" idiom.
Definition Cloneable.h:40
void HandleCommands(const StringList &commands, const ExecutionContext &context, const CommandInterpreterRunOptions &options, CommandReturnObject &result)
Execute a list of commands in sequence.
void SetImmediateErrorStream(const lldb::StreamSP &stream_sp)
void SetImmediateOutputStream(const lldb::StreamSP &stream_sp)
Generic representation of a type in a programming language.
A uniqued constant string class.
Definition ConstString.h:40
A subclass of DataBuffer that stores a data buffer on the heap.
lldb::offset_t GetByteSize() const override
Get the number of bytes in the data buffer.
An data extractor class.
uint32_t GetMaxU32(lldb::offset_t *offset_ptr, size_t byte_size) const
Extract an integer of size byte_size from *offset_ptr.
uint64_t GetMaxU64(lldb::offset_t *offset_ptr, size_t byte_size) const
Extract an unsigned integer of size byte_size from *offset_ptr.
static const FileSpecList & GetDefaultSafeAutoLoadPaths()
Definition Debugger.cpp:237
void SetAsyncExecution(bool async)
CommandInterpreter & GetCommandInterpreter()
Definition Debugger.h:182
lldb::StreamUP GetAsyncErrorStream()
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:220
static void ReportWarning(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *>
Report warning events.
static llvm::ThreadPoolInterface & GetThreadPool()
Shared thread pool. Use only with ThreadPoolTaskGroup.
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *>
Report error events.
PlatformList & GetPlatformList()
Definition Debugger.h:222
lldb::ListenerSP GetListener()
Definition Debugger.h:191
llvm::Error GetAsError(lldb::ExpressionResults result, llvm::Twine message={}) const
Returns an ExpressionError with arg as error code.
static lldb::DisassemblerSP DisassembleBytes(const ArchSpec &arch, const char *plugin_name, const char *flavor, const char *cpu, const char *features, const Address &start, const void *bytes, size_t length, uint32_t max_num_instructions, bool data_from_file)
A class that measures elapsed time in an exception safe way.
Definition Statistics.h:76
void SetCppIgnoreContextQualifiers(bool value)
Definition Target.cpp:6146
const StructuredData::Dictionary & GetLanguageOptions() const
Definition Target.cpp:6124
llvm::Expected< bool > GetBooleanLanguageOption(llvm::StringRef option_name) const
Get the language-plugin specific boolean option called option_name.
Definition Target.cpp:6108
void SetTryAllThreads(bool try_others=true)
Definition Target.h:435
void SetStopOthers(bool stop_others=true)
Definition Target.h:439
llvm::Error SetBooleanLanguageOption(llvm::StringRef option_name, bool value)
Set language-plugin specific option called option_name to the specified boolean value.
Definition Target.cpp:6091
StructuredData::DictionarySP m_language_options_sp
Dictionary mapping names of language-plugin specific options to values.
Definition Target.h:573
friend class Event
Definition Event.h:36
virtual llvm::StringRef GetFlavor() const =0
EventData * GetData()
Definition Event.h:199
"lldb/Target/ExecutionContextScope.h" Inherit from this if your object can reconstruct its execution ...
virtual void CalculateExecutionContext(ExecutionContext &exe_ctx)=0
Reconstruct the object's execution context into sc.
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
void Clear()
Clear the object's state.
void SetTargetPtr(Target *target)
Set accessor to set only the target shared pointer from a target pointer.
StackFrame * GetFramePtr() const
Returns a pointer to the frame object.
void SetContext(const lldb::TargetSP &target_sp, bool get_process)
Target * GetTargetPtr() const
Returns a pointer to the target object.
Thread & GetThreadRef() const
Returns a reference to the thread object.
Represents a file descriptor action to be performed during process launch.
Definition FileAction.h:21
const FileSpec & GetFileSpec() const
Get the file specification for open actions.
A file collection class.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
Get file at index.
void Append(const FileSpec &file)
Append a FileSpec object to the list.
size_t GetSize() const
Get the number of files in the file list.
bool AppendIfUnique(const FileSpec &file)
Append a FileSpec object if unique.
A file utility class.
Definition FileSpec.h:56
void AppendPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:454
void SetFilename(llvm::StringRef filename)
Filename string set accessor.
Definition FileSpec.cpp:363
void SetPath(llvm::StringRef p)
Temporary helper for FileSystem change.
Definition FileSpec.h:286
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
llvm::StringRef GetDirectory() const
Directory string const get accessor.
Definition FileSpec.h:233
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
void SetDirectory(llvm::StringRef directory)
Directory string set accessor.
Definition FileSpec.cpp:358
bool IsSourceImplementationFile() const
Returns true if the filespec represents an implementation source file (files with a "....
Definition FileSpec.cpp:501
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
bool IsDirectory(const FileSpec &file_spec) const
Returns whether the given path is a directory.
static FileSystem & Instance()
bool IsValid() const override
IsValid.
Definition File.cpp:106
A class to manage flags.
Definition Flags.h:22
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
Encapsulates a function that can be called.
static lldb::BreakpointSP CreateExceptionBreakpoint(Target &target, lldb::LanguageType language, bool catch_bp, bool throw_bp, bool is_internal=false)
static LanguageSet GetLanguagesSupportingREPLs()
Definition Language.cpp:475
static Language * FindPlugin(lldb::LanguageType language)
Definition Language.cpp:84
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:305
static LanguageSet GetLanguagesSupportingTypeSystemsForExpressions()
Definition Language.cpp:471
virtual llvm::StringRef GetUserEntryPointName() const
Definition Language.h:179
static std::set< lldb::LanguageType > GetSupportedLanguages()
Definition Language.cpp:458
static lldb::ListenerSP MakeListener(llvm::StringRef name)
Definition Listener.cpp:373
A collection class for Module objects.
Definition ModuleList.h:125
static Status GetSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr, bool invoke_locate_callback=true, bool invoke_symbol_locators=true)
bool AnyOf(std::function< bool(lldb_private::Module &module)> const &callback) const
Returns true if 'callback' returns true for one of the modules in this ModuleList.
static bool RemoveSharedModuleIfOrphaned(const lldb::ModuleWP module_ptr)
void PreloadSymbols(bool parallelize) const
For each module in this ModuleList, preload its symbols.
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
void FindModules(const ModuleSpec &module_spec, ModuleList &matching_module_list) const
Finds modules whose file specification matches module_spec.
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
bool LoadScriptingResourcesInTarget(Target *target, std::list< Status > &errors, bool continue_on_error=true)
size_t GetSize() const
Gets the size of the module list.
void ForEach(std::function< IterationAction(const lldb::ModuleSP &module_sp)> const &callback) const
Applies 'callback' to each module in this ModuleList.
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
void SetTarget(lldb::TargetSP target)
Set the target to be used when resolving a module.
Definition ModuleSpec.h:150
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:91
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition Module.cpp:1177
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:447
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
virtual uint32_t GetDependentModules(FileSpecList &file_list)=0
Extract the dependent modules from an object file.
virtual lldb_private::Address GetEntryPointAddress()
Returns the address of the Entry Point in this object file - if the object file doesn't have an entry...
Definition ObjectFile.h:452
@ eTypeExecutable
A normal executable.
Definition ObjectFile.h:55
@ eTypeDebugInfo
An object file that contains only debug information.
Definition ObjectFile.h:57
@ eTypeStubLibrary
A library that can be linked against but not used for execution.
Definition ObjectFile.h:65
@ eTypeObjectFile
An intermediate object file.
Definition ObjectFile.h:61
@ eTypeDynamicLinker
The platform's dynamic linker executable.
Definition ObjectFile.h:59
@ eTypeCoreFile
A core file that has a checkpoint of a program's execution state.
Definition ObjectFile.h:53
@ eTypeSharedLibrary
A shared library that can be used during execution.
Definition ObjectFile.h:63
virtual size_t ReadSectionData(Section *section, lldb::offset_t section_offset, void *dst, size_t dst_len)
void AppendCurrentValue(const FileSpec &value)
const lldb::DataBufferSP & GetFileContents()
auto GetPropertyAtIndexAs(size_t idx, const ExecutionContext *exe_ctx=nullptr) const
Property * ProtectedGetPropertyAtIndex(size_t idx)
bool SetPropertyAtIndex(size_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
static lldb::OptionValuePropertiesSP CreateLocalCopy(const Properties &global_properties)
bool RemapPath(ConstString path, ConstString &new_path) const
std::optional< llvm::StringRef > ReverseRemapPath(const FileSpec &file, FileSpec &fixed) const
Perform reverse source path remap for input file.
lldb::PlatformSP GetSelectedPlatform()
Select the active platform.
Definition Platform.h:1202
static std::unique_ptr< Architecture > CreateArchitectureInstance(const ArchSpec &arch)
static lldb::RegisterTypeBuilderSP GetRegisterTypeBuilder(Target &target)
bool ProcessInfoSpecified() const
Definition Process.h:179
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:3213
llvm::StringRef GetProcessPluginName() const
Definition Process.h:162
void SetHijackListener(const lldb::ListenerSP &listener_sp)
void SetExecutableFile(const FileSpec &exe_file, bool add_exe_file_as_first_arg)
lldb::ScriptedMetadataSP GetScriptedMetadata() const
Definition ProcessInfo.h:91
lldb::ListenerSP GetHijackListener() const
llvm::StringRef GetArg0() const
void SetScriptedMetadata(lldb::ScriptedMetadataSP metadata_sp)
Definition ProcessInfo.h:95
FileSpec & GetExecutableFile()
Definition ProcessInfo.h:41
lldb::ListenerSP GetListener() const
lldb::ListenerSP GetShadowListener() const
Environment & GetEnvironment()
Definition ProcessInfo.h:86
ArchSpec & GetArchitecture()
Definition ProcessInfo.h:60
llvm::StringRef GetProcessPluginName() const
const FileSpec & GetShell() const
bool AppendOpenFileAction(int fd, const FileSpec &file_spec, bool read, bool write)
bool AppendSuppressFileAction(int fd, bool read, bool write)
const FileAction * GetFileActionForFD(int fd) const
void SetProcessPluginName(llvm::StringRef plugin)
static void SettingsInitialize()
Definition Process.cpp:5035
static constexpr llvm::StringRef AttachSynchronousHijackListenerName
Definition Process.h:405
static lldb::ProcessSP FindPlugin(lldb::TargetSP target_sp, llvm::StringRef plugin_name, lldb::ListenerSP listener_sp, const FileSpec *crash_file_path, bool can_connect)
Find a Process plug-in that can debug module using the currently selected architecture.
Definition Process.cpp:410
static constexpr llvm::StringRef LaunchSynchronousHijackListenerName
Definition Process.h:407
static ProcessProperties & GetGlobalProperties()
Definition Process.cpp:556
static void SettingsTerminate()
Definition Process.cpp:5037
A Progress indicator helper class.
Definition Progress.h:60
lldb::OptionValuePropertiesSP m_collection_sp
T GetPropertyAtIndexAs(uint32_t idx, T default_value, const ExecutionContext *exe_ctx=nullptr) const
static llvm::StringRef GetExperimentalSettingsName()
bool SetPropertyAtIndex(uint32_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
lldb::OptionValuePropertiesSP GetValueProperties() const
const lldb::OptionValueSP & GetValue() const
Definition Property.h:50
static lldb::REPLSP Create(Status &Status, lldb::LanguageType language, Debugger *debugger, Target *target, const char *repl_options)
Get a REPL with an existing target (or, failing that, a debugger to use), and (optional) extra argume...
Definition REPL.cpp:38
bool SignExtend(uint32_t bit_pos)
Definition Scalar.cpp:762
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition Scalar.cpp:365
long long SLongLong(long long fail_value=0) const
Definition Scalar.cpp:361
virtual lldb::ScriptedHookInterfaceSP CreateScriptedHookInterface()
size_t GetNumSections(uint32_t depth) const
Definition Section.cpp:544
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:555
void Dump(Stream &s, Target *target)
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, bool allow_section_end=false) const
lldb::addr_t GetSectionLoadAddress(const lldb::SectionSP &section_sp) const
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
Class that provides a registry of known stack frame recognizers.
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
An error handling class.
Definition Status.h:118
void Clear()
Clear the object state.
Definition Status.cpp:214
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition Status.cpp:106
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition Status.cpp:136
bool Success() const
Test for success condition.
Definition Status.cpp:303
const char * GetData() const
llvm::StringRef GetString() const
A stream class that can stream formatted output to a file.
Definition Stream.h:28
void Format(const char *format, Args &&... args)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:370
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:405
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:131
IndentScope MakeIndentScope(unsigned indent_amount=2)
Create an indentation scope that restores the original indent level when the object goes out of scope...
Definition Stream.cpp:213
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:204
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:201
void SetObjectSP(const StructuredData::ObjectSP &obj)
void AddItem(const ObjectSP &item)
ObjectSP GetItemAtIndex(size_t idx) const
bool GetValueForKeyAsBoolean(llvm::StringRef key, bool &result) const
ObjectSP GetValueForKey(llvm::StringRef key) const
bool HasKey(llvm::StringRef key) const
void Dump(lldb_private::Stream &s, bool pretty_print=true) const
A class which can hold structured data.
std::shared_ptr< Dictionary > DictionarySP
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
static ObjectSP ParseJSONFromFile(const FileSpec &file, Status &error)
A class that wraps a std::map of SummaryStatistics objects behind a mutex.
Definition Statistics.h:281
bool SymbolContextMatches(const SymbolContext &sc)
Defines a symbol context baton that can be handed other debug core functions.
lldb::TargetSP target_sp
The Target for a given query.
lldb::TargetSP GetTargetAtIndex(uint32_t index) const
size_t GetNumTargets() const
uint32_t GetMaximumSizeOfStringSummary() const
Definition Target.cpp:5626
FileSpecList GetDebugFileSearchPaths()
Definition Target.cpp:5501
llvm::StringRef GetLaunchWorkingDirectory() const
Definition Target.cpp:5307
bool GetDisplayRecognizedArguments() const
Definition Target.cpp:5790
ImportStdModule GetImportStdModule() const
Definition Target.cpp:5517
void AppendExecutableSearchPaths(const FileSpec &)
Definition Target.cpp:5488
bool GetEnableSyntheticValue() const
Definition Target.cpp:5593
ProcessLaunchInfo m_launch_info
Definition Target.h:333
bool GetCheckValueObjectOwnership() const
Definition Target.cpp:5918
uint64_t GetExprAllocAlign() const
Definition Target.cpp:5705
MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const
Definition Target.cpp:5762
llvm::StringRef GetArg0() const
Definition Target.cpp:5360
uint32_t GetMaximumMemReadSize() const
Definition Target.cpp:5632
void SetRunArguments(const Args &args)
Definition Target.cpp:5377
FileSpec GetStandardErrorPath() const
Definition Target.cpp:5658
void SetLoadScriptFromSymbolFile(LoadScriptFromSymFile load_style)
Set the target-wide target.load-script-from-symbol-file setting.
Definition Target.cpp:5742
bool GetEnableNotifyAboutFixIts() const
Definition Target.cpp:5543
bool SetPreferDynamicValue(lldb::DynamicValueType d)
Definition Target.cpp:5244
void SetDisplayRecognizedArguments(bool b)
Definition Target.cpp:5796
std::optional< bool > GetExperimentalPropertyValue(size_t prop_idx, ExecutionContext *exe_ctx=nullptr) const
Definition Target.cpp:5183
const ProcessLaunchInfo & GetProcessLaunchInfo() const
Definition Target.cpp:5801
Environment ComputeEnvironment() const
Definition Target.cpp:5383
bool GetUserSpecifiedTrapHandlerNames(Args &args) const
Definition Target.cpp:5769
uint64_t GetExprErrorLimit() const
Definition Target.cpp:5687
bool GetEnableAutoImportClangModules() const
Definition Target.cpp:5511
bool GetDebugUtilityExpression() const
Definition Target.cpp:5907
JITEngine GetJITEngine() const
Definition Target.cpp:5554
DynamicClassInfoHelper GetDynamicClassInfoHelper() const
Definition Target.cpp:5524
FileSpec GetStandardOutputPath() const
Definition Target.cpp:5648
void SetDisplayRuntimeSupportValues(bool b)
Definition Target.cpp:5785
uint32_t GetMaximumNumberOfChildrenToDisplay() const
Definition Target.cpp:5611
void SetRequireHardwareBreakpoints(bool b)
Definition Target.cpp:5839
bool GetAutoInstallMainExecutable() const
Definition Target.cpp:5844
const char * GetDisassemblyFeatures() const
Definition Target.cpp:5339
void SetAutoLoadScriptsForModule(llvm::StringRef module_name, LoadScriptFromSymFile load_style)
Set the LoadScriptFromSymFile for a module called module_name (excluding file extension).
Definition Target.cpp:5944
RealpathPrefixes GetSourceRealpathPrefixes() const
Definition Target.cpp:5355
void SetCheckValueObjectOwnership(bool check)
Definition Target.cpp:5924
uint64_t GetNumberOfRetriesWithFixits() const
Definition Target.cpp:5537
uint64_t GetExprAllocSize() const
Definition Target.cpp:5699
std::optional< LoadScriptFromSymFile > GetAutoLoadScriptsForModule(llvm::StringRef module_name) const
Definition Target.cpp:5930
llvm::StringRef GetExpressionPrefixContents()
Definition Target.cpp:5673
PathMappingList & GetObjectPathMap() const
Definition Target.cpp:5474
const char * GetDisassemblyFlavor() const
Definition Target.cpp:5319
FileSpec GetStandardInputPath() const
Definition Target.cpp:5638
lldb::DynamicValueType GetPreferDynamicValue() const
Definition Target.cpp:5237
InlineStrategy GetInlineStrategy() const
Definition Target.cpp:5346
Environment GetTargetEnvironment() const
Definition Target.cpp:5443
bool GetDisplayRuntimeSupportValues() const
Definition Target.cpp:5779
void SetUserSpecifiedTrapHandlerNames(const Args &args)
Definition Target.cpp:5774
uint32_t GetMaxZeroPaddingInFloatFormat() const
Definition Target.cpp:5605
uint64_t GetExprAllocAddress() const
Definition Target.cpp:5693
LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const
Definition Target.cpp:5748
Environment GetInheritedEnvironment() const
Definition Target.cpp:5415
void SetArg0(llvm::StringRef arg)
Definition Target.cpp:5366
bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const
Definition Target.cpp:5194
bool ShowHexVariableValuesWithLeadingZeroes() const
Definition Target.cpp:5599
SourceLanguage GetLanguage() const
Definition Target.cpp:5668
Environment GetEnvironment() const
Definition Target.cpp:5411
void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
Definition Target.cpp:5805
FileSpec GetSaveJITObjectsDir() const
Definition Target.cpp:5549
void SetEnvironment(Environment env)
Definition Target.cpp:5454
LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const
Definition Target.cpp:5735
const char * GetDisassemblyCPU() const
Definition Target.cpp:5332
void SetStandardErrorPath(llvm::StringRef path)
Definition Target.cpp:5663
bool GetRunArguments(Args &args) const
Definition Target.cpp:5372
FileSpecList GetExecutableSearchPaths()
Definition Target.cpp:5496
ArchSpec GetDefaultArchitecture() const
Definition Target.cpp:5221
Disassembler::HexImmediateStyle GetHexImmediateStyle() const
Definition Target.cpp:5755
void SetUseDIL(ExecutionContext *exe_ctx, bool b)
Definition Target.cpp:5212
std::unique_ptr< TargetExperimentalProperties > m_experimental_properties_up
Definition Target.h:334
FileSpecList GetClangModuleSearchPaths()
Definition Target.cpp:5506
void SetStandardOutputPath(llvm::StringRef path)
Definition Target.cpp:5653
bool GetRequireHardwareBreakpoints() const
Definition Target.cpp:5833
PathMappingList & GetSourcePathMap() const
Definition Target.cpp:5466
bool GetAutoSourceMapRelative() const
Definition Target.cpp:5482
bool GetUseDIL(ExecutionContext *exe_ctx) const
Definition Target.cpp:5200
void SetDefaultArchitecture(const ArchSpec &arch)
Definition Target.cpp:5226
void SetStandardInputPath(llvm::StringRef path)
Definition Target.cpp:5643
TargetProperties(Target *target)
Definition Target.cpp:5107
bool GetDisplayExpressionsInCrashlogs() const
Definition Target.cpp:5729
bool GetEnableAutoApplyFixIts() const
Definition Target.cpp:5531
void SetDebugUtilityExpression(bool debug)
Definition Target.cpp:5913
std::pair< uint32_t, bool > GetMaximumDepthOfChildrenToDisplay() const
Get the max depth value, augmented with a bool to indicate whether the depth is the default.
Definition Target.cpp:5618
std::unique_ptr< Architecture > m_plugin_up
Definition Target.h:2079
const Arch & operator=(const ArchSpec &spec)
Definition Target.cpp:168
Arch(const ArchSpec &spec)
Definition Target.cpp:164
void GetDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4529
void SetActionFromString(const std::string &string)
Populate the command list by splitting a single string on newlines.
Definition Target.cpp:4556
void SetActionFromStrings(const std::vector< std::string > &strings)
Populate the command list from a vector of individual command strings.
Definition Target.cpp:4560
void HandleModuleLoaded(lldb::StreamSP output) override
Definition Target.cpp:4566
StringList & GetCommands()
Return the list of commands that this hook runs.
Definition Target.h:1876
StopHook::StopHookResult HandleStop(ExecutionContext &exe_ctx, lldb::StreamSP output) override
Called when the process stops.
Definition Target.cpp:4606
void HandleModuleUnloaded(lldb::StreamSP output) override
Definition Target.cpp:4600
llvm::StringRef GetScriptClassName() const
Definition Target.cpp:4720
Status SetScriptCallback(const ScriptedMetadata &scripted_metadata)
Definition Target.cpp:4641
void HandleModuleLoaded(lldb::StreamSP output) override
Definition Target.cpp:4683
StopHook::StopHookResult HandleStop(ExecutionContext &exe_ctx, lldb::StreamSP output) override
Called when the process stops.
Definition Target.cpp:4702
void GetDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4726
lldb::ScriptedHookInterfaceSP m_interface_sp
Definition Target.h:1914
void HandleModuleUnloaded(lldb::StreamSP output) override
Definition Target.cpp:4692
ThreadSpec * GetThreadSpecifier()
Definition Target.h:1807
lldb::SymbolContextSpecifierSP m_sc_specifier_sp
Definition Target.h:1851
bool ExecutionContextPasses(const ExecutionContext &exe_ctx)
Check if the execution context passes the specifier and thread spec filters.
Definition Target.cpp:4452
Hook(const Hook &rhs)
Definition Target.cpp:4433
void GetFilterDescription(Stream &s, lldb::DescriptionLevel level) const
Print the filter portion of the description (AutoContinue, Specifier, ThreadSpec).
Definition Target.cpp:4501
lldb::TargetSP & GetTarget()
Definition Target.h:1783
SymbolContextSpecifier * GetSCSpecifier()
Definition Target.h:1799
lldb::TargetSP m_target_sp
Definition Target.h:1845
virtual void GetDescription(Stream &s, lldb::DescriptionLevel level) const
Definition Target.cpp:4468
void SetSCSpecifier(SymbolContextSpecifier *specifier)
Set the symbol context specifier. The hook takes ownership.
Definition Target.cpp:4444
void SetThreadSpecifier(ThreadSpec *specifier)
Set the thread specifier. The hook takes ownership.
Definition Target.cpp:4448
std::unique_ptr< ThreadSpec > m_thread_spec_up
Definition Target.h:1852
void SetActionFromString(const std::string &strings)
Definition Target.cpp:4280
void SetActionFromStrings(const std::vector< std::string > &strings)
Definition Target.cpp:4284
StopHookResult HandleStop(ExecutionContext &exc_ctx, lldb::StreamSP output_sp) override
Definition Target.cpp:4291
void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4262
lldb::ScriptedHookInterfaceSP m_interface_sp
Definition Target.h:1703
StopHookResult HandleStop(ExecutionContext &exc_ctx, lldb::StreamSP output) override
Definition Target.cpp:4363
Status SetScriptCallback(const ScriptedMetadata &scripted_metadata)
Definition Target.cpp:4326
void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4391
llvm::StringRef GetScriptClassName() const
Definition Target.cpp:4385
SymbolContextSpecifier * GetSpecifier()
Definition Target.h:1611
void SetSpecifier(SymbolContextSpecifier *specifier)
Definition Target.cpp:4200
std::unique_ptr< ThreadSpec > m_thread_spec_up
Definition Target.h:1657
void SetThreadSpecifier(ThreadSpec *specifier)
Definition Target.cpp:4204
ThreadSpec * GetThreadSpecifier()
Definition Target.h:1626
StopHook(const StopHook &rhs)
Definition Target.cpp:4192
bool ExecutionContextPasses(const ExecutionContext &exe_ctx)
Definition Target.cpp:4208
lldb::TargetSP & GetTarget()
Definition Target.h:1605
lldb::SymbolContextSpecifierSP m_specifier_sp
Definition Target.h:1656
virtual void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const =0
void GetDescription(Stream &s, lldb::DescriptionLevel level) const
Definition Target.cpp:4224
void Dump(Stream *s) const override
Definition Target.cpp:5976
static llvm::StringRef GetFlavorString()
Definition Target.cpp:5972
static lldb::TargetSP GetCreatedTargetFromEvent(const Event *event_ptr)
Definition Target.cpp:6005
static ModuleList GetModuleListFromEvent(const Event *event_ptr)
Definition Target.cpp:6014
static const TargetEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Target.cpp:5986
TargetEventData(const lldb::TargetSP &target_sp)
Definition Target.cpp:5958
static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr)
Definition Target.cpp:5996
void ModulesDidLoad(ModuleList &module_list)
This call may preload module symbols, and may do so in parallel depending on the following target set...
Definition Target.cpp:1939
lldb::ThreadSP CalculateThread() override
Definition Target.cpp:2691
llvm::Expected< uint32_t > AddScriptedFrameProviderDescriptor(const ScriptedFrameProviderDescriptor &descriptor)
Add or update a scripted frame provider descriptor for this target.
Definition Target.cpp:3890
StopHookCollection m_stop_hooks
Definition Target.h:2136
Module * GetExecutableModulePointer()
Definition Target.cpp:1639
void Dump(Stream *s, lldb::DescriptionLevel description_level)
Dump a description of this object to a Stream.
Definition Target.cpp:257
void DisableAllBreakpoints(bool internal_also=false)
Definition Target.cpp:1171
bool RemoveHookByID(lldb::user_id_t uid)
Definition Target.cpp:4788
lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size, const CompilerType *type, uint32_t kind, Status &error)
Definition Target.cpp:1053
void ApplyNameToBreakpoints(BreakpointName &bp_name)
Definition Target.cpp:930
lldb::user_id_t m_hook_next_id
Definition Target.h:2147
lldb::TraceSP GetTrace()
Get the Trace object containing processor trace information of this target.
Definition Target.cpp:3765
PathMappingList & GetImageSearchPathList()
Definition Target.cpp:2700
void FinalizeFileActions(ProcessLaunchInfo &info)
Definition Target.cpp:3972
lldb::addr_t GetCallableLoadAddress(lldb::addr_t load_addr, AddressClass addr_class=AddressClass::eInvalid) const
Get load_addr as a callable code load address for this target.
Definition Target.cpp:3097
lldb::addr_t GetOpcodeLoadAddress(lldb::addr_t load_addr, AddressClass addr_class=AddressClass::eInvalid) const
Get load_addr as an opcode for this target.
Definition Target.cpp:3105
lldb::BreakpointSP CreateScriptedBreakpoint(const llvm::StringRef class_name, const FileSpecList *containingModules, const FileSpecList *containingSourceFiles, bool internal, bool request_hardware, StructuredData::ObjectSP extra_args_sp, Status *creation_error=nullptr)
Definition Target.cpp:775
static Target * GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
Definition Target.cpp:2932
lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr)
Definition Target.cpp:3112
void ClearDummySignals(Args &signal_names)
Clear the dummy signals in signal_names from the target, or all signals if signal_names is empty.
Definition Target.cpp:4132
static void ImageSearchPathsChanged(const PathMappingList &path_list, void *baton)
Definition Target.cpp:2704
llvm::Expected< lldb_private::Address > GetEntryPointAddress()
This method will return the address of the starting function for this binary, e.g.
Definition Target.cpp:3063
bool IgnoreWatchpointByID(lldb::watch_id_t watch_id, uint32_t ignore_count)
Definition Target.cpp:1607
lldb::BreakpointSP CreateFuncRegexBreakpoint(const FileSpecList *containingModules, const FileSpecList *containingSourceFiles, RegularExpression func_regexp, lldb::LanguageType requested_language, LazyBool skip_prologue, bool internal, bool request_hardware)
Definition Target.cpp:741
lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:436
std::shared_ptr< StopHook > StopHookSP
Definition Target.h:1750
void SymbolsDidLoad(ModuleList &module_list)
Definition Target.cpp:1967
bool ClearAllWatchpointHistoricValues()
Definition Target.cpp:1521
const std::vector< StopHookSP > GetStopHooks(bool internal=false) const
Definition Target.cpp:3228
void SetTrace(const lldb::TraceSP &trace_sp)
Set the Trace object containing processor trace information of this target.
Definition Target.cpp:3763
BreakpointList & GetBreakpointList(bool internal=false)
Definition Target.cpp:422
uint32_t m_next_frame_provider_id
Definition Target.h:2128
lldb_private::SummaryStatisticsCache & GetSummaryStatisticsCache()
Definition Target.cpp:3580
const llvm::MapVector< uint32_t, ScriptedFrameProviderDescriptor > & GetScriptedFrameProviderDescriptors() const
Get all scripted frame provider descriptors for this target.
Definition Target.cpp:3951
lldb::addr_t GetSectionLoadAddress(const lldb::SectionSP &section_sp)
Definition Target.cpp:6036
llvm::StringRef GetABIName() const
Returns the name of the target's ABI plugin.
Definition Target.cpp:411
SourceManager & GetSourceManager()
Definition Target.cpp:3152
lldb::SearchFilterSP GetSearchFilterForModuleList(const FileSpecList *containingModuleList)
Definition Target.cpp:704
StopHookSP GetStopHookByID(lldb::user_id_t uid)
Definition Target.cpp:3194
llvm::StringMap< DummySignalValues > m_dummy_signals
These are used to set the signal state when you don't have a process and more usefully in the Dummy t...
Definition Target.h:2163
lldb::user_id_t AddBreakpointResolverOverride(BreakpointResolverOverrideUP override_up)
Add a breakpoint override resolver. This version can't fail.
Definition Target.h:1058
lldb::ProcessSP m_process_sp
Definition Target.h:2116
Debugger & GetDebugger() const
Definition Target.h:1337
lldb::SearchFilterSP m_search_filter_sp
Definition Target.h:2117
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition Target.cpp:2782
void UpdateSignalsFromDummy(lldb::UnixSignalsSP signals_sp, lldb::StreamSP warning_stream_sp)
Updates the signals in signals_sp using the stored dummy signals.
Definition Target.cpp:4120
bool m_is_dummy_target
Used to not run stop hooks for expressions.
Definition Target.h:2143
static bool UpdateSignalFromDummy(lldb::UnixSignalsSP signals_sp, const DummySignalElement &element)
Definition Target.cpp:4078
PathMappingList m_image_search_paths
Definition Target.h:2118
bool ModuleIsExcludedForUnconstrainedSearches(const FileSpec &module_spec)
Return whether this FileSpec corresponds to a module that should be considered for general searches.
Definition Target.cpp:2025
lldb::StackFrameSP CalculateStackFrame() override
Definition Target.cpp:2693
SectionLoadList & GetSectionLoadList()
Definition Target.h:2220
lldb::addr_t GetPersistentSymbol(ConstString name)
Definition Target.cpp:3043
TargetAPIMutex GetAPIMutex()
Returns a handle resolved to the mutex to serialize on before touching the target through the SB API.
Definition Target.cpp:6022
void PrimeFromDummyTarget(Target &target)
Definition Target.cpp:224
bool RemoveScriptedFrameProviderDescriptor(uint32_t id)
Remove a scripted frame provider descriptor by id.
Definition Target.cpp:3926
lldb::RegisterTypeBuilderSP m_register_type_builder_sp
Definition Target.h:2165
static void SettingsTerminate()
Definition Target.cpp:2894
bool EnableWatchpointByID(lldb::watch_id_t watch_id)
Definition Target.cpp:1572
void DeleteBreakpointName(llvm::StringRef name)
Definition Target.cpp:907
HookSP CreateHook(Hook::HookKind kind)
Definition Target.cpp:4766
bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr)
Definition Target.cpp:3496
bool ClearAllWatchpointHitCounts()
Definition Target.cpp:1507
CompilerType GetRegisterType(const RegisterInfo &reg_info)
Definition Target.cpp:2740
size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len, Status &error)
Definition Target.cpp:2057
void ClearAllLoadedSections()
Definition Target.cpp:3572
std::vector< lldb::TypeSystemSP > GetScratchTypeSystems(bool create_on_demand=true)
Definition Target.cpp:2748
size_t ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size, bool is_signed, Scalar &scalar, Status &error, bool force_live_memory=false)
Definition Target.cpp:2365
void AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name, Status &error)
Definition Target.cpp:852
void DumpSectionLoadList(Stream &s)
Definition Target.cpp:6042
void DeleteCurrentProcess()
Definition Target.cpp:293
BreakpointList m_internal_breakpoint_list
Definition Target.h:2100
int64_t ReadSignedIntegerFromMemory(const Address &addr, size_t integer_byte_size, int64_t fail_value, Status &error, bool force_live_memory=false)
Definition Target.cpp:2396
friend class TargetAPIMutex
Definition Target.h:590
void DisableAllowedBreakpoints()
Definition Target.cpp:1181
bool SetHookEnabledStateByID(lldb::user_id_t uid, bool enabled)
Definition Target.cpp:4810
bool SetSectionUnloaded(const lldb::SectionSP &section_sp)
Definition Target.cpp:3550
lldb::TargetSP CalculateTarget() override
Definition Target.cpp:2687
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:327
void ClearModules(bool delete_locations)
Definition Target.cpp:1643
void RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp, llvm::StringRef name)
Definition Target.cpp:917
BreakpointNameMap m_breakpoint_names
Definition Target.h:2102
bool RemoveBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:1205
llvm::MapVector< uint32_t, ScriptedFrameProviderDescriptor > m_frame_provider_descriptors
Map of scripted frame provider descriptors for this target.
Definition Target.h:2126
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition Target.cpp:2448
static bool ResetSignalFromDummy(lldb::UnixSignalsSP signals_sp, const DummySignalElement &element)
Definition Target.cpp:4105
Architecture * GetArchitecturePlugin() const
Definition Target.h:1335
llvm::json::Value ReportStatistics(const lldb_private::StatisticsOptions &options)
Get metrics associated with this target in JSON format.
Definition Target.cpp:6028
friend class TargetList
Definition Target.h:588
FunctionCaller * GetFunctionCallerForLanguage(lldb::LanguageType language, const CompilerType &return_type, const Address &function_address, const ValueList &arg_value_list, const char *name, Status &error)
Definition Target.cpp:2835
void EnableAllBreakpoints(bool internal_also=false)
Definition Target.cpp:1188
Status Launch(ProcessLaunchInfo &launch_info, Stream *stream)
Definition Target.cpp:3595
bool DisableBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:1225
lldb::BreakpointSP CreateBreakpointAtUserEntry(Status &error)
Definition Target.cpp:448
llvm::Expected< lldb::TraceSP > CreateTrace()
Create a Trace object for the current target using the using the default supported tracing technology...
Definition Target.cpp:3767
lldb::TraceSP m_trace_sp
An optional lldb_private::Trace object containing processor trace information of this target.
Definition Target.h:2157
bool RemoveAllWatchpoints(bool end_to_end=true)
Definition Target.cpp:1425
bool ReadPointerFromMemory(const Address &addr, Status &error, Address &pointer_addr, bool force_live_memory=false)
Definition Target.cpp:2418
void UndoCreateStopHook(lldb::user_id_t uid)
If you tried to create a stop hook, and that failed, call this to remove the stop hook,...
Definition Target.cpp:3180
WatchpointList m_watchpoint_list
Definition Target.h:2111
BreakpointList m_breakpoint_list
Definition Target.h:2099
void DescribeBreakpointOverrides(Stream &stream, std::vector< lldb::user_id_t > &idxs, uint32_t terminal_width, bool use_color)
Describe the breakpoint overrides.
Definition Target.cpp:984
lldb::SourceManagerUP m_source_manager_up
Definition Target.h:2133
bool RemoveWatchpointByID(lldb::watch_id_t watch_id)
Definition Target.cpp:1591
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3490
size_t ReadStringFromMemory(const Address &addr, char *dst, size_t max_bytes, Status &error, size_t type_width, bool force_live_memory=true)
Read a NULL terminated string from memory.
Definition Target.cpp:2316
HookSP GetHookByID(lldb::user_id_t uid)
Definition Target.cpp:4795
void NotifyWillClearList(const ModuleList &module_list) override
Definition Target.cpp:1901
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1785
void NotifyModuleAdded(const ModuleList &module_list, const lldb::ModuleSP &module_sp) override
Implementing of ModuleList::Notifier.
Definition Target.cpp:1903
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
Definition Target.cpp:2713
void ConfigureBreakpointName(BreakpointName &bp_name, const BreakpointOptions &options, const BreakpointName::Permissions &permissions)
Definition Target.cpp:922
lldb_private::SummaryStatisticsSP GetSummaryStatisticsSPForProviderName(lldb_private::TypeSummaryImpl &summary_provider)
Definition Target.cpp:3574
lldb::SearchFilterSP GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules, const FileSpecList *containingSourceFiles)
Definition Target.cpp:721
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1623
bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state)
Definition Target.cpp:3204
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition Target.cpp:315
void SetAllStopHooksActiveState(bool active_state)
Definition Target.cpp:3215
std::vector< StopHookSP > m_internal_stop_hooks
Definition Target.h:2138
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition Target.cpp:3024
void NotifyModulesRemoved(lldb_private::ModuleList &module_list) override
Definition Target.cpp:1935
StopHookSP CreateStopHook(StopHook::StopHookKind kind, bool internal=false)
Add an empty stop hook to the Target's stop hook list, and returns a shared pointer to the new hook.
Definition Target.cpp:3158
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error, bool force_live_memory=false)
Definition Target.cpp:2226
void SetAllHooksEnabledState(bool enabled)
Definition Target.cpp:4818
std::recursive_mutex m_mutex
An API mutex that is used by the lldb::SB* classes make the SB interface thread safe.
Definition Target.h:2085
std::recursive_mutex m_frame_provider_descriptors_mutex
Definition Target.h:2127
lldb::user_id_t m_target_unique_id
The globally unique ID assigned to this target.
Definition Target.h:2149
void ModulesDidUnload(ModuleList &module_list, bool delete_locations)
Definition Target.cpp:1983
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Target.cpp:2695
llvm::Expected< lldb::DisassemblerSP > ReadInstructions(const Address &start_addr, uint32_t count, const char *flavor_string=nullptr)
Definition Target.cpp:3118
llvm::Expected< lldb::TraceSP > GetTraceOrCreate()
If a Trace object is present, this returns it, otherwise a new Trace is created with Trace::CreateTra...
Definition Target.cpp:3792
void NotifyModuleUpdated(const ModuleList &module_list, const lldb::ModuleSP &old_module_sp, const lldb::ModuleSP &new_module_sp) override
Definition Target.cpp:1923
SummaryStatisticsCache m_summary_statistics_cache
Definition Target.h:2097
Status SerializeBreakpointsToFile(const FileSpec &file, const BreakpointIDList &bp_ids, bool append)
Definition Target.cpp:1266
void DidExec()
Called as the last function in Process::DidExec().
Definition Target.cpp:1650
void SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info)
Definition Target.cpp:3584
std::string m_label
Definition Target.h:2094
lldb::user_id_t m_stop_hook_next_id
Definition Target.h:2137
static FileSpecList GetDefaultExecutableSearchPaths()
Definition Target.cpp:2896
lldb::BreakpointSP CreateExceptionBreakpoint(enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal, Args *additional_args=nullptr, Status *additional_args_error=nullptr)
Definition Target.cpp:758
void NotifyBreakpointChanged(Breakpoint &bp, lldb::BreakpointEventType event_kind)
Sends a breakpoint notification event.
Definition Target.cpp:6046
lldb::SearchFilterSP GetSearchFilterForModule(const FileSpec *containingModule)
Definition Target.cpp:686
llvm::StringMapEntry< DummySignalValues > DummySignalElement
Definition Target.h:2028
static llvm::StringRef GetStaticBroadcasterClass()
Definition Target.cpp:174
static FileSpecList GetDefaultDebugFileSearchPaths()
Definition Target.cpp:2900
void EnableAllowedBreakpoints()
Definition Target.cpp:1198
virtual size_t ReadMemory(const Address &addr, void *dst, size_t dst_len, Status &error, bool force_live_memory=false, lldb::addr_t *load_addr_ptr=nullptr, bool *did_read_live_memory=nullptr)
Definition Target.cpp:2090
llvm::Error SetLabel(llvm::StringRef label)
Set a label for a target.
Definition Target.cpp:2915
uint32_t m_latest_stop_hook_id
Definition Target.h:2139
void RunModuleHooks(bool is_load)
Definition Target.cpp:4823
std::map< lldb::user_id_t, BreakpointResolverOverrideUP > m_breakpoint_overrides
Definition Target.h:2105
void RemoveAllowedBreakpoints()
Definition Target.cpp:1150
bool DisableAllWatchpoints(bool end_to_end=true)
Definition Target.cpp:1454
bool RunStopHooks(bool at_initial_stop=false)
Definition Target.cpp:3239
void ClearSectionLoadList()
Definition Target.cpp:6040
lldb::addr_t GetReasonableReadSize(const Address &addr)
Return a recommended size for memory reads at addr, optimizing for cache usage.
Definition Target.cpp:2303
lldb::PlatformSP m_platform_sp
The platform for this target.
Definition Target.h:2084
void UndoCreateHook(lldb::user_id_t uid)
Removes the most recently created hook.
Definition Target.cpp:4781
llvm::Expected< std::unique_ptr< UtilityFunction > > CreateUtilityFunction(std::string expression, std::string name, lldb::LanguageType language, ExecutionContext &exe_ctx)
Creates and installs a UtilityFunction for the given language.
Definition Target.cpp:2865
FileSpecList GetSafeAutoLoadPaths() const
Get the list of paths that LLDB will consider automatically loading scripting resources from.
Definition Target.cpp:6062
static TargetProperties & GetGlobalProperties()
Definition Target.cpp:3454
Status Install(ProcessLaunchInfo *launch_info)
Definition Target.cpp:3462
HookSP GetHookAtIndex(size_t index)
Definition Target.cpp:4802
lldb::PlatformSP GetPlatform()
Definition Target.h:1980
void NotifyModuleRemoved(const ModuleList &module_list, const lldb::ModuleSP &module_sp) override
Definition Target.cpp:1913
lldb::BreakpointSP CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal, const FileSpec &file_spec, bool request_hardware)
Definition Target.cpp:592
lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, uint32_t column, lldb::addr_t offset, LazyBool check_inlines, LazyBool skip_prologue, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition Target.cpp:503
void RemoveAllBreakpoints(bool internal_also=false)
Definition Target.cpp:1159
lldb::BreakpointSP CreateSourceRegexBreakpoint(const FileSpecList *containingModules, const FileSpecList *source_file_list, const std::unordered_set< std::string > &function_names, RegularExpression source_regex, bool internal, bool request_hardware, LazyBool move_to_nearest_code)
Definition Target.cpp:486
static ArchSpec GetDefaultArchitecture()
Definition Target.cpp:2904
void ResetBreakpointHitCounts()
Resets the hit count of all breakpoints.
Definition Target.cpp:1262
std::unique_ptr< BreakpointResolverOverride > BreakpointResolverOverrideUP
Definition Target.h:1030
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1254
const ArchSpec & GetArchitecture() const
Definition Target.h:1296
WatchpointList & GetWatchpointList()
Definition Target.h:966
@ eBroadcastBitWatchpointChanged
Definition Target.h:597
@ eBroadcastBitBreakpointChanged
Definition Target.h:594
@ eBroadcastBitNewTargetCreated
Definition Target.h:600
bool EnableBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:1243
uint64_t ReadUnsignedIntegerFromMemory(const Address &addr, size_t integer_byte_size, uint64_t fail_value, Status &error, bool force_live_memory=false)
Definition Target.cpp:2407
void InvalidateThreadFrameProviders()
Invalidate all potentially cached frame providers for all threads and trigger a stack changed event f...
Definition Target.cpp:3957
TargetStats m_stats
Definition Target.h:2173
bool IgnoreAllWatchpoints(uint32_t ignore_count)
Definition Target.cpp:1536
void AddBreakpoint(lldb::BreakpointSP breakpoint_sp, bool internal)
Definition Target.cpp:829
std::string m_target_session_name
The target session name for this target, used to name debugging sessions in DAP.
Definition Target.h:2152
TypeSystemMap m_scratch_type_system_map
Definition Target.h:2119
void AddBreakpointName(std::unique_ptr< BreakpointName > bp_name)
Definition Target.cpp:879
SectionLoadHistory m_section_load_history
Definition Target.h:2098
lldb::BreakpointResolverSP CheckBreakpointOverrides(lldb::BreakpointResolverSP original_sp)
Definition Target.cpp:1022
void GetBreakpointNames(std::vector< std::string > &names)
Definition Target.cpp:944
bool IsDummyTarget() const
Definition Target.h:678
Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp, bool is_dummy_target)
Construct with optional file and arch.
Definition Target.cpp:179
size_t UnloadModuleSections(const lldb::ModuleSP &module_sp)
Definition Target.cpp:3531
bool m_valid
This records the last natural stop at which we ran a stop-hook.
Definition Target.h:2141
bool DisableWatchpointByID(lldb::watch_id_t watch_id)
Definition Target.cpp:1553
void AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool print, LazyBool stop)
Add a signal to the Target's list of stored signals/actions.
Definition Target.cpp:4063
void ClearScriptedFrameProviderDescriptors()
Clear all scripted frame provider descriptors for this target.
Definition Target.cpp:3939
lldb::WatchpointSP m_last_created_watchpoint
Definition Target.h:2112
Status CreateBreakpointsFromFile(const FileSpec &file, BreakpointIDList &new_bps)
Definition Target.cpp:1358
Debugger & m_debugger
Definition Target.h:2083
void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp)
Definition Target.cpp:380
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1656
lldb::StackFrameRecognizerManagerUP m_frame_recognizer_manager_up
Stores the frame recognizers of this target.
Definition Target.h:2159
HookCollection m_hooks
Definition Target.h:2146
lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language, const char *repl_options, bool can_create)
Definition Target.cpp:329
std::shared_ptr< Hook > HookSP
Definition Target.h:1921
UserExpression * GetUserExpressionForLanguage(llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language, Expression::ResultType desired_type, const EvaluateExpressionOptions &options, ValueObject *ctx_obj, Status &error)
Definition Target.cpp:2802
ModuleList m_images
The list of images for this process (shared libraries and anything dynamically loaded).
Definition Target.h:2095
lldb::ProcessSP CalculateProcess() override
Definition Target.cpp:2689
void PrintDummySignals(Stream &strm, Args &signals)
Print all the signals set in this target.
Definition Target.cpp:4157
void SetPlatform(const lldb::PlatformSP &platform_sp)
Definition Target.h:1982
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3501
BreakpointName * FindBreakpointName(llvm::StringRef name, bool can_create, Status &error)
Definition Target.cpp:884
Status Attach(ProcessAttachInfo &attach_info, Stream *stream)
Definition Target.cpp:3798
static void SetDefaultArchitecture(const ArchSpec &arch)
Definition Target.cpp:2908
lldb::BreakpointSP m_last_created_breakpoint
Definition Target.h:2110
bool RemoveStopHookByID(lldb::user_id_t uid)
Definition Target.cpp:3187
friend class Debugger
Definition Target.h:589
static void SettingsInitialize()
Definition Target.cpp:2892
~Target() override
Definition Target.cpp:218
bool EnableAllWatchpoints(bool end_to_end=true)
Definition Target.cpp:1481
lldb::ExpressionResults EvaluateExpression(llvm::StringRef expression, ExecutionContextScope *exe_scope, lldb::ValueObjectSP &result_valobj_sp, const EvaluateExpressionOptions &options=EvaluateExpressionOptions(), std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Definition Target.cpp:2946
bool MergeArchitecture(const ArchSpec &arch_spec)
Definition Target.cpp:1876
uint32_t GetSize(bool can_update=true)
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
static llvm::Expected< lldb::TraceSP > FindPluginForLiveProcess(llvm::StringRef plugin_name, Process &process)
Find a trace plug-in to trace a live process.
Definition Trace.cpp:133
Represents UUID's of various sizes.
Definition UUID.h:27
void Dump(Stream &s) const
Definition UUID.cpp:68
void Clear()
Definition UUID.h:62
bool IsValid() const
Definition UUID.h:69
Encapsulates a one-time expression for use in lldb.
static lldb::ExpressionResults Evaluate(ExecutionContext &exe_ctx, const EvaluateExpressionOptions &options, llvm::StringRef expr_cstr, llvm::StringRef expr_prefix, lldb::ValueObjectSP &result_valobj_sp, std::string *fixed_expression=nullptr, ValueObject *ctx_obj=nullptr)
Evaluate one expression in the scratch context of the target passed in the exe_ctx and return its res...
void GetListMutex(std::unique_lock< std::recursive_mutex > &lock)
Sets the passed in Locker to hold the Watchpoint List mutex.
uint8_t * GetBytes()
Get a pointer to the data.
Definition DataBuffer.h:108
#define LLDB_WATCH_TYPE_WRITE
#define LLDB_INVALID_BREAK_ID
#define LLDB_INVALID_SIGNAL_NUMBER
#define LLDB_INVALID_INDEX32
#define LLDB_WATCH_TYPE_IS_VALID(type)
#define LLDB_BREAK_ID_IS_INTERNAL(bid)
#define LLDB_INVALID_UID
#define LLDB_WATCH_TYPE_MODIFY
#define LLDB_WATCH_TYPE_READ
#define LLDB_INVALID_ADDRESS
#define LLDB_INVALID_PROCESS_ID
@ SelectMostRelevantFrame
void OutputWordWrappedLines(Stream &strm, llvm::StringRef text, uint32_t output_max_columns, bool use_color)
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
std::shared_ptr< SummaryStatistics > SummaryStatisticsSP
Definition Statistics.h:33
LoadScriptFromSymFile
Definition Target.h:61
@ eLoadScriptFromSymFileTrue
Definition Target.h:62
@ eLoadScriptFromSymFileTrusted
Definition Target.h:65
@ eLoadScriptFromSymFileFalse
Definition Target.h:63
@ eLoadScriptFromSymFileWarn
Definition Target.h:64
static uint32_t bit(const uint32_t val, const uint32_t msbit)
Definition ARMUtils.h:270
@ eJITEngineMCJIT
Definition Target.h:87
@ eJITEngineORC
Definition Target.h:87
DynamicClassInfoHelper
Definition Target.h:80
@ eDynamicClassInfoHelperCopyRealizedClassList
Definition Target.h:83
@ eDynamicClassInfoHelperGetRealizedClassList
Definition Target.h:84
@ eDynamicClassInfoHelperAuto
Definition Target.h:81
@ eDynamicClassInfoHelperRealizedClassesStruct
Definition Target.h:82
OptionEnumValues GetDynamicValueTypes()
Definition Target.cpp:4871
@ eImportStdModuleFalse
Definition Target.h:75
@ eImportStdModuleFallback
Definition Target.h:76
@ eImportStdModuleTrue
Definition Target.h:77
void LoadTypeSummariesForModule(lldb::ModuleSP module_sp)
Load type summaries embedded in the binary.
const char * StateAsCString(lldb::StateType state)
Converts a StateType to a C string.
Definition State.cpp:14
LoadCWDlldbinitFile
Definition Target.h:68
@ eLoadCWDlldbinitTrue
Definition Target.h:69
@ eLoadCWDlldbinitFalse
Definition Target.h:70
@ eLoadCWDlldbinitWarn
Definition Target.h:71
llvm::ArrayRef< OptionEnumValueElement > OptionEnumValues
void LoadFormattersForModule(lldb::ModuleSP module_sp)
Load data formatters embedded in the binary.
@ eInlineBreakpointsNever
Definition Target.h:56
@ eInlineBreakpointsAlways
Definition Target.h:58
@ eInlineBreakpointsHeaders
Definition Target.h:57
std::shared_ptr< lldb_private::OptionValueProperties > OptionValuePropertiesSP
std::shared_ptr< lldb_private::Trace > TraceSP
std::shared_ptr< lldb_private::TypeSystem > TypeSystemSP
std::shared_ptr< lldb_private::ABI > ABISP
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
std::shared_ptr< lldb_private::SearchFilter > SearchFilterSP
std::shared_ptr< lldb_private::BreakpointResolver > BreakpointResolverSP
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelBrief
@ eDescriptionLevelVerbose
std::shared_ptr< lldb_private::Thread > ThreadSP
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
std::shared_ptr< lldb_private::Platform > PlatformSP
uint64_t offset_t
Definition lldb-types.h:86
StateType
Process and Thread States.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
LanguageType
Programming language type.
@ eLanguageTypeMipsAssembler
Mips_Assembler.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC
Non-standardized C, such as K&R.
@ eLanguageTypeAssembly
std::shared_ptr< lldb_private::Stream > StreamSP
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionSetupError
int32_t break_id_t
Definition lldb-types.h:88
std::shared_ptr< lldb_private::Process > ProcessSP
std::shared_ptr< lldb_private::BreakpointPrecondition > BreakpointPreconditionSP
std::shared_ptr< lldb_private::Event > EventSP
ReturnStatus
Command Return Status Types.
@ eReturnStatusSuccessContinuingResult
@ eReturnStatusSuccessContinuingNoResult
uint64_t pid_t
Definition lldb-types.h:84
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
std::shared_ptr< lldb_private::Listener > ListenerSP
int32_t watch_id_t
Definition lldb-types.h:89
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
@ eDynamicDontRunTarget
@ eDynamicCanRunTarget
@ eStructuredDataTypeBoolean
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::OptionValue > OptionValueSP
std::shared_ptr< lldb_private::EventData > EventDataSP
std::shared_ptr< lldb_private::REPL > REPLSP
A SmallBitVector that represents a set of source languages (lldb::LanguageType).
Definition Type.h:38
llvm::SmallBitVector bitvector
Definition Type.h:39
std::optional< lldb::LanguageType > GetSingularLanguage()
If the set contains a single language only, return it.
Every register is described in detail including its name, alternate name (optional),...
This struct contains the metadata needed to instantiate a frame provider and optional filters to cont...
llvm::StringRef GetName() const
Get the name of this descriptor (the scripted class name).
uint32_t GetHash() const
Get the content-based hash from ScriptedMetadata.
void SetID(uint32_t id)
Set the monotonically increasing ID for this descriptor.
bool IsValid() const
Check if this descriptor has valid metadata for script-based providers.
A type-erased pair of llvm::dwarf::SourceLanguageName and version.
lldb::LanguageType AsLanguageType() const
Definition Language.cpp:614
llvm::StringRef GetDescription() const
Definition Language.cpp:621
static TestingProperties & GetGlobalTestingProperties()
Definition Debugger.cpp:270
UserID(lldb::user_id_t uid=LLDB_INVALID_UID)
Construct with optional user ID.
Definition UserID.h:33
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47
std::string triple
The triple of this executable module.
Definition Telemetry.h:192
bool is_start_entry
If true, this entry was emitted at the beginning of an event (eg., before the executable is set).
Definition Telemetry.h:197
UUID uuid
The same as the executable-module's UUID.
Definition Telemetry.h:188
lldb::pid_t pid
PID of the process owned by this target.
Definition Telemetry.h:190
Helper RAII class for collecting telemetry.
Definition Telemetry.h:269
void DispatchOnExit(llvm::unique_function< void(Info *info)> final_callback)
Definition Telemetry.h:287
void DispatchNow(llvm::unique_function< void(Info *info)> populate_fields_cb)
Definition Telemetry.h:293