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 m_scratch_type_system_map.ForEach([&](lldb::TypeSystemSP type_system) {
2001 type_system->ModulesDidLoad(module_list);
2002 return true;
2003 });
2004 RunModuleHooks(/*is_load=*/true);
2005 auto data_sp =
2006 std::make_shared<TargetEventData>(shared_from_this(), module_list);
2008 }
2009}
2010
2012 if (m_valid && module_list.GetSize()) {
2013 if (m_process_sp) {
2014 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
2015 runtime->SymbolsDidLoad(module_list);
2016 }
2017 }
2018
2019 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
2020 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
2021 auto data_sp =
2022 std::make_shared<TargetEventData>(shared_from_this(), module_list);
2024 }
2025}
2026
2027void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
2028 if (m_valid && module_list.GetSize()) {
2029 UnloadModuleSections(module_list);
2030 auto data_sp =
2031 std::make_shared<TargetEventData>(shared_from_this(), module_list);
2033 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
2034 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
2035 delete_locations);
2036
2037 // If a module was torn down it will have torn down the 'TypeSystemClang's
2038 // that we used as source 'ASTContext's for the persistent variables in
2039 // the current target. Those would now be unsafe to access because the
2040 // 'DeclOrigin' are now possibly stale. Thus clear all persistent
2041 // variables. We only want to flush 'TypeSystem's if the module being
2042 // unloaded was capable of describing a source type. JITted module unloads
2043 // happen frequently for Objective-C utility functions or the REPL and rely
2044 // on the persistent variables to stick around.
2045 const bool should_flush_type_systems =
2046 module_list.AnyOf([](lldb_private::Module &module) {
2047 auto *object_file = module.GetObjectFile();
2048
2049 if (!object_file)
2050 return false;
2051
2052 auto type = object_file->GetType();
2053
2054 // eTypeExecutable: when debugged binary was rebuilt
2055 // eTypeSharedLibrary: if dylib was re-loaded
2056 return module.FileHasChanged() &&
2057 (type == ObjectFile::eTypeObjectFile ||
2058 type == ObjectFile::eTypeExecutable ||
2059 type == ObjectFile::eTypeSharedLibrary);
2060 });
2061
2062 if (should_flush_type_systems)
2064
2065 RunModuleHooks(/*is_load=*/false);
2066 }
2067}
2068
2070 const FileSpec &module_file_spec) {
2072 ModuleList matchingModules;
2073 ModuleSpec module_spec(module_file_spec);
2074 GetImages().FindModules(module_spec, matchingModules);
2075 size_t num_modules = matchingModules.GetSize();
2076
2077 // If there is more than one module for this file spec, only
2078 // return true if ALL the modules are on the black list.
2079 if (num_modules > 0) {
2080 for (size_t i = 0; i < num_modules; i++) {
2082 matchingModules.GetModuleAtIndex(i)))
2083 return false;
2084 }
2085 return true;
2086 }
2087 }
2088 return false;
2089}
2090
2092 const lldb::ModuleSP &module_sp) {
2094 if (m_platform_sp)
2095 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
2096 module_sp);
2097 }
2098 return false;
2099}
2100
2101size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
2102 size_t dst_len, Status &error) {
2103 SectionSP section_sp(addr.GetSection());
2104 if (section_sp) {
2105 // If the contents of this section are encrypted, the on-disk file is
2106 // unusable. Read only from live memory.
2107 if (section_sp->IsEncrypted()) {
2108 error = Status::FromErrorString("section is encrypted");
2109 return 0;
2110 }
2111 ModuleSP module_sp(section_sp->GetModule());
2112 if (module_sp) {
2113 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
2114 if (objfile) {
2115 size_t bytes_read = objfile->ReadSectionData(
2116 section_sp.get(), addr.GetOffset(), dst, dst_len);
2117 if (bytes_read > 0)
2118 return bytes_read;
2119 else
2121 "error reading data from section {0}", section_sp->GetName());
2122 } else
2123 error = Status::FromErrorString("address isn't from a object file");
2124 } else
2125 error = Status::FromErrorString("address isn't in a module");
2126 } else
2128 "address doesn't contain a section that points to a "
2129 "section in a object file");
2130
2131 return 0;
2132}
2133
2134size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len,
2135 Status &error, bool force_live_memory,
2136 lldb::addr_t *load_addr_ptr,
2137 bool *did_read_live_memory) {
2138 error.Clear();
2139 if (did_read_live_memory)
2140 *did_read_live_memory = false;
2141
2142 Address fixed_addr = addr;
2143 if (ProcessIsValid())
2144 if (const ABISP &abi = m_process_sp->GetABI())
2145 fixed_addr.SetLoadAddress(abi->FixAnyAddress(addr.GetLoadAddress(this)),
2146 this);
2147
2148 // if we end up reading this from process memory, we will fill this with the
2149 // actual load address
2150 if (load_addr_ptr)
2151 *load_addr_ptr = LLDB_INVALID_ADDRESS;
2152
2153 size_t bytes_read = 0;
2154
2155 addr_t load_addr = LLDB_INVALID_ADDRESS;
2156 addr_t file_addr = LLDB_INVALID_ADDRESS;
2157 Address resolved_addr;
2158 if (!fixed_addr.IsSectionOffset()) {
2159 SectionLoadList &section_load_list = GetSectionLoadList();
2160 if (section_load_list.IsEmpty()) {
2161 // No sections are loaded, so we must assume we are not running yet and
2162 // anything we are given is a file address.
2163 file_addr =
2164 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
2165 // its offset is the file address
2166 m_images.ResolveFileAddress(file_addr, resolved_addr);
2167 } else {
2168 // We have at least one section loaded. This can be because we have
2169 // manually loaded some sections with "target modules load ..." or
2170 // because we have a live process that has sections loaded through
2171 // the dynamic loader
2172 load_addr =
2173 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
2174 // its offset is the load address
2175 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
2176 }
2177 }
2178 if (!resolved_addr.IsValid())
2179 resolved_addr = fixed_addr;
2180
2181 // If we read from the file cache but can't get as many bytes as requested,
2182 // we keep the result around in this buffer, in case this result is the
2183 // best we can do.
2184 std::unique_ptr<uint8_t[]> file_cache_read_buffer;
2185 size_t file_cache_bytes_read = 0;
2186
2187 // Read from file cache if read-only section.
2188 if (!force_live_memory && resolved_addr.IsSectionOffset()) {
2189 SectionSP section_sp(resolved_addr.GetSection());
2190 if (section_sp) {
2191 auto permissions = Flags(section_sp->GetPermissions());
2192 bool is_readonly = !permissions.Test(ePermissionsWritable) &&
2193 permissions.Test(ePermissionsReadable);
2194 if (is_readonly) {
2195 file_cache_bytes_read =
2196 ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2197 if (file_cache_bytes_read == dst_len)
2198 return file_cache_bytes_read;
2199 else if (file_cache_bytes_read > 0) {
2200 file_cache_read_buffer =
2201 std::make_unique<uint8_t[]>(file_cache_bytes_read);
2202 std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read);
2203 }
2204 }
2205 }
2206 }
2207
2208 if (ProcessIsValid()) {
2209 if (load_addr == LLDB_INVALID_ADDRESS)
2210 load_addr = resolved_addr.GetLoadAddress(this);
2211
2212 if (load_addr == LLDB_INVALID_ADDRESS) {
2213 ModuleSP addr_module_sp(resolved_addr.GetModule());
2214 if (addr_module_sp && addr_module_sp->GetFileSpec())
2216 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
2217 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
2218 else
2220 "0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
2221 } else {
2222 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
2223 if (bytes_read != dst_len) {
2224 if (error.Success()) {
2225 if (bytes_read == 0)
2227 "read memory from 0x%" PRIx64 " failed", load_addr);
2228 else
2230 "only %" PRIu64 " of %" PRIu64
2231 " bytes were read from memory at 0x%" PRIx64,
2232 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
2233 }
2234 }
2235 if (bytes_read) {
2236 if (load_addr_ptr)
2237 *load_addr_ptr = load_addr;
2238 if (did_read_live_memory)
2239 *did_read_live_memory = true;
2240 return bytes_read;
2241 }
2242 }
2243 }
2244
2245 if (file_cache_read_buffer && file_cache_bytes_read > 0) {
2246 // Reading from the process failed. If we've previously succeeded in reading
2247 // something from the file cache, then copy that over and return that.
2248 std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read);
2249 return file_cache_bytes_read;
2250 }
2251
2252 if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) {
2253 // If we didn't already try and read from the object file cache, then try
2254 // it after failing to read from the process.
2255 error.Clear();
2256 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2257 // A short read here is only a failure if a live read already failed too.
2258 // Reaching this point with a valid process means the process contributed
2259 // nothing.
2260 if (bytes_read > 0 && bytes_read != dst_len && error.Success() &&
2263 "only {0} of {1} bytes were read from the object file cache",
2264 bytes_read, dst_len);
2265 return bytes_read;
2266 }
2267 return 0;
2268}
2269
2270size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
2271 Status &error, bool force_live_memory) {
2272 char buf[256];
2273 out_str.clear();
2274 addr_t curr_addr = addr.GetLoadAddress(this);
2275 Address address(addr);
2276 while (true) {
2277 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error,
2278 force_live_memory);
2279 if (length == 0)
2280 break;
2281 out_str.append(buf, length);
2282 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2283 // to read some more characters
2284 if (length == sizeof(buf) - 1)
2285 curr_addr += length;
2286 else
2287 break;
2288 address = Address(curr_addr);
2289 }
2290 return out_str.size();
2291}
2292
2293size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
2294 size_t dst_max_len, Status &result_error,
2295 bool force_live_memory) {
2296 size_t total_cstr_len = 0;
2297 if (dst && dst_max_len) {
2298 result_error.Clear();
2299 // NULL out everything just to be safe
2300 memset(dst, 0, dst_max_len);
2301 addr_t curr_addr = addr.GetLoadAddress(this);
2302 Address address(addr);
2303
2304 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
2305 // this really needs to be tied to the memory cache subsystem's cache line
2306 // size, so leave this as a fixed constant.
2307 const size_t cache_line_size = 512;
2308
2309 size_t bytes_left = dst_max_len - 1;
2310 char *curr_dst = dst;
2311
2312 while (bytes_left > 0) {
2313 addr_t cache_line_bytes_left =
2314 cache_line_size - (curr_addr % cache_line_size);
2315 addr_t bytes_to_read =
2316 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2317 Status error;
2318 size_t bytes_read = ReadMemory(address, curr_dst, bytes_to_read, error,
2319 force_live_memory);
2320
2321 if (bytes_read == 0) {
2322 result_error = std::move(error);
2323 dst[total_cstr_len] = '\0';
2324 break;
2325 }
2326 const size_t len = strlen(curr_dst);
2327
2328 total_cstr_len += len;
2329
2330 if (len < bytes_to_read)
2331 break;
2332
2333 curr_dst += bytes_read;
2334 curr_addr += bytes_read;
2335 bytes_left -= bytes_read;
2336 address = Address(curr_addr);
2337 }
2338 } else {
2339 if (dst == nullptr)
2340 result_error = Status::FromErrorString("invalid arguments");
2341 else
2342 result_error.Clear();
2343 }
2344 return total_cstr_len;
2345}
2346
2348 addr_t load_addr = addr.GetLoadAddress(this);
2349 if (load_addr != LLDB_INVALID_ADDRESS && m_process_sp) {
2350 // Avoid crossing cache line boundaries.
2351 addr_t cache_line_size = m_process_sp->GetMemoryCacheLineSize();
2352 return cache_line_size - (load_addr % cache_line_size);
2353 }
2354
2355 // The read is going to go to the file cache, so we can just pick a largish
2356 // value.
2357 return 0x1000;
2358}
2359
2360size_t Target::ReadStringFromMemory(const Address &addr, char *dst,
2361 size_t max_bytes, Status &error,
2362 size_t type_width, bool force_live_memory) {
2363 if (!dst || !max_bytes || !type_width || max_bytes < type_width)
2364 return 0;
2365
2366 size_t total_bytes_read = 0;
2367
2368 // Ensure a null terminator independent of the number of bytes that is
2369 // read.
2370 memset(dst, 0, max_bytes);
2371 size_t bytes_left = max_bytes - type_width;
2372
2373 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2374 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2375 "string with more than 4 bytes "
2376 "per character!");
2377
2378 Address address = addr;
2379 char *curr_dst = dst;
2380
2381 error.Clear();
2382 while (bytes_left > 0 && error.Success()) {
2383 addr_t bytes_to_read =
2384 std::min<addr_t>(bytes_left, GetReasonableReadSize(address));
2385 size_t bytes_read =
2386 ReadMemory(address, curr_dst, bytes_to_read, error, force_live_memory);
2387
2388 if (bytes_read == 0)
2389 break;
2390
2391 // Search for a null terminator of correct size and alignment in
2392 // bytes_read
2393 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2394 for (size_t i = aligned_start;
2395 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2396 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2397 error.Clear();
2398 return i;
2399 }
2400
2401 total_bytes_read += bytes_read;
2402 curr_dst += bytes_read;
2403 address.Slide(bytes_read);
2404 bytes_left -= bytes_read;
2405 }
2406 return total_bytes_read;
2407}
2408
2409size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
2410 bool is_signed, Scalar &scalar,
2411 Status &error,
2412 bool force_live_memory) {
2413 uint64_t uval;
2414
2415 if (byte_size <= sizeof(uval)) {
2416 size_t bytes_read =
2417 ReadMemory(addr, &uval, byte_size, error, force_live_memory);
2418 if (bytes_read == byte_size) {
2419 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
2420 m_arch.GetSpec().GetAddressByteSize());
2421 lldb::offset_t offset = 0;
2422 if (byte_size <= 4)
2423 scalar = data.GetMaxU32(&offset, byte_size);
2424 else
2425 scalar = data.GetMaxU64(&offset, byte_size);
2426
2427 if (is_signed) {
2428 scalar.MakeSigned();
2429 scalar.SignExtend(byte_size * 8);
2430 }
2431 return bytes_read;
2432 }
2433 } else {
2435 "byte size of %u is too large for integer scalar type", byte_size);
2436 }
2437 return 0;
2438}
2439
2441 size_t integer_byte_size,
2442 int64_t fail_value, Status &error,
2443 bool force_live_memory) {
2444 Scalar scalar;
2445 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, true, scalar, error,
2446 force_live_memory))
2447 return scalar.SLongLong(fail_value);
2448 return fail_value;
2449}
2450
2452 size_t integer_byte_size,
2453 uint64_t fail_value, Status &error,
2454 bool force_live_memory) {
2455 Scalar scalar;
2456 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
2457 force_live_memory))
2458 return scalar.ULongLong(fail_value);
2459 return fail_value;
2460}
2461
2463 Address &pointer_addr,
2464 bool force_live_memory) {
2465 Scalar scalar;
2466 if (ReadScalarIntegerFromMemory(addr, m_arch.GetSpec().GetAddressByteSize(),
2467 false, scalar, error, force_live_memory)) {
2468 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
2469 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
2470 SectionLoadList &section_load_list = GetSectionLoadList();
2471 if (section_load_list.IsEmpty()) {
2472 // No sections are loaded, so we must assume we are not running yet and
2473 // anything we are given is a file address.
2474 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
2475 } else {
2476 // We have at least one section loaded. This can be because we have
2477 // manually loaded some sections with "target modules load ..." or
2478 // because we have a live process that has sections loaded through
2479 // the dynamic loader
2480 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
2481 }
2482 // We weren't able to resolve the pointer value, so just return an
2483 // address with no section
2484 if (!pointer_addr.IsValid())
2485 pointer_addr.SetOffset(pointer_vm_addr);
2486 return true;
2487 }
2488 }
2489 return false;
2490}
2491
2493 bool notify, Status *error_ptr,
2494 bool invoke_symbol_locators) {
2495 ModuleSP module_sp;
2496
2497 Status error;
2498
2499 // Apply any remappings specified in target.object-map:
2500 ModuleSpec module_spec(orig_module_spec);
2501 module_spec.SetTarget(shared_from_this());
2502 PathMappingList &obj_mapping = GetObjectPathMap();
2503 if (std::optional<FileSpec> remapped_obj_file =
2504 obj_mapping.RemapPath(orig_module_spec.GetFileSpec().GetPath(),
2505 true /* only_if_exists */)) {
2506 module_spec.GetFileSpec().SetPath(remapped_obj_file->GetPath());
2507 }
2508
2509 // First see if we already have this module in our module list. If we do,
2510 // then we're done, we don't need to consult the shared modules list. But
2511 // only do this if we are passed a UUID.
2512
2513 if (module_spec.GetUUID().IsValid())
2514 module_sp = m_images.FindFirstModule(module_spec);
2515
2516 if (!module_sp) {
2517 llvm::SmallVector<ModuleSP, 1>
2518 old_modules; // This will get filled in if we have a new version
2519 // of the library
2520 bool did_create_module = false;
2521 FileSpecList search_paths = GetExecutableSearchPaths();
2522 FileSpec symbol_file_spec;
2523
2524 // Call locate module callback if set. This allows users to implement their
2525 // own module cache system. For example, to leverage build system artifacts,
2526 // to bypass pulling files from remote platform, or to search symbol files
2527 // from symbol servers.
2528 if (m_platform_sp)
2529 m_platform_sp->CallLocateModuleCallbackIfSet(
2530 module_spec, module_sp, symbol_file_spec, &did_create_module);
2531
2532 // The result of this CallLocateModuleCallbackIfSet is one of the following.
2533 // 1. module_sp:loaded, symbol_file_spec:set
2534 // The callback found a module file and a symbol file for the
2535 // module_spec. We will call module_sp->SetSymbolFileFileSpec with
2536 // the symbol_file_spec later.
2537 // 2. module_sp:loaded, symbol_file_spec:empty
2538 // The callback only found a module file for the module_spec.
2539 // 3. module_sp:empty, symbol_file_spec:set
2540 // The callback only found a symbol file for the module. We continue
2541 // to find a module file for this module_spec and we will call
2542 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
2543 // 4. module_sp:empty, symbol_file_spec:empty
2544 // Platform does not exist, the callback is not set, the callback did
2545 // not find any module files nor any symbol files, the callback failed,
2546 // or something went wrong. We continue to find a module file for this
2547 // module_spec.
2548
2549 if (!module_sp) {
2550 // If there are image search path entries, try to use them to acquire a
2551 // suitable image.
2552 if (m_image_search_paths.GetSize()) {
2553 ModuleSpec transformed_spec(module_spec);
2554 std::string transformed_dir;
2555 if (m_image_search_paths.RemapPath(
2556 module_spec.GetFileSpec().GetDirectory(), transformed_dir)) {
2557 transformed_spec.GetFileSpec().SetDirectory(transformed_dir);
2558 transformed_spec.GetFileSpec().SetFilename(
2559 module_spec.GetFileSpec().GetFilename());
2560 transformed_spec.SetTarget(shared_from_this());
2562 transformed_spec, module_sp, &old_modules, &did_create_module,
2563 /*invoke_locate_callback=*/true, invoke_symbol_locators);
2564 }
2565 }
2566 }
2567
2568 if (!module_sp) {
2569 // If we have a UUID, we can check our global shared module list in case
2570 // we already have it. If we don't have a valid UUID, then we can't since
2571 // the path in "module_spec" will be a platform path, and we will need to
2572 // let the platform find that file. For example, we could be asking for
2573 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2574 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2575 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2576 // cache.
2577 if (module_spec.GetUUID().IsValid()) {
2578 // We have a UUID, it is OK to check the global module list...
2580 module_spec, module_sp, &old_modules, &did_create_module,
2581 /*invoke_locate_callback=*/true, invoke_symbol_locators);
2582 }
2583
2584 if (!module_sp && invoke_symbol_locators) {
2585 // The platform is responsible for finding and caching an appropriate
2586 // module in the shared module cache.
2587 if (m_platform_sp) {
2588 error = m_platform_sp->GetSharedModule(
2589 module_spec, *this, module_sp, &old_modules, &did_create_module);
2590 } else {
2591 error = Status::FromErrorString("no platform is currently set");
2592 }
2593 }
2594 }
2595
2596 // We found a module that wasn't in our target list. Let's make sure that
2597 // there wasn't an equivalent module in the list already, and if there was,
2598 // let's remove it.
2599 if (module_sp) {
2600 ObjectFile *objfile = module_sp->GetObjectFile();
2601 if (objfile) {
2602 switch (objfile->GetType()) {
2603 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2604 /// a program's execution state
2605 case ObjectFile::eTypeExecutable: /// A normal executable
2606 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2607 /// executable
2608 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2609 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2610 /// used during execution
2611 break;
2612 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2613 /// debug information
2614 if (error_ptr)
2615 *error_ptr = Status::FromErrorString(
2616 "debug info files aren't valid target "
2617 "modules, please specify an executable");
2618 return ModuleSP();
2619 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2620 /// against but not used for
2621 /// execution
2622 if (error_ptr)
2623 *error_ptr = Status::FromErrorString(
2624 "stub libraries aren't valid target "
2625 "modules, please specify an executable");
2626 return ModuleSP();
2627 default:
2628 if (error_ptr)
2629 *error_ptr = Status::FromErrorString(
2630 "unsupported file type, please specify an executable");
2631 return ModuleSP();
2632 }
2633 // GetSharedModule is not guaranteed to find the old shared module, for
2634 // instance in the common case where you pass in the UUID, it is only
2635 // going to find the one module matching the UUID. In fact, it has no
2636 // good way to know what the "old module" relevant to this target is,
2637 // since there might be many copies of a module with this file spec in
2638 // various running debug sessions, but only one of them will belong to
2639 // this target. So let's remove the UUID from the module list, and look
2640 // in the target's module list. Only do this if there is SOMETHING else
2641 // in the module spec...
2642 if (module_spec.GetUUID().IsValid() &&
2643 !module_spec.GetFileSpec().GetFilename().empty() &&
2644 !module_spec.GetFileSpec().GetDirectory().empty()) {
2645 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2646 module_spec_copy.GetUUID().Clear();
2647
2648 ModuleList found_modules;
2649 m_images.FindModules(module_spec_copy, found_modules);
2650 found_modules.ForEach([&](const ModuleSP &found_module) {
2651 old_modules.push_back(found_module);
2653 });
2654 }
2655
2656 // If the locate module callback had found a symbol file, set it to the
2657 // module_sp before preloading symbols.
2658 if (symbol_file_spec)
2659 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
2660
2661 llvm::SmallVector<ModuleSP, 1> replaced_modules;
2662 for (ModuleSP &old_module_sp : old_modules) {
2663 if (m_images.GetIndexForModule(old_module_sp.get()) !=
2665 if (replaced_modules.empty())
2666 m_images.ReplaceModule(old_module_sp, module_sp);
2667 else
2668 m_images.Remove(old_module_sp);
2669
2670 replaced_modules.push_back(std::move(old_module_sp));
2671 }
2672 }
2673
2674 if (replaced_modules.size() > 1) {
2675 // The same new module replaced multiple old modules
2676 // simultaneously. It's not clear this should ever
2677 // happen (if we always replace old modules as we add
2678 // new ones, presumably we should never have more than
2679 // one old one). If there are legitimate cases where
2680 // this happens, then the ModuleList::Notifier interface
2681 // may need to be adjusted to allow reporting this.
2682 // In the meantime, just log that this has happened; just
2683 // above we called ReplaceModule on the first one, and Remove
2684 // on the rest.
2686 StreamString message;
2687 auto dump = [&message](Module &dump_module) -> void {
2688 UUID dump_uuid = dump_module.GetUUID();
2689
2690 message << '[';
2691 dump_module.GetDescription(message.AsRawOstream());
2692 message << " (uuid ";
2693
2694 if (dump_uuid.IsValid())
2695 dump_uuid.Dump(message);
2696 else
2697 message << "not specified";
2698
2699 message << ")]";
2700 };
2701
2702 message << "New module ";
2703 dump(*module_sp);
2704 message.AsRawOstream()
2705 << llvm::formatv(" simultaneously replaced {0} old modules: ",
2706 replaced_modules.size());
2707 for (ModuleSP &replaced_module_sp : replaced_modules)
2708 dump(*replaced_module_sp);
2709
2710 log->PutString(message.GetString());
2711 }
2712 }
2713
2714 if (replaced_modules.empty()) {
2715 if (!m_images.AppendIfNeeded(module_sp, notify) && notify)
2716 NotifyModuleAdded(m_images, module_sp);
2717 }
2718
2719 for (ModuleSP &old_module_sp : replaced_modules) {
2720 auto old_module_wp = old_module_sp->weak_from_this();
2721 old_module_sp.reset();
2723 }
2724 } else
2725 module_sp.reset();
2726 }
2727 }
2728 if (error_ptr)
2729 *error_ptr = std::move(error);
2730 return module_sp;
2731}
2732
2733TargetSP Target::CalculateTarget() { return shared_from_this(); }
2734
2736
2738
2740
2742 exe_ctx.Clear();
2743 exe_ctx.SetTargetPtr(this);
2744}
2745
2749
2751 void *baton) {
2752 Target *target = (Target *)baton;
2753 ModuleSP exe_module_sp(target->GetExecutableModule());
2754 if (exe_module_sp)
2756}
2757
2758llvm::Expected<lldb::TypeSystemSP>
2760 bool create_on_demand) {
2761 if (!m_valid)
2762 return llvm::createStringError("invalid target");
2763
2764 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2765 // assembly code
2766 || language == eLanguageTypeAssembly ||
2767 language == eLanguageTypeUnknown) {
2768 LanguageSet languages_for_expressions =
2770
2771 if (languages_for_expressions[eLanguageTypeC]) {
2772 language = eLanguageTypeC; // LLDB's default. Override by setting the
2773 // target language.
2774 } else {
2775 if (languages_for_expressions.Empty())
2776 return llvm::createStringError(
2777 "No expression support for any languages");
2778 language = (LanguageType)languages_for_expressions.bitvector.find_first();
2779 }
2780 }
2781
2782 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2783 create_on_demand);
2784}
2785
2792
2793std::vector<lldb::TypeSystemSP>
2794Target::GetScratchTypeSystems(bool create_on_demand) {
2795 if (!m_valid)
2796 return {};
2797
2798 // Some TypeSystem instances are associated with several LanguageTypes so
2799 // they will show up several times in the loop below. The SetVector filters
2800 // out all duplicates as they serve no use for the caller.
2801 //
2802 // The insertion order matters: callers such as SBTarget::GetBasicType query
2803 // the TypeSystems in order and use the first one that can answer, so the
2804 // result has to be a function of the languages and not of where the
2805 // instances happen to live in memory.
2806 llvm::SetVector<lldb::TypeSystemSP, std::vector<lldb::TypeSystemSP>,
2807 std::set<lldb::TypeSystemSP>>
2808 scratch_type_systems;
2809
2810 LanguageSet languages_for_expressions =
2812
2813 for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2814 auto language = (LanguageType)bit;
2815 auto type_system_or_err =
2816 GetScratchTypeSystemForLanguage(language, create_on_demand);
2817 if (!type_system_or_err)
2819 GetLog(LLDBLog::Target), type_system_or_err.takeError(),
2820 "Language '{1}' has expression support but no scratch type "
2821 "system available: {0}",
2823 else if (auto ts = *type_system_or_err)
2824 scratch_type_systems.insert(ts);
2825 }
2826
2827 return scratch_type_systems.takeVector();
2828}
2829
2832 auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2833
2834 if (auto err = type_system_or_err.takeError()) {
2836 GetLog(LLDBLog::Target), std::move(err),
2837 "Unable to get persistent expression state for language {1}: {0}",
2839 return nullptr;
2840 }
2841
2842 if (auto ts = *type_system_or_err)
2843 return ts->GetPersistentExpressionState();
2844
2846 "Unable to get persistent expression state for language {}:",
2848 return nullptr;
2849}
2850
2852 llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language,
2853 Expression::ResultType desired_type,
2854 const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2855 Status &error) {
2856 auto type_system_or_err =
2858 if (auto err = type_system_or_err.takeError()) {
2860 "Could not find type system for language %s: %s",
2862 llvm::toString(std::move(err)).c_str());
2863 return nullptr;
2864 }
2865
2866 auto ts = *type_system_or_err;
2867 if (!ts) {
2869 "Type system for language %s is no longer live",
2870 language.GetDescription().data());
2871 return nullptr;
2872 }
2873
2874 auto *user_expr = ts->GetUserExpression(expr, prefix, language, desired_type,
2875 options, ctx_obj);
2876 if (!user_expr)
2878 "Could not create an expression for language %s",
2879 language.GetDescription().data());
2880
2881 return user_expr;
2882}
2883
2885 lldb::LanguageType language, const CompilerType &return_type,
2886 const Address &function_address, const ValueList &arg_value_list,
2887 const char *name, Status &error) {
2888 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2889 if (auto err = type_system_or_err.takeError()) {
2891 "Could not find type system for language %s: %s",
2893 llvm::toString(std::move(err)).c_str());
2894 return nullptr;
2895 }
2896 auto ts = *type_system_or_err;
2897 if (!ts) {
2899 "Type system for language %s is no longer live",
2901 return nullptr;
2902 }
2903 auto *persistent_fn = ts->GetFunctionCaller(return_type, function_address,
2904 arg_value_list, name);
2905 if (!persistent_fn)
2907 "Could not create an expression for language %s",
2909
2910 return persistent_fn;
2911}
2912
2913llvm::Expected<std::unique_ptr<UtilityFunction>>
2914Target::CreateUtilityFunction(std::string expression, std::string name,
2915 lldb::LanguageType language,
2916 ExecutionContext &exe_ctx) {
2917 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2918 if (!type_system_or_err)
2919 return type_system_or_err.takeError();
2920 auto ts = *type_system_or_err;
2921 if (!ts)
2922 return llvm::createStringError(
2923 llvm::StringRef("Type system for language ") +
2925 llvm::StringRef(" is no longer live"));
2926 std::unique_ptr<UtilityFunction> utility_fn =
2927 ts->CreateUtilityFunction(std::move(expression), std::move(name));
2928 if (!utility_fn)
2929 return llvm::createStringError(
2930 llvm::StringRef("Could not create an expression for language") +
2932
2933 DiagnosticManager diagnostics;
2934 if (!utility_fn->Install(diagnostics, exe_ctx))
2935 return diagnostics.GetAsError(lldb::eExpressionSetupError,
2936 "Could not install utility function:");
2937
2938 return std::move(utility_fn);
2939}
2940
2942
2944
2948
2952
2956
2959 "setting target's default architecture to {0} ({1})",
2960 arch.GetArchitectureName(), arch.GetTriple().getTriple());
2962}
2963
2964llvm::Error Target::SetLabel(llvm::StringRef label) {
2965 size_t n = LLDB_INVALID_INDEX32;
2966 if (llvm::to_integer(label, n))
2967 return llvm::createStringError("cannot use integer as target label");
2968 TargetList &targets = GetDebugger().GetTargetList();
2969 for (size_t i = 0; i < targets.GetNumTargets(); i++) {
2970 TargetSP target_sp = targets.GetTargetAtIndex(i);
2971 if (target_sp && target_sp->GetLabel() == label) {
2972 return llvm::createStringErrorV(
2973 "Cannot use label '{0}' since it's set in target #{1}.", label, i);
2974 }
2975 }
2976
2977 m_label = label.str();
2978 return llvm::Error::success();
2979}
2980
2982 const SymbolContext *sc_ptr) {
2983 // The target can either exist in the "process" of ExecutionContext, or in
2984 // the "target_sp" member of SymbolContext. This accessor helper function
2985 // will get the target from one of these locations.
2986
2987 Target *target = nullptr;
2988 if (sc_ptr != nullptr)
2989 target = sc_ptr->target_sp.get();
2990 if (target == nullptr && exe_ctx_ptr)
2991 target = exe_ctx_ptr->GetTargetPtr();
2992 return target;
2993}
2994
2996 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2997 lldb::ValueObjectSP &result_valobj_sp,
2998 const EvaluateExpressionOptions &options, std::string *fixed_expression,
2999 ValueObject *ctx_obj) {
3000 result_valobj_sp.reset();
3001
3002 ExpressionResults execution_results = eExpressionSetupError;
3003
3004 if (expr.empty()) {
3005 m_stats.GetExpressionStats().NotifyFailure();
3006 return execution_results;
3007 }
3008
3009 // We shouldn't run stop hooks in expressions.
3010 bool old_suppress_value = m_suppress_stop_hooks;
3011 m_suppress_stop_hooks = true;
3012 llvm::scope_exit on_exit([this, old_suppress_value]() {
3013 m_suppress_stop_hooks = old_suppress_value;
3014 });
3015
3016 ExecutionContext exe_ctx;
3017
3018 if (exe_scope) {
3019 exe_scope->CalculateExecutionContext(exe_ctx);
3020 } else if (m_process_sp) {
3021 m_process_sp->CalculateExecutionContext(exe_ctx);
3022 } else {
3024 }
3025
3026 // Make sure we aren't just trying to see the value of a persistent variable
3027 // (something like "$0")
3028 // Only check for persistent variables the expression starts with a '$'
3029 lldb::ExpressionVariableSP persistent_var_sp;
3030 if (expr[0] == '$') {
3031 auto type_system_or_err =
3033 if (auto err = type_system_or_err.takeError()) {
3034 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
3035 "Unable to get scratch type system: {0}");
3036 } else {
3037 auto ts = *type_system_or_err;
3038 if (!ts)
3039 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
3040 "Scratch type system is no longer live: {0}");
3041 else
3042 persistent_var_sp =
3043 ts->GetPersistentExpressionState()->GetVariable(expr);
3044 }
3045 }
3046 if (persistent_var_sp) {
3047 result_valobj_sp = persistent_var_sp->GetValueObject();
3048 execution_results = eExpressionCompleted;
3049 } else {
3050 llvm::StringRef prefix = GetExpressionPrefixContents();
3051 execution_results =
3052 UserExpression::Evaluate(exe_ctx, options, expr, prefix,
3053 result_valobj_sp, fixed_expression, ctx_obj);
3054 }
3055
3056 if (execution_results == eExpressionCompleted)
3057 m_stats.GetExpressionStats().NotifySuccess();
3058 else
3059 m_stats.GetExpressionStats().NotifyFailure();
3060 return execution_results;
3061}
3062
3064 lldb::ExpressionVariableSP variable_sp;
3066 [name, &variable_sp](TypeSystemSP type_system) -> bool {
3067 auto ts = type_system.get();
3068 if (!ts)
3069 return true;
3070 if (PersistentExpressionState *persistent_state =
3071 ts->GetPersistentExpressionState()) {
3072 variable_sp = persistent_state->GetVariable(name);
3073
3074 if (variable_sp)
3075 return false; // Stop iterating the ForEach
3076 }
3077 return true; // Keep iterating the ForEach
3078 });
3079 return variable_sp;
3080}
3081
3084
3086 [name, &address](lldb::TypeSystemSP type_system) -> bool {
3087 auto ts = type_system.get();
3088 if (!ts)
3089 return true;
3090
3091 if (PersistentExpressionState *persistent_state =
3092 ts->GetPersistentExpressionState()) {
3093 address = persistent_state->LookupSymbol(name);
3094 if (address != LLDB_INVALID_ADDRESS)
3095 return false; // Stop iterating the ForEach
3096 }
3097 return true; // Keep iterating the ForEach
3098 });
3099 return address;
3100}
3101
3102llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
3103 Module *exe_module = GetExecutableModulePointer();
3104
3105 // Try to find the entry point address in the primary executable.
3106 const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
3107 if (has_primary_executable) {
3108 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
3109 if (entry_addr.IsValid())
3110 return entry_addr;
3111 }
3112
3113 const ModuleList &modules = GetImages();
3114 const size_t num_images = modules.GetSize();
3115 for (size_t idx = 0; idx < num_images; ++idx) {
3116 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
3117 if (!module_sp || !module_sp->GetObjectFile())
3118 continue;
3119
3120 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
3121 if (entry_addr.IsValid())
3122 return entry_addr;
3123 }
3124
3125 // We haven't found the entry point address. Return an appropriate error.
3126 if (!has_primary_executable)
3127 return llvm::createStringError(
3128 "No primary executable found and could not find entry point address in "
3129 "any executable module");
3130
3131 return llvm::createStringError(
3132 "Could not find entry point address for primary executable module \"" +
3133 exe_module->GetFileSpec().GetFilename() + "\"");
3134}
3135
3137 AddressClass addr_class) const {
3138 auto arch_plugin = GetArchitecturePlugin();
3139 return arch_plugin
3140 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
3141 : load_addr;
3142}
3143
3145 AddressClass addr_class) const {
3146 auto arch_plugin = GetArchitecturePlugin();
3147 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
3148 : load_addr;
3149}
3150
3152 auto arch_plugin = GetArchitecturePlugin();
3153 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
3154}
3155
3156llvm::Expected<lldb::DisassemblerSP>
3157Target::ReadInstructions(const Address &start_addr, uint32_t count,
3158 const char *flavor_string) {
3159 DataBufferHeap data(GetArchitecture().GetMaximumOpcodeByteSize() * count, 0);
3160 bool force_live_memory = true;
3163 const size_t bytes_read =
3164 ReadMemory(start_addr, data.GetBytes(), data.GetByteSize(), error,
3165 force_live_memory, &load_addr);
3166
3167 if (error.Fail()) {
3168 return llvm::joinErrors(
3169 llvm::createStringErrorV(
3170 "Target::ReadInstructions failed to read memory at {:x}: ",
3171 start_addr.GetLoadAddress(this)),
3172 error.takeError());
3173 }
3174
3175 const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
3176 if (!flavor_string || flavor_string[0] == '\0') {
3177 // FIXME - we don't have the mechanism in place to do per-architecture
3178 // settings. But since we know that for now we only support flavors on
3179 // x86 & x86_64,
3180 const llvm::Triple::ArchType arch = GetArchitecture().GetTriple().getArch();
3181 if (arch == llvm::Triple::x86 || arch == llvm::Triple::x86_64)
3182 flavor_string = GetDisassemblyFlavor();
3183 }
3184
3186 GetArchitecture(), nullptr, flavor_string, GetDisassemblyCPU(),
3187 GetDisassemblyFeatures(), start_addr, data.GetBytes(), bytes_read, count,
3188 data_from_file);
3189}
3190
3193 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
3194 return *m_source_manager_up;
3195}
3196
3198 bool internal) {
3199 user_id_t new_uid = (internal ? LLDB_INVALID_UID : ++m_stop_hook_next_id);
3200 Target::StopHookSP stop_hook_sp;
3201 switch (kind) {
3203 stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
3204 break;
3206 stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
3207 break;
3209 stop_hook_sp.reset(new StopHookCoded(shared_from_this(), new_uid));
3210 break;
3211 }
3212 if (internal)
3213 m_internal_stop_hooks.push_back(stop_hook_sp);
3214 else
3215 m_stop_hooks[new_uid] = stop_hook_sp;
3216 return stop_hook_sp;
3217}
3218
3220 if (!RemoveStopHookByID(user_id))
3221 return;
3222 if (user_id == m_stop_hook_next_id)
3224}
3225
3227 size_t num_removed = m_stop_hooks.erase(user_id);
3228 return (num_removed != 0);
3229}
3230
3232
3234 StopHookSP found_hook;
3235
3236 StopHookCollection::iterator specified_hook_iter;
3237 specified_hook_iter = m_stop_hooks.find(user_id);
3238 if (specified_hook_iter != m_stop_hooks.end())
3239 found_hook = (*specified_hook_iter).second;
3240 return found_hook;
3241}
3242
3244 bool active_state) {
3245 StopHookCollection::iterator specified_hook_iter;
3246 specified_hook_iter = m_stop_hooks.find(user_id);
3247 if (specified_hook_iter == m_stop_hooks.end())
3248 return false;
3249
3250 (*specified_hook_iter).second->SetIsActive(active_state);
3251 return true;
3252}
3253
3254void Target::SetAllStopHooksActiveState(bool active_state) {
3255 StopHookCollection::iterator pos, end = m_stop_hooks.end();
3256 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
3257 (*pos).second->SetIsActive(active_state);
3258 }
3259}
3260
3261// FIXME: Ideally we would like to return a `const &` (const reference) instead
3262// of creating copy here, but that is not possible due to different container
3263// types. In C++20, we should be able to use `std::ranges::views::values` to
3264// adapt the key-pair entries in the `std::map` (behind `StopHookCollection`)
3265// to avoid creating the copy.
3266const std::vector<Target::StopHookSP>
3267Target::GetStopHooks(bool internal) const {
3268 if (internal)
3269 return m_internal_stop_hooks;
3270
3271 std::vector<StopHookSP> stop_hooks;
3272 for (auto &[_, hook] : m_stop_hooks)
3273 stop_hooks.push_back(hook);
3274
3275 return stop_hooks;
3276}
3277
3278bool Target::RunStopHooks(bool at_initial_stop) {
3280 return false;
3281
3282 if (!m_process_sp)
3283 return false;
3284
3285 // Somebody might have restarted the process:
3286 // Still return false, the return value is about US restarting the target.
3287 lldb::StateType state = m_process_sp->GetState();
3288 if (!(state == eStateStopped || state == eStateAttaching))
3289 return false;
3290
3291 auto is_active = [at_initial_stop](StopHookSP hook) {
3292 bool should_run_now = (!at_initial_stop || hook->GetRunAtInitialStop());
3293 return hook->IsActive() && should_run_now;
3294 };
3295
3296 // Create list of active internal and user stop hooks.
3297 std::vector<StopHookSP> active_hooks;
3298 llvm::copy_if(m_internal_stop_hooks, std::back_inserter(active_hooks),
3299 is_active);
3300 for (auto &[_, hook] : m_stop_hooks) {
3301 if (is_active(hook))
3302 active_hooks.push_back(hook);
3303 }
3304
3305 // Also collect unified hooks that fire on process stop.
3306 std::vector<HookSP> active_unified_hooks;
3307 for (auto &[_, hook] : m_hooks) {
3308 if (hook->IsEnabled() && hook->FiresOn(Hook::kProcessStop) &&
3309 (!at_initial_stop || hook->GetRunAtInitialStop()))
3310 active_unified_hooks.push_back(hook);
3311 }
3312
3313 if (active_hooks.empty() && active_unified_hooks.empty())
3314 return false;
3315
3316 // Make sure we check that we are not stopped because of us running a user
3317 // expression since in that case we do not want to run the stop-hooks. Note,
3318 // you can't just check whether the last stop was for a User Expression,
3319 // because breakpoint commands get run before stop hooks, and one of them
3320 // might have run an expression. You have to ensure you run the stop hooks
3321 // once per natural stop.
3322 uint32_t last_natural_stop = m_process_sp->GetModIDRef().GetLastNaturalStopID();
3323 if (last_natural_stop != 0 && m_latest_stop_hook_id == last_natural_stop)
3324 return false;
3325
3326 std::vector<ExecutionContext> exc_ctx_with_reasons;
3327
3328 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
3329 size_t num_threads = cur_threadlist.GetSize();
3330 for (size_t i = 0; i < num_threads; i++) {
3331 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
3332 if (cur_thread_sp->ThreadStoppedForAReason()) {
3333 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
3334 exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
3335 cur_frame_sp.get());
3336 }
3337 }
3338
3339 // If no threads stopped for a reason, don't run the stop-hooks.
3340 // However, if this is the FIRST stop for this process, then we are in the
3341 // state where an attach or a core file load was completed without designating
3342 // a particular thread as responsible for the stop. In that case, we do
3343 // want to run the stop hooks, but do so just on one thread.
3344 size_t num_exe_ctx = exc_ctx_with_reasons.size();
3345 if (num_exe_ctx == 0) {
3346 if (at_initial_stop && num_threads > 0) {
3347 lldb::ThreadSP thread_to_use_sp = cur_threadlist.GetThreadAtIndex(0);
3348 exc_ctx_with_reasons.emplace_back(
3349 m_process_sp.get(), thread_to_use_sp.get(),
3350 thread_to_use_sp->GetStackFrameAtIndex(0).get());
3351 num_exe_ctx = 1;
3352 } else {
3353 return false;
3354 }
3355 }
3356
3357 m_latest_stop_hook_id = last_natural_stop;
3358
3359 StreamSP output_sp = m_debugger.GetAsyncOutputStream();
3360 llvm::scope_exit on_exit([output_sp] { output_sp->Flush(); });
3361
3362 size_t num_hooks_with_output = llvm::count_if(
3363 active_hooks, [](auto h) { return !h->GetSuppressOutput(); });
3364 num_hooks_with_output += llvm::count_if(
3365 active_unified_hooks, [](auto h) { return !h->GetSuppressOutput(); });
3366 bool print_hook_header = (num_hooks_with_output > 1);
3367 bool print_thread_header = (num_exe_ctx > 1);
3368 bool should_stop = false;
3369 bool requested_continue = false;
3370
3371 // A stop hook might get deleted while running stop hooks.
3372 // We have to decide what that means. We will follow the rule that deleting
3373 // a stop hook while processing these stop hooks will delete it for FUTURE
3374 // stops but not this stop. Fortunately, copying the m_stop_hooks to the
3375 // active_hooks list before iterating over the hooks has this effect.
3376 for (auto cur_hook_sp : active_hooks) {
3377 bool any_thread_matched = false;
3378 for (auto exc_ctx : exc_ctx_with_reasons) {
3379 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
3380 continue;
3381
3382 bool suppress_output = cur_hook_sp->GetSuppressOutput();
3383 if (print_hook_header && !any_thread_matched && !suppress_output) {
3384 StreamString s;
3385 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
3386 if (s.GetSize() != 0)
3387 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
3388 s.GetData());
3389 else
3390 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
3391 any_thread_matched = true;
3392 }
3393
3394 if (print_thread_header && !suppress_output)
3395 output_sp->Printf("-- Thread %d\n",
3396 exc_ctx.GetThreadPtr()->GetIndexID());
3397
3398 auto result = cur_hook_sp->HandleStop(exc_ctx, output_sp);
3399 switch (result) {
3401 if (cur_hook_sp->GetAutoContinue())
3402 requested_continue = true;
3403 else
3404 should_stop = true;
3405 break;
3407 requested_continue = true;
3408 break;
3410 // Do nothing
3411 break;
3413 // We don't have a good way to prohibit people from restarting the
3414 // target willy nilly in a stop hook. If the hook did so, give a
3415 // gentle suggestion here and back out of the hook processing.
3416 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3417 " set the program running.\n"
3418 " Consider using '-G true' to make "
3419 "stop hooks auto-continue.\n",
3420 cur_hook_sp->GetID());
3421 // FIXME: if we are doing non-stop mode for real, we would have to
3422 // check that OUR thread was restarted, otherwise we should keep
3423 // processing stop hooks.
3424 return true;
3425 }
3426 }
3427 }
3428
3429 // Run unified hooks that fire on process stop.
3430 for (auto cur_hook_sp : active_unified_hooks) {
3431 bool any_thread_matched = false;
3432 for (auto exc_ctx : exc_ctx_with_reasons) {
3433 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
3434 continue;
3435
3436 bool suppress_output = cur_hook_sp->GetSuppressOutput();
3437 if (print_hook_header && !any_thread_matched && !suppress_output) {
3438 StreamString s;
3439 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
3440 if (s.GetSize() != 0)
3441 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
3442 s.GetData());
3443 else
3444 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
3445 any_thread_matched = true;
3446 }
3447
3448 if (print_thread_header && !suppress_output)
3449 output_sp->Printf("-- Thread %d\n",
3450 exc_ctx.GetThreadPtr()->GetIndexID());
3451
3452 auto result = cur_hook_sp->HandleStop(exc_ctx, output_sp);
3453 switch (result) {
3455 if (cur_hook_sp->GetAutoContinue())
3456 requested_continue = true;
3457 else
3458 should_stop = true;
3459 break;
3461 requested_continue = true;
3462 break;
3464 break;
3466 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3467 " set the program running.\n"
3468 " Consider using '-G true' to make "
3469 "stop hooks auto-continue.\n",
3470 cur_hook_sp->GetID());
3471 return true;
3472 }
3473 }
3474 }
3475
3476 // Resume iff at least one hook requested to continue and no hook asked to
3477 // stop.
3478 if (requested_continue && !should_stop) {
3479 Log *log = GetLog(LLDBLog::Process);
3480 Status error = m_process_sp->PrivateResume();
3481 if (error.Success()) {
3482 LLDB_LOG(log, "Resuming from RunStopHooks");
3483 return true;
3484 } else {
3485 LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
3486 return false;
3487 }
3488 }
3489
3490 return false;
3491}
3492
3494 // NOTE: intentional leak so we don't crash if global destructor chain gets
3495 // called as other threads still use the result of this function
3496 static TargetProperties *g_settings_ptr =
3497 new TargetProperties(nullptr);
3498 return *g_settings_ptr;
3499}
3500
3502 Status error;
3503 PlatformSP platform_sp(GetPlatform());
3504 if (!platform_sp || !platform_sp->IsRemote() || !platform_sp->IsConnected())
3505 return error;
3506
3507 // Install all files that have an install path when connected to a
3508 // remote platform. If target.auto-install-main-executable is set then
3509 // also install the main executable even if it does not have an explicit
3510 // install path specified.
3511
3512 for (auto module_sp : GetImages().Modules()) {
3513 if (module_sp == GetExecutableModule()) {
3514 MainExecutableInstaller installer{platform_sp, module_sp,
3515 shared_from_this(), *launch_info};
3516 error = installExecutable(installer);
3517 } else {
3518 ExecutableInstaller installer{platform_sp, module_sp};
3519 error = installExecutable(installer);
3520 }
3521
3522 if (error.Fail())
3523 return error;
3524 }
3525
3526 return error;
3527}
3528
3530 uint32_t stop_id, bool allow_section_end) {
3531 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr,
3532 allow_section_end);
3533}
3534
3536 Address &resolved_addr) {
3537 return m_images.ResolveFileAddress(file_addr, resolved_addr);
3538}
3539
3541 addr_t new_section_load_addr,
3542 bool warn_multiple) {
3543 const addr_t old_section_load_addr =
3544 m_section_load_history.GetSectionLoadAddress(
3545 SectionLoadHistory::eStopIDNow, section_sp);
3546 if (old_section_load_addr != new_section_load_addr) {
3547 uint32_t stop_id = 0;
3548 ProcessSP process_sp(GetProcessSP());
3549 if (process_sp)
3550 stop_id = process_sp->GetStopID();
3551 else
3552 stop_id = m_section_load_history.GetLastStopID();
3553 if (m_section_load_history.SetSectionLoadAddress(
3554 stop_id, section_sp, new_section_load_addr, warn_multiple))
3555 return true; // Return true if the section load address was changed...
3556 }
3557 return false; // Return false to indicate nothing changed
3558}
3559
3560size_t Target::UnloadModuleSections(const ModuleList &module_list) {
3561 size_t section_unload_count = 0;
3562 size_t num_modules = module_list.GetSize();
3563 for (size_t i = 0; i < num_modules; ++i) {
3564 section_unload_count +=
3565 UnloadModuleSections(module_list.GetModuleAtIndex(i));
3566 }
3567 return section_unload_count;
3568}
3569
3571 uint32_t stop_id = 0;
3572 ProcessSP process_sp(GetProcessSP());
3573 if (process_sp)
3574 stop_id = process_sp->GetStopID();
3575 else
3576 stop_id = m_section_load_history.GetLastStopID();
3577 SectionList *sections = module_sp->GetSectionList();
3578 size_t section_unload_count = 0;
3579 if (sections) {
3580 const uint32_t num_sections = sections->GetNumSections(0);
3581 for (uint32_t i = 0; i < num_sections; ++i) {
3582 section_unload_count += m_section_load_history.SetSectionUnloaded(
3583 stop_id, sections->GetSectionAtIndex(i));
3584 }
3585 }
3586 return section_unload_count;
3587}
3588
3590 uint32_t stop_id = 0;
3591 ProcessSP process_sp(GetProcessSP());
3592 if (process_sp)
3593 stop_id = process_sp->GetStopID();
3594 else
3595 stop_id = m_section_load_history.GetLastStopID();
3596 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
3597}
3598
3600 addr_t load_addr) {
3601 uint32_t stop_id = 0;
3602 ProcessSP process_sp(GetProcessSP());
3603 if (process_sp)
3604 stop_id = process_sp->GetStopID();
3605 else
3606 stop_id = m_section_load_history.GetLastStopID();
3607 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
3608 load_addr);
3609}
3610
3612
3614 lldb_private::TypeSummaryImpl &summary_provider) {
3615 return m_summary_statistics_cache.GetSummaryStatisticsForProvider(
3616 summary_provider);
3617}
3618
3622
3624 if (process_info.IsScriptedProcess()) {
3625 // Only copy scripted process launch options.
3626 ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>(
3628 default_launch_info.SetProcessPluginName("ScriptedProcess");
3629 default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata());
3630 SetProcessLaunchInfo(default_launch_info);
3631 }
3632}
3633
3635 m_stats.SetLaunchOrAttachTime();
3636 Status error;
3637 Log *log = GetLog(LLDBLog::Target);
3638
3639 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
3640 launch_info.GetExecutableFile().GetPath().c_str());
3641
3642 StateType state = eStateInvalid;
3643
3644 // Scope to temporarily get the process state in case someone has manually
3645 // remotely connected already to a process and we can skip the platform
3646 // launching.
3647 {
3648 ProcessSP process_sp(GetProcessSP());
3649
3650 if (process_sp) {
3651 state = process_sp->GetState();
3652 LLDB_LOGF(log,
3653 "Target::%s the process exists, and its current state is %s",
3654 __FUNCTION__, StateAsCString(state));
3655 } else {
3656 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
3657 __FUNCTION__);
3658 }
3659 }
3660
3661 launch_info.GetFlags().Set(eLaunchFlagDebug);
3662
3663 SaveScriptedLaunchInfo(launch_info);
3664
3665 // Get the value of synchronous execution here. If you wait till after you
3666 // have started to run, then you could have hit a breakpoint, whose command
3667 // might switch the value, and then you'll pick up that incorrect value.
3668 Debugger &debugger = GetDebugger();
3669 const bool synchronous_execution =
3671
3672 PlatformSP platform_sp(GetPlatform());
3673
3674 FinalizeFileActions(launch_info);
3675
3676 if (state == eStateConnected) {
3677 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY))
3679 "can't launch in tty when launching through a remote connection");
3680 }
3681
3682 if (!launch_info.GetArchitecture().IsValid())
3683 launch_info.GetArchitecture() = GetArchitecture();
3684
3685 // Hijacking events of the process to be created to be sure that all events
3686 // until the first stop are intercepted (in case if platform doesn't define
3687 // its own hijacking listener or if the process is created by the target
3688 // manually, without the platform).
3689 if (!launch_info.GetHijackListener())
3690 launch_info.SetHijackListener(
3692
3693 // If we're not already connected to the process, and if we have a platform
3694 // that can launch a process for debugging, go ahead and do that here.
3695 if (state != eStateConnected && platform_sp &&
3696 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) {
3697 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
3698 __FUNCTION__);
3699
3700 // If there was a previous process, delete it before we make the new one.
3701 // One subtle point, we delete the process before we release the reference
3702 // to m_process_sp. That way even if we are the last owner, the process
3703 // will get Finalized before it gets destroyed.
3705
3706 m_process_sp =
3707 GetPlatform()->DebugProcess(launch_info, debugger, *this, error);
3708
3709 } else {
3710 LLDB_LOGF(log,
3711 "Target::%s the platform doesn't know how to debug a "
3712 "process, getting a process plugin to do this for us.",
3713 __FUNCTION__);
3714
3715 if (state == eStateConnected) {
3716 assert(m_process_sp);
3717 } else {
3718 // Use a Process plugin to construct the process.
3719 CreateProcess(launch_info.GetListener(),
3720 launch_info.GetProcessPluginName(), nullptr, false);
3721 }
3722
3723 // Since we didn't have a platform launch the process, launch it here.
3724 if (m_process_sp) {
3725 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener());
3726 m_process_sp->SetShadowListener(launch_info.GetShadowListener());
3727 error = m_process_sp->Launch(launch_info);
3728 }
3729 }
3730
3731 if (!error.Success())
3732 return error;
3733
3734 if (!m_process_sp)
3735 return Status::FromErrorString("failed to launch or debug process");
3736
3737 bool rebroadcast_first_stop =
3738 !synchronous_execution &&
3739 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry);
3740
3741 assert(launch_info.GetHijackListener());
3742
3743 EventSP first_stop_event_sp;
3744 state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp,
3745 rebroadcast_first_stop,
3746 launch_info.GetHijackListener());
3747 m_process_sp->RestoreProcessEvents();
3748
3749 if (rebroadcast_first_stop) {
3750 // We don't need to run the stop hooks by hand here, they will get
3751 // triggered when this rebroadcast event gets fetched.
3752 assert(first_stop_event_sp);
3753 m_process_sp->BroadcastEvent(first_stop_event_sp);
3754 return error;
3755 }
3756 // Run the stop hooks that want to run at entry.
3757 RunStopHooks(true /* at entry point */);
3758
3759 switch (state) {
3760 case eStateStopped: {
3761 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3762 break;
3763 if (synchronous_execution)
3764 // Now we have handled the stop-from-attach, and we are just
3765 // switching to a synchronous resume. So we should switch to the
3766 // SyncResume hijacker.
3767 m_process_sp->ResumeSynchronous(stream);
3768 else
3769 error = m_process_sp->Resume();
3770 if (!error.Success()) {
3772 "process resume at entry point failed: %s", error.AsCString());
3773 }
3774 } break;
3775 case eStateExited: {
3776 bool with_shell = !!launch_info.GetShell();
3777 const int exit_status = m_process_sp->GetExitStatus();
3778 const char *exit_desc = m_process_sp->GetExitDescription();
3779 std::string desc;
3780 if (exit_desc && exit_desc[0])
3781 desc = " (" + std::string(exit_desc) + ')';
3782 if (with_shell)
3784 "process exited with status %i%s\n"
3785 "'r' and 'run' are aliases that default to launching through a "
3786 "shell.\n"
3787 "Try launching without going through a shell by using "
3788 "'process launch'.",
3789 exit_status, desc.c_str());
3790 else
3792 "process exited with status %i%s", exit_status, desc.c_str());
3793 } break;
3794 default:
3796 "initial process state wasn't stopped: %s", StateAsCString(state));
3797 break;
3798 }
3799 return error;
3800}
3801
3802void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3803
3805
3806llvm::Expected<TraceSP> Target::CreateTrace() {
3807 if (!m_process_sp)
3808 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3809 "A process is required for tracing");
3810 if (m_trace_sp)
3811 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3812 "A trace already exists for the target");
3813
3814 llvm::Expected<TraceSupportedResponse> trace_type =
3815 m_process_sp->TraceSupported();
3816 if (!trace_type)
3817 return llvm::createStringError(
3818 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3819 llvm::toString(trace_type.takeError()).c_str());
3820 if (llvm::Expected<TraceSP> trace_sp =
3822 m_trace_sp = *trace_sp;
3823 else
3824 return llvm::createStringError(
3825 llvm::inconvertibleErrorCode(),
3826 "Couldn't create a Trace object for the process. %s",
3827 llvm::toString(trace_sp.takeError()).c_str());
3828 return m_trace_sp;
3829}
3830
3831llvm::Expected<TraceSP> Target::GetTraceOrCreate() {
3832 if (m_trace_sp)
3833 return m_trace_sp;
3834 return CreateTrace();
3835}
3836
3838 Progress attach_progress("Waiting to attach to process");
3839 m_stats.SetLaunchOrAttachTime();
3840 auto state = eStateInvalid;
3841 auto process_sp = GetProcessSP();
3842 if (process_sp) {
3843 state = process_sp->GetState();
3844 if (process_sp->IsAlive() && state != eStateConnected) {
3845 if (state == eStateAttaching)
3846 return Status::FromErrorString("process attach is in progress");
3847 return Status::FromErrorString("a process is already being debugged");
3848 }
3849 }
3850
3851 const ModuleSP old_exec_module_sp = GetExecutableModule();
3852
3853 // If no process info was specified, then use the target executable name as
3854 // the process to attach to by default
3855 if (!attach_info.ProcessInfoSpecified()) {
3856 if (old_exec_module_sp)
3857 attach_info.GetExecutableFile().SetFilename(
3858 old_exec_module_sp->GetPlatformFileSpec().GetFilename());
3859
3860 if (!attach_info.ProcessInfoSpecified()) {
3862 "no process specified, create a target with a file, or "
3863 "specify the --pid or --name");
3864 }
3865 }
3866
3867 const auto platform_sp =
3869 ListenerSP hijack_listener_sp;
3870 const bool async = attach_info.GetAsync();
3871 if (!async) {
3872 hijack_listener_sp =
3874 attach_info.SetHijackListener(hijack_listener_sp);
3875 }
3876
3877 Status error;
3878 if (state != eStateConnected && platform_sp != nullptr &&
3879 platform_sp->CanDebugProcess() && !attach_info.IsScriptedProcess()) {
3880 SetPlatform(platform_sp);
3881 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3882 } else {
3883 if (state != eStateConnected) {
3884 SaveScriptedLaunchInfo(attach_info);
3885 llvm::StringRef plugin_name = attach_info.GetProcessPluginName();
3886 process_sp =
3888 plugin_name, nullptr, false);
3889 if (!process_sp) {
3891 "failed to create process using plugin '{0}'",
3892 plugin_name.empty() ? "<empty>" : plugin_name);
3893 return error;
3894 }
3895 }
3896 if (hijack_listener_sp)
3897 process_sp->HijackProcessEvents(hijack_listener_sp);
3898 error = process_sp->Attach(attach_info);
3899 }
3900
3901 if (error.Success() && process_sp) {
3902 if (async) {
3903 process_sp->RestoreProcessEvents();
3904 } else {
3905 // We are stopping all the way out to the user, so update selected frames.
3906 state = process_sp->WaitForProcessToStop(
3907 std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
3909 process_sp->RestoreProcessEvents();
3910
3911 // Run the stop hooks here. Since we were hijacking the events, they
3912 // wouldn't have gotten run as part of event delivery.
3913 RunStopHooks(/* at_initial_stop= */ true);
3914
3915 if (state != eStateStopped) {
3916 const char *exit_desc = process_sp->GetExitDescription();
3917 if (exit_desc)
3918 error = Status::FromErrorStringWithFormat("%s", exit_desc);
3919 else
3921 "process did not stop (no such process or permission problem?)");
3922 process_sp->Destroy(false);
3923 }
3924 }
3925 }
3926 return error;
3927}
3928
3930 const ScriptedFrameProviderDescriptor &descriptor) {
3931 if (!descriptor.IsValid())
3932 return llvm::createStringError("invalid frame provider descriptor");
3933
3934 llvm::StringRef name = descriptor.GetName();
3935 if (name.empty())
3936 return llvm::createStringError(
3937 "frame provider descriptor has no class name");
3938
3939 {
3940 std::unique_lock<std::recursive_mutex> guard(
3942
3943 // Check for duplicate: same class name and args (content hash).
3944 uint32_t descriptor_hash = descriptor.GetHash();
3945 for (const auto &entry : m_frame_provider_descriptors) {
3946 if (entry.second.GetHash() == descriptor_hash)
3948 llvm::formatv("frame provider idx={0} with the same class name and "
3949 "arguments is already registered",
3950 entry.second.GetID())
3951 .str());
3952 }
3953
3954 uint32_t descriptor_id = m_next_frame_provider_id++;
3955 ScriptedFrameProviderDescriptor new_descriptor = descriptor;
3956 new_descriptor.SetID(descriptor_id);
3957 m_frame_provider_descriptors[descriptor_id] = new_descriptor;
3958
3960
3961 return descriptor_id;
3962 }
3963}
3964
3966 bool removed = false;
3967 {
3968 std::lock_guard<std::recursive_mutex> guard(
3970 removed = m_frame_provider_descriptors.erase(id);
3971 }
3972
3973 if (removed)
3975 return removed;
3976}
3977
3979 {
3980 std::lock_guard<std::recursive_mutex> guard(
3984 }
3985
3987}
3988
3989const llvm::MapVector<uint32_t, ScriptedFrameProviderDescriptor> &
3991 std::lock_guard<std::recursive_mutex> guard(
3994}
3995
3997 ProcessSP process_sp = GetProcessSP();
3998 if (!process_sp)
3999 return;
4000 for (ThreadSP thread_sp : process_sp->Threads()) {
4001 // Clear frame providers on existing threads so they reload with new config.
4002 thread_sp->ClearScriptedFrameProvider();
4003 // Notify threads that the stack traces might have changed.
4004 if (thread_sp->EventTypeHasListeners(Thread::eBroadcastBitStackChanged)) {
4005 auto data_sp = std::make_shared<Thread::ThreadEventData>(thread_sp);
4006 thread_sp->BroadcastEvent(Thread::eBroadcastBitStackChanged, data_sp);
4007 }
4008 }
4009}
4010
4012 Log *log = GetLog(LLDBLog::Process);
4013
4014 // Finalize the file actions, and if none were given, default to opening up a
4015 // pseudo terminal
4016 PlatformSP platform_sp = GetPlatform();
4017 const bool default_to_use_pty =
4018 m_platform_sp ? m_platform_sp->IsHost() : false;
4019 LLDB_LOG(
4020 log,
4021 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
4022 bool(platform_sp),
4023 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
4024 default_to_use_pty);
4025
4026 // If nothing for stdin or stdout or stderr was specified, then check the
4027 // process for any default settings that were set with "settings set"
4028 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
4029 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
4030 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
4031 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
4032 "default handling");
4033
4034 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
4035 // Do nothing, if we are launching in a remote terminal no file actions
4036 // should be done at all.
4037 return;
4038 }
4039
4040 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
4041 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
4042 "for stdin, stdout and stderr");
4043 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
4044 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
4045 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
4046 } else {
4047 // Check for any values that might have gotten set with any of: (lldb)
4048 // settings set target.input-path (lldb) settings set target.output-path
4049 // (lldb) settings set target.error-path
4050 FileSpec in_file_spec;
4051 FileSpec out_file_spec;
4052 FileSpec err_file_spec;
4053 // Only override with the target settings if we don't already have an
4054 // action for in, out or error
4055 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
4056 in_file_spec = GetStandardInputPath();
4057 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
4058 out_file_spec = GetStandardOutputPath();
4059 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
4060 err_file_spec = GetStandardErrorPath();
4061
4062 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{2}'",
4063 in_file_spec, out_file_spec, err_file_spec);
4064
4065 if (in_file_spec) {
4066 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
4067 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
4068 }
4069
4070 if (out_file_spec) {
4071 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
4072 LLDB_LOG(log, "appended stdout open file action for {0}",
4073 out_file_spec);
4074 }
4075
4076 if (err_file_spec) {
4077 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
4078 LLDB_LOG(log, "appended stderr open file action for {0}",
4079 err_file_spec);
4080 }
4081
4082 if (default_to_use_pty) {
4083#ifdef _WIN32
4084 if (info.GetFlags().Test(eLaunchFlagUsePipes) ||
4085 ::getenv("LLDB_LAUNCH_FLAG_USE_PIPES")) {
4086 llvm::Error Err = info.SetUpPipeRedirection();
4087 LLDB_LOG_ERROR(log, std::move(Err),
4088 "SetUpPipeRedirection failed: {0}");
4089 } else {
4090#endif
4091 llvm::Error Err = info.SetUpPtyRedirection();
4092 LLDB_LOG_ERROR(log, std::move(Err),
4093 "SetUpPtyRedirection failed: {0}");
4094#ifdef _WIN32
4095 }
4096#endif
4097 }
4098 }
4099 }
4100}
4101
4102void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify,
4103 LazyBool stop) {
4104 if (name.empty())
4105 return;
4106 // Don't add a signal if all the actions are trivial:
4107 if (pass == eLazyBoolCalculate && notify == eLazyBoolCalculate
4108 && stop == eLazyBoolCalculate)
4109 return;
4110
4111 auto& elem = m_dummy_signals[name];
4112 elem.pass = pass;
4113 elem.notify = notify;
4114 elem.stop = stop;
4115}
4116
4118 const DummySignalElement &elem) {
4119 if (!signals_sp)
4120 return false;
4121
4122 int32_t signo
4123 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
4124 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
4125 return false;
4126
4127 if (elem.second.pass == eLazyBoolYes)
4128 signals_sp->SetShouldSuppress(signo, false);
4129 else if (elem.second.pass == eLazyBoolNo)
4130 signals_sp->SetShouldSuppress(signo, true);
4131
4132 if (elem.second.notify == eLazyBoolYes)
4133 signals_sp->SetShouldNotify(signo, true);
4134 else if (elem.second.notify == eLazyBoolNo)
4135 signals_sp->SetShouldNotify(signo, false);
4136
4137 if (elem.second.stop == eLazyBoolYes)
4138 signals_sp->SetShouldStop(signo, true);
4139 else if (elem.second.stop == eLazyBoolNo)
4140 signals_sp->SetShouldStop(signo, false);
4141 return true;
4142}
4143
4145 const DummySignalElement &elem) {
4146 if (!signals_sp)
4147 return false;
4148 int32_t signo
4149 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
4150 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
4151 return false;
4152 bool do_pass = elem.second.pass != eLazyBoolCalculate;
4153 bool do_stop = elem.second.stop != eLazyBoolCalculate;
4154 bool do_notify = elem.second.notify != eLazyBoolCalculate;
4155 signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass);
4156 return true;
4157}
4158
4160 StreamSP warning_stream_sp) {
4161 if (!signals_sp)
4162 return;
4163
4164 for (const auto &elem : m_dummy_signals) {
4165 if (!UpdateSignalFromDummy(signals_sp, elem))
4166 warning_stream_sp->Printf("Target signal '%s' not found in process\n",
4167 elem.first().str().c_str());
4168 }
4169}
4170
4171void Target::ClearDummySignals(Args &signal_names) {
4172 ProcessSP process_sp = GetProcessSP();
4173 // The simplest case, delete them all with no process to update.
4174 if (signal_names.GetArgumentCount() == 0 && !process_sp) {
4175 m_dummy_signals.clear();
4176 return;
4177 }
4178 UnixSignalsSP signals_sp;
4179 if (process_sp)
4180 signals_sp = process_sp->GetUnixSignals();
4181
4182 for (const Args::ArgEntry &entry : signal_names) {
4183 const char *signal_name = entry.c_str();
4184 auto elem = m_dummy_signals.find(signal_name);
4185 // If we didn't find it go on.
4186 // FIXME: Should I pipe error handling through here?
4187 if (elem == m_dummy_signals.end()) {
4188 continue;
4189 }
4190 if (signals_sp)
4191 ResetSignalFromDummy(signals_sp, *elem);
4192 m_dummy_signals.erase(elem);
4193 }
4194}
4195
4196void Target::PrintDummySignals(Stream &strm, Args &signal_args) {
4197 strm.PutCString("NAME PASS STOP NOTIFY\n");
4198 strm.PutCString("=========== ======= ======= =======\n");
4199
4200 auto str_for_lazy = [] (LazyBool lazy) -> const char * {
4201 switch (lazy) {
4202 case eLazyBoolCalculate: return "not set";
4203 case eLazyBoolYes: return "true ";
4204 case eLazyBoolNo: return "false ";
4205 }
4206 llvm_unreachable("Fully covered switch above!");
4207 };
4208 size_t num_args = signal_args.GetArgumentCount();
4209 for (const auto &elem : m_dummy_signals) {
4210 bool print_it = false;
4211 for (size_t idx = 0; idx < num_args; idx++) {
4212 if (elem.first() == signal_args.GetArgumentAtIndex(idx)) {
4213 print_it = true;
4214 break;
4215 }
4216 }
4217 if (print_it) {
4218 strm.Printf("%-11s ", elem.first().str().c_str());
4219 strm.Printf("%s %s %s\n", str_for_lazy(elem.second.pass),
4220 str_for_lazy(elem.second.stop),
4221 str_for_lazy(elem.second.notify));
4222 }
4223 }
4224}
4225
4226// Target::StopHook
4230
4232 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
4235 if (rhs.m_thread_spec_up)
4236 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
4237}
4238
4240 m_specifier_sp.reset(specifier);
4241}
4242
4244 m_thread_spec_up.reset(specifier);
4245}
4246
4248 SymbolContextSpecifier *specifier = GetSpecifier();
4249 if (!specifier)
4250 return true;
4251
4252 bool will_run = true;
4253 if (exc_ctx.GetFramePtr())
4254 will_run = GetSpecifier()->SymbolContextMatches(
4255 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
4256 if (will_run && GetThreadSpecifier() != nullptr)
4257 will_run =
4258 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
4259
4260 return will_run;
4261}
4262
4264 lldb::DescriptionLevel level) const {
4265
4266 // For brief descriptions, only print the subclass description:
4267 if (level == eDescriptionLevelBrief) {
4268 GetSubclassDescription(s, level);
4269 return;
4270 }
4271
4272 auto indent_scope = s.MakeIndentScope();
4273
4274 s.Printf("Hook: %" PRIu64 "\n", GetID());
4275 if (m_active)
4276 s.Indent("State: enabled\n");
4277 else
4278 s.Indent("State: disabled\n");
4279
4280 if (m_auto_continue)
4281 s.Indent("AutoContinue on\n");
4282
4283 if (m_specifier_sp) {
4284 s.Indent();
4285 s.PutCString("Specifier:\n");
4286 auto indent_scope = s.MakeIndentScope();
4287 m_specifier_sp->GetDescription(&s, level);
4288 }
4289
4290 if (m_thread_spec_up) {
4291 StreamString tmp;
4292 s.Indent("Thread:\n");
4293 m_thread_spec_up->GetDescription(&tmp, level);
4294 auto indent_scope = s.MakeIndentScope();
4295 s.Indent(tmp.GetString());
4296 s.PutCString("\n");
4297 }
4298 GetSubclassDescription(s, level);
4299}
4300
4302 Stream &s, lldb::DescriptionLevel level) const {
4303 // The brief description just prints the first command.
4304 if (level == eDescriptionLevelBrief) {
4305 if (m_commands.GetSize() == 1)
4306 s.PutCString(m_commands.GetStringAtIndex(0));
4307 return;
4308 }
4309 s.Indent("Commands:\n");
4310 auto indent_scope = s.MakeIndentScope(4);
4311 uint32_t num_commands = m_commands.GetSize();
4312 for (uint32_t i = 0; i < num_commands; i++) {
4313 s.Indent(m_commands.GetStringAtIndex(i));
4314 s.PutCString("\n");
4315 }
4316}
4317
4318// Target::StopHookCommandLine
4320 GetCommands().SplitIntoLines(string);
4321}
4322
4324 const std::vector<std::string> &strings) {
4325 for (auto string : strings)
4326 GetCommands().AppendString(string.c_str());
4327}
4328
4331 StreamSP output_sp) {
4332 assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
4333 "with no target");
4334
4335 if (!m_commands.GetSize())
4337
4338 CommandReturnObject result(false);
4339 result.SetImmediateOutputStream(output_sp);
4340 result.SetImmediateErrorStream(output_sp);
4341 result.SetInteractive(false);
4342 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
4344 options.SetStopOnContinue(true);
4345 options.SetStopOnError(true);
4346 options.SetEchoCommands(false);
4347 options.SetPrintResults(true);
4348 options.SetPrintErrors(true);
4349 options.SetAddToHistory(false);
4350
4351 // Force Async:
4352 bool old_async = debugger.GetAsyncExecution();
4353 debugger.SetAsyncExecution(true);
4354 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
4355 options, result);
4356 debugger.SetAsyncExecution(old_async);
4357 lldb::ReturnStatus status = result.GetStatus();
4362}
4363
4364// Target::StopHookScripted
4366 const ScriptedMetadata &scripted_metadata) {
4367 Status error;
4368
4369 ScriptInterpreter *script_interp =
4370 GetTarget()->GetDebugger().GetScriptInterpreter();
4371 if (!script_interp) {
4372 error = Status::FromErrorString("No script interpreter installed.");
4373 return error;
4374 }
4375
4377 if (!m_interface_sp) {
4379 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__,
4380 "Script interpreter couldn't create Scripted Stop Hook Interface");
4381 return error;
4382 }
4383
4384 auto obj_or_err =
4385 m_interface_sp->CreatePluginObject(scripted_metadata, GetTarget());
4386 if (!obj_or_err) {
4387 return Status::FromError(obj_or_err.takeError());
4388 }
4389
4390 StructuredData::ObjectSP object_sp = *obj_or_err;
4391 if (!object_sp || !object_sp->IsValid()) {
4393 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__,
4394 "Failed to create valid script object");
4395 return error;
4396 }
4397
4398 return {};
4399}
4400
4401/// Hook callbacks have no caller to return an error to, so report a failure
4402/// as a debugger diagnostic. \a what names the hook, e.g. "stop hook 1".
4403static void ReportScriptedHookError(llvm::Error error, llvm::StringRef what,
4404 Debugger &debugger) {
4405 if (!error)
4406 return;
4407
4409 llvm::formatv("{0} failed: {1}", what, llvm::toString(std::move(error)))
4410 .str(),
4411 debugger.GetID());
4412}
4413
4416 StreamSP output_sp) {
4417 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
4418 "with no target");
4419
4420 if (!m_interface_sp)
4422
4423 lldb::StreamSP stream = std::make_shared<lldb_private::StreamString>();
4424 auto should_stop_or_err = m_interface_sp->HandleStop(exc_ctx, stream);
4425 output_sp->PutCString(
4426 reinterpret_cast<StreamString *>(stream.get())->GetData());
4427 if (!should_stop_or_err) {
4428 ReportScriptedHookError(should_stop_or_err.takeError(),
4429 llvm::formatv("stop hook {0}", GetID()).str(),
4430 exc_ctx.GetTargetPtr()->GetDebugger());
4432 }
4433
4434 return *should_stop_or_err ? StopHookResult::KeepStopped
4436}
4437
4439 if (m_interface_sp && m_interface_sp->GetScriptedMetadata())
4440 return m_interface_sp->GetScriptedMetadata()->GetClassName();
4441 return "<unknown>";
4442}
4443
4445 Stream &s, lldb::DescriptionLevel level) const {
4446 llvm::StringRef class_name = GetScriptClassName();
4447 if (level == eDescriptionLevelBrief) {
4448 s.PutCString(class_name);
4449 return;
4450 }
4451 s.Indent("Class:");
4452 s.Format("{0}\n", class_name);
4453
4454 // Now print the extra args:
4455 // FIXME: We should use StructuredData.GetDescription on the args dict
4456 // but that seems to rely on some printing plugin that doesn't exist.
4458 (m_interface_sp && m_interface_sp->GetScriptedMetadata())
4459 ? m_interface_sp->GetScriptedMetadata()->GetArgsSP()
4460 : nullptr;
4461 if (!as_dict || !as_dict->IsValid())
4462 return;
4463
4464 uint32_t num_keys = as_dict->GetSize();
4465 if (num_keys == 0)
4466 return;
4467
4468 s.Indent("Args:\n");
4469 auto indent_scope = s.MakeIndentScope(4);
4470
4471 auto print_one_element = [&s](llvm::StringRef key,
4472 StructuredData::Object *object) {
4473 s.Indent();
4474 s.Format("{0} : {1}\n", key, object->GetStringValue());
4475 return true;
4476 };
4477
4478 as_dict->ForEach(print_one_element);
4479}
4480
4481// Hook
4482
4484 : UserID(uid), m_target_sp(std::move(target_sp)), m_kind(kind) {}
4485
4496
4498 m_sc_specifier_sp.reset(specifier);
4499}
4500
4502 m_thread_spec_up.reset(specifier);
4503}
4504
4507 if (!specifier)
4508 return true;
4509
4510 bool will_run = true;
4511 if (exc_ctx.GetFramePtr())
4512 will_run = specifier->SymbolContextMatches(
4513 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
4514 if (will_run && GetThreadSpecifier() != nullptr)
4515 will_run =
4516 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
4517
4518 return will_run;
4519}
4520
4522 lldb::DescriptionLevel level) const {
4523 s.Printf("Hook: %" PRIu64 "\n", GetID());
4524 if (level == eDescriptionLevelBrief)
4525 return;
4526 s.IndentMore();
4527 s.Indent();
4528 s.Printf("State: %s\n", m_enabled ? "enabled" : "disabled");
4529
4530 {
4531 std::string fires_on;
4533 fires_on += "load";
4535 if (!fires_on.empty())
4536 fires_on += ", ";
4537 fires_on += "unload";
4538 }
4540 if (!fires_on.empty())
4541 fires_on += ", ";
4542 fires_on += "stop";
4543 }
4544 if (!fires_on.empty()) {
4545 s.Indent();
4546 s.Printf("Triggers: %s\n", fires_on.c_str());
4547 }
4548 }
4549 // Subclasses add their content (commands or class) then call
4550 // GetFilterDescription to print filters.
4551 s.IndentLess();
4552}
4553
4555 lldb::DescriptionLevel level) const {
4556 s.IndentMore();
4557
4558 if (m_auto_continue)
4559 s.Indent("AutoContinue on\n");
4560
4561 if (m_sc_specifier_sp) {
4562 s.Indent();
4563 s.PutCString("Specifier:\n");
4564 s.IndentMore();
4565 m_sc_specifier_sp->GetDescription(&s, level);
4566 s.IndentLess();
4567 }
4568
4569 if (m_thread_spec_up) {
4570 StreamString tmp;
4571 s.Indent("Thread:\n");
4572 m_thread_spec_up->GetDescription(&tmp, level);
4573 s.IndentMore();
4574 s.Indent(tmp.GetString());
4575 s.PutCString("\n");
4576 s.IndentLess();
4577 }
4578
4579 s.IndentLess();
4580}
4581
4583 Stream &s, lldb::DescriptionLevel level) const {
4584 Hook::GetDescription(s, level);
4585 if (level == eDescriptionLevelBrief) {
4586 if (m_commands.GetSize() == 1)
4587 s.PutCString(m_commands.GetStringAtIndex(0));
4588 else
4589 s.Printf("%" PRIu64 " commands", (uint64_t)m_commands.GetSize());
4590 return;
4591 }
4592
4593 // Commands come after the header (ID, State, Triggers) but before filters.
4594 s.IndentMore();
4595 s.Indent("Commands: \n");
4596 s.IndentMore();
4597 for (uint32_t i = 0; i < m_commands.GetSize(); i++) {
4598 s.Indent(m_commands.GetStringAtIndex(i));
4599 s.PutCString("\n");
4600 }
4601 s.IndentLess();
4602 s.IndentLess();
4603
4604 GetFilterDescription(s, level);
4605}
4606
4607// HookCommandLine
4608
4609void Target::HookCommandLine::SetActionFromString(const std::string &string) {
4610 GetCommands().SplitIntoLines(string);
4611}
4612
4614 const std::vector<std::string> &strings) {
4615 for (const auto &string : strings)
4616 GetCommands().AppendString(string.c_str());
4617}
4618
4620 if (!m_commands.GetSize())
4621 return;
4622
4623 TargetSP target_sp = GetTarget();
4624 if (!target_sp)
4625 return;
4626
4627 CommandReturnObject result(false);
4628 result.SetImmediateOutputStream(output_sp);
4629 result.SetInteractive(false);
4630 Debugger &debugger = target_sp->GetDebugger();
4631
4632 ExecutionContext exe_ctx;
4633 if (target_sp->GetProcessSP())
4634 exe_ctx.SetContext(target_sp->GetProcessSP());
4635 else
4636 exe_ctx.SetContext(target_sp, false);
4637
4639 options.SetStopOnContinue(true);
4640 options.SetStopOnError(true);
4641 options.SetEchoCommands(false);
4642 options.SetPrintResults(true);
4643 options.SetPrintErrors(true);
4644 options.SetAddToHistory(false);
4645
4646 bool old_async = debugger.GetAsyncExecution();
4647 debugger.SetAsyncExecution(true);
4648 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exe_ctx,
4649 options, result);
4650 debugger.SetAsyncExecution(old_async);
4651}
4652
4654 // Command-based hooks run the same commands on unload as on load.
4655 HandleModuleLoaded(output_sp);
4656}
4657
4660 StreamSP output_sp) {
4661 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
4662 "with no target");
4663
4664 if (!m_commands.GetSize())
4666
4667 CommandReturnObject result(false);
4668 result.SetImmediateOutputStream(output_sp);
4669 result.SetImmediateErrorStream(output_sp);
4670 result.SetInteractive(false);
4671 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
4673 options.SetStopOnContinue(true);
4674 options.SetStopOnError(true);
4675 options.SetEchoCommands(false);
4676 options.SetPrintResults(true);
4677 options.SetPrintErrors(true);
4678 options.SetAddToHistory(false);
4679
4680 bool old_async = debugger.GetAsyncExecution();
4681 debugger.SetAsyncExecution(true);
4682 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
4683 options, result);
4684 debugger.SetAsyncExecution(old_async);
4685 lldb::ReturnStatus status = result.GetStatus();
4690}
4691
4692// HookScripted
4693
4695 const ScriptedMetadata &scripted_metadata) {
4696 ScriptInterpreter *script_interp =
4697 GetTarget()->GetDebugger().GetScriptInterpreter();
4698 if (!script_interp)
4699 return Status::FromErrorString("No script interpreter installed.");
4700
4702 if (!m_interface_sp)
4704 "ScriptedHook::%s () - ERROR: %s", __FUNCTION__,
4705 "Script interpreter couldn't create Scripted Hook Interface");
4706
4707 auto obj_or_err =
4708 m_interface_sp->CreatePluginObject(scripted_metadata, GetTarget());
4709 if (!obj_or_err)
4710 return Status::FromError(obj_or_err.takeError());
4711
4712 StructuredData::ObjectSP object_sp = *obj_or_err;
4713 if (!object_sp || !object_sp->IsValid())
4715 "ScriptedHook::%s () - ERROR: %s", __FUNCTION__,
4716 "Failed to create valid script object");
4717
4718 // Determine which triggers the class supports by checking which callback
4719 // methods it implements.
4720 auto methods = m_interface_sp->GetSupportedMethods();
4721 if (!methods.any())
4723 "hook class implements none of the expected methods "
4724 "(handle_module_loaded, handle_module_unloaded, handle_stop)");
4725
4726 if (methods.handle_module_loaded)
4728 if (methods.handle_module_unloaded)
4730 if (methods.handle_stop)
4732
4733 return {};
4734}
4735
4737 if (!m_interface_sp)
4738 return;
4739
4740 TargetSP target_sp = GetTarget();
4741 if (!target_sp)
4742 return;
4743
4744 StreamSP stream = std::make_shared<StreamString>();
4745 llvm::Error error = m_interface_sp->HandleModuleLoaded(stream);
4746 output_sp->PutCString(static_cast<StreamString *>(stream.get())->GetData());
4747 ReportScriptedHookError(std::move(error),
4748 llvm::formatv("hook {0}", GetID()).str(),
4749 target_sp->GetDebugger());
4750}
4751
4753 if (!m_interface_sp)
4754 return;
4755
4756 TargetSP target_sp = GetTarget();
4757 if (!target_sp)
4758 return;
4759
4760 StreamSP stream = std::make_shared<StreamString>();
4761 llvm::Error error = m_interface_sp->HandleModuleUnloaded(stream);
4762 output_sp->PutCString(static_cast<StreamString *>(stream.get())->GetData());
4763 ReportScriptedHookError(std::move(error),
4764 llvm::formatv("hook {0}", GetID()).str(),
4765 target_sp->GetDebugger());
4766}
4767
4770 StreamSP output_sp) {
4771 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
4772 "with no target");
4773
4774 if (!m_interface_sp)
4776
4777 lldb::StreamSP stream = std::make_shared<lldb_private::StreamString>();
4778 auto should_stop_or_err = m_interface_sp->HandleStop(exc_ctx, stream);
4779 output_sp->PutCString(static_cast<StreamString *>(stream.get())->GetData());
4780 if (!should_stop_or_err) {
4781 ReportScriptedHookError(should_stop_or_err.takeError(),
4782 llvm::formatv("hook {0}", GetID()).str(),
4783 exc_ctx.GetTargetPtr()->GetDebugger());
4785 }
4786
4787 return *should_stop_or_err ? StopHook::StopHookResult::KeepStopped
4789}
4790
4792 if (m_interface_sp && m_interface_sp->GetScriptedMetadata())
4793 return m_interface_sp->GetScriptedMetadata()->GetClassName();
4794 return "<unknown>";
4795}
4796
4798 lldb::DescriptionLevel level) const {
4799 Hook::GetDescription(s, level);
4800 llvm::StringRef class_name = GetScriptClassName();
4801 if (level == eDescriptionLevelBrief) {
4802 s.PutCString(class_name);
4803 return;
4804 }
4805
4806 // Class and args come after the header (ID, State, Triggers) but before
4807 // filters.
4808 s.IndentMore();
4809 s.Indent("Class: ");
4810 s.Format("{0}\n", class_name);
4811
4813 (m_interface_sp && m_interface_sp->GetScriptedMetadata())
4814 ? m_interface_sp->GetScriptedMetadata()->GetArgsSP()
4815 : nullptr;
4816 if (as_dict && as_dict->IsValid() && as_dict->GetSize() > 0) {
4817 s.Indent("Args:\n");
4818 s.IndentMore();
4819
4820 auto print_one_element = [&s](llvm::StringRef key,
4821 StructuredData::Object *object) {
4822 s.Indent();
4823 s.Format("{0} : {1}\n", key, object->GetStringValue());
4824 return true;
4825 };
4826
4827 as_dict->ForEach(print_one_element);
4828 s.IndentLess();
4829 }
4830 s.IndentLess();
4831
4832 GetFilterDescription(s, level);
4833}
4834
4835// Hook management methods
4836
4838 lldb::user_id_t new_uid = ++m_hook_next_id;
4839 HookSP hook_sp;
4840 switch (kind) {
4842 hook_sp.reset(new HookCommandLine(shared_from_this(), new_uid));
4843 break;
4845 hook_sp.reset(new HookScripted(shared_from_this(), new_uid));
4846 break;
4847 }
4848 m_hooks[new_uid] = hook_sp;
4849 return hook_sp;
4850}
4851
4853 if (!RemoveHookByID(uid))
4854 return;
4855 if (uid > 0)
4857}
4858
4860 size_t num_removed = m_hooks.erase(uid);
4861 return (num_removed != 0);
4862}
4863
4865
4867 auto iter = m_hooks.find(uid);
4868 if (iter == m_hooks.end())
4869 return {};
4870 return iter->second;
4871}
4872
4874 if (index >= m_hooks.size())
4875 return {};
4876 auto iter = m_hooks.begin();
4877 std::advance(iter, index);
4878 return iter->second;
4879}
4880
4882 auto iter = m_hooks.find(uid);
4883 if (iter == m_hooks.end())
4884 return false;
4885 iter->second->SetIsEnabled(enabled);
4886 return true;
4887}
4888
4890 for (auto &[_, hook] : m_hooks)
4891 hook->SetIsEnabled(enabled);
4892}
4893
4895 if (m_hooks.empty())
4896 return;
4897
4899
4900 // Copy active hooks into a local vector before iterating, in case a
4901 // callback modifies m_hooks (same pattern as RunStopHooks).
4902 std::vector<HookSP> active_hooks;
4903 for (auto &[_, hook_sp] : m_hooks) {
4904 if (hook_sp->IsEnabled() && hook_sp->FiresOn(trigger))
4905 active_hooks.push_back(hook_sp);
4906 }
4907
4908 if (active_hooks.empty())
4909 return;
4910
4911 StreamSP output_sp = m_debugger.GetAsyncOutputStream();
4912
4913 for (auto &hook_sp : active_hooks) {
4914 if (is_load)
4915 hook_sp->HandleModuleLoaded(output_sp);
4916 else
4917 hook_sp->HandleModuleUnloaded(output_sp);
4918 }
4919
4920 output_sp->Flush();
4921}
4922
4924 {
4926 "no-dynamic-values",
4927 "Don't calculate the dynamic type of values",
4928 },
4929 {
4931 "run-target",
4932 "Calculate the dynamic type of values "
4933 "even if you have to run the target.",
4934 },
4935 {
4937 "no-run-target",
4938 "Calculate the dynamic type of values, but don't run the target.",
4939 },
4940};
4941
4945
4947 {
4949 "never",
4950 "Never look for inline breakpoint locations (fastest). This setting "
4951 "should only be used if you know that no inlining occurs in your"
4952 "programs.",
4953 },
4954 {
4956 "headers",
4957 "Only check for inline breakpoint locations when setting breakpoints "
4958 "in header files, but not when setting breakpoint in implementation "
4959 "source files (default).",
4960 },
4961 {
4963 "always",
4964 "Always look for inline breakpoint locations when setting file and "
4965 "line breakpoints (slower but most accurate).",
4966 },
4967};
4968
4974
4976 {
4978 "default",
4979 "Disassembler default (currently att).",
4980 },
4981 {
4983 "intel",
4984 "Intel disassembler flavor.",
4985 },
4986 {
4988 "att",
4989 "AT&T disassembler flavor.",
4990 },
4991};
4992
4994 {
4996 "mcjit",
4997 "Use LLVM's MCJIT execution engine.",
4998 },
4999 {
5001 "orc",
5002 "Use LLVM's ORC execution engine.",
5003 },
5004};
5005
5007 {
5009 "false",
5010 "Never import the 'std' C++ module in the expression parser.",
5011 },
5012 {
5014 "fallback",
5015 "Retry evaluating expressions with an imported 'std' C++ module if they"
5016 " failed to parse without the module. This allows evaluating more "
5017 "complex expressions involving C++ standard library types."
5018 },
5019 {
5021 "true",
5022 "Always import the 'std' C++ module. This allows evaluating more "
5023 "complex expressions involving C++ standard library types. This feature"
5024 " is experimental."
5025 },
5026};
5027
5028static constexpr OptionEnumValueElement
5030 {
5032 "auto",
5033 "Automatically determine the most appropriate method for the "
5034 "target OS.",
5035 },
5036 {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct",
5037 "Prefer using the realized classes struct."},
5038 {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList",
5039 "Prefer using the CopyRealizedClassList API."},
5040 {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList",
5041 "Prefer using the GetRealizedClassList API."},
5042};
5043
5045 {
5047 "c",
5048 "C-style (0xffff).",
5049 },
5050 {
5052 "asm",
5053 "Asm-style (0ffffh).",
5054 },
5055};
5056
5058 {
5060 "true",
5061 "Load debug scripts inside symbol files",
5062 },
5063 {
5065 "false",
5066 "Do not load debug scripts inside symbol files.",
5067 },
5068 {
5070 "warn",
5071 "Warn about debug scripts inside symbol files but do not load them.",
5072 },
5073 {
5075 "trusted",
5076 "Load debug scripts inside trusted symbol files, and warn about "
5077 "scripts from untrusted symbol files.",
5078 },
5079};
5080
5082 {
5084 "true",
5085 "Load .lldbinit files from current directory",
5086 },
5087 {
5089 "false",
5090 "Do not load .lldbinit files from current directory",
5091 },
5092 {
5094 "warn",
5095 "Warn about loading .lldbinit files from current directory",
5096 },
5097};
5098
5100 {
5102 "minimal",
5103 "Load minimal information when loading modules from memory. Currently "
5104 "this setting loads sections only.",
5105 },
5106 {
5108 "partial",
5109 "Load partial information when loading modules from memory. Currently "
5110 "this setting loads sections and function bounds.",
5111 },
5112 {
5114 "complete",
5115 "Load complete information when loading modules from memory. Currently "
5116 "this setting loads sections and all symbols.",
5117 },
5118};
5119
5120#define LLDB_PROPERTIES_target
5121#include "TargetProperties.inc"
5122
5123enum {
5124#define LLDB_PROPERTIES_target
5125#include "TargetPropertiesEnum.inc"
5127};
5128
5130 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
5131public:
5132 TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
5133
5134 const Property *
5136 const ExecutionContext *exe_ctx = nullptr) const override {
5137 // When getting the value for a key from the target options, we will always
5138 // try and grab the setting from the current target if there is one. Else
5139 // we just use the one from this instance.
5140 if (exe_ctx) {
5141 Target *target = exe_ctx->GetTargetPtr();
5142 if (target && !target->IsDummyTarget()) {
5143 TargetOptionValueProperties *target_properties =
5144 static_cast<TargetOptionValueProperties *>(
5145 target->GetValueProperties().get());
5146 if (this != target_properties)
5147 return target_properties->ProtectedGetPropertyAtIndex(idx);
5148 }
5149 }
5150 return ProtectedGetPropertyAtIndex(idx);
5151 }
5152};
5153
5154// TargetProperties
5155#define LLDB_PROPERTIES_target_experimental
5156#include "TargetProperties.inc"
5157
5158enum {
5159#define LLDB_PROPERTIES_target_experimental
5160#include "TargetPropertiesEnum.inc"
5161};
5162
5164 : public Cloneable<TargetExperimentalOptionValueProperties,
5165 OptionValueProperties> {
5166public:
5168 : Cloneable(Properties::GetExperimentalSettingsName()) {}
5169};
5170
5176
5177// TargetProperties
5179 : Properties(), m_launch_info(), m_target(target) {
5180 if (target) {
5183
5184 // Set callbacks to update launch_info whenever "settins set" updated any
5185 // of these properties
5186 m_collection_sp->SetValueChangedCallback(
5187 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
5188 m_collection_sp->SetValueChangedCallback(
5189 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
5190 m_collection_sp->SetValueChangedCallback(
5191 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
5192 m_collection_sp->SetValueChangedCallback(
5193 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
5194 m_collection_sp->SetValueChangedCallback(
5195 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
5196 m_collection_sp->SetValueChangedCallback(
5197 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
5198 m_collection_sp->SetValueChangedCallback(
5199 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
5200 m_collection_sp->SetValueChangedCallback(
5201 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
5202 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
5204 });
5205 m_collection_sp->SetValueChangedCallback(
5206 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
5207 m_collection_sp->SetValueChangedCallback(
5208 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
5209 m_collection_sp->SetValueChangedCallback(
5210 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
5211
5212 m_collection_sp->SetValueChangedCallback(
5213 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
5215 std::make_unique<TargetExperimentalProperties>();
5216 m_collection_sp->AppendProperty(
5218 "Experimental settings - setting these won't produce "
5219 "errors if the setting is not present.",
5220 true, m_experimental_properties_up->GetValueProperties());
5221 } else {
5222 m_collection_sp = std::make_shared<TargetOptionValueProperties>("target");
5223 m_collection_sp->Initialize(g_target_properties_def);
5225 std::make_unique<TargetExperimentalProperties>();
5226 m_collection_sp->AppendProperty(
5228 "Experimental settings - setting these won't produce "
5229 "errors if the setting is not present.",
5230 true, m_experimental_properties_up->GetValueProperties());
5231 m_collection_sp->AppendProperty(
5232 "process", "Settings specific to processes.", true,
5234 m_collection_sp->SetValueChangedCallback(
5235 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
5236 }
5237}
5238
5240
5253
5255 size_t prop_idx, ExecutionContext *exe_ctx) const {
5256 const Property *exp_property =
5257 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
5258 OptionValueProperties *exp_values =
5259 exp_property->GetValue()->GetAsProperties();
5260 if (exp_values)
5261 return exp_values->GetPropertyAtIndexAs<bool>(prop_idx, exe_ctx);
5262 return std::nullopt;
5263}
5264
5266 ExecutionContext *exe_ctx) const {
5267 return GetExperimentalPropertyValue(ePropertyInjectLocalVars, exe_ctx)
5268 .value_or(true);
5269}
5270
5272 const Property *exp_property =
5273 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
5274 OptionValueProperties *exp_values =
5275 exp_property->GetValue()->GetAsProperties();
5276 if (exp_values)
5277 return exp_values->GetPropertyAtIndexAs<bool>(ePropertyUseDIL, exe_ctx)
5278 .value_or(false);
5279 else
5280 return true;
5281}
5282
5284 const Property *exp_property =
5285 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
5286 OptionValueProperties *exp_values =
5287 exp_property->GetValue()->GetAsProperties();
5288 if (exp_values)
5289 exp_values->SetPropertyAtIndex(ePropertyUseDIL, true, exe_ctx);
5290}
5291
5293 const Property *exp_property =
5294 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);
5295 OptionValueProperties *exp_values =
5296 exp_property->GetValue()->GetAsProperties();
5297 if (exp_values)
5298 return exp_values
5299 ->GetPropertyAtIndexAs<bool>(ePropertyUseDILForCreatingValues)
5300 .value_or(false);
5301 else
5302 return true;
5303}
5304
5306 const Property *exp_property =
5307 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental);
5308 OptionValueProperties *exp_values =
5309 exp_property->GetValue()->GetAsProperties();
5310 if (exp_values)
5311 exp_values->SetPropertyAtIndex(ePropertyUseDILForCreatingValues, b);
5312}
5313
5315 const uint32_t idx = ePropertyDefaultArch;
5316 return GetPropertyAtIndexAs<ArchSpec>(idx, {});
5317}
5318
5320 const uint32_t idx = ePropertyDefaultArch;
5321 SetPropertyAtIndex(idx, arch);
5322}
5323
5325 const uint32_t idx = ePropertyMoveToNearestCode;
5327 idx, g_target_properties[idx].default_uint_value != 0);
5328}
5329
5331 const uint32_t idx = ePropertyPreferDynamic;
5333 idx, static_cast<lldb::DynamicValueType>(
5334 g_target_properties[idx].default_uint_value));
5335}
5336
5338 const uint32_t idx = ePropertyPreferDynamic;
5339 return SetPropertyAtIndex(idx, d);
5340}
5341
5343 if (INTERRUPT_REQUESTED(m_target->GetDebugger(),
5344 "Interrupted checking preload symbols")) {
5345 return false;
5346 }
5347 const uint32_t idx = ePropertyPreloadSymbols;
5349 idx, g_target_properties[idx].default_uint_value != 0);
5350}
5351
5353 const uint32_t idx = ePropertyPreloadSymbols;
5354 SetPropertyAtIndex(idx, b);
5355}
5356
5358 const uint32_t idx = ePropertyDisableASLR;
5360 idx, g_target_properties[idx].default_uint_value != 0);
5361}
5362
5364 const uint32_t idx = ePropertyDisableASLR;
5365 SetPropertyAtIndex(idx, b);
5366}
5367
5369 const uint32_t idx = ePropertyInheritTCC;
5371 idx, g_target_properties[idx].default_uint_value != 0);
5372}
5373
5375 const uint32_t idx = ePropertyInheritTCC;
5376 SetPropertyAtIndex(idx, b);
5377}
5378
5380 const uint32_t idx = ePropertyDetachOnError;
5382 idx, g_target_properties[idx].default_uint_value != 0);
5383}
5384
5386 const uint32_t idx = ePropertyDetachOnError;
5387 SetPropertyAtIndex(idx, b);
5388}
5389
5391 const uint32_t idx = ePropertyDisableSTDIO;
5393 idx, g_target_properties[idx].default_uint_value != 0);
5394}
5395
5397 const uint32_t idx = ePropertyDisableSTDIO;
5398 SetPropertyAtIndex(idx, b);
5399}
5401 const uint32_t idx = ePropertyLaunchWorkingDir;
5403 idx, g_target_properties[idx].default_cstr_value);
5404}
5405
5407 const uint32_t idx = ePropertyParallelModuleLoad;
5409 idx, g_target_properties[idx].default_uint_value != 0);
5410}
5411
5413 const uint32_t idx = ePropertyDisassemblyFlavor;
5414 const char *return_value;
5415
5416 x86DisassemblyFlavor flavor_value =
5418 idx, static_cast<x86DisassemblyFlavor>(
5419 g_target_properties[idx].default_uint_value));
5420
5421 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
5422 return return_value;
5423}
5424
5426 const uint32_t idx = ePropertyDisassemblyCPU;
5427 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
5428 idx, g_target_properties[idx].default_cstr_value);
5429 return str.empty() ? nullptr : str.data();
5430}
5431
5433 const uint32_t idx = ePropertyDisassemblyFeatures;
5434 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
5435 idx, g_target_properties[idx].default_cstr_value);
5436 return str.empty() ? nullptr : str.data();
5437}
5438
5440 const uint32_t idx = ePropertyInlineStrategy;
5442 idx,
5443 static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value));
5444}
5445
5446// Returning RealpathPrefixes, but the setting's type is FileSpecList. We do
5447// this because we want the FileSpecList to normalize the file paths for us.
5449 const uint32_t idx = ePropertySourceRealpathPrefixes;
5451}
5452
5453llvm::StringRef TargetProperties::GetArg0() const {
5454 const uint32_t idx = ePropertyArg0;
5456 idx, g_target_properties[idx].default_cstr_value);
5457}
5458
5459void TargetProperties::SetArg0(llvm::StringRef arg) {
5460 const uint32_t idx = ePropertyArg0;
5461 SetPropertyAtIndex(idx, arg);
5462 m_launch_info.SetArg0(arg);
5463}
5464
5466 const uint32_t idx = ePropertyRunArgs;
5467 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
5468}
5469
5471 const uint32_t idx = ePropertyRunArgs;
5472 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
5473 m_launch_info.GetArguments() = args;
5474}
5475
5477 Environment env;
5478
5479 if (m_target &&
5481 ePropertyInheritEnv,
5482 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
5483 if (auto platform_sp = m_target->GetPlatform()) {
5484 Environment platform_env = platform_sp->GetEnvironment();
5485 for (const auto &KV : platform_env)
5486 env[KV.first()] = KV.second;
5487 }
5488 }
5489
5490 Args property_unset_env;
5491 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
5492 property_unset_env);
5493 for (const auto &var : property_unset_env)
5494 env.erase(var.ref());
5495
5496 Args property_env;
5497 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env);
5498 for (const auto &KV : Environment(property_env))
5499 env[KV.first()] = KV.second;
5500
5501 return env;
5502}
5503
5507
5509 Environment environment;
5510
5511 if (m_target == nullptr)
5512 return environment;
5513
5515 ePropertyInheritEnv,
5516 g_target_properties[ePropertyInheritEnv].default_uint_value != 0))
5517 return environment;
5518
5519 PlatformSP platform_sp = m_target->GetPlatform();
5520 if (platform_sp == nullptr)
5521 return environment;
5522
5523 Environment platform_environment = platform_sp->GetEnvironment();
5524 for (const auto &KV : platform_environment)
5525 environment[KV.first()] = KV.second;
5526
5527 Args property_unset_environment;
5528 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
5529 property_unset_environment);
5530 for (const auto &var : property_unset_environment)
5531 environment.erase(var.ref());
5532
5533 return environment;
5534}
5535
5537 Args property_environment;
5538 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars,
5539 property_environment);
5540 Environment environment;
5541 for (const auto &KV : Environment(property_environment))
5542 environment[KV.first()] = KV.second;
5543
5544 return environment;
5545}
5546
5548 // TODO: Get rid of the Args intermediate step
5549 const uint32_t idx = ePropertyEnvVars;
5550 m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env));
5551}
5552
5554 const uint32_t idx = ePropertySkipPrologue;
5556 idx, g_target_properties[idx].default_uint_value != 0);
5557}
5558
5560 const uint32_t idx = ePropertySourceMap;
5561 OptionValuePathMappings *option_value =
5562 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
5563 assert(option_value);
5564 return option_value->GetCurrentValue();
5565}
5566
5568 const uint32_t idx = ePropertyObjectMap;
5569 OptionValuePathMappings *option_value =
5570 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
5571 assert(option_value);
5572 return option_value->GetCurrentValue();
5573}
5574
5576 const uint32_t idx = ePropertyAutoSourceMapRelative;
5578 idx, g_target_properties[idx].default_uint_value != 0);
5579}
5580
5582 const uint32_t idx = ePropertyExecutableSearchPaths;
5583 OptionValueFileSpecList *option_value =
5584 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
5585 assert(option_value);
5586 option_value->AppendCurrentValue(dir);
5587}
5588
5590 const uint32_t idx = ePropertyExecutableSearchPaths;
5591 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
5592}
5593
5595 const uint32_t idx = ePropertyDebugFileSearchPaths;
5596 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
5597}
5598
5600 const uint32_t idx = ePropertyClangModuleSearchPaths;
5601 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
5602}
5603
5605 const uint32_t idx = ePropertyAutoImportClangModules;
5607 idx, g_target_properties[idx].default_uint_value != 0);
5608}
5609
5611 const uint32_t idx = ePropertyImportStdModule;
5613 idx, static_cast<ImportStdModule>(
5614 g_target_properties[idx].default_uint_value));
5615}
5616
5618 const uint32_t idx = ePropertyDynamicClassInfoHelper;
5620 idx, static_cast<DynamicClassInfoHelper>(
5621 g_target_properties[idx].default_uint_value));
5622}
5623
5625 const uint32_t idx = ePropertyAutoApplyFixIts;
5627 idx, g_target_properties[idx].default_uint_value != 0);
5628}
5629
5631 const uint32_t idx = ePropertyRetriesWithFixIts;
5633 idx, g_target_properties[idx].default_uint_value);
5634}
5635
5637 const uint32_t idx = ePropertyNotifyAboutFixIts;
5639 idx, g_target_properties[idx].default_uint_value != 0);
5640}
5641
5643 const uint32_t idx = ePropertySaveObjectsDir;
5644 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5645}
5646
5648 const uint32_t idx = ePropertyJITEngine;
5650 idx, static_cast<JITEngine>(g_target_properties[idx].default_uint_value));
5651}
5652
5654 FileSpec new_dir = GetSaveJITObjectsDir();
5655 if (!new_dir)
5656 return;
5657
5658 const FileSystem &instance = FileSystem::Instance();
5659 bool exists = instance.Exists(new_dir);
5660 bool is_directory = instance.IsDirectory(new_dir);
5661 std::string path = new_dir.GetPath(true);
5662 bool writable = llvm::sys::fs::can_write(path);
5663 if (exists && is_directory && writable)
5664 return;
5665
5666 m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir)
5667 ->GetValue()
5668 ->Clear();
5669
5670 std::string buffer;
5671 llvm::raw_string_ostream os(buffer);
5672 os << "JIT object dir '" << path << "' ";
5673 if (!exists)
5674 os << "does not exist";
5675 else if (!is_directory)
5676 os << "is not a directory";
5677 else if (!writable)
5678 os << "is not writable";
5679
5680 std::optional<lldb::user_id_t> debugger_id;
5681 if (m_target)
5682 debugger_id = m_target->GetDebugger().GetID();
5683 Debugger::ReportError(buffer, debugger_id);
5684}
5685
5687 const uint32_t idx = ePropertyEnableSynthetic;
5689 idx, g_target_properties[idx].default_uint_value != 0);
5690}
5691
5693 const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes;
5695 idx, g_target_properties[idx].default_uint_value != 0);
5696}
5697
5699 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
5701 idx, g_target_properties[idx].default_uint_value);
5702}
5703
5705 const uint32_t idx = ePropertyMaxChildrenCount;
5707 idx, g_target_properties[idx].default_uint_value);
5708}
5709
5710std::pair<uint32_t, bool>
5712 const uint32_t idx = ePropertyMaxChildrenDepth;
5713 auto *option_value =
5714 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx);
5715 bool is_default = !option_value->OptionWasSet();
5716 return {option_value->GetCurrentValue(), is_default};
5717}
5718
5720 const uint32_t idx = ePropertyMaxSummaryLength;
5722 idx, g_target_properties[idx].default_uint_value);
5723}
5724
5726 const uint32_t idx = ePropertyMaxMemReadSize;
5728 idx, g_target_properties[idx].default_uint_value);
5729}
5730
5732 const uint32_t idx = ePropertyInputPath;
5733 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5734}
5735
5736void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
5737 const uint32_t idx = ePropertyInputPath;
5738 SetPropertyAtIndex(idx, path);
5739}
5740
5742 const uint32_t idx = ePropertyOutputPath;
5743 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5744}
5745
5747 const uint32_t idx = ePropertyOutputPath;
5748 SetPropertyAtIndex(idx, path);
5749}
5750
5752 const uint32_t idx = ePropertyErrorPath;
5753 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5754}
5755
5756void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
5757 const uint32_t idx = ePropertyErrorPath;
5758 SetPropertyAtIndex(idx, path);
5759}
5760
5762 const uint32_t idx = ePropertyLanguage;
5764}
5765
5767 const uint32_t idx = ePropertyExprPrefix;
5768 OptionValueFileSpec *file =
5769 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx);
5770 if (file) {
5771 DataBufferSP data_sp(file->GetFileContents());
5772 if (data_sp)
5773 return llvm::StringRef(
5774 reinterpret_cast<const char *>(data_sp->GetBytes()),
5775 data_sp->GetByteSize());
5776 }
5777 return "";
5778}
5779
5781 const uint32_t idx = ePropertyExprErrorLimit;
5783 idx, g_target_properties[idx].default_uint_value);
5784}
5785
5787 const uint32_t idx = ePropertyExprAllocAddress;
5789 idx, g_target_properties[idx].default_uint_value);
5790}
5791
5793 const uint32_t idx = ePropertyExprAllocSize;
5795 idx, g_target_properties[idx].default_uint_value);
5796}
5797
5799 const uint32_t idx = ePropertyExprAllocAlign;
5801 idx, g_target_properties[idx].default_uint_value);
5802}
5803
5805 const uint32_t idx = ePropertyBreakpointUseAvoidList;
5807 idx, g_target_properties[idx].default_uint_value != 0);
5808}
5809
5811 const uint32_t idx = ePropertyBreakpointsConditionMode;
5813 idx, static_cast<BreakpointConditionMode>(
5814 g_target_properties[idx].default_uint_value));
5815}
5816
5818 const uint32_t idx = ePropertyUseHexImmediates;
5820 idx, g_target_properties[idx].default_uint_value != 0);
5821}
5822
5824 const uint32_t idx = ePropertyUseFastStepping;
5826 idx, g_target_properties[idx].default_uint_value != 0);
5827}
5828
5830 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
5832 idx, g_target_properties[idx].default_uint_value != 0);
5833}
5834
5836 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
5838 idx, static_cast<LoadScriptFromSymFile>(
5839 g_target_properties[idx].default_uint_value));
5840}
5841
5843 LoadScriptFromSymFile load_style) {
5844 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
5845 SetPropertyAtIndex(idx, load_style);
5846}
5847
5849 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
5851 idx, static_cast<LoadCWDlldbinitFile>(
5852 g_target_properties[idx].default_uint_value));
5853}
5854
5856 const uint32_t idx = ePropertyHexImmediateStyle;
5858 idx, static_cast<Disassembler::HexImmediateStyle>(
5859 g_target_properties[idx].default_uint_value));
5860}
5861
5863 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
5865 idx, static_cast<MemoryModuleLoadLevel>(
5866 g_target_properties[idx].default_uint_value));
5867}
5868
5870 const uint32_t idx = ePropertyTrapHandlerNames;
5871 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
5872}
5873
5875 const uint32_t idx = ePropertyTrapHandlerNames;
5876 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
5877}
5878
5880 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
5882 idx, g_target_properties[idx].default_uint_value != 0);
5883}
5884
5886 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
5887 SetPropertyAtIndex(idx, b);
5888}
5889
5891 const uint32_t idx = ePropertyDisplayRecognizedArguments;
5893 idx, g_target_properties[idx].default_uint_value != 0);
5894}
5895
5897 const uint32_t idx = ePropertyDisplayRecognizedArguments;
5898 SetPropertyAtIndex(idx, b);
5899}
5900
5904
5906 const ProcessLaunchInfo &launch_info) {
5907 m_launch_info = launch_info;
5908 SetArg0(launch_info.GetArg0());
5909 SetRunArguments(launch_info.GetArguments());
5910 SetEnvironment(launch_info.GetEnvironment());
5911 const FileAction *input_file_action =
5912 launch_info.GetFileActionForFD(STDIN_FILENO);
5913 if (input_file_action) {
5914 SetStandardInputPath(input_file_action->GetFileSpec().GetPath());
5915 }
5916 const FileAction *output_file_action =
5917 launch_info.GetFileActionForFD(STDOUT_FILENO);
5918 if (output_file_action) {
5919 SetStandardOutputPath(output_file_action->GetFileSpec().GetPath());
5920 }
5921 const FileAction *error_file_action =
5922 launch_info.GetFileActionForFD(STDERR_FILENO);
5923 if (error_file_action) {
5924 SetStandardErrorPath(error_file_action->GetFileSpec().GetPath());
5925 }
5926 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
5927 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
5929 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
5930 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
5931}
5932
5934 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5936 idx, g_target_properties[idx].default_uint_value != 0);
5937}
5938
5940 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5941 m_collection_sp->SetPropertyAtIndex(idx, b);
5942}
5943
5945 const uint32_t idx = ePropertyAutoInstallMainExecutable;
5947 idx, g_target_properties[idx].default_uint_value != 0);
5948}
5949
5953
5955 Args args;
5956 if (GetRunArguments(args))
5957 m_launch_info.GetArguments() = args;
5958}
5959
5963
5965 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
5966 false);
5967}
5968
5970 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
5971 false, true);
5972}
5973
5975 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
5976 false, true);
5977}
5978
5980 if (GetDetachOnError())
5981 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
5982 else
5983 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
5984}
5985
5987 if (GetDisableASLR())
5988 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
5989 else
5990 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
5991}
5992
5994 if (GetInheritTCC())
5995 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
5996 else
5997 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
5998}
5999
6001 if (GetDisableSTDIO())
6002 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
6003 else
6004 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
6005}
6006
6008 const uint32_t idx = ePropertyDebugUtilityExpression;
6010 idx, g_target_properties[idx].default_uint_value != 0);
6011}
6012
6014 const uint32_t idx = ePropertyDebugUtilityExpression;
6015 SetPropertyAtIndex(idx, debug);
6016}
6017
6019 const uint32_t idx = ePropertyCheckValueObjectOwnership;
6021 idx, g_target_properties[idx].default_uint_value != 0);
6022}
6023
6025 const uint32_t idx = ePropertyCheckValueObjectOwnership;
6026 SetPropertyAtIndex(idx, check);
6027}
6028
6029std::optional<LoadScriptFromSymFile>
6031 llvm::StringRef module_name) const {
6032 auto *dict = m_collection_sp->GetPropertyAtIndexAsOptionValueDictionary(
6033 ePropertyAutoLoadScriptsForModules);
6034 if (!dict)
6035 return std::nullopt;
6036
6037 OptionValueSP value_sp = dict->GetValueForKey(module_name);
6038 if (!value_sp)
6039 return std::nullopt;
6040
6041 return value_sp->GetValueAs<LoadScriptFromSymFile>();
6042}
6043
6045 llvm::StringRef module_name, LoadScriptFromSymFile load_style) {
6046 auto *dict = m_collection_sp->GetPropertyAtIndexAsOptionValueDictionary(
6047 ePropertyAutoLoadScriptsForModules);
6048 if (!dict)
6049 return;
6050
6051 dict->SetValueForKey(module_name,
6052 std::make_shared<OptionValueEnumeration>(
6054}
6055
6056// Target::TargetEventData
6057
6060
6062 const ModuleList &module_list)
6063 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
6064
6066 const lldb::TargetSP &target_sp, const lldb::TargetSP &created_target_sp)
6067 : EventData(), m_target_sp(target_sp),
6068 m_created_target_sp(created_target_sp), m_module_list() {}
6069
6071
6073 return "Target::TargetEventData";
6074}
6075
6077 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
6078 if (i != 0)
6079 *s << ", ";
6080 m_module_list.GetModuleAtIndex(i)->GetDescription(
6082 }
6083}
6084
6087 if (event_ptr) {
6088 const EventData *event_data = event_ptr->GetData();
6089 if (event_data &&
6091 return static_cast<const TargetEventData *>(event_ptr->GetData());
6092 }
6093 return nullptr;
6094}
6095
6097 TargetSP target_sp;
6098 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
6099 if (event_data)
6100 target_sp = event_data->m_target_sp;
6101 return target_sp;
6102}
6103
6106 TargetSP created_target_sp;
6107 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
6108 if (event_data)
6109 created_target_sp = event_data->m_created_target_sp;
6110 return created_target_sp;
6111}
6112
6115 ModuleList module_list;
6116 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
6117 if (event_data)
6118 module_list = event_data->m_module_list;
6119 return module_list;
6120}
6121
6123 return TargetAPIMutex(shared_from_this());
6124}
6125
6127 Policy policy = PolicyStack::Get().Current();
6129 return nullptr;
6130 return policy.view == Policy::View::Private ? &m_private_mutex : &m_mutex;
6131}
6132
6133/// Get metrics associated with this target in JSON format.
6134llvm::json::Value
6136 return m_stats.ToJSON(*this, options);
6137}
6138
6139void Target::ResetStatistics() { m_stats.Reset(*this); }
6140
6142
6146
6148
6152
6154 lldb::BreakpointEventType eventKind) {
6156 std::shared_ptr<Breakpoint::BreakpointEventData> data_sp =
6157 std::make_shared<Breakpoint::BreakpointEventData>(
6158 eventKind, bp.shared_from_this());
6160 }
6161}
6162
6168
6171
6172 // Add platform-specific safe-paths.
6173 if (m_platform_sp) {
6174 if (auto platform_fspecs_or_err =
6175 m_platform_sp->GetSafeAutoLoadPaths(*this))
6176 fspecs.Append(*platform_fspecs_or_err);
6177 else
6179 platform_fspecs_or_err.takeError(),
6180 "Skipping safe auto-load: {0}");
6181 }
6182
6183 // Properties for testing get added last so they take priority.
6184#ifndef NDEBUG
6185 for (const auto &fspec :
6187 fspecs.Append(fspec);
6188#endif
6189
6190 return fspecs;
6191}
6192
6193// FIXME: the language plugin should expression options dynamically and
6194// we should validate here (by asking the language plugin) that the options
6195// being set/retrieved are actually valid options.
6196
6197llvm::Error
6199 bool value) {
6200 if (option_name.empty())
6201 return llvm::createStringError("can't set an option with an empty name");
6202
6203 if (StructuredData::ObjectSP existing_sp =
6204 GetLanguageOptions().GetValueForKey(option_name);
6205 existing_sp && existing_sp->GetType() != eStructuredDataTypeBoolean)
6206 return llvm::createStringErrorV("trying to override existing option '{0}' "
6207 "of type '{1}' with a boolean value",
6208 option_name, existing_sp->GetType());
6209
6210 GetLanguageOptions().AddBooleanItem(option_name, value);
6211
6212 return llvm::Error::success();
6213}
6214
6216 llvm::StringRef option_name) const {
6218
6219 if (!opts.HasKey(option_name))
6220 return llvm::createStringErrorV("option '{0}' does not exist", option_name);
6221
6222 bool result;
6223 if (!opts.GetValueForKeyAsBoolean(option_name, result))
6224 return llvm::createStringErrorV("failed to get option '{0}' as boolean",
6225 option_name);
6226
6227 return result;
6228}
6229
6236
6242
6243// FIXME: this option is C++ plugin specific and should be registered by it,
6244// instead of hard-coding it here.
6245constexpr llvm::StringLiteral s_cpp_ignore_context_qualifiers_option =
6246 "c++-ignore-context-qualifiers";
6247
6252
6257
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:530
#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:6245
static constexpr OptionEnumValueElement g_dynamic_class_info_helper_value_types[]
Definition Target.cpp:5029
@ ePropertyExperimental
Definition Target.cpp:5126
static bool CheckIfWatchpointsSupported(Target *target, Status &error)
Definition Target.cpp:1058
static constexpr OptionEnumValueElement g_jit_engine_value_types[]
Definition Target.cpp:4993
static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[]
Definition Target.cpp:5081
x86DisassemblyFlavor
Definition Target.cpp:4969
@ eX86DisFlavorDefault
Definition Target.cpp:4970
@ eX86DisFlavorIntel
Definition Target.cpp:4971
@ eX86DisFlavorATT
Definition Target.cpp:4972
static constexpr OptionEnumValueElement g_dynamic_value_types[]
Definition Target.cpp:4923
static constexpr OptionEnumValueElement g_memory_module_load_level_values[]
Definition Target.cpp:5099
static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[]
Definition Target.cpp:5057
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:4975
static constexpr OptionEnumValueElement g_hex_immediate_style_values[]
Definition Target.cpp:5044
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:4403
static constexpr OptionEnumValueElement g_inline_breakpoint_enums[]
Definition Target.cpp:4946
static constexpr OptionEnumValueElement g_import_std_module_value_types[]
Definition Target.cpp:5006
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:91
const Property * GetPropertyAtIndex(size_t idx, const ExecutionContext *exe_ctx=nullptr) const override
Definition Target.cpp:5135
TargetOptionValueProperties(llvm::StringRef name)
Definition Target.cpp:5132
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:375
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition ArchSpec.h:465
void MergeFrom(const ArchSpec &other)
Merges fields from another ArchSpec into this ArchSpec.
Definition ArchSpec.cpp:842
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:568
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:104
static const FileSpecList & GetDefaultSafeAutoLoadPaths()
Definition Debugger.cpp:237
void SetAsyncExecution(bool async)
CommandInterpreter & GetCommandInterpreter()
Definition Debugger.h:190
lldb::StreamUP GetAsyncErrorStream()
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:228
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:232
lldb::ListenerSP GetListener()
Definition Debugger.h:199
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:6253
const StructuredData::Dictionary & GetLanguageOptions() const
Definition Target.cpp:6231
llvm::Expected< bool > GetBooleanLanguageOption(llvm::StringRef option_name) const
Get the language-plugin specific boolean option called option_name.
Definition Target.cpp:6215
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:6198
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:532
static Language * FindPlugin(lldb::LanguageType language)
Definition Language.cpp:89
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:348
static LanguageSet GetLanguagesSupportingTypeSystemsForExpressions()
Definition Language.cpp:528
virtual llvm::StringRef GetUserEntryPointName() const
Definition Language.h:189
static std::set< lldb::LanguageType > GetSupportedLanguages()
Definition Language.cpp:515
static lldb::ListenerSP MakeListener(llvm::StringRef name)
Definition Listener.cpp:373
A collection class for Module objects.
Definition ModuleList.h:127
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:92
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition Module.cpp:1203
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition Module.h:448
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:462
@ 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:3239
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:5131
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:5133
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:283
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:5292
uint32_t GetMaximumSizeOfStringSummary() const
Definition Target.cpp:5719
FileSpecList GetDebugFileSearchPaths()
Definition Target.cpp:5594
llvm::StringRef GetLaunchWorkingDirectory() const
Definition Target.cpp:5400
bool GetDisplayRecognizedArguments() const
Definition Target.cpp:5890
ImportStdModule GetImportStdModule() const
Definition Target.cpp:5610
void AppendExecutableSearchPaths(const FileSpec &)
Definition Target.cpp:5581
bool GetEnableSyntheticValue() const
Definition Target.cpp:5686
ProcessLaunchInfo m_launch_info
Definition Target.h:341
bool GetCheckValueObjectOwnership() const
Definition Target.cpp:6018
uint64_t GetExprAllocAlign() const
Definition Target.cpp:5798
MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const
Definition Target.cpp:5862
llvm::StringRef GetArg0() const
Definition Target.cpp:5453
uint32_t GetMaximumMemReadSize() const
Definition Target.cpp:5725
void SetRunArguments(const Args &args)
Definition Target.cpp:5470
FileSpec GetStandardErrorPath() const
Definition Target.cpp:5751
void SetLoadScriptFromSymbolFile(LoadScriptFromSymFile load_style)
Set the target-wide target.load-script-from-symbol-file setting.
Definition Target.cpp:5842
bool GetEnableNotifyAboutFixIts() const
Definition Target.cpp:5636
bool SetPreferDynamicValue(lldb::DynamicValueType d)
Definition Target.cpp:5337
void SetDisplayRecognizedArguments(bool b)
Definition Target.cpp:5896
void SetUseDILForCreatingValues(bool b)
Definition Target.cpp:5305
std::optional< bool > GetExperimentalPropertyValue(size_t prop_idx, ExecutionContext *exe_ctx=nullptr) const
Definition Target.cpp:5254
const ProcessLaunchInfo & GetProcessLaunchInfo() const
Definition Target.cpp:5901
Environment ComputeEnvironment() const
Definition Target.cpp:5476
bool GetUserSpecifiedTrapHandlerNames(Args &args) const
Definition Target.cpp:5869
uint64_t GetExprErrorLimit() const
Definition Target.cpp:5780
bool GetEnableAutoImportClangModules() const
Definition Target.cpp:5604
bool GetDebugUtilityExpression() const
Definition Target.cpp:6007
JITEngine GetJITEngine() const
Definition Target.cpp:5647
DynamicClassInfoHelper GetDynamicClassInfoHelper() const
Definition Target.cpp:5617
FileSpec GetStandardOutputPath() const
Definition Target.cpp:5741
void SetDisplayRuntimeSupportValues(bool b)
Definition Target.cpp:5885
uint32_t GetMaximumNumberOfChildrenToDisplay() const
Definition Target.cpp:5704
void SetRequireHardwareBreakpoints(bool b)
Definition Target.cpp:5939
lldb::BreakpointConditionMode GetBreakpointsConditionMode() const
Definition Target.cpp:5810
bool GetAutoInstallMainExecutable() const
Definition Target.cpp:5944
const char * GetDisassemblyFeatures() const
Definition Target.cpp:5432
void SetAutoLoadScriptsForModule(llvm::StringRef module_name, LoadScriptFromSymFile load_style)
Set the LoadScriptFromSymFile for a module called module_name (excluding file extension).
Definition Target.cpp:6044
RealpathPrefixes GetSourceRealpathPrefixes() const
Definition Target.cpp:5448
void SetCheckValueObjectOwnership(bool check)
Definition Target.cpp:6024
uint64_t GetNumberOfRetriesWithFixits() const
Definition Target.cpp:5630
uint64_t GetExprAllocSize() const
Definition Target.cpp:5792
std::optional< LoadScriptFromSymFile > GetAutoLoadScriptsForModule(llvm::StringRef module_name) const
Definition Target.cpp:6030
llvm::StringRef GetExpressionPrefixContents()
Definition Target.cpp:5766
PathMappingList & GetObjectPathMap() const
Definition Target.cpp:5567
const char * GetDisassemblyFlavor() const
Definition Target.cpp:5412
FileSpec GetStandardInputPath() const
Definition Target.cpp:5731
lldb::DynamicValueType GetPreferDynamicValue() const
Definition Target.cpp:5330
InlineStrategy GetInlineStrategy() const
Definition Target.cpp:5439
Environment GetTargetEnvironment() const
Definition Target.cpp:5536
bool GetDisplayRuntimeSupportValues() const
Definition Target.cpp:5879
void SetUserSpecifiedTrapHandlerNames(const Args &args)
Definition Target.cpp:5874
uint32_t GetMaxZeroPaddingInFloatFormat() const
Definition Target.cpp:5698
uint64_t GetExprAllocAddress() const
Definition Target.cpp:5786
LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const
Definition Target.cpp:5848
Environment GetInheritedEnvironment() const
Definition Target.cpp:5508
void SetArg0(llvm::StringRef arg)
Definition Target.cpp:5459
bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const
Definition Target.cpp:5265
bool ShowHexVariableValuesWithLeadingZeroes() const
Definition Target.cpp:5692
SourceLanguage GetLanguage() const
Definition Target.cpp:5761
Environment GetEnvironment() const
Definition Target.cpp:5504
void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
Definition Target.cpp:5905
FileSpec GetSaveJITObjectsDir() const
Definition Target.cpp:5642
void SetEnvironment(Environment env)
Definition Target.cpp:5547
LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const
Definition Target.cpp:5835
const char * GetDisassemblyCPU() const
Definition Target.cpp:5425
void SetStandardErrorPath(llvm::StringRef path)
Definition Target.cpp:5756
bool GetRunArguments(Args &args) const
Definition Target.cpp:5465
FileSpecList GetExecutableSearchPaths()
Definition Target.cpp:5589
ArchSpec GetDefaultArchitecture() const
Definition Target.cpp:5314
Disassembler::HexImmediateStyle GetHexImmediateStyle() const
Definition Target.cpp:5855
void SetUseDIL(ExecutionContext *exe_ctx, bool b)
Definition Target.cpp:5283
std::unique_ptr< TargetExperimentalProperties > m_experimental_properties_up
Definition Target.h:342
FileSpecList GetClangModuleSearchPaths()
Definition Target.cpp:5599
void SetStandardOutputPath(llvm::StringRef path)
Definition Target.cpp:5746
bool GetRequireHardwareBreakpoints() const
Definition Target.cpp:5933
PathMappingList & GetSourcePathMap() const
Definition Target.cpp:5559
bool GetAutoSourceMapRelative() const
Definition Target.cpp:5575
bool GetUseDIL(ExecutionContext *exe_ctx) const
Definition Target.cpp:5271
void SetDefaultArchitecture(const ArchSpec &arch)
Definition Target.cpp:5319
void SetStandardInputPath(llvm::StringRef path)
Definition Target.cpp:5736
TargetProperties(Target *target)
Definition Target.cpp:5178
bool GetDisplayExpressionsInCrashlogs() const
Definition Target.cpp:5829
bool GetEnableAutoApplyFixIts() const
Definition Target.cpp:5624
void SetDebugUtilityExpression(bool debug)
Definition Target.cpp:6013
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:5711
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:4582
void SetActionFromString(const std::string &string)
Populate the command list by splitting a single string on newlines.
Definition Target.cpp:4609
void SetActionFromStrings(const std::vector< std::string > &strings)
Populate the command list from a vector of individual command strings.
Definition Target.cpp:4613
void HandleModuleLoaded(lldb::StreamSP output) override
Definition Target.cpp:4619
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:4659
void HandleModuleUnloaded(lldb::StreamSP output) override
Definition Target.cpp:4653
llvm::StringRef GetScriptClassName() const
Definition Target.cpp:4791
Status SetScriptCallback(const ScriptedMetadata &scripted_metadata)
Definition Target.cpp:4694
void HandleModuleLoaded(lldb::StreamSP output) override
Definition Target.cpp:4736
StopHook::StopHookResult HandleStop(ExecutionContext &exe_ctx, lldb::StreamSP output) override
Called when the process stops.
Definition Target.cpp:4769
void GetDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4797
lldb::ScriptedHookInterfaceSP m_interface_sp
Definition Target.h:1942
void HandleModuleUnloaded(lldb::StreamSP output) override
Definition Target.cpp:4752
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:4505
Hook(const Hook &rhs)
Definition Target.cpp:4486
void GetFilterDescription(Stream &s, lldb::DescriptionLevel level) const
Print the filter portion of the description (AutoContinue, Specifier, ThreadSpec).
Definition Target.cpp:4554
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:4521
void SetSCSpecifier(SymbolContextSpecifier *specifier)
Set the symbol context specifier. The hook takes ownership.
Definition Target.cpp:4497
void SetThreadSpecifier(ThreadSpec *specifier)
Set the thread specifier. The hook takes ownership.
Definition Target.cpp:4501
std::unique_ptr< ThreadSpec > m_thread_spec_up
Definition Target.h:1880
void SetActionFromString(const std::string &strings)
Definition Target.cpp:4319
void SetActionFromStrings(const std::vector< std::string > &strings)
Definition Target.cpp:4323
StopHookResult HandleStop(ExecutionContext &exc_ctx, lldb::StreamSP output_sp) override
Definition Target.cpp:4330
void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4301
lldb::ScriptedHookInterfaceSP m_interface_sp
Definition Target.h:1731
StopHookResult HandleStop(ExecutionContext &exc_ctx, lldb::StreamSP output) override
Definition Target.cpp:4415
Status SetScriptCallback(const ScriptedMetadata &scripted_metadata)
Definition Target.cpp:4365
void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4444
llvm::StringRef GetScriptClassName() const
Definition Target.cpp:4438
SymbolContextSpecifier * GetSpecifier()
Definition Target.h:1639
void SetSpecifier(SymbolContextSpecifier *specifier)
Definition Target.cpp:4239
std::unique_ptr< ThreadSpec > m_thread_spec_up
Definition Target.h:1685
void SetThreadSpecifier(ThreadSpec *specifier)
Definition Target.cpp:4243
ThreadSpec * GetThreadSpecifier()
Definition Target.h:1654
StopHook(const StopHook &rhs)
Definition Target.cpp:4231
bool ExecutionContextPasses(const ExecutionContext &exe_ctx)
Definition Target.cpp:4247
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:4263
void Dump(Stream *s) const override
Definition Target.cpp:6076
static llvm::StringRef GetFlavorString()
Definition Target.cpp:6072
static lldb::TargetSP GetCreatedTargetFromEvent(const Event *event_ptr)
Definition Target.cpp:6105
static ModuleList GetModuleListFromEvent(const Event *event_ptr)
Definition Target.cpp:6114
static const TargetEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Target.cpp:6086
TargetEventData(const lldb::TargetSP &target_sp)
Definition Target.cpp:6058
static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr)
Definition Target.cpp:6096
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:2737
llvm::Expected< uint32_t > AddScriptedFrameProviderDescriptor(const ScriptedFrameProviderDescriptor &descriptor)
Add or update a scripted frame provider descriptor for this target.
Definition Target.cpp:3929
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:4859
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:6126
lldb::TraceSP GetTrace()
Get the Trace object containing processor trace information of this target.
Definition Target.cpp:3804
PathMappingList & GetImageSearchPathList()
Definition Target.cpp:2746
void FinalizeFileActions(ProcessLaunchInfo &info)
Definition Target.cpp:4011
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:3136
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:3144
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:2981
lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr)
Definition Target.cpp:3151
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:4171
static void ImageSearchPathsChanged(const PathMappingList &path_list, void *baton)
Definition Target.cpp:2750
llvm::Expected< lldb_private::Address > GetEntryPointAddress()
This method will return the address of the starting function for this binary, e.g.
Definition Target.cpp:3102
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:2011
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:3267
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:3802
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:3619
const llvm::MapVector< uint32_t, ScriptedFrameProviderDescriptor > & GetScriptedFrameProviderDescriptors() const
Get all scripted frame provider descriptors for this target.
Definition Target.cpp:3990
lldb::addr_t GetSectionLoadAddress(const lldb::SectionSP &section_sp)
Definition Target.cpp:6143
llvm::StringRef GetABIName() const
Returns the name of the target's ABI plugin.
Definition Target.cpp:432
SourceManager & GetSourceManager()
Definition Target.cpp:3191
lldb::SearchFilterSP GetSearchFilterForModuleList(const FileSpecList *containingModuleList)
Definition Target.cpp:729
StopHookSP GetStopHookByID(lldb::user_id_t uid)
Definition Target.cpp:3233
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:2831
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:4159
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:4117
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:2069
lldb::StackFrameSP CalculateStackFrame() override
Definition Target.cpp:2739
SectionLoadList & GetSectionLoadList()
Definition Target.h:2280
lldb::addr_t GetPersistentSymbol(ConstString name)
Definition Target.cpp:3082
TargetAPIMutex GetAPIMutex()
Returns a handle resolved to the mutex to serialize on before touching the target through the SB API.
Definition Target.cpp:6122
void PrimeFromDummyTarget(Target &target)
Definition Target.cpp:228
bool RemoveScriptedFrameProviderDescriptor(uint32_t id)
Remove a scripted frame provider descriptor by id.
Definition Target.cpp:3965
lldb::RegisterTypeBuilderSP m_register_type_builder_sp
Definition Target.h:2225
friend class TargetGroup
Definition Target.h:2096
static void SettingsTerminate()
Definition Target.cpp:2943
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:4837
bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr)
Definition Target.cpp:3535
bool ClearAllWatchpointHitCounts()
Definition Target.cpp:1532
CompilerType GetRegisterType(const RegisterInfo &reg_info)
Definition Target.cpp:2786
size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len, Status &error)
Definition Target.cpp:2101
void ClearAllLoadedSections()
Definition Target.cpp:3611
std::vector< lldb::TypeSystemSP > GetScratchTypeSystems(bool create_on_demand=true)
Definition Target.cpp:2794
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:2409
void AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name, Status &error)
Definition Target.cpp:877
void DumpSectionLoadList(Stream &s)
Definition Target.cpp:6149
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:2440
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:4881
bool SetSectionUnloaded(const lldb::SectionSP &section_sp)
Definition Target.cpp:3589
lldb::TargetSP CalculateTarget() override
Definition Target.cpp:2733
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:4144
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:2492
llvm::json::Value ReportStatistics(const lldb_private::StatisticsOptions &options)
Get metrics associated with this target in JSON format.
Definition Target.cpp:6135
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:2884
void EnableAllBreakpoints(bool internal_also=false)
Definition Target.cpp:1213
Status Launch(ProcessLaunchInfo &launch_info, Stream *stream)
Definition Target.cpp:3634
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:3806
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:2462
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:3219
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:3529
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:2360
HookSP GetHookByID(lldb::user_id_t uid)
Definition Target.cpp:4866
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:2759
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:3613
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:3243
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:3254
std::vector< StopHookSP > m_internal_stop_hooks
Definition Target.h:2195
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition Target.cpp:3063
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:3197
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error, bool force_live_memory=false)
Definition Target.cpp:2270
void SetAllHooksEnabledState(bool enabled)
Definition Target.cpp:4889
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:2027
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Target.cpp:2741
llvm::Expected< lldb::DisassemblerSP > ReadInstructions(const Address &start_addr, uint32_t count, const char *flavor_string=nullptr)
Definition Target.cpp:3157
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:3831
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:3623
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:2945
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:6153
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:2949
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:2134
llvm::Error SetLabel(llvm::StringRef label)
Set a label for a target.
Definition Target.cpp:2964
uint32_t m_latest_stop_hook_id
Definition Target.h:2196
void RunModuleHooks(bool is_load)
Definition Target.cpp:4894
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:3278
void ClearSectionLoadList()
Definition Target.cpp:6147
lldb::addr_t GetReasonableReadSize(const Address &addr)
Return a recommended size for memory reads at addr, optimizing for cache usage.
Definition Target.cpp:2347
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:4852
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:2914
FileSpecList GetSafeAutoLoadPaths() const
Get the list of paths that LLDB will consider automatically loading scripting resources from.
Definition Target.cpp:6169
static TargetProperties & GetGlobalProperties()
Definition Target.cpp:3493
Status Install(ProcessLaunchInfo *launch_info)
Definition Target.cpp:3501
HookSP GetHookAtIndex(size_t index)
Definition Target.cpp:4873
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:2953
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:2451
void InvalidateThreadFrameProviders()
Invalidate all potentially cached frame providers for all threads and trigger a stack changed event f...
Definition Target.cpp:3996
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:3570
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:4102
void ClearScriptedFrameProviderDescriptors()
Clear all scripted frame provider descriptors for this target.
Definition Target.cpp:3978
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:2851
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:2735
void PrintDummySignals(Stream &strm, Args &signals)
Print all the signals set in this target.
Definition Target.cpp:4196
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:3540
BreakpointName * FindBreakpointName(llvm::StringRef name, bool can_create, Status &error)
Definition Target.cpp:909
Status Attach(ProcessAttachInfo &attach_info, Stream *stream)
Definition Target.cpp:3837
static void SetDefaultArchitecture(const ArchSpec &arch)
Definition Target.cpp:2957
lldb::BreakpointSP m_last_created_breakpoint
Definition Target.h:2167
bool RemoveStopHookByID(lldb::user_id_t uid)
Definition Target.cpp:3226
friend class Debugger
Definition Target.h:605
static void SettingsInitialize()
Definition Target.cpp:2941
~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:2995
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:4942
@ 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:671
llvm::StringRef GetDescription() const
Definition Language.cpp:678
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