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