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