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