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