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