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
19#include "lldb/Core/Debugger.h"
20#include "lldb/Core/Module.h"
24#include "lldb/Core/Section.h"
33#include "lldb/Host/Host.h"
34#include "lldb/Host/PosixApi.h"
44#include "lldb/Symbol/Symbol.h"
45#include "lldb/Target/ABI.h"
49#include "lldb/Target/Process.h"
55#include "lldb/Target/Thread.h"
58#include "lldb/Utility/Event.h"
62#include "lldb/Utility/Log.h"
64#include "lldb/Utility/State.h"
66#include "lldb/Utility/Timer.h"
67
68#include "llvm/ADT/ScopeExit.h"
69#include "llvm/ADT/SetVector.h"
70#include "llvm/Support/ThreadPool.h"
71
72#include <memory>
73#include <mutex>
74#include <optional>
75#include <sstream>
76
77using namespace lldb;
78using namespace lldb_private;
79
80namespace {
81
82struct ExecutableInstaller {
83
84 ExecutableInstaller(PlatformSP platform, ModuleSP module)
85 : m_platform{platform}, m_module{module},
86 m_local_file{m_module->GetFileSpec()},
87 m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
88
89 void setupRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
90
91 PlatformSP m_platform;
92 ModuleSP m_module;
93 const FileSpec m_local_file;
94 const FileSpec m_remote_file;
95};
96
97struct MainExecutableInstaller {
98
99 MainExecutableInstaller(PlatformSP platform, ModuleSP module, TargetSP target,
100 ProcessLaunchInfo &launch_info)
101 : m_platform{platform}, m_module{module},
102 m_local_file{m_module->GetFileSpec()},
103 m_remote_file{
104 getRemoteFileSpec(m_platform, target, m_module, m_local_file)},
105 m_launch_info{launch_info} {}
106
107 void setupRemoteFile() const {
108 m_module->SetPlatformFileSpec(m_remote_file);
109 m_launch_info.SetExecutableFile(m_remote_file,
110 /*add_exe_file_as_first_arg=*/false);
111 m_platform->SetFilePermissions(m_remote_file, 0700 /*-rwx------*/);
112 }
113
114 PlatformSP m_platform;
115 ModuleSP m_module;
116 const FileSpec m_local_file;
117 const FileSpec m_remote_file;
118
119private:
120 static FileSpec getRemoteFileSpec(PlatformSP platform, TargetSP target,
121 ModuleSP module,
122 const FileSpec &local_file) {
123 FileSpec remote_file = module->GetRemoteInstallFileSpec();
124 if (remote_file || !target->GetAutoInstallMainExecutable())
125 return remote_file;
126
127 if (!local_file)
128 return {};
129
130 remote_file = platform->GetRemoteWorkingDirectory();
131 remote_file.AppendPathComponent(local_file.GetFilename().GetCString());
132
133 return remote_file;
134 }
135
136 ProcessLaunchInfo &m_launch_info;
137};
138} // namespace
139
140template <typename Installer>
141static Status installExecutable(const Installer &installer) {
142 if (!installer.m_local_file || !installer.m_remote_file)
143 return Status();
144
145 Status error = installer.m_platform->Install(installer.m_local_file,
146 installer.m_remote_file);
147 if (error.Fail())
148 return error;
149
150 installer.setupRemoteFile();
151 return Status();
152}
153
154constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
155
157 : m_spec(spec),
158 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
159
161 m_spec = spec;
163 return *this;
164}
165
167 static constexpr llvm::StringLiteral class_name("lldb.target");
168 return class_name;
169}
170
171Target::Target(Debugger &debugger, const ArchSpec &target_arch,
172 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
173 : TargetProperties(this),
174 Broadcaster(debugger.GetBroadcasterManager(),
176 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
177 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
183 m_is_dummy_target(is_dummy_target),
185 std::make_unique<StackFrameRecognizerManager>()) {
186 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
187 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
188 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
189 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
190 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
191
193
194 LLDB_LOG(GetLog(LLDBLog::Object), "{0} Target::Target()",
195 static_cast<void *>(this));
196 if (target_arch.IsValid()) {
198 "Target::Target created with architecture {0} ({1})",
199 target_arch.GetArchitectureName(),
200 target_arch.GetTriple().getTriple().c_str());
201 }
202
204}
205
207 Log *log = GetLog(LLDBLog::Object);
208 LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this));
210}
211
213 m_stop_hooks = target.m_stop_hooks;
214
215 for (const auto &breakpoint_sp : target.m_breakpoint_list.Breakpoints()) {
216 if (breakpoint_sp->IsInternal())
217 continue;
218
219 BreakpointSP new_bp(
220 Breakpoint::CopyFromBreakpoint(shared_from_this(), *breakpoint_sp));
221 AddBreakpoint(std::move(new_bp), false);
222 }
223
224 for (const auto &bp_name_entry : target.m_breakpoint_names) {
225 AddBreakpointName(std::make_unique<BreakpointName>(*bp_name_entry.second));
226 }
227
228 m_frame_recognizer_manager_up = std::make_unique<StackFrameRecognizerManager>(
230
232}
233
234void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
235 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
236 if (description_level != lldb::eDescriptionLevelBrief) {
237 s->Indent();
238 s->PutCString("Target\n");
239 s->IndentMore();
240 m_images.Dump(s);
243 s->IndentLess();
244 } else {
245 Module *exe_module = GetExecutableModulePointer();
246 if (exe_module)
247 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
248 else
249 s->PutCString("No executable module.");
250 }
251}
252
254 // Do any cleanup of the target we need to do between process instances.
255 // NB It is better to do this before destroying the process in case the
256 // clean up needs some help from the process.
260 // Disable watchpoints just on the debugger side.
261 std::unique_lock<std::recursive_mutex> lock;
262 this->GetWatchpointList().GetListMutex(lock);
267}
268
270 if (m_process_sp) {
271 // We dispose any active tracing sessions on the current process
272 m_trace_sp.reset();
274 if (m_process_sp->IsAlive())
275 m_process_sp->Destroy(false);
276
277 m_process_sp->Finalize(false /* not destructing */);
278
280
281 m_process_sp.reset();
282 }
283}
284
286 llvm::StringRef plugin_name,
287 const FileSpec *crash_file,
288 bool can_connect) {
289 if (!listener_sp)
290 listener_sp = GetDebugger().GetListener();
292 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
293 listener_sp, crash_file, can_connect);
294 return m_process_sp;
295}
296
298
300 const char *repl_options, bool can_create) {
301 if (language == eLanguageTypeUnknown)
302 language = m_debugger.GetREPLLanguage();
303
304 if (language == eLanguageTypeUnknown) {
306
307 if (auto single_lang = repl_languages.GetSingularLanguage()) {
308 language = *single_lang;
309 } else if (repl_languages.Empty()) {
311 "LLDB isn't configured with REPL support for any languages.");
312 return REPLSP();
313 } else {
315 "Multiple possible REPL languages. Please specify a language.");
316 return REPLSP();
317 }
318 }
319
320 REPLMap::iterator pos = m_repl_map.find(language);
321
322 if (pos != m_repl_map.end()) {
323 return pos->second;
324 }
325
326 if (!can_create) {
328 "Couldn't find an existing REPL for %s, and can't create a new one",
330 return lldb::REPLSP();
331 }
332
333 Debugger *const debugger = nullptr;
334 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
335
336 if (ret) {
337 m_repl_map[language] = ret;
338 return m_repl_map[language];
339 }
340
341 if (err.Success()) {
343 "Couldn't create a REPL for %s",
345 }
346
347 return lldb::REPLSP();
348}
349
351 lldbassert(!m_repl_map.count(language));
352
353 m_repl_map[language] = repl_sp;
354}
355
357 std::lock_guard<std::recursive_mutex> guard(m_mutex);
358 m_valid = false;
360 m_platform_sp.reset();
361 m_arch = ArchSpec();
362 ClearModules(true);
364 const bool notify = false;
370 m_search_filter_sp.reset();
372 m_stop_hooks.clear();
374 m_suppress_stop_hooks = false;
375 m_repl_map.clear();
376 Args signal_args;
377 ClearDummySignals(signal_args);
378}
379
380llvm::StringRef Target::GetABIName() const {
381 lldb::ABISP abi_sp;
382 if (m_process_sp)
383 abi_sp = m_process_sp->GetABI();
384 if (!abi_sp)
386 if (abi_sp)
387 return abi_sp->GetPluginName();
388 return {};
389}
390
392 if (internal)
394 else
395 return m_breakpoint_list;
396}
397
398const BreakpointList &Target::GetBreakpointList(bool internal) const {
399 if (internal)
401 else
402 return m_breakpoint_list;
403}
404
406 BreakpointSP bp_sp;
407
408 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
410 else
411 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
412
413 return bp_sp;
414}
415
418 ModuleSP main_module_sp = GetExecutableModule();
419 FileSpecList shared_lib_filter;
420 shared_lib_filter.Append(main_module_sp->GetFileSpec());
421 llvm::SetVector<std::string, std::vector<std::string>,
422 std::unordered_set<std::string>>
423 entryPointNamesSet;
425 Language *lang = Language::FindPlugin(lang_type);
426 if (!lang) {
427 error = Status::FromErrorString("Language not found\n");
428 return lldb::BreakpointSP();
429 }
430 std::string entryPointName = lang->GetUserEntryPointName().str();
431 if (!entryPointName.empty())
432 entryPointNamesSet.insert(entryPointName);
433 }
434 if (entryPointNamesSet.empty()) {
435 error = Status::FromErrorString("No entry point name found\n");
436 return lldb::BreakpointSP();
437 }
438 BreakpointSP bp_sp = CreateBreakpoint(
439 &shared_lib_filter,
440 /*containingSourceFiles=*/nullptr, entryPointNamesSet.takeVector(),
441 /*func_name_type_mask=*/eFunctionNameTypeFull,
442 /*language=*/eLanguageTypeUnknown,
443 /*offset=*/0,
444 /*skip_prologue=*/eLazyBoolNo,
445 /*internal=*/false,
446 /*hardware=*/false);
447 if (!bp_sp) {
448 error = Status::FromErrorString("Breakpoint creation failed.\n");
449 return lldb::BreakpointSP();
450 }
451 bp_sp->SetOneShot(true);
452 return bp_sp;
453}
454
456 const FileSpecList *containingModules,
457 const FileSpecList *source_file_spec_list,
458 const std::unordered_set<std::string> &function_names,
459 RegularExpression source_regex, bool internal, bool hardware,
460 LazyBool move_to_nearest_code) {
462 containingModules, source_file_spec_list));
463 if (move_to_nearest_code == eLazyBoolCalculate)
464 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
466 nullptr, std::move(source_regex), function_names,
467 !static_cast<bool>(move_to_nearest_code)));
468
469 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
470}
471
473 const FileSpec &file, uint32_t line_no,
474 uint32_t column, lldb::addr_t offset,
475 LazyBool check_inlines,
476 LazyBool skip_prologue, bool internal,
477 bool hardware,
478 LazyBool move_to_nearest_code) {
479 FileSpec remapped_file;
480 std::optional<llvm::StringRef> removed_prefix_opt =
481 GetSourcePathMap().ReverseRemapPath(file, remapped_file);
482 if (!removed_prefix_opt)
483 remapped_file = file;
484
485 if (check_inlines == eLazyBoolCalculate) {
486 const InlineStrategy inline_strategy = GetInlineStrategy();
487 switch (inline_strategy) {
489 check_inlines = eLazyBoolNo;
490 break;
491
493 if (remapped_file.IsSourceImplementationFile())
494 check_inlines = eLazyBoolNo;
495 else
496 check_inlines = eLazyBoolYes;
497 break;
498
500 check_inlines = eLazyBoolYes;
501 break;
502 }
503 }
504 SearchFilterSP filter_sp;
505 if (check_inlines == eLazyBoolNo) {
506 // Not checking for inlines, we are looking only for matching compile units
507 FileSpecList compile_unit_list;
508 compile_unit_list.Append(remapped_file);
509 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
510 &compile_unit_list);
511 } else {
512 filter_sp = GetSearchFilterForModuleList(containingModules);
513 }
514 if (skip_prologue == eLazyBoolCalculate)
515 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
516 if (move_to_nearest_code == eLazyBoolCalculate)
517 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
518
519 SourceLocationSpec location_spec(remapped_file, line_no, column,
520 check_inlines,
521 !static_cast<bool>(move_to_nearest_code));
522 if (!location_spec)
523 return nullptr;
524
526 nullptr, offset, skip_prologue, location_spec, removed_prefix_opt));
527 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
528}
529
531 bool hardware) {
532 Address so_addr;
533
534 // Check for any reason we want to move this breakpoint to other address.
535 addr = GetBreakableLoadAddress(addr);
536
537 // Attempt to resolve our load address if possible, though it is ok if it
538 // doesn't resolve to section/offset.
539
540 // Try and resolve as a load address if possible
541 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
542 if (!so_addr.IsValid()) {
543 // The address didn't resolve, so just set this as an absolute address
544 so_addr.SetOffset(addr);
545 }
546 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
547 return bp_sp;
548}
549
551 bool hardware) {
552 SearchFilterSP filter_sp(
553 new SearchFilterForUnconstrainedSearches(shared_from_this()));
554 BreakpointResolverSP resolver_sp(
555 new BreakpointResolverAddress(nullptr, addr));
556 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
557}
558
561 const FileSpec &file_spec,
562 bool request_hardware) {
563 SearchFilterSP filter_sp(
564 new SearchFilterForUnconstrainedSearches(shared_from_this()));
566 nullptr, file_addr, file_spec));
567 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
568 false);
569}
570
572 const FileSpecList *containingModules,
573 const FileSpecList *containingSourceFiles, const char *func_name,
574 FunctionNameType func_name_type_mask, LanguageType language,
575 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
576 BreakpointSP bp_sp;
577 if (func_name) {
579 containingModules, containingSourceFiles));
580
581 if (skip_prologue == eLazyBoolCalculate)
582 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
583 if (language == lldb::eLanguageTypeUnknown)
584 language = GetLanguage().AsLanguageType();
585
587 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
588 offset, skip_prologue));
589 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
590 }
591 return bp_sp;
592}
593
595Target::CreateBreakpoint(const FileSpecList *containingModules,
596 const FileSpecList *containingSourceFiles,
597 const std::vector<std::string> &func_names,
598 FunctionNameType func_name_type_mask,
599 LanguageType language, lldb::addr_t offset,
600 LazyBool skip_prologue, bool internal, bool hardware) {
601 BreakpointSP bp_sp;
602 size_t num_names = func_names.size();
603 if (num_names > 0) {
605 containingModules, containingSourceFiles));
606
607 if (skip_prologue == eLazyBoolCalculate)
608 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
609 if (language == lldb::eLanguageTypeUnknown)
610 language = GetLanguage().AsLanguageType();
611
612 BreakpointResolverSP resolver_sp(
613 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
614 language, offset, skip_prologue));
615 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
616 }
617 return bp_sp;
618}
619
621Target::CreateBreakpoint(const FileSpecList *containingModules,
622 const FileSpecList *containingSourceFiles,
623 const char *func_names[], size_t num_names,
624 FunctionNameType func_name_type_mask,
625 LanguageType language, lldb::addr_t offset,
626 LazyBool skip_prologue, bool internal, bool hardware) {
627 BreakpointSP bp_sp;
628 if (num_names > 0) {
630 containingModules, containingSourceFiles));
631
632 if (skip_prologue == eLazyBoolCalculate) {
633 if (offset == 0)
634 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
635 else
636 skip_prologue = eLazyBoolNo;
637 }
638 if (language == lldb::eLanguageTypeUnknown)
639 language = GetLanguage().AsLanguageType();
640
642 nullptr, func_names, num_names, func_name_type_mask, language, offset,
643 skip_prologue));
644 resolver_sp->SetOffset(offset);
645 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
646 }
647 return bp_sp;
648}
649
652 SearchFilterSP filter_sp;
653 if (containingModule != nullptr) {
654 // TODO: We should look into sharing module based search filters
655 // across many breakpoints like we do for the simple target based one
656 filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(),
657 *containingModule);
658 } else {
661 std::make_shared<SearchFilterForUnconstrainedSearches>(
662 shared_from_this());
663 filter_sp = m_search_filter_sp;
664 }
665 return filter_sp;
666}
667
670 SearchFilterSP filter_sp;
671 if (containingModules && containingModules->GetSize() != 0) {
672 // TODO: We should look into sharing module based search filters
673 // across many breakpoints like we do for the simple target based one
674 filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(),
675 *containingModules);
676 } else {
679 std::make_shared<SearchFilterForUnconstrainedSearches>(
680 shared_from_this());
681 filter_sp = m_search_filter_sp;
682 }
683 return filter_sp;
684}
685
687 const FileSpecList *containingModules,
688 const FileSpecList *containingSourceFiles) {
689 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
690 return GetSearchFilterForModuleList(containingModules);
691
692 SearchFilterSP filter_sp;
693 if (containingModules == nullptr) {
694 // We could make a special "CU List only SearchFilter". Better yet was if
695 // these could be composable, but that will take a little reworking.
696
697 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
698 shared_from_this(), FileSpecList(), *containingSourceFiles);
699 } else {
700 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
701 shared_from_this(), *containingModules, *containingSourceFiles);
702 }
703 return filter_sp;
704}
705
707 const FileSpecList *containingModules,
708 const FileSpecList *containingSourceFiles, RegularExpression func_regex,
709 lldb::LanguageType requested_language, LazyBool skip_prologue,
710 bool internal, bool hardware) {
712 containingModules, containingSourceFiles));
713 bool skip = (skip_prologue == eLazyBoolCalculate)
715 : static_cast<bool>(skip_prologue);
717 nullptr, std::move(func_regex), requested_language, 0, skip));
718
719 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
720}
721
724 bool catch_bp, bool throw_bp, bool internal,
725 Args *additional_args, Status *error) {
727 *this, language, catch_bp, throw_bp, internal);
728 if (exc_bkpt_sp && additional_args) {
729 BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
730 if (precondition_sp && additional_args) {
731 if (error)
732 *error = precondition_sp->ConfigurePrecondition(*additional_args);
733 else
734 precondition_sp->ConfigurePrecondition(*additional_args);
735 }
736 }
737 return exc_bkpt_sp;
738}
739
741 const llvm::StringRef class_name, const FileSpecList *containingModules,
742 const FileSpecList *containingSourceFiles, bool internal,
743 bool request_hardware, StructuredData::ObjectSP extra_args_sp,
744 Status *creation_error) {
745 SearchFilterSP filter_sp;
746
748 bool has_files =
749 containingSourceFiles && containingSourceFiles->GetSize() > 0;
750 bool has_modules = containingModules && containingModules->GetSize() > 0;
751
752 if (has_files && has_modules) {
753 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
754 containingSourceFiles);
755 } else if (has_files) {
756 filter_sp =
757 GetSearchFilterForModuleAndCUList(nullptr, containingSourceFiles);
758 } else if (has_modules) {
759 filter_sp = GetSearchFilterForModuleList(containingModules);
760 } else {
761 filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
762 shared_from_this());
763 }
764
766 nullptr, class_name, depth, StructuredDataImpl(extra_args_sp)));
767 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
768}
769
771 BreakpointResolverSP &resolver_sp,
772 bool internal, bool request_hardware,
773 bool resolve_indirect_symbols) {
774 BreakpointSP bp_sp;
775 if (filter_sp && resolver_sp) {
776 const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
777 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
778 resolve_indirect_symbols));
779 resolver_sp->SetBreakpoint(bp_sp);
780 AddBreakpoint(bp_sp, internal);
781 }
782 return bp_sp;
783}
784
785void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
786 if (!bp_sp)
787 return;
788 if (internal)
789 m_internal_breakpoint_list.Add(bp_sp, false);
790 else
791 m_breakpoint_list.Add(bp_sp, true);
792
794 if (log) {
795 StreamString s;
796 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
797 LLDB_LOGF(log, "Target::%s (internal = %s) => break_id = %s\n",
798 __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
799 }
800
801 bp_sp->ResolveBreakpoint();
802
803 if (!internal) {
805 }
806}
807
808void Target::AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name,
809 Status &error) {
810 BreakpointSP bp_sp =
811 m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
812 if (!bp_sp) {
813 StreamString s;
814 id.GetDescription(&s, eDescriptionLevelBrief);
815 error = Status::FromErrorStringWithFormat("Could not find breakpoint %s",
816 s.GetData());
817 return;
818 }
819 AddNameToBreakpoint(bp_sp, name, error);
820}
821
822void Target::AddNameToBreakpoint(BreakpointSP &bp_sp, llvm::StringRef name,
823 Status &error) {
824 if (!bp_sp)
825 return;
826
827 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
828 if (!bp_name)
829 return;
830
831 bp_name->ConfigureBreakpoint(bp_sp);
832 bp_sp->AddName(name);
833}
834
835void Target::AddBreakpointName(std::unique_ptr<BreakpointName> bp_name) {
836 m_breakpoint_names.insert(
837 std::make_pair(bp_name->GetName(), std::move(bp_name)));
838}
839
841 Status &error) {
843 if (!error.Success())
844 return nullptr;
845
846 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
847 if (iter != m_breakpoint_names.end()) {
848 return iter->second.get();
849 }
850
851 if (!can_create) {
853 "Breakpoint name \"%s\" doesn't exist and "
854 "can_create is false.",
855 name.AsCString());
856 return nullptr;
857 }
858
859 return m_breakpoint_names
860 .insert(std::make_pair(name, std::make_unique<BreakpointName>(name)))
861 .first->second.get();
862}
863
865 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
866
867 if (iter != m_breakpoint_names.end()) {
868 const char *name_cstr = name.AsCString();
869 m_breakpoint_names.erase(iter);
870 for (auto bp_sp : m_breakpoint_list.Breakpoints())
871 bp_sp->RemoveName(name_cstr);
872 }
873}
874
876 ConstString name) {
877 bp_sp->RemoveName(name.AsCString());
878}
879
881 BreakpointName &bp_name, const BreakpointOptions &new_options,
882 const BreakpointName::Permissions &new_permissions) {
883 bp_name.GetOptions().CopyOverSetOptions(new_options);
884 bp_name.GetPermissions().MergeInto(new_permissions);
885 ApplyNameToBreakpoints(bp_name);
886}
887
889 llvm::Expected<std::vector<BreakpointSP>> expected_vector =
891
892 if (!expected_vector) {
893 LLDB_LOG(GetLog(LLDBLog::Breakpoints), "invalid breakpoint name: {}",
894 llvm::toString(expected_vector.takeError()));
895 return;
896 }
897
898 for (auto bp_sp : *expected_vector)
899 bp_name.ConfigureBreakpoint(bp_sp);
900}
901
902void Target::GetBreakpointNames(std::vector<std::string> &names) {
903 names.clear();
904 for (const auto& bp_name_entry : m_breakpoint_names) {
905 names.push_back(bp_name_entry.first.AsCString());
906 }
907 llvm::sort(names);
908}
909
911 return (m_process_sp && m_process_sp->IsAlive());
912}
913
915 std::optional<uint32_t> num_supported_hardware_watchpoints =
916 target->GetProcessSP()->GetWatchpointSlotCount();
917
918 // If unable to determine the # of watchpoints available,
919 // assume they are supported.
920 if (!num_supported_hardware_watchpoints)
921 return true;
922
923 if (*num_supported_hardware_watchpoints == 0) {
925 "Target supports (%u) hardware watchpoint slots.\n",
926 *num_supported_hardware_watchpoints);
927 return false;
928 }
929 return true;
930}
931
932// See also Watchpoint::SetWatchpointType(uint32_t type) and the
933// OptionGroupWatchpoint::WatchType enum type.
935 const CompilerType *type, uint32_t kind,
936 Status &error) {
938 LLDB_LOGF(log,
939 "Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
940 " type = %u)\n",
941 __FUNCTION__, addr, (uint64_t)size, kind);
942
943 WatchpointSP wp_sp;
944 if (!ProcessIsValid()) {
945 error = Status::FromErrorString("process is not alive");
946 return wp_sp;
947 }
948
949 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
950 if (size == 0)
952 "cannot set a watchpoint with watch_size of 0");
953 else
955 "invalid watch address: %" PRIu64, addr);
956 return wp_sp;
957 }
958
959 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
960 error =
961 Status::FromErrorStringWithFormat("invalid watchpoint type: %d", kind);
962 }
963
965 return wp_sp;
966
967 // Currently we only support one watchpoint per address, with total number of
968 // watchpoints limited by the hardware which the inferior is running on.
969
970 // Grab the list mutex while doing operations.
971 const bool notify = false; // Don't notify about all the state changes we do
972 // on creating the watchpoint.
973
974 // Mask off ignored bits from watchpoint address.
975 if (ABISP abi = m_process_sp->GetABI())
976 addr = abi->FixDataAddress(addr);
977
978 // LWP_TODO this sequence is looking for an existing watchpoint
979 // at the exact same user-specified address, disables the new one
980 // if addr/size/type match. If type/size differ, disable old one.
981 // This isn't correct, we need both watchpoints to use a shared
982 // WatchpointResource in the target, and expand the WatchpointResource
983 // to handle the needs of both Watchpoints.
984 // Also, even if the addresses don't match, they may need to be
985 // supported by the same WatchpointResource, e.g. a watchpoint
986 // watching 1 byte at 0x102 and a watchpoint watching 1 byte at 0x103.
987 // They're in the same word and must be watched by a single hardware
988 // watchpoint register.
989
990 std::unique_lock<std::recursive_mutex> lock;
991 this->GetWatchpointList().GetListMutex(lock);
993 if (matched_sp) {
994 size_t old_size = matched_sp->GetByteSize();
995 uint32_t old_type =
996 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
997 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0) |
998 (matched_sp->WatchpointModify() ? LLDB_WATCH_TYPE_MODIFY : 0);
999 // Return the existing watchpoint if both size and type match.
1000 if (size == old_size && kind == old_type) {
1001 wp_sp = matched_sp;
1002 wp_sp->SetEnabled(false, notify);
1003 } else {
1004 // Nil the matched watchpoint; we will be creating a new one.
1005 m_process_sp->DisableWatchpoint(matched_sp, notify);
1006 m_watchpoint_list.Remove(matched_sp->GetID(), true);
1007 }
1008 }
1009
1010 if (!wp_sp) {
1011 wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type);
1012 wp_sp->SetWatchpointType(kind, notify);
1013 m_watchpoint_list.Add(wp_sp, true);
1014 }
1015
1016 error = m_process_sp->EnableWatchpoint(wp_sp, notify);
1017 LLDB_LOGF(log, "Target::%s (creation of watchpoint %s with id = %u)\n",
1018 __FUNCTION__, error.Success() ? "succeeded" : "failed",
1019 wp_sp->GetID());
1020
1021 if (error.Fail()) {
1022 // Enabling the watchpoint on the device side failed. Remove the said
1023 // watchpoint from the list maintained by the target instance.
1024 m_watchpoint_list.Remove(wp_sp->GetID(), true);
1025 wp_sp.reset();
1026 } else
1028 return wp_sp;
1029}
1030
1033 LLDB_LOGF(log, "Target::%s \n", __FUNCTION__);
1034
1036
1038}
1039
1040void Target::RemoveAllBreakpoints(bool internal_also) {
1042 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1043 internal_also ? "yes" : "no");
1044
1046 if (internal_also)
1048
1050}
1051
1052void Target::DisableAllBreakpoints(bool internal_also) {
1054 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1055 internal_also ? "yes" : "no");
1056
1058 if (internal_also)
1060}
1061
1064 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
1065
1067}
1068
1069void Target::EnableAllBreakpoints(bool internal_also) {
1071 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1072 internal_also ? "yes" : "no");
1073
1075 if (internal_also)
1077}
1078
1081 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
1082
1084}
1085
1088 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1089 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1090
1091 if (DisableBreakpointByID(break_id)) {
1092 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1093 m_internal_breakpoint_list.Remove(break_id, false);
1094 else {
1096 if (m_last_created_breakpoint->GetID() == break_id)
1098 }
1099 m_breakpoint_list.Remove(break_id, true);
1100 }
1101 return true;
1102 }
1103 return false;
1104}
1105
1108 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1109 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1110
1111 BreakpointSP bp_sp;
1112
1113 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1115 else
1116 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1117 if (bp_sp) {
1118 bp_sp->SetEnabled(false);
1119 return true;
1120 }
1121 return false;
1122}
1123
1126 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1127 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1128
1129 BreakpointSP bp_sp;
1130
1131 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1133 else
1134 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1135
1136 if (bp_sp) {
1137 bp_sp->SetEnabled(true);
1138 return true;
1139 }
1140 return false;
1141}
1142
1145}
1146
1148 const BreakpointIDList &bp_ids,
1149 bool append) {
1150 Status error;
1151
1152 if (!file) {
1153 error = Status::FromErrorString("Invalid FileSpec.");
1154 return error;
1155 }
1156
1157 std::string path(file.GetPath());
1158 StructuredData::ObjectSP input_data_sp;
1159
1160 StructuredData::ArraySP break_store_sp;
1161 StructuredData::Array *break_store_ptr = nullptr;
1162
1163 if (append) {
1164 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1165 if (error.Success()) {
1166 break_store_ptr = input_data_sp->GetAsArray();
1167 if (!break_store_ptr) {
1169 "Tried to append to invalid input file %s", path.c_str());
1170 return error;
1171 }
1172 }
1173 }
1174
1175 if (!break_store_ptr) {
1176 break_store_sp = std::make_shared<StructuredData::Array>();
1177 break_store_ptr = break_store_sp.get();
1178 }
1179
1180 StreamFile out_file(path.c_str(),
1184 lldb::eFilePermissionsFileDefault);
1185 if (!out_file.GetFile().IsValid()) {
1186 error = Status::FromErrorStringWithFormat("Unable to open output file: %s.",
1187 path.c_str());
1188 return error;
1189 }
1190
1191 std::unique_lock<std::recursive_mutex> lock;
1193
1194 if (bp_ids.GetSize() == 0) {
1195 const BreakpointList &breakpoints = GetBreakpointList();
1196
1197 size_t num_breakpoints = breakpoints.GetSize();
1198 for (size_t i = 0; i < num_breakpoints; i++) {
1199 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1201 // If a breakpoint can't serialize it, just ignore it for now:
1202 if (bkpt_save_sp)
1203 break_store_ptr->AddItem(bkpt_save_sp);
1204 }
1205 } else {
1206
1207 std::unordered_set<lldb::break_id_t> processed_bkpts;
1208 const size_t count = bp_ids.GetSize();
1209 for (size_t i = 0; i < count; ++i) {
1210 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1211 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1212
1213 if (bp_id != LLDB_INVALID_BREAK_ID) {
1214 // Only do each breakpoint once:
1215 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1216 insert_result = processed_bkpts.insert(bp_id);
1217 if (!insert_result.second)
1218 continue;
1219
1220 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1222 // If the user explicitly asked to serialize a breakpoint, and we
1223 // can't, then raise an error:
1224 if (!bkpt_save_sp) {
1226 "Unable to serialize breakpoint %d", bp_id);
1227 return error;
1228 }
1229 break_store_ptr->AddItem(bkpt_save_sp);
1230 }
1231 }
1232 }
1233
1234 break_store_ptr->Dump(out_file, false);
1235 out_file.PutChar('\n');
1236 return error;
1237}
1238
1240 BreakpointIDList &new_bps) {
1241 std::vector<std::string> no_names;
1242 return CreateBreakpointsFromFile(file, no_names, new_bps);
1243}
1244
1246 std::vector<std::string> &names,
1247 BreakpointIDList &new_bps) {
1248 std::unique_lock<std::recursive_mutex> lock;
1250
1251 Status error;
1252 StructuredData::ObjectSP input_data_sp =
1254 if (!error.Success()) {
1255 return error;
1256 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1258 "Invalid JSON from input file: %s.", file.GetPath().c_str());
1259 return error;
1260 }
1261
1262 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1263 if (!bkpt_array) {
1265 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1266 return error;
1267 }
1268
1269 size_t num_bkpts = bkpt_array->GetSize();
1270 size_t num_names = names.size();
1271
1272 for (size_t i = 0; i < num_bkpts; i++) {
1273 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1274 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1275 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1276 if (!bkpt_dict) {
1278 "Invalid breakpoint data for element %zu from input file: %s.", i,
1279 file.GetPath().c_str());
1280 return error;
1281 }
1282 StructuredData::ObjectSP bkpt_data_sp =
1284 if (num_names &&
1286 continue;
1287
1289 shared_from_this(), bkpt_data_sp, error);
1290 if (!error.Success()) {
1292 "Error restoring breakpoint %zu from %s: %s.", i,
1293 file.GetPath().c_str(), error.AsCString());
1294 return error;
1295 }
1296 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1297 }
1298 return error;
1299}
1300
1301// The flag 'end_to_end', default to true, signifies that the operation is
1302// performed end to end, for both the debugger and the debuggee.
1303
1304// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1305// to end operations.
1306bool Target::RemoveAllWatchpoints(bool end_to_end) {
1308 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1309
1310 if (!end_to_end) {
1312 return true;
1313 }
1314
1315 // Otherwise, it's an end to end operation.
1316
1317 if (!ProcessIsValid())
1318 return false;
1319
1321 if (!wp_sp)
1322 return false;
1323
1324 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1325 if (rc.Fail())
1326 return false;
1327 }
1330 return true; // Success!
1331}
1332
1333// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1334// to end operations.
1335bool Target::DisableAllWatchpoints(bool end_to_end) {
1337 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1338
1339 if (!end_to_end) {
1341 return true;
1342 }
1343
1344 // Otherwise, it's an end to end operation.
1345
1346 if (!ProcessIsValid())
1347 return false;
1348
1350 if (!wp_sp)
1351 return false;
1352
1353 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1354 if (rc.Fail())
1355 return false;
1356 }
1357 return true; // Success!
1358}
1359
1360// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1361// to end operations.
1362bool Target::EnableAllWatchpoints(bool end_to_end) {
1364 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1365
1366 if (!end_to_end) {
1368 return true;
1369 }
1370
1371 // Otherwise, it's an end to end operation.
1372
1373 if (!ProcessIsValid())
1374 return false;
1375
1377 if (!wp_sp)
1378 return false;
1379
1380 Status rc = m_process_sp->EnableWatchpoint(wp_sp);
1381 if (rc.Fail())
1382 return false;
1383 }
1384 return true; // Success!
1385}
1386
1387// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1390 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1391
1393 if (!wp_sp)
1394 return false;
1395
1396 wp_sp->ResetHitCount();
1397 }
1398 return true; // Success!
1399}
1400
1401// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1404 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1405
1407 if (!wp_sp)
1408 return false;
1409
1410 wp_sp->ResetHistoricValues();
1411 }
1412 return true; // Success!
1413}
1414
1415// Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1416// these operations.
1417bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1419 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1420
1421 if (!ProcessIsValid())
1422 return false;
1423
1425 if (!wp_sp)
1426 return false;
1427
1428 wp_sp->SetIgnoreCount(ignore_count);
1429 }
1430 return true; // Success!
1431}
1432
1433// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1436 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1437
1438 if (!ProcessIsValid())
1439 return false;
1440
1441 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1442 if (wp_sp) {
1443 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1444 if (rc.Success())
1445 return true;
1446
1447 // Else, fallthrough.
1448 }
1449 return false;
1450}
1451
1452// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1455 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1456
1457 if (!ProcessIsValid())
1458 return false;
1459
1460 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1461 if (wp_sp) {
1462 Status rc = m_process_sp->EnableWatchpoint(wp_sp);
1463 if (rc.Success())
1464 return true;
1465
1466 // Else, fallthrough.
1467 }
1468 return false;
1469}
1470
1471// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1474 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1475
1476 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1477 if (watch_to_remove_sp == m_last_created_watchpoint)
1479
1480 if (DisableWatchpointByID(watch_id)) {
1481 m_watchpoint_list.Remove(watch_id, true);
1482 return true;
1483 }
1484 return false;
1485}
1486
1487// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1489 uint32_t ignore_count) {
1491 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1492
1493 if (!ProcessIsValid())
1494 return false;
1495
1496 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1497 if (wp_sp) {
1498 wp_sp->SetIgnoreCount(ignore_count);
1499 return true;
1500 }
1501 return false;
1502}
1503
1505 // search for the first executable in the module list
1506 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1507 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1508 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1509 if (obj == nullptr)
1510 continue;
1512 return module_sp;
1513 }
1514 // as fall back return the first module loaded
1515 return m_images.GetModuleAtIndex(0);
1516}
1517
1519 return GetExecutableModule().get();
1520}
1521
1522static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1523 Target *target) {
1524 Status error;
1525 StreamString feedback_stream;
1526 if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error,
1527 feedback_stream)) {
1528 if (error.AsCString())
1529 target->GetDebugger().GetErrorStream().Printf(
1530 "unable to load scripting data for module %s - error reported was "
1531 "%s\n",
1532 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1533 error.AsCString());
1534 }
1535 if (feedback_stream.GetSize())
1536 target->GetDebugger().GetErrorStream().Printf("%s\n",
1537 feedback_stream.GetData());
1538}
1539
1540void Target::ClearModules(bool delete_locations) {
1541 ModulesDidUnload(m_images, delete_locations);
1543 m_images.Clear();
1545}
1546
1548 // When a process exec's we need to know about it so we can do some cleanup.
1551}
1552
1554 LoadDependentFiles load_dependent_files) {
1555 Log *log = GetLog(LLDBLog::Target);
1556 ClearModules(false);
1557
1558 if (executable_sp) {
1560 LLDB_SCOPED_TIMERF("Target::SetExecutableModule (executable = '%s')",
1561 executable_sp->GetFileSpec().GetPath().c_str());
1562
1563 const bool notify = true;
1564 m_images.Append(executable_sp,
1565 notify); // The first image is our executable file
1566
1567 // If we haven't set an architecture yet, reset our architecture based on
1568 // what we found in the executable module.
1569 if (!m_arch.GetSpec().IsValid()) {
1570 m_arch = executable_sp->GetArchitecture();
1571 LLDB_LOG(log,
1572 "Target::SetExecutableModule setting architecture to {0} ({1}) "
1573 "based on executable file",
1575 m_arch.GetSpec().GetTriple().getTriple());
1576 }
1577
1578 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1579 bool load_dependents = true;
1580 switch (load_dependent_files) {
1582 load_dependents = executable_sp->IsExecutable();
1583 break;
1584 case eLoadDependentsYes:
1585 load_dependents = true;
1586 break;
1587 case eLoadDependentsNo:
1588 load_dependents = false;
1589 break;
1590 }
1591
1592 if (executable_objfile && load_dependents) {
1593 // FileSpecList is not thread safe and needs to be synchronized.
1594 FileSpecList dependent_files;
1595 std::mutex dependent_files_mutex;
1596
1597 // ModuleList is thread safe.
1598 ModuleList added_modules;
1599
1600 auto GetDependentModules = [&](FileSpec dependent_file_spec) {
1601 FileSpec platform_dependent_file_spec;
1602 if (m_platform_sp)
1603 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1604 platform_dependent_file_spec);
1605 else
1606 platform_dependent_file_spec = dependent_file_spec;
1607
1608 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1609 ModuleSP image_module_sp(
1610 GetOrCreateModule(module_spec, false /* notify */));
1611 if (image_module_sp) {
1612 added_modules.AppendIfNeeded(image_module_sp, false);
1613 ObjectFile *objfile = image_module_sp->GetObjectFile();
1614 if (objfile) {
1615 // Create a local copy of the dependent file list so we don't have
1616 // to lock for the whole duration of GetDependentModules.
1617 FileSpecList dependent_files_copy;
1618 {
1619 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1620 dependent_files_copy = dependent_files;
1621 }
1622
1623 // Remember the size of the local copy so we can append only the
1624 // modules that have been added by GetDependentModules.
1625 const size_t previous_dependent_files =
1626 dependent_files_copy.GetSize();
1627
1628 objfile->GetDependentModules(dependent_files_copy);
1629
1630 {
1631 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1632 for (size_t i = previous_dependent_files;
1633 i < dependent_files_copy.GetSize(); ++i)
1634 dependent_files.AppendIfUnique(
1635 dependent_files_copy.GetFileSpecAtIndex(i));
1636 }
1637 }
1638 }
1639 };
1640
1641 executable_objfile->GetDependentModules(dependent_files);
1642
1643 llvm::ThreadPoolTaskGroup task_group(Debugger::GetThreadPool());
1644 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1645 // Process all currently known dependencies in parallel in the innermost
1646 // loop. This may create newly discovered dependencies to be appended to
1647 // dependent_files. We'll deal with these files during the next
1648 // iteration of the outermost loop.
1649 {
1650 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1651 for (; i < dependent_files.GetSize(); i++)
1652 task_group.async(GetDependentModules,
1653 dependent_files.GetFileSpecAtIndex(i));
1654 }
1655 task_group.wait();
1656 }
1657 ModulesDidLoad(added_modules);
1658 }
1659 }
1660}
1661
1662bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform,
1663 bool merge) {
1664 Log *log = GetLog(LLDBLog::Target);
1665 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1666 bool replace_local_arch = true;
1667 bool compatible_local_arch = false;
1668 ArchSpec other(arch_spec);
1669
1670 // Changing the architecture might mean that the currently selected platform
1671 // isn't compatible. Set the platform correctly if we are asked to do so,
1672 // otherwise assume the user will set the platform manually.
1673 if (set_platform) {
1674 if (other.IsValid()) {
1675 auto platform_sp = GetPlatform();
1676 if (!platform_sp || !platform_sp->IsCompatibleArchitecture(
1677 other, {}, ArchSpec::CompatibleMatch, nullptr)) {
1678 ArchSpec platform_arch;
1679 if (PlatformSP arch_platform_sp =
1680 GetDebugger().GetPlatformList().GetOrCreate(other, {},
1681 &platform_arch)) {
1682 SetPlatform(arch_platform_sp);
1683 if (platform_arch.IsValid())
1684 other = platform_arch;
1685 }
1686 }
1687 }
1688 }
1689
1690 if (!missing_local_arch) {
1691 if (merge && m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1692 other.MergeFrom(m_arch.GetSpec());
1693
1694 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1695 compatible_local_arch = true;
1696
1697 if (m_arch.GetSpec().GetTriple() == other.GetTriple())
1698 replace_local_arch = false;
1699 }
1700 }
1701 }
1702
1703 if (compatible_local_arch || missing_local_arch) {
1704 // If we haven't got a valid arch spec, or the architectures are compatible
1705 // update the architecture, unless the one we already have is more
1706 // specified
1707 if (replace_local_arch)
1708 m_arch = other;
1709 LLDB_LOG(log,
1710 "Target::SetArchitecture merging compatible arch; arch "
1711 "is now {0} ({1})",
1713 m_arch.GetSpec().GetTriple().getTriple());
1714 return true;
1715 }
1716
1717 // If we have an executable file, try to reset the executable to the desired
1718 // architecture
1719 LLDB_LOGF(
1720 log,
1721 "Target::SetArchitecture changing architecture to %s (%s) from %s (%s)",
1722 arch_spec.GetArchitectureName(),
1723 arch_spec.GetTriple().getTriple().c_str(),
1725 m_arch.GetSpec().GetTriple().getTriple().c_str());
1726 m_arch = other;
1727 ModuleSP executable_sp = GetExecutableModule();
1728
1729 ClearModules(true);
1730 // Need to do something about unsetting breakpoints.
1731
1732 if (executable_sp) {
1733 LLDB_LOGF(log,
1734 "Target::SetArchitecture Trying to select executable file "
1735 "architecture %s (%s)",
1736 arch_spec.GetArchitectureName(),
1737 arch_spec.GetTriple().getTriple().c_str());
1738 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1739 FileSpecList search_paths = GetExecutableSearchPaths();
1740 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1741 &search_paths, nullptr, nullptr);
1742
1743 if (!error.Fail() && executable_sp) {
1745 return true;
1746 }
1747 }
1748 return false;
1749}
1750
1751bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1752 Log *log = GetLog(LLDBLog::Target);
1753 if (arch_spec.IsValid()) {
1754 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1755 // The current target arch is compatible with "arch_spec", see if we can
1756 // improve our current architecture using bits from "arch_spec"
1757
1758 LLDB_LOGF(log,
1759 "Target::MergeArchitecture target has arch %s, merging with "
1760 "arch %s",
1761 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1762 arch_spec.GetTriple().getTriple().c_str());
1763
1764 // Merge bits from arch_spec into "merged_arch" and set our architecture
1765 ArchSpec merged_arch(m_arch.GetSpec());
1766 merged_arch.MergeFrom(arch_spec);
1767 return SetArchitecture(merged_arch);
1768 } else {
1769 // The new architecture is different, we just need to replace it
1770 return SetArchitecture(arch_spec);
1771 }
1772 }
1773 return false;
1774}
1775
1776void Target::NotifyWillClearList(const ModuleList &module_list) {}
1777
1779 const ModuleSP &module_sp) {
1780 // A module is being added to this target for the first time
1781 if (m_valid) {
1782 ModuleList my_module_list;
1783 my_module_list.Append(module_sp);
1784 ModulesDidLoad(my_module_list);
1785 }
1786}
1787
1789 const ModuleSP &module_sp) {
1790 // A module is being removed from this target.
1791 if (m_valid) {
1792 ModuleList my_module_list;
1793 my_module_list.Append(module_sp);
1794 ModulesDidUnload(my_module_list, false);
1795 }
1796}
1797
1799 const ModuleSP &old_module_sp,
1800 const ModuleSP &new_module_sp) {
1801 // A module is replacing an already added module
1802 if (m_valid) {
1804 new_module_sp);
1806 old_module_sp, new_module_sp);
1807 }
1808}
1809
1811 ModulesDidUnload(module_list, false);
1812}
1813
1815 const size_t num_images = module_list.GetSize();
1816 if (m_valid && num_images) {
1817 for (size_t idx = 0; idx < num_images; ++idx) {
1818 ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1819 LoadScriptingResourceForModule(module_sp, this);
1820 LoadTypeSummariesForModule(module_sp);
1821 LoadFormattersForModule(module_sp);
1822 }
1823 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1824 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1825 if (m_process_sp) {
1826 m_process_sp->ModulesDidLoad(module_list);
1827 }
1828 auto data_sp =
1829 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1831 }
1832}
1833
1835 if (m_valid && module_list.GetSize()) {
1836 if (m_process_sp) {
1837 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1838 runtime->SymbolsDidLoad(module_list);
1839 }
1840 }
1841
1842 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1843 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1844 auto data_sp =
1845 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1847 }
1848}
1849
1850void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1851 if (m_valid && module_list.GetSize()) {
1852 UnloadModuleSections(module_list);
1853 auto data_sp =
1854 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1856 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1858 delete_locations);
1859
1860 // If a module was torn down it will have torn down the 'TypeSystemClang's
1861 // that we used as source 'ASTContext's for the persistent variables in
1862 // the current target. Those would now be unsafe to access because the
1863 // 'DeclOrigin' are now possibly stale. Thus clear all persistent
1864 // variables. We only want to flush 'TypeSystem's if the module being
1865 // unloaded was capable of describing a source type. JITted module unloads
1866 // happen frequently for Objective-C utility functions or the REPL and rely
1867 // on the persistent variables to stick around.
1868 const bool should_flush_type_systems =
1869 module_list.AnyOf([](lldb_private::Module &module) {
1870 auto *object_file = module.GetObjectFile();
1871
1872 if (!object_file)
1873 return false;
1874
1875 auto type = object_file->GetType();
1876
1877 // eTypeExecutable: when debugged binary was rebuilt
1878 // eTypeSharedLibrary: if dylib was re-loaded
1879 return module.FileHasChanged() &&
1880 (type == ObjectFile::eTypeObjectFile ||
1883 });
1884
1885 if (should_flush_type_systems)
1887 }
1888}
1889
1891 const FileSpec &module_file_spec) {
1893 ModuleList matchingModules;
1894 ModuleSpec module_spec(module_file_spec);
1895 GetImages().FindModules(module_spec, matchingModules);
1896 size_t num_modules = matchingModules.GetSize();
1897
1898 // If there is more than one module for this file spec, only
1899 // return true if ALL the modules are on the black list.
1900 if (num_modules > 0) {
1901 for (size_t i = 0; i < num_modules; i++) {
1903 matchingModules.GetModuleAtIndex(i)))
1904 return false;
1905 }
1906 return true;
1907 }
1908 }
1909 return false;
1910}
1911
1913 const lldb::ModuleSP &module_sp) {
1915 if (m_platform_sp)
1916 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1917 module_sp);
1918 }
1919 return false;
1920}
1921
1922size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1923 size_t dst_len, Status &error) {
1924 SectionSP section_sp(addr.GetSection());
1925 if (section_sp) {
1926 // If the contents of this section are encrypted, the on-disk file is
1927 // unusable. Read only from live memory.
1928 if (section_sp->IsEncrypted()) {
1929 error = Status::FromErrorString("section is encrypted");
1930 return 0;
1931 }
1932 ModuleSP module_sp(section_sp->GetModule());
1933 if (module_sp) {
1934 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1935 if (objfile) {
1936 size_t bytes_read = objfile->ReadSectionData(
1937 section_sp.get(), addr.GetOffset(), dst, dst_len);
1938 if (bytes_read > 0)
1939 return bytes_read;
1940 else
1942 "error reading data from section %s",
1943 section_sp->GetName().GetCString());
1944 } else
1945 error = Status::FromErrorString("address isn't from a object file");
1946 } else
1947 error = Status::FromErrorString("address isn't in a module");
1948 } else
1950 "address doesn't contain a section that points to a "
1951 "section in a object file");
1952
1953 return 0;
1954}
1955
1956size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len,
1957 Status &error, bool force_live_memory,
1958 lldb::addr_t *load_addr_ptr) {
1959 error.Clear();
1960
1961 Address fixed_addr = addr;
1962 if (ProcessIsValid())
1963 if (const ABISP &abi = m_process_sp->GetABI())
1964 fixed_addr.SetLoadAddress(abi->FixAnyAddress(addr.GetLoadAddress(this)),
1965 this);
1966
1967 // if we end up reading this from process memory, we will fill this with the
1968 // actual load address
1969 if (load_addr_ptr)
1970 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1971
1972 size_t bytes_read = 0;
1973
1974 addr_t load_addr = LLDB_INVALID_ADDRESS;
1975 addr_t file_addr = LLDB_INVALID_ADDRESS;
1976 Address resolved_addr;
1977 if (!fixed_addr.IsSectionOffset()) {
1978 SectionLoadList &section_load_list = GetSectionLoadList();
1979 if (section_load_list.IsEmpty()) {
1980 // No sections are loaded, so we must assume we are not running yet and
1981 // anything we are given is a file address.
1982 file_addr =
1983 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
1984 // its offset is the file address
1985 m_images.ResolveFileAddress(file_addr, resolved_addr);
1986 } else {
1987 // We have at least one section loaded. This can be because we have
1988 // manually loaded some sections with "target modules load ..." or
1989 // because we have a live process that has sections loaded through
1990 // the dynamic loader
1991 load_addr =
1992 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
1993 // its offset is the load address
1994 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1995 }
1996 }
1997 if (!resolved_addr.IsValid())
1998 resolved_addr = fixed_addr;
1999
2000 // If we read from the file cache but can't get as many bytes as requested,
2001 // we keep the result around in this buffer, in case this result is the
2002 // best we can do.
2003 std::unique_ptr<uint8_t[]> file_cache_read_buffer;
2004 size_t file_cache_bytes_read = 0;
2005
2006 // Read from file cache if read-only section.
2007 if (!force_live_memory && resolved_addr.IsSectionOffset()) {
2008 SectionSP section_sp(resolved_addr.GetSection());
2009 if (section_sp) {
2010 auto permissions = Flags(section_sp->GetPermissions());
2011 bool is_readonly = !permissions.Test(ePermissionsWritable) &&
2012 permissions.Test(ePermissionsReadable);
2013 if (is_readonly) {
2014 file_cache_bytes_read =
2015 ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2016 if (file_cache_bytes_read == dst_len)
2017 return file_cache_bytes_read;
2018 else if (file_cache_bytes_read > 0) {
2019 file_cache_read_buffer =
2020 std::make_unique<uint8_t[]>(file_cache_bytes_read);
2021 std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read);
2022 }
2023 }
2024 }
2025 }
2026
2027 if (ProcessIsValid()) {
2028 if (load_addr == LLDB_INVALID_ADDRESS)
2029 load_addr = resolved_addr.GetLoadAddress(this);
2030
2031 if (load_addr == LLDB_INVALID_ADDRESS) {
2032 ModuleSP addr_module_sp(resolved_addr.GetModule());
2033 if (addr_module_sp && addr_module_sp->GetFileSpec())
2035 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
2036 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
2037 else
2039 "0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
2040 } else {
2041 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
2042 if (bytes_read != dst_len) {
2043 if (error.Success()) {
2044 if (bytes_read == 0)
2046 "read memory from 0x%" PRIx64 " failed", load_addr);
2047 else
2049 "only %" PRIu64 " of %" PRIu64
2050 " bytes were read from memory at 0x%" PRIx64,
2051 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
2052 }
2053 }
2054 if (bytes_read) {
2055 if (load_addr_ptr)
2056 *load_addr_ptr = load_addr;
2057 return bytes_read;
2058 }
2059 }
2060 }
2061
2062 if (file_cache_read_buffer && file_cache_bytes_read > 0) {
2063 // Reading from the process failed. If we've previously succeeded in reading
2064 // something from the file cache, then copy that over and return that.
2065 std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read);
2066 return file_cache_bytes_read;
2067 }
2068
2069 if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) {
2070 // If we didn't already try and read from the object file cache, then try
2071 // it after failing to read from the process.
2072 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2073 }
2074 return 0;
2075}
2076
2077size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
2078 Status &error, bool force_live_memory) {
2079 char buf[256];
2080 out_str.clear();
2081 addr_t curr_addr = addr.GetLoadAddress(this);
2082 Address address(addr);
2083 while (true) {
2084 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error,
2085 force_live_memory);
2086 if (length == 0)
2087 break;
2088 out_str.append(buf, length);
2089 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2090 // to read some more characters
2091 if (length == sizeof(buf) - 1)
2092 curr_addr += length;
2093 else
2094 break;
2095 address = Address(curr_addr);
2096 }
2097 return out_str.size();
2098}
2099
2100size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
2101 size_t dst_max_len, Status &result_error,
2102 bool force_live_memory) {
2103 size_t total_cstr_len = 0;
2104 if (dst && dst_max_len) {
2105 result_error.Clear();
2106 // NULL out everything just to be safe
2107 memset(dst, 0, dst_max_len);
2108 addr_t curr_addr = addr.GetLoadAddress(this);
2109 Address address(addr);
2110
2111 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
2112 // this really needs to be tied to the memory cache subsystem's cache line
2113 // size, so leave this as a fixed constant.
2114 const size_t cache_line_size = 512;
2115
2116 size_t bytes_left = dst_max_len - 1;
2117 char *curr_dst = dst;
2118
2119 while (bytes_left > 0) {
2120 addr_t cache_line_bytes_left =
2121 cache_line_size - (curr_addr % cache_line_size);
2122 addr_t bytes_to_read =
2123 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2124 Status error;
2125 size_t bytes_read = ReadMemory(address, curr_dst, bytes_to_read, error,
2126 force_live_memory);
2127
2128 if (bytes_read == 0) {
2129 result_error = std::move(error);
2130 dst[total_cstr_len] = '\0';
2131 break;
2132 }
2133 const size_t len = strlen(curr_dst);
2134
2135 total_cstr_len += len;
2136
2137 if (len < bytes_to_read)
2138 break;
2139
2140 curr_dst += bytes_read;
2141 curr_addr += bytes_read;
2142 bytes_left -= bytes_read;
2143 address = Address(curr_addr);
2144 }
2145 } else {
2146 if (dst == nullptr)
2147 result_error = Status::FromErrorString("invalid arguments");
2148 else
2149 result_error.Clear();
2150 }
2151 return total_cstr_len;
2152}
2153
2155 addr_t load_addr = addr.GetLoadAddress(this);
2156 if (load_addr != LLDB_INVALID_ADDRESS && m_process_sp) {
2157 // Avoid crossing cache line boundaries.
2158 addr_t cache_line_size = m_process_sp->GetMemoryCacheLineSize();
2159 return cache_line_size - (load_addr % cache_line_size);
2160 }
2161
2162 // The read is going to go to the file cache, so we can just pick a largish
2163 // value.
2164 return 0x1000;
2165}
2166
2167size_t Target::ReadStringFromMemory(const Address &addr, char *dst,
2168 size_t max_bytes, Status &error,
2169 size_t type_width, bool force_live_memory) {
2170 if (!dst || !max_bytes || !type_width || max_bytes < type_width)
2171 return 0;
2172
2173 size_t total_bytes_read = 0;
2174
2175 // Ensure a null terminator independent of the number of bytes that is
2176 // read.
2177 memset(dst, 0, max_bytes);
2178 size_t bytes_left = max_bytes - type_width;
2179
2180 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2181 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2182 "string with more than 4 bytes "
2183 "per character!");
2184
2185 Address address = addr;
2186 char *curr_dst = dst;
2187
2188 error.Clear();
2189 while (bytes_left > 0 && error.Success()) {
2190 addr_t bytes_to_read =
2191 std::min<addr_t>(bytes_left, GetReasonableReadSize(address));
2192 size_t bytes_read =
2193 ReadMemory(address, curr_dst, bytes_to_read, error, force_live_memory);
2194
2195 if (bytes_read == 0)
2196 break;
2197
2198 // Search for a null terminator of correct size and alignment in
2199 // bytes_read
2200 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2201 for (size_t i = aligned_start;
2202 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2203 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2204 error.Clear();
2205 return i;
2206 }
2207
2208 total_bytes_read += bytes_read;
2209 curr_dst += bytes_read;
2210 address.Slide(bytes_read);
2211 bytes_left -= bytes_read;
2212 }
2213 return total_bytes_read;
2214}
2215
2216size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
2217 bool is_signed, Scalar &scalar,
2218 Status &error,
2219 bool force_live_memory) {
2220 uint64_t uval;
2221
2222 if (byte_size <= sizeof(uval)) {
2223 size_t bytes_read =
2224 ReadMemory(addr, &uval, byte_size, error, force_live_memory);
2225 if (bytes_read == byte_size) {
2226 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
2228 lldb::offset_t offset = 0;
2229 if (byte_size <= 4)
2230 scalar = data.GetMaxU32(&offset, byte_size);
2231 else
2232 scalar = data.GetMaxU64(&offset, byte_size);
2233
2234 if (is_signed)
2235 scalar.SignExtend(byte_size * 8);
2236 return bytes_read;
2237 }
2238 } else {
2240 "byte size of %u is too large for integer scalar type", byte_size);
2241 }
2242 return 0;
2243}
2244
2246 size_t integer_byte_size,
2247 uint64_t fail_value, Status &error,
2248 bool force_live_memory) {
2249 Scalar scalar;
2250 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
2251 force_live_memory))
2252 return scalar.ULongLong(fail_value);
2253 return fail_value;
2254}
2255
2257 Address &pointer_addr,
2258 bool force_live_memory) {
2259 Scalar scalar;
2261 false, scalar, error, force_live_memory)) {
2262 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
2263 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
2264 SectionLoadList &section_load_list = GetSectionLoadList();
2265 if (section_load_list.IsEmpty()) {
2266 // No sections are loaded, so we must assume we are not running yet and
2267 // anything we are given is a file address.
2268 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
2269 } else {
2270 // We have at least one section loaded. This can be because we have
2271 // manually loaded some sections with "target modules load ..." or
2272 // because we have a live process that has sections loaded through
2273 // the dynamic loader
2274 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
2275 }
2276 // We weren't able to resolve the pointer value, so just return an
2277 // address with no section
2278 if (!pointer_addr.IsValid())
2279 pointer_addr.SetOffset(pointer_vm_addr);
2280 return true;
2281 }
2282 }
2283 return false;
2284}
2285
2287 bool notify, Status *error_ptr) {
2288 ModuleSP module_sp;
2289
2290 Status error;
2291
2292 // Apply any remappings specified in target.object-map:
2293 ModuleSpec module_spec(orig_module_spec);
2294 PathMappingList &obj_mapping = GetObjectPathMap();
2295 if (std::optional<FileSpec> remapped_obj_file =
2296 obj_mapping.RemapPath(orig_module_spec.GetFileSpec().GetPath(),
2297 true /* only_if_exists */)) {
2298 module_spec.GetFileSpec().SetPath(remapped_obj_file->GetPath());
2299 }
2300
2301 // First see if we already have this module in our module list. If we do,
2302 // then we're done, we don't need to consult the shared modules list. But
2303 // only do this if we are passed a UUID.
2304
2305 if (module_spec.GetUUID().IsValid())
2306 module_sp = m_images.FindFirstModule(module_spec);
2307
2308 if (!module_sp) {
2309 llvm::SmallVector<ModuleSP, 1>
2310 old_modules; // This will get filled in if we have a new version
2311 // of the library
2312 bool did_create_module = false;
2313 FileSpecList search_paths = GetExecutableSearchPaths();
2314 FileSpec symbol_file_spec;
2315
2316 // Call locate module callback if set. This allows users to implement their
2317 // own module cache system. For example, to leverage build system artifacts,
2318 // to bypass pulling files from remote platform, or to search symbol files
2319 // from symbol servers.
2320 if (m_platform_sp)
2321 m_platform_sp->CallLocateModuleCallbackIfSet(
2322 module_spec, module_sp, symbol_file_spec, &did_create_module);
2323
2324 // The result of this CallLocateModuleCallbackIfSet is one of the following.
2325 // 1. module_sp:loaded, symbol_file_spec:set
2326 // The callback found a module file and a symbol file for the
2327 // module_spec. We will call module_sp->SetSymbolFileFileSpec with
2328 // the symbol_file_spec later.
2329 // 2. module_sp:loaded, symbol_file_spec:empty
2330 // The callback only found a module file for the module_spec.
2331 // 3. module_sp:empty, symbol_file_spec:set
2332 // The callback only found a symbol file for the module. We continue
2333 // to find a module file for this module_spec and we will call
2334 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
2335 // 4. module_sp:empty, symbol_file_spec:empty
2336 // Platform does not exist, the callback is not set, the callback did
2337 // not find any module files nor any symbol files, the callback failed,
2338 // or something went wrong. We continue to find a module file for this
2339 // module_spec.
2340
2341 if (!module_sp) {
2342 // If there are image search path entries, try to use them to acquire a
2343 // suitable image.
2345 ModuleSpec transformed_spec(module_spec);
2346 ConstString transformed_dir;
2348 module_spec.GetFileSpec().GetDirectory(), transformed_dir)) {
2349 transformed_spec.GetFileSpec().SetDirectory(transformed_dir);
2350 transformed_spec.GetFileSpec().SetFilename(
2351 module_spec.GetFileSpec().GetFilename());
2352 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2353 &search_paths, &old_modules,
2354 &did_create_module);
2355 }
2356 }
2357 }
2358
2359 if (!module_sp) {
2360 // If we have a UUID, we can check our global shared module list in case
2361 // we already have it. If we don't have a valid UUID, then we can't since
2362 // the path in "module_spec" will be a platform path, and we will need to
2363 // let the platform find that file. For example, we could be asking for
2364 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2365 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2366 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2367 // cache.
2368 if (module_spec.GetUUID().IsValid()) {
2369 // We have a UUID, it is OK to check the global module list...
2370 error =
2371 ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
2372 &old_modules, &did_create_module);
2373 }
2374
2375 if (!module_sp) {
2376 // The platform is responsible for finding and caching an appropriate
2377 // module in the shared module cache.
2378 if (m_platform_sp) {
2379 error = m_platform_sp->GetSharedModule(
2380 module_spec, m_process_sp.get(), module_sp, &search_paths,
2381 &old_modules, &did_create_module);
2382 } else {
2383 error = Status::FromErrorString("no platform is currently set");
2384 }
2385 }
2386 }
2387
2388 // We found a module that wasn't in our target list. Let's make sure that
2389 // there wasn't an equivalent module in the list already, and if there was,
2390 // let's remove it.
2391 if (module_sp) {
2392 ObjectFile *objfile = module_sp->GetObjectFile();
2393 if (objfile) {
2394 switch (objfile->GetType()) {
2395 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2396 /// a program's execution state
2397 case ObjectFile::eTypeExecutable: /// A normal executable
2398 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2399 /// executable
2400 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2401 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2402 /// used during execution
2403 break;
2404 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2405 /// debug information
2406 if (error_ptr)
2407 *error_ptr = Status::FromErrorString(
2408 "debug info files aren't valid target "
2409 "modules, please specify an executable");
2410 return ModuleSP();
2411 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2412 /// against but not used for
2413 /// execution
2414 if (error_ptr)
2415 *error_ptr = Status::FromErrorString(
2416 "stub libraries aren't valid target "
2417 "modules, please specify an executable");
2418 return ModuleSP();
2419 default:
2420 if (error_ptr)
2421 *error_ptr = Status::FromErrorString(
2422 "unsupported file type, please specify an executable");
2423 return ModuleSP();
2424 }
2425 // GetSharedModule is not guaranteed to find the old shared module, for
2426 // instance in the common case where you pass in the UUID, it is only
2427 // going to find the one module matching the UUID. In fact, it has no
2428 // good way to know what the "old module" relevant to this target is,
2429 // since there might be many copies of a module with this file spec in
2430 // various running debug sessions, but only one of them will belong to
2431 // this target. So let's remove the UUID from the module list, and look
2432 // in the target's module list. Only do this if there is SOMETHING else
2433 // in the module spec...
2434 if (module_spec.GetUUID().IsValid() &&
2435 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2436 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2437 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2438 module_spec_copy.GetUUID().Clear();
2439
2440 ModuleList found_modules;
2441 m_images.FindModules(module_spec_copy, found_modules);
2442 found_modules.ForEach([&](const ModuleSP &found_module) -> bool {
2443 old_modules.push_back(found_module);
2444 return true;
2445 });
2446 }
2447
2448 // If the locate module callback had found a symbol file, set it to the
2449 // module_sp before preloading symbols.
2450 if (symbol_file_spec)
2451 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
2452
2453 // Preload symbols outside of any lock, so hopefully we can do this for
2454 // each library in parallel.
2455 if (GetPreloadSymbols())
2456 module_sp->PreloadSymbols();
2457 llvm::SmallVector<ModuleSP, 1> replaced_modules;
2458 for (ModuleSP &old_module_sp : old_modules) {
2459 if (m_images.GetIndexForModule(old_module_sp.get()) !=
2461 if (replaced_modules.empty())
2462 m_images.ReplaceModule(old_module_sp, module_sp);
2463 else
2464 m_images.Remove(old_module_sp);
2465
2466 replaced_modules.push_back(std::move(old_module_sp));
2467 }
2468 }
2469
2470 if (replaced_modules.size() > 1) {
2471 // The same new module replaced multiple old modules
2472 // simultaneously. It's not clear this should ever
2473 // happen (if we always replace old modules as we add
2474 // new ones, presumably we should never have more than
2475 // one old one). If there are legitimate cases where
2476 // this happens, then the ModuleList::Notifier interface
2477 // may need to be adjusted to allow reporting this.
2478 // In the meantime, just log that this has happened; just
2479 // above we called ReplaceModule on the first one, and Remove
2480 // on the rest.
2482 StreamString message;
2483 auto dump = [&message](Module &dump_module) -> void {
2484 UUID dump_uuid = dump_module.GetUUID();
2485
2486 message << '[';
2487 dump_module.GetDescription(message.AsRawOstream());
2488 message << " (uuid ";
2489
2490 if (dump_uuid.IsValid())
2491 dump_uuid.Dump(message);
2492 else
2493 message << "not specified";
2494
2495 message << ")]";
2496 };
2497
2498 message << "New module ";
2499 dump(*module_sp);
2500 message.AsRawOstream()
2501 << llvm::formatv(" simultaneously replaced {0} old modules: ",
2502 replaced_modules.size());
2503 for (ModuleSP &replaced_module_sp : replaced_modules)
2504 dump(*replaced_module_sp);
2505
2506 log->PutString(message.GetString());
2507 }
2508 }
2509
2510 if (replaced_modules.empty())
2511 m_images.Append(module_sp, notify);
2512
2513 for (ModuleSP &old_module_sp : replaced_modules) {
2514 Module *old_module_ptr = old_module_sp.get();
2515 old_module_sp.reset();
2517 }
2518 } else
2519 module_sp.reset();
2520 }
2521 }
2522 if (error_ptr)
2523 *error_ptr = std::move(error);
2524 return module_sp;
2525}
2526
2527TargetSP Target::CalculateTarget() { return shared_from_this(); }
2528
2530
2532
2534
2536 exe_ctx.Clear();
2537 exe_ctx.SetTargetPtr(this);
2538}
2539
2541 return m_image_search_paths;
2542}
2543
2545 void *baton) {
2546 Target *target = (Target *)baton;
2547 ModuleSP exe_module_sp(target->GetExecutableModule());
2548 if (exe_module_sp)
2549 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2550}
2551
2552llvm::Expected<lldb::TypeSystemSP>
2554 bool create_on_demand) {
2555 if (!m_valid)
2556 return llvm::createStringError("Invalid Target");
2557
2558 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2559 // assembly code
2560 || language == eLanguageTypeUnknown) {
2561 LanguageSet languages_for_expressions =
2563
2564 if (languages_for_expressions[eLanguageTypeC]) {
2565 language = eLanguageTypeC; // LLDB's default. Override by setting the
2566 // target language.
2567 } else {
2568 if (languages_for_expressions.Empty())
2569 return llvm::createStringError(
2570 "No expression support for any languages");
2571 language = (LanguageType)languages_for_expressions.bitvector.find_first();
2572 }
2573 }
2574
2576 create_on_demand);
2577}
2578
2580 const lldb_private::RegisterFlags &flags,
2581 uint32_t byte_size) {
2583 assert(provider);
2584 return provider->GetRegisterType(name, flags, byte_size);
2585}
2586
2587std::vector<lldb::TypeSystemSP>
2588Target::GetScratchTypeSystems(bool create_on_demand) {
2589 if (!m_valid)
2590 return {};
2591
2592 // Some TypeSystem instances are associated with several LanguageTypes so
2593 // they will show up several times in the loop below. The SetVector filters
2594 // out all duplicates as they serve no use for the caller.
2595 std::vector<lldb::TypeSystemSP> scratch_type_systems;
2596
2597 LanguageSet languages_for_expressions =
2599
2600 for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2601 auto language = (LanguageType)bit;
2602 auto type_system_or_err =
2603 GetScratchTypeSystemForLanguage(language, create_on_demand);
2604 if (!type_system_or_err)
2606 GetLog(LLDBLog::Target), type_system_or_err.takeError(),
2607 "Language '{1}' has expression support but no scratch type "
2608 "system available: {0}",
2610 else
2611 if (auto ts = *type_system_or_err)
2612 scratch_type_systems.push_back(ts);
2613 }
2614
2615 std::sort(scratch_type_systems.begin(), scratch_type_systems.end());
2616 scratch_type_systems.erase(
2617 std::unique(scratch_type_systems.begin(), scratch_type_systems.end()),
2618 scratch_type_systems.end());
2619 return scratch_type_systems;
2620}
2621
2624 auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2625
2626 if (auto err = type_system_or_err.takeError()) {
2628 GetLog(LLDBLog::Target), std::move(err),
2629 "Unable to get persistent expression state for language {1}: {0}",
2631 return nullptr;
2632 }
2633
2634 if (auto ts = *type_system_or_err)
2635 return ts->GetPersistentExpressionState();
2636
2638 "Unable to get persistent expression state for language {1}: {0}",
2640 return nullptr;
2641}
2642
2644 llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language,
2645 Expression::ResultType desired_type,
2646 const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2647 Status &error) {
2648 auto type_system_or_err =
2650 if (auto err = type_system_or_err.takeError()) {
2652 "Could not find type system for language %s: %s",
2654 llvm::toString(std::move(err)).c_str());
2655 return nullptr;
2656 }
2657
2658 auto ts = *type_system_or_err;
2659 if (!ts) {
2661 "Type system for language %s is no longer live",
2662 language.GetDescription().data());
2663 return nullptr;
2664 }
2665
2666 auto *user_expr = ts->GetUserExpression(expr, prefix, language, desired_type,
2667 options, ctx_obj);
2668 if (!user_expr)
2670 "Could not create an expression for language %s",
2671 language.GetDescription().data());
2672
2673 return user_expr;
2674}
2675
2677 lldb::LanguageType language, const CompilerType &return_type,
2678 const Address &function_address, const ValueList &arg_value_list,
2679 const char *name, Status &error) {
2680 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2681 if (auto err = type_system_or_err.takeError()) {
2683 "Could not find type system for language %s: %s",
2685 llvm::toString(std::move(err)).c_str());
2686 return nullptr;
2687 }
2688 auto ts = *type_system_or_err;
2689 if (!ts) {
2691 "Type system for language %s is no longer live",
2693 return nullptr;
2694 }
2695 auto *persistent_fn = ts->GetFunctionCaller(return_type, function_address,
2696 arg_value_list, name);
2697 if (!persistent_fn)
2699 "Could not create an expression for language %s",
2701
2702 return persistent_fn;
2703}
2704
2705llvm::Expected<std::unique_ptr<UtilityFunction>>
2706Target::CreateUtilityFunction(std::string expression, std::string name,
2707 lldb::LanguageType language,
2708 ExecutionContext &exe_ctx) {
2709 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2710 if (!type_system_or_err)
2711 return type_system_or_err.takeError();
2712 auto ts = *type_system_or_err;
2713 if (!ts)
2714 return llvm::createStringError(
2715 llvm::StringRef("Type system for language ") +
2717 llvm::StringRef(" is no longer live"));
2718 std::unique_ptr<UtilityFunction> utility_fn =
2719 ts->CreateUtilityFunction(std::move(expression), std::move(name));
2720 if (!utility_fn)
2721 return llvm::createStringError(
2722 llvm::StringRef("Could not create an expression for language") +
2724
2725 DiagnosticManager diagnostics;
2726 if (!utility_fn->Install(diagnostics, exe_ctx))
2727 return diagnostics.GetAsError(lldb::eExpressionSetupError,
2728 "Could not install utility function:");
2729
2730 return std::move(utility_fn);
2731}
2732
2734
2736
2739}
2740
2743}
2744
2747}
2748
2751 "setting target's default architecture to {0} ({1})",
2752 arch.GetArchitectureName(), arch.GetTriple().getTriple());
2754}
2755
2756llvm::Error Target::SetLabel(llvm::StringRef label) {
2757 size_t n = LLDB_INVALID_INDEX32;
2758 if (llvm::to_integer(label, n))
2759 return llvm::createStringError("Cannot use integer as target label.");
2760 TargetList &targets = GetDebugger().GetTargetList();
2761 for (size_t i = 0; i < targets.GetNumTargets(); i++) {
2762 TargetSP target_sp = targets.GetTargetAtIndex(i);
2763 if (target_sp && target_sp->GetLabel() == label) {
2764 return llvm::make_error<llvm::StringError>(
2765 llvm::formatv(
2766 "Cannot use label '{0}' since it's set in target #{1}.", label,
2767 i),
2768 llvm::inconvertibleErrorCode());
2769 }
2770 }
2771
2772 m_label = label.str();
2773 return llvm::Error::success();
2774}
2775
2777 const SymbolContext *sc_ptr) {
2778 // The target can either exist in the "process" of ExecutionContext, or in
2779 // the "target_sp" member of SymbolContext. This accessor helper function
2780 // will get the target from one of these locations.
2781
2782 Target *target = nullptr;
2783 if (sc_ptr != nullptr)
2784 target = sc_ptr->target_sp.get();
2785 if (target == nullptr && exe_ctx_ptr)
2786 target = exe_ctx_ptr->GetTargetPtr();
2787 return target;
2788}
2789
2791 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2792 lldb::ValueObjectSP &result_valobj_sp,
2793 const EvaluateExpressionOptions &options, std::string *fixed_expression,
2794 ValueObject *ctx_obj) {
2795 result_valobj_sp.reset();
2796
2797 ExpressionResults execution_results = eExpressionSetupError;
2798
2799 if (expr.empty()) {
2801 return execution_results;
2802 }
2803
2804 // We shouldn't run stop hooks in expressions.
2805 bool old_suppress_value = m_suppress_stop_hooks;
2806 m_suppress_stop_hooks = true;
2807 auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2808 m_suppress_stop_hooks = old_suppress_value;
2809 });
2810
2811 ExecutionContext exe_ctx;
2812
2813 if (exe_scope) {
2814 exe_scope->CalculateExecutionContext(exe_ctx);
2815 } else if (m_process_sp) {
2816 m_process_sp->CalculateExecutionContext(exe_ctx);
2817 } else {
2819 }
2820
2821 // Make sure we aren't just trying to see the value of a persistent variable
2822 // (something like "$0")
2823 // Only check for persistent variables the expression starts with a '$'
2824 lldb::ExpressionVariableSP persistent_var_sp;
2825 if (expr[0] == '$') {
2826 auto type_system_or_err =
2828 if (auto err = type_system_or_err.takeError()) {
2829 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2830 "Unable to get scratch type system");
2831 } else {
2832 auto ts = *type_system_or_err;
2833 if (!ts)
2834 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2835 "Scratch type system is no longer live: {0}");
2836 else
2837 persistent_var_sp =
2838 ts->GetPersistentExpressionState()->GetVariable(expr);
2839 }
2840 }
2841 if (persistent_var_sp) {
2842 result_valobj_sp = persistent_var_sp->GetValueObject();
2843 execution_results = eExpressionCompleted;
2844 } else {
2845 llvm::StringRef prefix = GetExpressionPrefixContents();
2846 execution_results =
2847 UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2848 result_valobj_sp, fixed_expression, ctx_obj);
2849 }
2850
2851 if (execution_results == eExpressionCompleted)
2853 else
2855 return execution_results;
2856}
2857
2859 lldb::ExpressionVariableSP variable_sp;
2861 [name, &variable_sp](TypeSystemSP type_system) -> bool {
2862 auto ts = type_system.get();
2863 if (!ts)
2864 return true;
2865 if (PersistentExpressionState *persistent_state =
2866 ts->GetPersistentExpressionState()) {
2867 variable_sp = persistent_state->GetVariable(name);
2868
2869 if (variable_sp)
2870 return false; // Stop iterating the ForEach
2871 }
2872 return true; // Keep iterating the ForEach
2873 });
2874 return variable_sp;
2875}
2876
2879
2881 [name, &address](lldb::TypeSystemSP type_system) -> bool {
2882 auto ts = type_system.get();
2883 if (!ts)
2884 return true;
2885
2886 if (PersistentExpressionState *persistent_state =
2887 ts->GetPersistentExpressionState()) {
2888 address = persistent_state->LookupSymbol(name);
2889 if (address != LLDB_INVALID_ADDRESS)
2890 return false; // Stop iterating the ForEach
2891 }
2892 return true; // Keep iterating the ForEach
2893 });
2894 return address;
2895}
2896
2897llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2898 Module *exe_module = GetExecutableModulePointer();
2899
2900 // Try to find the entry point address in the primary executable.
2901 const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2902 if (has_primary_executable) {
2903 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2904 if (entry_addr.IsValid())
2905 return entry_addr;
2906 }
2907
2908 const ModuleList &modules = GetImages();
2909 const size_t num_images = modules.GetSize();
2910 for (size_t idx = 0; idx < num_images; ++idx) {
2911 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2912 if (!module_sp || !module_sp->GetObjectFile())
2913 continue;
2914
2915 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2916 if (entry_addr.IsValid())
2917 return entry_addr;
2918 }
2919
2920 // We haven't found the entry point address. Return an appropriate error.
2921 if (!has_primary_executable)
2922 return llvm::createStringError(
2923 "No primary executable found and could not find entry point address in "
2924 "any executable module");
2925
2926 return llvm::createStringError(
2927 "Could not find entry point address for primary executable module \"" +
2928 exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"");
2929}
2930
2932 AddressClass addr_class) const {
2933 auto arch_plugin = GetArchitecturePlugin();
2934 return arch_plugin
2935 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2936 : load_addr;
2937}
2938
2940 AddressClass addr_class) const {
2941 auto arch_plugin = GetArchitecturePlugin();
2942 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2943 : load_addr;
2944}
2945
2947 auto arch_plugin = GetArchitecturePlugin();
2948 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2949}
2950
2953 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2954 return *m_source_manager_up;
2955}
2956
2959 Target::StopHookSP stop_hook_sp;
2960 switch (kind) {
2962 stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
2963 break;
2965 stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
2966 break;
2967 }
2968 m_stop_hooks[new_uid] = stop_hook_sp;
2969 return stop_hook_sp;
2970}
2971
2973 if (!RemoveStopHookByID(user_id))
2974 return;
2975 if (user_id == m_stop_hook_next_id)
2977}
2978
2980 size_t num_removed = m_stop_hooks.erase(user_id);
2981 return (num_removed != 0);
2982}
2983
2985
2987 StopHookSP found_hook;
2988
2989 StopHookCollection::iterator specified_hook_iter;
2990 specified_hook_iter = m_stop_hooks.find(user_id);
2991 if (specified_hook_iter != m_stop_hooks.end())
2992 found_hook = (*specified_hook_iter).second;
2993 return found_hook;
2994}
2995
2997 bool active_state) {
2998 StopHookCollection::iterator specified_hook_iter;
2999 specified_hook_iter = m_stop_hooks.find(user_id);
3000 if (specified_hook_iter == m_stop_hooks.end())
3001 return false;
3002
3003 (*specified_hook_iter).second->SetIsActive(active_state);
3004 return true;
3005}
3006
3007void Target::SetAllStopHooksActiveState(bool active_state) {
3008 StopHookCollection::iterator pos, end = m_stop_hooks.end();
3009 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
3010 (*pos).second->SetIsActive(active_state);
3011 }
3012}
3013
3016 return false;
3017
3018 if (!m_process_sp)
3019 return false;
3020
3021 // Somebody might have restarted the process:
3022 // Still return false, the return value is about US restarting the target.
3023 if (m_process_sp->GetState() != eStateStopped)
3024 return false;
3025
3026 if (m_stop_hooks.empty())
3027 return false;
3028
3029 // If there aren't any active stop hooks, don't bother either.
3030 bool any_active_hooks = false;
3031 for (auto hook : m_stop_hooks) {
3032 if (hook.second->IsActive()) {
3033 any_active_hooks = true;
3034 break;
3035 }
3036 }
3037 if (!any_active_hooks)
3038 return false;
3039
3040 // Make sure we check that we are not stopped because of us running a user
3041 // expression since in that case we do not want to run the stop-hooks. Note,
3042 // you can't just check whether the last stop was for a User Expression,
3043 // because breakpoint commands get run before stop hooks, and one of them
3044 // might have run an expression. You have to ensure you run the stop hooks
3045 // once per natural stop.
3046 uint32_t last_natural_stop = m_process_sp->GetModIDRef().GetLastNaturalStopID();
3047 if (last_natural_stop != 0 && m_latest_stop_hook_id == last_natural_stop)
3048 return false;
3049
3050 m_latest_stop_hook_id = last_natural_stop;
3051
3052 std::vector<ExecutionContext> exc_ctx_with_reasons;
3053
3054 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
3055 size_t num_threads = cur_threadlist.GetSize();
3056 for (size_t i = 0; i < num_threads; i++) {
3057 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
3058 if (cur_thread_sp->ThreadStoppedForAReason()) {
3059 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
3060 exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
3061 cur_frame_sp.get());
3062 }
3063 }
3064
3065 // If no threads stopped for a reason, don't run the stop-hooks.
3066 size_t num_exe_ctx = exc_ctx_with_reasons.size();
3067 if (num_exe_ctx == 0)
3068 return false;
3069
3071
3072 bool auto_continue = false;
3073 bool hooks_ran = false;
3074 bool print_hook_header = (m_stop_hooks.size() != 1);
3075 bool print_thread_header = (num_exe_ctx != 1);
3076 bool should_stop = false;
3077 bool somebody_restarted = false;
3078
3079 for (auto stop_entry : m_stop_hooks) {
3080 StopHookSP cur_hook_sp = stop_entry.second;
3081 if (!cur_hook_sp->IsActive())
3082 continue;
3083
3084 bool any_thread_matched = false;
3085 for (auto exc_ctx : exc_ctx_with_reasons) {
3086 // We detect somebody restarted in the stop-hook loop, and broke out of
3087 // that loop back to here. So break out of here too.
3088 if (somebody_restarted)
3089 break;
3090
3091 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
3092 continue;
3093
3094 // We only consult the auto-continue for a stop hook if it matched the
3095 // specifier.
3096 auto_continue |= cur_hook_sp->GetAutoContinue();
3097
3098 if (!hooks_ran)
3099 hooks_ran = true;
3100
3101 if (print_hook_header && !any_thread_matched) {
3102 StreamString s;
3103 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
3104 if (s.GetSize() != 0)
3105 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
3106 s.GetData());
3107 else
3108 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
3109 any_thread_matched = true;
3110 }
3111
3112 if (print_thread_header)
3113 output_sp->Printf("-- Thread %d\n",
3114 exc_ctx.GetThreadPtr()->GetIndexID());
3115
3116 StopHook::StopHookResult this_result =
3117 cur_hook_sp->HandleStop(exc_ctx, output_sp);
3118 bool this_should_stop = true;
3119
3120 switch (this_result) {
3122 // If this hook is set to auto-continue that should override the
3123 // HandleStop result...
3124 if (cur_hook_sp->GetAutoContinue())
3125 this_should_stop = false;
3126 else
3127 this_should_stop = true;
3128
3129 break;
3131 this_should_stop = false;
3132 break;
3134 // We don't have a good way to prohibit people from restarting the
3135 // target willy nilly in a stop hook. If the hook did so, give a
3136 // gentle suggestion here and bag out if the hook processing.
3137 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3138 " set the program running.\n"
3139 " Consider using '-G true' to make "
3140 "stop hooks auto-continue.\n",
3141 cur_hook_sp->GetID());
3142 somebody_restarted = true;
3143 break;
3144 }
3145 // If we're already restarted, stop processing stop hooks.
3146 // FIXME: if we are doing non-stop mode for real, we would have to
3147 // check that OUR thread was restarted, otherwise we should keep
3148 // processing stop hooks.
3149 if (somebody_restarted)
3150 break;
3151
3152 // If anybody wanted to stop, we should all stop.
3153 if (!should_stop)
3154 should_stop = this_should_stop;
3155 }
3156 }
3157
3158 output_sp->Flush();
3159
3160 // If one of the commands in the stop hook already restarted the target,
3161 // report that fact.
3162 if (somebody_restarted)
3163 return true;
3164
3165 // Finally, if auto-continue was requested, do it now:
3166 // We only compute should_stop against the hook results if a hook got to run
3167 // which is why we have to do this conjoint test.
3168 if ((hooks_ran && !should_stop) || auto_continue) {
3169 Log *log = GetLog(LLDBLog::Process);
3170 Status error = m_process_sp->PrivateResume();
3171 if (error.Success()) {
3172 LLDB_LOG(log, "Resuming from RunStopHooks");
3173 return true;
3174 } else {
3175 LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
3176 return false;
3177 }
3178 }
3179
3180 return false;
3181}
3182
3184 // NOTE: intentional leak so we don't crash if global destructor chain gets
3185 // called as other threads still use the result of this function
3186 static TargetProperties *g_settings_ptr =
3187 new TargetProperties(nullptr);
3188 return *g_settings_ptr;
3189}
3190
3192 Status error;
3193 PlatformSP platform_sp(GetPlatform());
3194 if (!platform_sp || !platform_sp->IsRemote() || !platform_sp->IsConnected())
3195 return error;
3196
3197 // Install all files that have an install path when connected to a
3198 // remote platform. If target.auto-install-main-executable is set then
3199 // also install the main executable even if it does not have an explicit
3200 // install path specified.
3201
3202 for (auto module_sp : GetImages().Modules()) {
3203 if (module_sp == GetExecutableModule()) {
3204 MainExecutableInstaller installer{platform_sp, module_sp,
3205 shared_from_this(), *launch_info};
3206 error = installExecutable(installer);
3207 } else {
3208 ExecutableInstaller installer{platform_sp, module_sp};
3209 error = installExecutable(installer);
3210 }
3211
3212 if (error.Fail())
3213 return error;
3214 }
3215
3216 return error;
3217}
3218
3220 uint32_t stop_id) {
3221 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
3222}
3223
3225 Address &resolved_addr) {
3226 return m_images.ResolveFileAddress(file_addr, resolved_addr);
3227}
3228
3230 addr_t new_section_load_addr,
3231 bool warn_multiple) {
3232 const addr_t old_section_load_addr =
3234 SectionLoadHistory::eStopIDNow, section_sp);
3235 if (old_section_load_addr != new_section_load_addr) {
3236 uint32_t stop_id = 0;
3237 ProcessSP process_sp(GetProcessSP());
3238 if (process_sp)
3239 stop_id = process_sp->GetStopID();
3240 else
3243 stop_id, section_sp, new_section_load_addr, warn_multiple))
3244 return true; // Return true if the section load address was changed...
3245 }
3246 return false; // Return false to indicate nothing changed
3247}
3248
3249size_t Target::UnloadModuleSections(const ModuleList &module_list) {
3250 size_t section_unload_count = 0;
3251 size_t num_modules = module_list.GetSize();
3252 for (size_t i = 0; i < num_modules; ++i) {
3253 section_unload_count +=
3254 UnloadModuleSections(module_list.GetModuleAtIndex(i));
3255 }
3256 return section_unload_count;
3257}
3258
3260 uint32_t stop_id = 0;
3261 ProcessSP process_sp(GetProcessSP());
3262 if (process_sp)
3263 stop_id = process_sp->GetStopID();
3264 else
3266 SectionList *sections = module_sp->GetSectionList();
3267 size_t section_unload_count = 0;
3268 if (sections) {
3269 const uint32_t num_sections = sections->GetNumSections(0);
3270 for (uint32_t i = 0; i < num_sections; ++i) {
3271 section_unload_count += m_section_load_history.SetSectionUnloaded(
3272 stop_id, sections->GetSectionAtIndex(i));
3273 }
3274 }
3275 return section_unload_count;
3276}
3277
3279 uint32_t stop_id = 0;
3280 ProcessSP process_sp(GetProcessSP());
3281 if (process_sp)
3282 stop_id = process_sp->GetStopID();
3283 else
3285 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
3286}
3287
3289 addr_t load_addr) {
3290 uint32_t stop_id = 0;
3291 ProcessSP process_sp(GetProcessSP());
3292 if (process_sp)
3293 stop_id = process_sp->GetStopID();
3294 else
3296 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
3297 load_addr);
3298}
3299
3301
3303 lldb_private::TypeSummaryImpl &summary_provider) {
3305 summary_provider);
3306}
3307
3310}
3311
3313 if (process_info.IsScriptedProcess()) {
3314 // Only copy scripted process launch options.
3315 ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>(
3317 default_launch_info.SetProcessPluginName("ScriptedProcess");
3318 default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata());
3319 SetProcessLaunchInfo(default_launch_info);
3320 }
3321}
3322
3325 Status error;
3326 Log *log = GetLog(LLDBLog::Target);
3327
3328 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
3329 launch_info.GetExecutableFile().GetPath().c_str());
3330
3331 StateType state = eStateInvalid;
3332
3333 // Scope to temporarily get the process state in case someone has manually
3334 // remotely connected already to a process and we can skip the platform
3335 // launching.
3336 {
3337 ProcessSP process_sp(GetProcessSP());
3338
3339 if (process_sp) {
3340 state = process_sp->GetState();
3341 LLDB_LOGF(log,
3342 "Target::%s the process exists, and its current state is %s",
3343 __FUNCTION__, StateAsCString(state));
3344 } else {
3345 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
3346 __FUNCTION__);
3347 }
3348 }
3349
3350 launch_info.GetFlags().Set(eLaunchFlagDebug);
3351
3352 SaveScriptedLaunchInfo(launch_info);
3353
3354 // Get the value of synchronous execution here. If you wait till after you
3355 // have started to run, then you could have hit a breakpoint, whose command
3356 // might switch the value, and then you'll pick up that incorrect value.
3357 Debugger &debugger = GetDebugger();
3358 const bool synchronous_execution =
3360
3361 PlatformSP platform_sp(GetPlatform());
3362
3363 FinalizeFileActions(launch_info);
3364
3365 if (state == eStateConnected) {
3366 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY))
3368 "can't launch in tty when launching through a remote connection");
3369 }
3370
3371 if (!launch_info.GetArchitecture().IsValid())
3372 launch_info.GetArchitecture() = GetArchitecture();
3373
3374 // Hijacking events of the process to be created to be sure that all events
3375 // until the first stop are intercepted (in case if platform doesn't define
3376 // its own hijacking listener or if the process is created by the target
3377 // manually, without the platform).
3378 if (!launch_info.GetHijackListener())
3381
3382 // If we're not already connected to the process, and if we have a platform
3383 // that can launch a process for debugging, go ahead and do that here.
3384 if (state != eStateConnected && platform_sp &&
3385 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) {
3386 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
3387 __FUNCTION__);
3388
3389 // If there was a previous process, delete it before we make the new one.
3390 // One subtle point, we delete the process before we release the reference
3391 // to m_process_sp. That way even if we are the last owner, the process
3392 // will get Finalized before it gets destroyed.
3394
3395 m_process_sp =
3396 GetPlatform()->DebugProcess(launch_info, debugger, *this, error);
3397
3398 } else {
3399 LLDB_LOGF(log,
3400 "Target::%s the platform doesn't know how to debug a "
3401 "process, getting a process plugin to do this for us.",
3402 __FUNCTION__);
3403
3404 if (state == eStateConnected) {
3405 assert(m_process_sp);
3406 } else {
3407 // Use a Process plugin to construct the process.
3408 CreateProcess(launch_info.GetListener(),
3409 launch_info.GetProcessPluginName(), nullptr, false);
3410 }
3411
3412 // Since we didn't have a platform launch the process, launch it here.
3413 if (m_process_sp) {
3414 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener());
3415 m_process_sp->SetShadowListener(launch_info.GetShadowListener());
3416 error = m_process_sp->Launch(launch_info);
3417 }
3418 }
3419
3420 if (!error.Success())
3421 return error;
3422
3423 if (!m_process_sp)
3424 return Status::FromErrorString("failed to launch or debug process");
3425
3426 bool rebroadcast_first_stop =
3427 !synchronous_execution &&
3428 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry);
3429
3430 assert(launch_info.GetHijackListener());
3431
3432 EventSP first_stop_event_sp;
3433 state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp,
3434 rebroadcast_first_stop,
3435 launch_info.GetHijackListener());
3436 m_process_sp->RestoreProcessEvents();
3437
3438 if (rebroadcast_first_stop) {
3439 assert(first_stop_event_sp);
3440 m_process_sp->BroadcastEvent(first_stop_event_sp);
3441 return error;
3442 }
3443
3444 switch (state) {
3445 case eStateStopped: {
3446 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3447 break;
3448 if (synchronous_execution)
3449 // Now we have handled the stop-from-attach, and we are just
3450 // switching to a synchronous resume. So we should switch to the
3451 // SyncResume hijacker.
3452 m_process_sp->ResumeSynchronous(stream);
3453 else
3454 error = m_process_sp->Resume();
3455 if (!error.Success()) {
3457 "process resume at entry point failed: %s", error.AsCString());
3458 }
3459 } break;
3460 case eStateExited: {
3461 bool with_shell = !!launch_info.GetShell();
3462 const int exit_status = m_process_sp->GetExitStatus();
3463 const char *exit_desc = m_process_sp->GetExitDescription();
3464 std::string desc;
3465 if (exit_desc && exit_desc[0])
3466 desc = " (" + std::string(exit_desc) + ')';
3467 if (with_shell)
3469 "process exited with status %i%s\n"
3470 "'r' and 'run' are aliases that default to launching through a "
3471 "shell.\n"
3472 "Try launching without going through a shell by using "
3473 "'process launch'.",
3474 exit_status, desc.c_str());
3475 else
3477 "process exited with status %i%s", exit_status, desc.c_str());
3478 } break;
3479 default:
3481 "initial process state wasn't stopped: %s", StateAsCString(state));
3482 break;
3483 }
3484 return error;
3485}
3486
3487void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3488
3490
3491llvm::Expected<TraceSP> Target::CreateTrace() {
3492 if (!m_process_sp)
3493 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3494 "A process is required for tracing");
3495 if (m_trace_sp)
3496 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3497 "A trace already exists for the target");
3498
3499 llvm::Expected<TraceSupportedResponse> trace_type =
3500 m_process_sp->TraceSupported();
3501 if (!trace_type)
3502 return llvm::createStringError(
3503 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3504 llvm::toString(trace_type.takeError()).c_str());
3505 if (llvm::Expected<TraceSP> trace_sp =
3507 m_trace_sp = *trace_sp;
3508 else
3509 return llvm::createStringError(
3510 llvm::inconvertibleErrorCode(),
3511 "Couldn't create a Trace object for the process. %s",
3512 llvm::toString(trace_sp.takeError()).c_str());
3513 return m_trace_sp;
3514}
3515
3516llvm::Expected<TraceSP> Target::GetTraceOrCreate() {
3517 if (m_trace_sp)
3518 return m_trace_sp;
3519 return CreateTrace();
3520}
3521
3524 auto state = eStateInvalid;
3525 auto process_sp = GetProcessSP();
3526 if (process_sp) {
3527 state = process_sp->GetState();
3528 if (process_sp->IsAlive() && state != eStateConnected) {
3529 if (state == eStateAttaching)
3530 return Status::FromErrorString("process attach is in progress");
3531 return Status::FromErrorString("a process is already being debugged");
3532 }
3533 }
3534
3535 const ModuleSP old_exec_module_sp = GetExecutableModule();
3536
3537 // If no process info was specified, then use the target executable name as
3538 // the process to attach to by default
3539 if (!attach_info.ProcessInfoSpecified()) {
3540 if (old_exec_module_sp)
3541 attach_info.GetExecutableFile().SetFilename(
3542 old_exec_module_sp->GetPlatformFileSpec().GetFilename());
3543
3544 if (!attach_info.ProcessInfoSpecified()) {
3546 "no process specified, create a target with a file, or "
3547 "specify the --pid or --name");
3548 }
3549 }
3550
3551 const auto platform_sp =
3553 ListenerSP hijack_listener_sp;
3554 const bool async = attach_info.GetAsync();
3555 if (!async) {
3556 hijack_listener_sp = Listener::MakeListener(
3558 attach_info.SetHijackListener(hijack_listener_sp);
3559 }
3560
3561 Status error;
3562 if (state != eStateConnected && platform_sp != nullptr &&
3563 platform_sp->CanDebugProcess() && !attach_info.IsScriptedProcess()) {
3564 SetPlatform(platform_sp);
3565 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3566 } else {
3567 if (state != eStateConnected) {
3568 SaveScriptedLaunchInfo(attach_info);
3569 llvm::StringRef plugin_name = attach_info.GetProcessPluginName();
3570 process_sp =
3572 plugin_name, nullptr, false);
3573 if (!process_sp) {
3575 "failed to create process using plugin '{0}'",
3576 plugin_name.empty() ? "<empty>" : plugin_name);
3577 return error;
3578 }
3579 }
3580 if (hijack_listener_sp)
3581 process_sp->HijackProcessEvents(hijack_listener_sp);
3582 error = process_sp->Attach(attach_info);
3583 }
3584
3585 if (error.Success() && process_sp) {
3586 if (async) {
3587 process_sp->RestoreProcessEvents();
3588 } else {
3589 // We are stopping all the way out to the user, so update selected frames.
3590 state = process_sp->WaitForProcessToStop(
3591 std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
3593 process_sp->RestoreProcessEvents();
3594
3595 if (state != eStateStopped) {
3596 const char *exit_desc = process_sp->GetExitDescription();
3597 if (exit_desc)
3598 error = Status::FromErrorStringWithFormat("%s", exit_desc);
3599 else
3601 "process did not stop (no such process or permission problem?)");
3602 process_sp->Destroy(false);
3603 }
3604 }
3605 }
3606 return error;
3607}
3608
3610 Log *log = GetLog(LLDBLog::Process);
3611
3612 // Finalize the file actions, and if none were given, default to opening up a
3613 // pseudo terminal
3614 PlatformSP platform_sp = GetPlatform();
3615 const bool default_to_use_pty =
3616 m_platform_sp ? m_platform_sp->IsHost() : false;
3617 LLDB_LOG(
3618 log,
3619 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3620 bool(platform_sp),
3621 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3622 default_to_use_pty);
3623
3624 // If nothing for stdin or stdout or stderr was specified, then check the
3625 // process for any default settings that were set with "settings set"
3626 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3627 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3628 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3629 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3630 "default handling");
3631
3632 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3633 // Do nothing, if we are launching in a remote terminal no file actions
3634 // should be done at all.
3635 return;
3636 }
3637
3638 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3639 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3640 "for stdin, stdout and stderr");
3641 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3642 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3643 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3644 } else {
3645 // Check for any values that might have gotten set with any of: (lldb)
3646 // settings set target.input-path (lldb) settings set target.output-path
3647 // (lldb) settings set target.error-path
3648 FileSpec in_file_spec;
3649 FileSpec out_file_spec;
3650 FileSpec err_file_spec;
3651 // Only override with the target settings if we don't already have an
3652 // action for in, out or error
3653 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3654 in_file_spec = GetStandardInputPath();
3655 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3656 out_file_spec = GetStandardOutputPath();
3657 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3658 err_file_spec = GetStandardErrorPath();
3659
3660 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{2}'",
3661 in_file_spec, out_file_spec, err_file_spec);
3662
3663 if (in_file_spec) {
3664 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3665 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3666 }
3667
3668 if (out_file_spec) {
3669 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3670 LLDB_LOG(log, "appended stdout open file action for {0}",
3671 out_file_spec);
3672 }
3673
3674 if (err_file_spec) {
3675 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3676 LLDB_LOG(log, "appended stderr open file action for {0}",
3677 err_file_spec);
3678 }
3679
3680 if (default_to_use_pty) {
3681 llvm::Error Err = info.SetUpPtyRedirection();
3682 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3683 }
3684 }
3685 }
3686}
3687
3688void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify,
3689 LazyBool stop) {
3690 if (name.empty())
3691 return;
3692 // Don't add a signal if all the actions are trivial:
3693 if (pass == eLazyBoolCalculate && notify == eLazyBoolCalculate
3694 && stop == eLazyBoolCalculate)
3695 return;
3696
3697 auto& elem = m_dummy_signals[name];
3698 elem.pass = pass;
3699 elem.notify = notify;
3700 elem.stop = stop;
3701}
3702
3704 const DummySignalElement &elem) {
3705 if (!signals_sp)
3706 return false;
3707
3708 int32_t signo
3709 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3710 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3711 return false;
3712
3713 if (elem.second.pass == eLazyBoolYes)
3714 signals_sp->SetShouldSuppress(signo, false);
3715 else if (elem.second.pass == eLazyBoolNo)
3716 signals_sp->SetShouldSuppress(signo, true);
3717
3718 if (elem.second.notify == eLazyBoolYes)
3719 signals_sp->SetShouldNotify(signo, true);
3720 else if (elem.second.notify == eLazyBoolNo)
3721 signals_sp->SetShouldNotify(signo, false);
3722
3723 if (elem.second.stop == eLazyBoolYes)
3724 signals_sp->SetShouldStop(signo, true);
3725 else if (elem.second.stop == eLazyBoolNo)
3726 signals_sp->SetShouldStop(signo, false);
3727 return true;
3728}
3729
3731 const DummySignalElement &elem) {
3732 if (!signals_sp)
3733 return false;
3734 int32_t signo
3735 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3736 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3737 return false;
3738 bool do_pass = elem.second.pass != eLazyBoolCalculate;
3739 bool do_stop = elem.second.stop != eLazyBoolCalculate;
3740 bool do_notify = elem.second.notify != eLazyBoolCalculate;
3741 signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass);
3742 return true;
3743}
3744
3746 StreamSP warning_stream_sp) {
3747 if (!signals_sp)
3748 return;
3749
3750 for (const auto &elem : m_dummy_signals) {
3751 if (!UpdateSignalFromDummy(signals_sp, elem))
3752 warning_stream_sp->Printf("Target signal '%s' not found in process\n",
3753 elem.first().str().c_str());
3754 }
3755}
3756
3757void Target::ClearDummySignals(Args &signal_names) {
3758 ProcessSP process_sp = GetProcessSP();
3759 // The simplest case, delete them all with no process to update.
3760 if (signal_names.GetArgumentCount() == 0 && !process_sp) {
3761 m_dummy_signals.clear();
3762 return;
3763 }
3764 UnixSignalsSP signals_sp;
3765 if (process_sp)
3766 signals_sp = process_sp->GetUnixSignals();
3767
3768 for (const Args::ArgEntry &entry : signal_names) {
3769 const char *signal_name = entry.c_str();
3770 auto elem = m_dummy_signals.find(signal_name);
3771 // If we didn't find it go on.
3772 // FIXME: Should I pipe error handling through here?
3773 if (elem == m_dummy_signals.end()) {
3774 continue;
3775 }
3776 if (signals_sp)
3777 ResetSignalFromDummy(signals_sp, *elem);
3778 m_dummy_signals.erase(elem);
3779 }
3780}
3781
3782void Target::PrintDummySignals(Stream &strm, Args &signal_args) {
3783 strm.Printf("NAME PASS STOP NOTIFY\n");
3784 strm.Printf("=========== ======= ======= =======\n");
3785
3786 auto str_for_lazy = [] (LazyBool lazy) -> const char * {
3787 switch (lazy) {
3788 case eLazyBoolCalculate: return "not set";
3789 case eLazyBoolYes: return "true ";
3790 case eLazyBoolNo: return "false ";
3791 }
3792 llvm_unreachable("Fully covered switch above!");
3793 };
3794 size_t num_args = signal_args.GetArgumentCount();
3795 for (const auto &elem : m_dummy_signals) {
3796 bool print_it = false;
3797 for (size_t idx = 0; idx < num_args; idx++) {
3798 if (elem.first() == signal_args.GetArgumentAtIndex(idx)) {
3799 print_it = true;
3800 break;
3801 }
3802 }
3803 if (print_it) {
3804 strm.Printf("%-11s ", elem.first().str().c_str());
3805 strm.Printf("%s %s %s\n", str_for_lazy(elem.second.pass),
3806 str_for_lazy(elem.second.stop),
3807 str_for_lazy(elem.second.notify));
3808 }
3809 }
3810}
3811
3812// Target::StopHook
3814 : UserID(uid), m_target_sp(target_sp), m_specifier_sp(),
3815 m_thread_spec_up() {}
3816
3818 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3819 m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(),
3820 m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) {
3821 if (rhs.m_thread_spec_up)
3822 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3823}
3824
3826 m_specifier_sp.reset(specifier);
3827}
3828
3830 m_thread_spec_up.reset(specifier);
3831}
3832
3834 SymbolContextSpecifier *specifier = GetSpecifier();
3835 if (!specifier)
3836 return true;
3837
3838 bool will_run = true;
3839 if (exc_ctx.GetFramePtr())
3840 will_run = GetSpecifier()->SymbolContextMatches(
3841 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
3842 if (will_run && GetThreadSpecifier() != nullptr)
3843 will_run =
3844 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
3845
3846 return will_run;
3847}
3848
3850 lldb::DescriptionLevel level) const {
3851
3852 // For brief descriptions, only print the subclass description:
3853 if (level == eDescriptionLevelBrief) {
3854 GetSubclassDescription(s, level);
3855 return;
3856 }
3857
3858 unsigned indent_level = s.GetIndentLevel();
3859
3860 s.SetIndentLevel(indent_level + 2);
3861
3862 s.Printf("Hook: %" PRIu64 "\n", GetID());
3863 if (m_active)
3864 s.Indent("State: enabled\n");
3865 else
3866 s.Indent("State: disabled\n");
3867
3868 if (m_auto_continue)
3869 s.Indent("AutoContinue on\n");
3870
3871 if (m_specifier_sp) {
3872 s.Indent();
3873 s.PutCString("Specifier:\n");
3874 s.SetIndentLevel(indent_level + 4);
3875 m_specifier_sp->GetDescription(&s, level);
3876 s.SetIndentLevel(indent_level + 2);
3877 }
3878
3879 if (m_thread_spec_up) {
3880 StreamString tmp;
3881 s.Indent("Thread:\n");
3882 m_thread_spec_up->GetDescription(&tmp, level);
3883 s.SetIndentLevel(indent_level + 4);
3884 s.Indent(tmp.GetString());
3885 s.PutCString("\n");
3886 s.SetIndentLevel(indent_level + 2);
3887 }
3888 GetSubclassDescription(s, level);
3889}
3890
3892 Stream &s, lldb::DescriptionLevel level) const {
3893 // The brief description just prints the first command.
3894 if (level == eDescriptionLevelBrief) {
3895 if (m_commands.GetSize() == 1)
3896 s.PutCString(m_commands.GetStringAtIndex(0));
3897 return;
3898 }
3899 s.Indent("Commands: \n");
3900 s.SetIndentLevel(s.GetIndentLevel() + 4);
3901 uint32_t num_commands = m_commands.GetSize();
3902 for (uint32_t i = 0; i < num_commands; i++) {
3903 s.Indent(m_commands.GetStringAtIndex(i));
3904 s.PutCString("\n");
3905 }
3906 s.SetIndentLevel(s.GetIndentLevel() - 4);
3907}
3908
3909// Target::StopHookCommandLine
3911 GetCommands().SplitIntoLines(string);
3912}
3913
3915 const std::vector<std::string> &strings) {
3916 for (auto string : strings)
3917 GetCommands().AppendString(string.c_str());
3918}
3919
3922 StreamSP output_sp) {
3923 assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
3924 "with no target");
3925
3926 if (!m_commands.GetSize())
3927 return StopHookResult::KeepStopped;
3928
3929 CommandReturnObject result(false);
3930 result.SetImmediateOutputStream(output_sp);
3931 result.SetInteractive(false);
3932 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
3934 options.SetStopOnContinue(true);
3935 options.SetStopOnError(true);
3936 options.SetEchoCommands(false);
3937 options.SetPrintResults(true);
3938 options.SetPrintErrors(true);
3939 options.SetAddToHistory(false);
3940
3941 // Force Async:
3942 bool old_async = debugger.GetAsyncExecution();
3943 debugger.SetAsyncExecution(true);
3944 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
3945 options, result);
3946 debugger.SetAsyncExecution(old_async);
3947 lldb::ReturnStatus status = result.GetStatus();
3950 return StopHookResult::AlreadyContinued;
3951 return StopHookResult::KeepStopped;
3952}
3953
3954// Target::StopHookScripted
3956 std::string class_name, StructuredData::ObjectSP extra_args_sp) {
3957 Status error;
3958
3959 ScriptInterpreter *script_interp =
3960 GetTarget()->GetDebugger().GetScriptInterpreter();
3961 if (!script_interp) {
3962 error = Status::FromErrorString("No script interpreter installed.");
3963 return error;
3964 }
3965
3966 m_interface_sp = script_interp->CreateScriptedStopHookInterface();
3967 if (!m_interface_sp) {
3969 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__,
3970 "Script interpreter couldn't create Scripted Stop Hook Interface");
3971 return error;
3972 }
3973
3974 m_class_name = class_name;
3975 m_extra_args.SetObjectSP(extra_args_sp);
3976
3977 auto obj_or_err = m_interface_sp->CreatePluginObject(
3978 m_class_name, GetTarget(), m_extra_args);
3979 if (!obj_or_err) {
3980 return Status::FromError(obj_or_err.takeError());
3981 }
3982
3983 StructuredData::ObjectSP object_sp = *obj_or_err;
3984 if (!object_sp || !object_sp->IsValid()) {
3986 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__,
3987 "Failed to create valid script object");
3988 return error;
3989 }
3990
3991 return {};
3992}
3993
3996 StreamSP output_sp) {
3997 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
3998 "with no target");
3999
4000 if (!m_interface_sp)
4001 return StopHookResult::KeepStopped;
4002
4003 lldb::StreamSP stream = std::make_shared<lldb_private::StreamString>();
4004 auto should_stop_or_err = m_interface_sp->HandleStop(exc_ctx, stream);
4005 output_sp->PutCString(
4006 reinterpret_cast<StreamString *>(stream.get())->GetData());
4007 if (!should_stop_or_err)
4008 return StopHookResult::KeepStopped;
4009
4010 return *should_stop_or_err ? StopHookResult::KeepStopped
4011 : StopHookResult::RequestContinue;
4012}
4013
4015 Stream &s, lldb::DescriptionLevel level) const {
4016 if (level == eDescriptionLevelBrief) {
4017 s.PutCString(m_class_name);
4018 return;
4019 }
4020 s.Indent("Class:");
4021 s.Printf("%s\n", m_class_name.c_str());
4022
4023 // Now print the extra args:
4024 // FIXME: We should use StructuredData.GetDescription on the m_extra_args
4025 // but that seems to rely on some printing plugin that doesn't exist.
4026 if (!m_extra_args.IsValid())
4027 return;
4028 StructuredData::ObjectSP object_sp = m_extra_args.GetObjectSP();
4029 if (!object_sp || !object_sp->IsValid())
4030 return;
4031
4032 StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary();
4033 if (!as_dict || !as_dict->IsValid())
4034 return;
4035
4036 uint32_t num_keys = as_dict->GetSize();
4037 if (num_keys == 0)
4038 return;
4039
4040 s.Indent("Args:\n");
4041 s.SetIndentLevel(s.GetIndentLevel() + 4);
4042
4043 auto print_one_element = [&s](llvm::StringRef key,
4044 StructuredData::Object *object) {
4045 s.Indent();
4046 s.Format("{0} : {1}\n", key, object->GetStringValue());
4047 return true;
4048 };
4049
4050 as_dict->ForEach(print_one_element);
4051
4052 s.SetIndentLevel(s.GetIndentLevel() - 4);
4053}
4054
4056 {
4058 "no-dynamic-values",
4059 "Don't calculate the dynamic type of values",
4060 },
4061 {
4063 "run-target",
4064 "Calculate the dynamic type of values "
4065 "even if you have to run the target.",
4066 },
4067 {
4069 "no-run-target",
4070 "Calculate the dynamic type of values, but don't run the target.",
4071 },
4072};
4073
4076}
4077
4079 {
4081 "never",
4082 "Never look for inline breakpoint locations (fastest). This setting "
4083 "should only be used if you know that no inlining occurs in your"
4084 "programs.",
4085 },
4086 {
4088 "headers",
4089 "Only check for inline breakpoint locations when setting breakpoints "
4090 "in header files, but not when setting breakpoint in implementation "
4091 "source files (default).",
4092 },
4093 {
4095 "always",
4096 "Always look for inline breakpoint locations when setting file and "
4097 "line breakpoints (slower but most accurate).",
4098 },
4099};
4100
4106
4108 {
4110 "default",
4111 "Disassembler default (currently att).",
4112 },
4113 {
4115 "intel",
4116 "Intel disassembler flavor.",
4117 },
4118 {
4120 "att",
4121 "AT&T disassembler flavor.",
4122 },
4123};
4124
4126 {
4128 "false",
4129 "Never import the 'std' C++ module in the expression parser.",
4130 },
4131 {
4133 "fallback",
4134 "Retry evaluating expressions with an imported 'std' C++ module if they"
4135 " failed to parse without the module. This allows evaluating more "
4136 "complex expressions involving C++ standard library types."
4137 },
4138 {
4140 "true",
4141 "Always import the 'std' C++ module. This allows evaluating more "
4142 "complex expressions involving C++ standard library types. This feature"
4143 " is experimental."
4144 },
4145};
4146
4147static constexpr OptionEnumValueElement
4149 {
4151 "auto",
4152 "Automatically determine the most appropriate method for the "
4153 "target OS.",
4154 },
4155 {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct",
4156 "Prefer using the realized classes struct."},
4157 {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList",
4158 "Prefer using the CopyRealizedClassList API."},
4159 {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList",
4160 "Prefer using the GetRealizedClassList API."},
4161};
4162
4164 {
4166 "c",
4167 "C-style (0xffff).",
4168 },
4169 {
4171 "asm",
4172 "Asm-style (0ffffh).",
4173 },
4174};
4175
4177 {
4179 "true",
4180 "Load debug scripts inside symbol files",
4181 },
4182 {
4184 "false",
4185 "Do not load debug scripts inside symbol files.",
4186 },
4187 {
4189 "warn",
4190 "Warn about debug scripts inside symbol files but do not load them.",
4191 },
4192};
4193
4195 {
4197 "true",
4198 "Load .lldbinit files from current directory",
4199 },
4200 {
4202 "false",
4203 "Do not load .lldbinit files from current directory",
4204 },
4205 {
4207 "warn",
4208 "Warn about loading .lldbinit files from current directory",
4209 },
4210};
4211
4213 {
4215 "minimal",
4216 "Load minimal information when loading modules from memory. Currently "
4217 "this setting loads sections only.",
4218 },
4219 {
4221 "partial",
4222 "Load partial information when loading modules from memory. Currently "
4223 "this setting loads sections and function bounds.",
4224 },
4225 {
4227 "complete",
4228 "Load complete information when loading modules from memory. Currently "
4229 "this setting loads sections and all symbols.",
4230 },
4231};
4232
4233#define LLDB_PROPERTIES_target
4234#include "TargetProperties.inc"
4235
4236enum {
4237#define LLDB_PROPERTIES_target
4238#include "TargetPropertiesEnum.inc"
4240};
4241
4243 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
4244public:
4245 TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
4246
4247 const Property *
4249 const ExecutionContext *exe_ctx = nullptr) const override {
4250 // When getting the value for a key from the target options, we will always
4251 // try and grab the setting from the current target if there is one. Else
4252 // we just use the one from this instance.
4253 if (exe_ctx) {
4254 Target *target = exe_ctx->GetTargetPtr();
4255 if (target) {
4256 TargetOptionValueProperties *target_properties =
4257 static_cast<TargetOptionValueProperties *>(
4258 target->GetValueProperties().get());
4259 if (this != target_properties)
4260 return target_properties->ProtectedGetPropertyAtIndex(idx);
4261 }
4262 }
4263 return ProtectedGetPropertyAtIndex(idx);
4264 }
4265};
4266
4267// TargetProperties
4268#define LLDB_PROPERTIES_target_experimental
4269#include "TargetProperties.inc"
4270
4271enum {
4272#define LLDB_PROPERTIES_target_experimental
4273#include "TargetPropertiesEnum.inc"
4274};
4275
4277 : public Cloneable<TargetExperimentalOptionValueProperties,
4278 OptionValueProperties> {
4279public:
4281 : Cloneable(Properties::GetExperimentalSettingsName()) {}
4282};
4283
4287 m_collection_sp->Initialize(g_target_experimental_properties);
4288}
4289
4290// TargetProperties
4292 : Properties(), m_launch_info(), m_target(target) {
4293 if (target) {
4296
4297 // Set callbacks to update launch_info whenever "settins set" updated any
4298 // of these properties
4299 m_collection_sp->SetValueChangedCallback(
4300 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
4301 m_collection_sp->SetValueChangedCallback(
4302 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
4303 m_collection_sp->SetValueChangedCallback(
4304 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
4305 m_collection_sp->SetValueChangedCallback(
4306 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
4307 m_collection_sp->SetValueChangedCallback(
4308 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
4309 m_collection_sp->SetValueChangedCallback(
4310 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
4311 m_collection_sp->SetValueChangedCallback(
4312 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
4313 m_collection_sp->SetValueChangedCallback(
4314 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
4315 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
4317 });
4318 m_collection_sp->SetValueChangedCallback(
4319 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
4320 m_collection_sp->SetValueChangedCallback(
4321 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
4322 m_collection_sp->SetValueChangedCallback(
4323 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
4324
4325 m_collection_sp->SetValueChangedCallback(
4326 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4328 std::make_unique<TargetExperimentalProperties>();
4329 m_collection_sp->AppendProperty(
4331 "Experimental settings - setting these won't produce "
4332 "errors if the setting is not present.",
4333 true, m_experimental_properties_up->GetValueProperties());
4334 } else {
4335 m_collection_sp = std::make_shared<TargetOptionValueProperties>("target");
4336 m_collection_sp->Initialize(g_target_properties);
4338 std::make_unique<TargetExperimentalProperties>();
4339 m_collection_sp->AppendProperty(
4341 "Experimental settings - setting these won't produce "
4342 "errors if the setting is not present.",
4343 true, m_experimental_properties_up->GetValueProperties());
4344 m_collection_sp->AppendProperty(
4345 "process", "Settings specific to processes.", true,
4347 m_collection_sp->SetValueChangedCallback(
4348 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4349 }
4350}
4351
4353
4365}
4366
4368 size_t prop_idx, ExecutionContext *exe_ctx) const {
4369 const Property *exp_property =
4370 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4371 OptionValueProperties *exp_values =
4372 exp_property->GetValue()->GetAsProperties();
4373 if (exp_values)
4374 return exp_values->GetPropertyAtIndexAs<bool>(prop_idx, exe_ctx);
4375 return std::nullopt;
4376}
4377
4379 ExecutionContext *exe_ctx) const {
4380 return GetExperimentalPropertyValue(ePropertyInjectLocalVars, exe_ctx)
4381 .value_or(true);
4382}
4383
4385 const Property *exp_property =
4386 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4387 OptionValueProperties *exp_values =
4388 exp_property->GetValue()->GetAsProperties();
4389 if (exp_values)
4390 return exp_values->GetPropertyAtIndexAs<bool>(ePropertyUseDIL, exe_ctx)
4391 .value_or(false);
4392 else
4393 return true;
4394}
4395
4397 const Property *exp_property =
4398 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4399 OptionValueProperties *exp_values =
4400 exp_property->GetValue()->GetAsProperties();
4401 if (exp_values)
4402 exp_values->SetPropertyAtIndex(ePropertyUseDIL, true, exe_ctx);
4403}
4404
4406 const uint32_t idx = ePropertyDefaultArch;
4407 return GetPropertyAtIndexAs<ArchSpec>(idx, {});
4408}
4409
4411 const uint32_t idx = ePropertyDefaultArch;
4412 SetPropertyAtIndex(idx, arch);
4413}
4414
4416 const uint32_t idx = ePropertyMoveToNearestCode;
4417 return GetPropertyAtIndexAs<bool>(
4418 idx, g_target_properties[idx].default_uint_value != 0);
4419}
4420
4422 const uint32_t idx = ePropertyPreferDynamic;
4423 return GetPropertyAtIndexAs<lldb::DynamicValueType>(
4424 idx, static_cast<lldb::DynamicValueType>(
4425 g_target_properties[idx].default_uint_value));
4426}
4427
4429 const uint32_t idx = ePropertyPreferDynamic;
4430 return SetPropertyAtIndex(idx, d);
4431}
4432
4435 "Interrupted checking preload symbols")) {
4436 return false;
4437 }
4438 const uint32_t idx = ePropertyPreloadSymbols;
4439 return GetPropertyAtIndexAs<bool>(
4440 idx, g_target_properties[idx].default_uint_value != 0);
4441}
4442
4444 const uint32_t idx = ePropertyPreloadSymbols;
4445 SetPropertyAtIndex(idx, b);
4446}
4447
4449 const uint32_t idx = ePropertyDisableASLR;
4450 return GetPropertyAtIndexAs<bool>(
4451 idx, g_target_properties[idx].default_uint_value != 0);
4452}
4453
4455 const uint32_t idx = ePropertyDisableASLR;
4456 SetPropertyAtIndex(idx, b);
4457}
4458
4460 const uint32_t idx = ePropertyInheritTCC;
4461 return GetPropertyAtIndexAs<bool>(
4462 idx, g_target_properties[idx].default_uint_value != 0);
4463}
4464
4466 const uint32_t idx = ePropertyInheritTCC;
4467 SetPropertyAtIndex(idx, b);
4468}
4469
4471 const uint32_t idx = ePropertyDetachOnError;
4472 return GetPropertyAtIndexAs<bool>(
4473 idx, g_target_properties[idx].default_uint_value != 0);
4474}
4475
4477 const uint32_t idx = ePropertyDetachOnError;
4478 SetPropertyAtIndex(idx, b);
4479}
4480
4482 const uint32_t idx = ePropertyDisableSTDIO;
4483 return GetPropertyAtIndexAs<bool>(
4484 idx, g_target_properties[idx].default_uint_value != 0);
4485}
4486
4488 const uint32_t idx = ePropertyDisableSTDIO;
4489 SetPropertyAtIndex(idx, b);
4490}
4492 const uint32_t idx = ePropertyLaunchWorkingDir;
4493 return GetPropertyAtIndexAs<llvm::StringRef>(
4494 idx, g_target_properties[idx].default_cstr_value);
4495}
4496
4498 const uint32_t idx = ePropertyDisassemblyFlavor;
4499 const char *return_value;
4500
4501 x86DisassemblyFlavor flavor_value =
4502 GetPropertyAtIndexAs<x86DisassemblyFlavor>(
4503 idx, static_cast<x86DisassemblyFlavor>(
4504 g_target_properties[idx].default_uint_value));
4505
4506 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
4507 return return_value;
4508}
4509
4511 const uint32_t idx = ePropertyDisassemblyCPU;
4512 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
4513 idx, g_target_properties[idx].default_cstr_value);
4514 return str.empty() ? nullptr : str.data();
4515}
4516
4518 const uint32_t idx = ePropertyDisassemblyFeatures;
4519 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
4520 idx, g_target_properties[idx].default_cstr_value);
4521 return str.empty() ? nullptr : str.data();
4522}
4523
4525 const uint32_t idx = ePropertyInlineStrategy;
4526 return GetPropertyAtIndexAs<InlineStrategy>(
4527 idx,
4528 static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value));
4529}
4530
4531// Returning RealpathPrefixes, but the setting's type is FileSpecList. We do
4532// this because we want the FileSpecList to normalize the file paths for us.
4534 const uint32_t idx = ePropertySourceRealpathPrefixes;
4535 return RealpathPrefixes(GetPropertyAtIndexAs<FileSpecList>(idx, {}));
4536}
4537
4538llvm::StringRef TargetProperties::GetArg0() const {
4539 const uint32_t idx = ePropertyArg0;
4540 return GetPropertyAtIndexAs<llvm::StringRef>(
4541 idx, g_target_properties[idx].default_cstr_value);
4542}
4543
4544void TargetProperties::SetArg0(llvm::StringRef arg) {
4545 const uint32_t idx = ePropertyArg0;
4546 SetPropertyAtIndex(idx, arg);
4548}
4549
4551 const uint32_t idx = ePropertyRunArgs;
4552 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4553}
4554
4556 const uint32_t idx = ePropertyRunArgs;
4557 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4558 m_launch_info.GetArguments() = args;
4559}
4560
4562 Environment env;
4563
4564 if (m_target &&
4565 GetPropertyAtIndexAs<bool>(
4566 ePropertyInheritEnv,
4567 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
4568 if (auto platform_sp = m_target->GetPlatform()) {
4569 Environment platform_env = platform_sp->GetEnvironment();
4570 for (const auto &KV : platform_env)
4571 env[KV.first()] = KV.second;
4572 }
4573 }
4574
4575 Args property_unset_env;
4576 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4577 property_unset_env);
4578 for (const auto &var : property_unset_env)
4579 env.erase(var.ref());
4580
4581 Args property_env;
4582 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env);
4583 for (const auto &KV : Environment(property_env))
4584 env[KV.first()] = KV.second;
4585
4586 return env;
4587}
4588
4590 return ComputeEnvironment();
4591}
4592
4594 Environment environment;
4595
4596 if (m_target == nullptr)
4597 return environment;
4598
4599 if (!GetPropertyAtIndexAs<bool>(
4600 ePropertyInheritEnv,
4601 g_target_properties[ePropertyInheritEnv].default_uint_value != 0))
4602 return environment;
4603
4604 PlatformSP platform_sp = m_target->GetPlatform();
4605 if (platform_sp == nullptr)
4606 return environment;
4607
4608 Environment platform_environment = platform_sp->GetEnvironment();
4609 for (const auto &KV : platform_environment)
4610 environment[KV.first()] = KV.second;
4611
4612 Args property_unset_environment;
4613 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4614 property_unset_environment);
4615 for (const auto &var : property_unset_environment)
4616 environment.erase(var.ref());
4617
4618 return environment;
4619}
4620
4622 Args property_environment;
4623 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars,
4624 property_environment);
4625 Environment environment;
4626 for (const auto &KV : Environment(property_environment))
4627 environment[KV.first()] = KV.second;
4628
4629 return environment;
4630}
4631
4633 // TODO: Get rid of the Args intermediate step
4634 const uint32_t idx = ePropertyEnvVars;
4635 m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env));
4636}
4637
4639 const uint32_t idx = ePropertySkipPrologue;
4640 return GetPropertyAtIndexAs<bool>(
4641 idx, g_target_properties[idx].default_uint_value != 0);
4642}
4643
4645 const uint32_t idx = ePropertySourceMap;
4646 OptionValuePathMappings *option_value =
4647 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4648 assert(option_value);
4649 return option_value->GetCurrentValue();
4650}
4651
4653 const uint32_t idx = ePropertyObjectMap;
4654 OptionValuePathMappings *option_value =
4655 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4656 assert(option_value);
4657 return option_value->GetCurrentValue();
4658}
4659
4661 const uint32_t idx = ePropertyAutoSourceMapRelative;
4662 return GetPropertyAtIndexAs<bool>(
4663 idx, g_target_properties[idx].default_uint_value != 0);
4664}
4665
4667 const uint32_t idx = ePropertyExecutableSearchPaths;
4668 OptionValueFileSpecList *option_value =
4669 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
4670 assert(option_value);
4671 option_value->AppendCurrentValue(dir);
4672}
4673
4675 const uint32_t idx = ePropertyExecutableSearchPaths;
4676 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4677}
4678
4680 const uint32_t idx = ePropertyDebugFileSearchPaths;
4681 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4682}
4683
4685 const uint32_t idx = ePropertyClangModuleSearchPaths;
4686 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4687}
4688
4690 const uint32_t idx = ePropertyAutoImportClangModules;
4691 return GetPropertyAtIndexAs<bool>(
4692 idx, g_target_properties[idx].default_uint_value != 0);
4693}
4694
4696 const uint32_t idx = ePropertyImportStdModule;
4697 return GetPropertyAtIndexAs<ImportStdModule>(
4698 idx, static_cast<ImportStdModule>(
4699 g_target_properties[idx].default_uint_value));
4700}
4701
4703 const uint32_t idx = ePropertyDynamicClassInfoHelper;
4704 return GetPropertyAtIndexAs<DynamicClassInfoHelper>(
4705 idx, static_cast<DynamicClassInfoHelper>(
4706 g_target_properties[idx].default_uint_value));
4707}
4708
4710 const uint32_t idx = ePropertyAutoApplyFixIts;
4711 return GetPropertyAtIndexAs<bool>(
4712 idx, g_target_properties[idx].default_uint_value != 0);
4713}
4714
4716 const uint32_t idx = ePropertyRetriesWithFixIts;
4717 return GetPropertyAtIndexAs<uint64_t>(
4718 idx, g_target_properties[idx].default_uint_value);
4719}
4720
4722 const uint32_t idx = ePropertyNotifyAboutFixIts;
4723 return GetPropertyAtIndexAs<bool>(
4724 idx, g_target_properties[idx].default_uint_value != 0);
4725}
4726
4728 const uint32_t idx = ePropertySaveObjectsDir;
4729 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4730}
4731
4733 FileSpec new_dir = GetSaveJITObjectsDir();
4734 if (!new_dir)
4735 return;
4736
4737 const FileSystem &instance = FileSystem::Instance();
4738 bool exists = instance.Exists(new_dir);
4739 bool is_directory = instance.IsDirectory(new_dir);
4740 std::string path = new_dir.GetPath(true);
4741 bool writable = llvm::sys::fs::can_write(path);
4742 if (exists && is_directory && writable)
4743 return;
4744
4745 m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir)
4746 ->GetValue()
4747 ->Clear();
4748
4749 std::string buffer;
4750 llvm::raw_string_ostream os(buffer);
4751 os << "JIT object dir '" << path << "' ";
4752 if (!exists)
4753 os << "does not exist";
4754 else if (!is_directory)
4755 os << "is not a directory";
4756 else if (!writable)
4757 os << "is not writable";
4758
4759 std::optional<lldb::user_id_t> debugger_id;
4760 if (m_target)
4761 debugger_id = m_target->GetDebugger().GetID();
4762 Debugger::ReportError(buffer, debugger_id);
4763}
4764
4766 const uint32_t idx = ePropertyEnableSynthetic;
4767 return GetPropertyAtIndexAs<bool>(
4768 idx, g_target_properties[idx].default_uint_value != 0);
4769}
4770
4772 const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes;
4773 return GetPropertyAtIndexAs<bool>(
4774 idx, g_target_properties[idx].default_uint_value != 0);
4775}
4776
4778 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
4779 return GetPropertyAtIndexAs<uint64_t>(
4780 idx, g_target_properties[idx].default_uint_value);
4781}
4782
4784 const uint32_t idx = ePropertyMaxChildrenCount;
4785 return GetPropertyAtIndexAs<uint64_t>(
4786 idx, g_target_properties[idx].default_uint_value);
4787}
4788
4789std::pair<uint32_t, bool>
4791 const uint32_t idx = ePropertyMaxChildrenDepth;
4792 auto *option_value =
4793 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx);
4794 bool is_default = !option_value->OptionWasSet();
4795 return {option_value->GetCurrentValue(), is_default};
4796}
4797
4799 const uint32_t idx = ePropertyMaxSummaryLength;
4800 return GetPropertyAtIndexAs<uint64_t>(
4801 idx, g_target_properties[idx].default_uint_value);
4802}
4803
4805 const uint32_t idx = ePropertyMaxMemReadSize;
4806 return GetPropertyAtIndexAs<uint64_t>(
4807 idx, g_target_properties[idx].default_uint_value);
4808}
4809
4811 const uint32_t idx = ePropertyInputPath;
4812 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4813}
4814
4815void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4816 const uint32_t idx = ePropertyInputPath;
4817 SetPropertyAtIndex(idx, path);
4818}
4819
4821 const uint32_t idx = ePropertyOutputPath;
4822 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4823}
4824
4826 const uint32_t idx = ePropertyOutputPath;
4827 SetPropertyAtIndex(idx, path);
4828}
4829
4831 const uint32_t idx = ePropertyErrorPath;
4832 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4833}
4834
4835void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4836 const uint32_t idx = ePropertyErrorPath;
4837 SetPropertyAtIndex(idx, path);
4838}
4839
4841 const uint32_t idx = ePropertyLanguage;
4842 return {GetPropertyAtIndexAs<LanguageType>(idx, {})};
4843}
4844
4846 const uint32_t idx = ePropertyExprPrefix;
4847 OptionValueFileSpec *file =
4848 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx);
4849 if (file) {
4850 DataBufferSP data_sp(file->GetFileContents());
4851 if (data_sp)
4852 return llvm::StringRef(
4853 reinterpret_cast<const char *>(data_sp->GetBytes()),
4854 data_sp->GetByteSize());
4855 }
4856 return "";
4857}
4858
4860 const uint32_t idx = ePropertyExprErrorLimit;
4861 return GetPropertyAtIndexAs<uint64_t>(
4862 idx, g_target_properties[idx].default_uint_value);
4863}
4864
4866 const uint32_t idx = ePropertyExprAllocAddress;
4867 return GetPropertyAtIndexAs<uint64_t>(
4868 idx, g_target_properties[idx].default_uint_value);
4869}
4870
4872 const uint32_t idx = ePropertyExprAllocSize;
4873 return GetPropertyAtIndexAs<uint64_t>(
4874 idx, g_target_properties[idx].default_uint_value);
4875}
4876
4878 const uint32_t idx = ePropertyExprAllocAlign;
4879 return GetPropertyAtIndexAs<uint64_t>(
4880 idx, g_target_properties[idx].default_uint_value);
4881}
4882
4884 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4885 return GetPropertyAtIndexAs<bool>(
4886 idx, g_target_properties[idx].default_uint_value != 0);
4887}
4888
4890 const uint32_t idx = ePropertyUseHexImmediates;
4891 return GetPropertyAtIndexAs<bool>(
4892 idx, g_target_properties[idx].default_uint_value != 0);
4893}
4894
4896 const uint32_t idx = ePropertyUseFastStepping;
4897 return GetPropertyAtIndexAs<bool>(
4898 idx, g_target_properties[idx].default_uint_value != 0);
4899}
4900
4902 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4903 return GetPropertyAtIndexAs<bool>(
4904 idx, g_target_properties[idx].default_uint_value != 0);
4905}
4906
4908 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4909 return GetPropertyAtIndexAs<LoadScriptFromSymFile>(
4910 idx, static_cast<LoadScriptFromSymFile>(
4911 g_target_properties[idx].default_uint_value));
4912}
4913
4915 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4916 return GetPropertyAtIndexAs<LoadCWDlldbinitFile>(
4917 idx, static_cast<LoadCWDlldbinitFile>(
4918 g_target_properties[idx].default_uint_value));
4919}
4920
4922 const uint32_t idx = ePropertyHexImmediateStyle;
4923 return GetPropertyAtIndexAs<Disassembler::HexImmediateStyle>(
4924 idx, static_cast<Disassembler::HexImmediateStyle>(
4925 g_target_properties[idx].default_uint_value));
4926}
4927
4929 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4930 return GetPropertyAtIndexAs<MemoryModuleLoadLevel>(
4931 idx, static_cast<MemoryModuleLoadLevel>(
4932 g_target_properties[idx].default_uint_value));
4933}
4934
4936 const uint32_t idx = ePropertyTrapHandlerNames;
4937 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4938}
4939
4941 const uint32_t idx = ePropertyTrapHandlerNames;
4942 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4943}
4944
4946 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4947 return GetPropertyAtIndexAs<bool>(
4948 idx, g_target_properties[idx].default_uint_value != 0);
4949}
4950
4952 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4953 SetPropertyAtIndex(idx, b);
4954}
4955
4957 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4958 return GetPropertyAtIndexAs<bool>(
4959 idx, g_target_properties[idx].default_uint_value != 0);
4960}
4961
4963 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4964 SetPropertyAtIndex(idx, b);
4965}
4966
4968 return m_launch_info;
4969}
4970
4972 const ProcessLaunchInfo &launch_info) {
4973 m_launch_info = launch_info;
4974 SetArg0(launch_info.GetArg0());
4975 SetRunArguments(launch_info.GetArguments());
4976 SetEnvironment(launch_info.GetEnvironment());
4977 const FileAction *input_file_action =
4978 launch_info.GetFileActionForFD(STDIN_FILENO);
4979 if (input_file_action) {
4980 SetStandardInputPath(input_file_action->GetPath());
4981 }
4982 const FileAction *output_file_action =
4983 launch_info.GetFileActionForFD(STDOUT_FILENO);
4984 if (output_file_action) {
4985 SetStandardOutputPath(output_file_action->GetPath());
4986 }
4987 const FileAction *error_file_action =
4988 launch_info.GetFileActionForFD(STDERR_FILENO);
4989 if (error_file_action) {
4990 SetStandardErrorPath(error_file_action->GetPath());
4991 }
4992 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4993 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4995 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
4996 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4997}
4998
5000 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5001 return GetPropertyAtIndexAs<bool>(
5002 idx, g_target_properties[idx].default_uint_value != 0);
5003}
5004
5006 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5007 m_collection_sp->SetPropertyAtIndex(idx, b);
5008}
5009
5011 const uint32_t idx = ePropertyAutoInstallMainExecutable;
5012 return GetPropertyAtIndexAs<bool>(
5013 idx, g_target_properties[idx].default_uint_value != 0);
5014}
5015
5018}
5019
5021 Args args;
5022 if (GetRunArguments(args))
5023 m_launch_info.GetArguments() = args;
5024}
5025
5028}
5029
5032 false);
5033}
5034
5037 false, true);
5038}
5039
5042 false, true);
5043}
5044
5046 if (GetDetachOnError())
5047 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
5048 else
5049 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
5050}
5051
5053 if (GetDisableASLR())
5054 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
5055 else
5056 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
5057}
5058
5060 if (GetInheritTCC())
5061 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
5062 else
5063 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
5064}
5065
5067 if (GetDisableSTDIO())
5068 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
5069 else
5070 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
5071}
5072
5074 const uint32_t idx = ePropertyDebugUtilityExpression;
5075 return GetPropertyAtIndexAs<bool>(
5076 idx, g_target_properties[idx].default_uint_value != 0);
5077}
5078
5080 const uint32_t idx = ePropertyDebugUtilityExpression;
5081 SetPropertyAtIndex(idx, debug);
5082}
5083
5084// Target::TargetEventData
5085
5087 : EventData(), m_target_sp(target_sp), m_module_list() {}
5088
5090 const ModuleList &module_list)
5091 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
5092
5094
5096 return "Target::TargetEventData";
5097}
5098
5100 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
5101 if (i != 0)
5102 *s << ", ";
5103 m_module_list.GetModuleAtIndex(i)->GetDescription(
5105 }
5106}
5107
5110 if (event_ptr) {
5111 const EventData *event_data = event_ptr->GetData();
5112 if (event_data &&
5114 return static_cast<const TargetEventData *>(event_ptr->GetData());
5115 }
5116 return nullptr;
5117}
5118
5120 TargetSP target_sp;
5121 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
5122 if (event_data)
5123 target_sp = event_data->m_target_sp;
5124 return target_sp;
5125}
5126
5129 ModuleList module_list;
5130 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
5131 if (event_data)
5132 module_list = event_data->m_module_list;
5133 return module_list;
5134}
5135
5136std::recursive_mutex &Target::GetAPIMutex() {
5137 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
5138 return m_private_mutex;
5139 else
5140 return m_mutex;
5141}
5142
5143/// Get metrics associated with this target in JSON format.
5144llvm::json::Value
5146 return m_stats.ToJSON(*this, options);
5147}
5148
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:454
#define bit
#define lldbassert(x)
Definition: LLDBAssert.h:15
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition: Log.h:369
#define LLDB_LOGF(log,...)
Definition: Log.h:376
#define LLDB_LOG_ERROR(log, error,...)
Definition: Log.h:392
@ ePropertyExperimental
Definition: Process.cpp:136
static double elapsed(const StatsTimepoint &start, const StatsTimepoint &end)
Definition: Statistics.cpp:39
static Status installExecutable(const Installer &installer)
Definition: Target.cpp:141
static constexpr OptionEnumValueElement g_dynamic_class_info_helper_value_types[]
Definition: Target.cpp:4148
static bool CheckIfWatchpointsSupported(Target *target, Status &error)
Definition: Target.cpp:914
static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[]
Definition: Target.cpp:4194
x86DisassemblyFlavor
Definition: Target.cpp:4101
@ eX86DisFlavorDefault
Definition: Target.cpp:4102
@ eX86DisFlavorIntel
Definition: Target.cpp:4103
@ eX86DisFlavorATT
Definition: Target.cpp:4104
static void LoadScriptingResourceForModule(const ModuleSP &module_sp, Target *target)
Definition: Target.cpp:1522
static constexpr OptionEnumValueElement g_dynamic_value_types[]
Definition: Target.cpp:4055
static constexpr OptionEnumValueElement g_memory_module_load_level_values[]
Definition: Target.cpp:4212
static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[]
Definition: Target.cpp:4176
static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[]
Definition: Target.cpp:4107
static constexpr OptionEnumValueElement g_hex_immediate_style_values[]
Definition: Target.cpp:4163
static constexpr OptionEnumValueElement g_inline_breakpoint_enums[]
Definition: Target.cpp:4078
static constexpr OptionEnumValueElement g_import_std_module_value_types[]
Definition: Target.cpp:4125
#define LLDB_SCOPED_TIMERF(...)
Definition: Timer.h:86
const Property * GetPropertyAtIndex(size_t idx, const ExecutionContext *exe_ctx=nullptr) const override
Definition: Target.cpp:4248
TargetOptionValueProperties(llvm::StringRef name)
Definition: Target.cpp:4245
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:313
bool SetLoadAddress(lldb::addr_t load_addr, Target *target, bool allow_section_end=false)
Set the address to represent load_addr.
Definition: Address.cpp:1047
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition: Address.h:439
bool Slide(int64_t offset)
Definition: Address.h:459
lldb::ModuleSP GetModule() const
Get accessor for the module for this address.
Definition: Address.cpp:285
lldb::addr_t GetFileAddress() const
Get the file address.
Definition: Address.cpp:293
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:448
An architecture specification class.
Definition: ArchSpec.h:31
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition: ArchSpec.cpp:709
bool IsValid() const
Tests if this ArchSpec is valid.
Definition: ArchSpec.h:359
llvm::Triple & GetTriple()
Architecture triple accessor.
Definition: ArchSpec.h:461
void MergeFrom(const ArchSpec &other)
Merges fields from another ArchSpec into this ArchSpec.
Definition: ArchSpec.cpp:827
bool IsCompatibleMatch(const ArchSpec &rhs) const
Shorthand for IsMatch(rhs, CompatibleMatch).
Definition: ArchSpec.h:513
lldb::ByteOrder GetByteOrder() const
Returns the byte order for the architecture specification.
Definition: ArchSpec.cpp:756
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition: ArchSpec.cpp:570
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
Definition: BreakpointID.h:33
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 RemoveInvalidLocations(const ArchSpec &arch)
Removes all invalid breakpoint locations.
lldb::BreakpointSP FindBreakpointByID(lldb::break_id_t breakID) const
Returns a shared pointer to the breakpoint with id breakID.
void GetListMutex(std::unique_lock< std::recursive_mutex > &lock)
Sets the passed in Locker to hold the Breakpoint List mutex.
lldb::break_id_t Add(lldb::BreakpointSP &bp_sp, bool notify)
Add the breakpoint bp_sp to the list.
void SetEnabledAllowed(bool enabled)
void ResetHitCounts()
Resets the hit count of all breakpoints.
size_t GetSize() const
Returns the number of elements in this breakpoint list.
void UpdateBreakpointsWhenModuleIsReplaced(lldb::ModuleSP old_module_sp, lldb::ModuleSP new_module_sp)
void RemoveAll(bool notify)
Removes all the breakpoints from this list.
void UpdateBreakpoints(ModuleList &module_list, bool load, bool delete_locations)
Tell all the breakpoints to update themselves due to a change in the modules in module_list.
llvm::Expected< std::vector< lldb::BreakpointSP > > FindBreakpointsByName(const char *name)
Find all the breakpoints with a given name.
void Dump(Stream *s) const
Standard "Dump" method. At present it does nothing.
bool Remove(lldb::break_id_t breakID, bool notify)
Removes the breakpoint given by breakID from this list.
void RemoveAllowed(bool notify)
Removes all the breakpoints from this list - first checking the ePermDelete on the breakpoints.
lldb::BreakpointSP GetBreakpointAtIndex(size_t i) const
Returns a shared pointer to the breakpoint with index i.
void SetEnabledAll(bool enabled)
void MergeInto(const Permissions &incoming)
ConstString GetName() const
BreakpointOptions & GetOptions()
void ConfigureBreakpoint(lldb::BreakpointSP bp_sp)
"lldb/Breakpoint/BreakpointOptions.h" Class that manages the options on a breakpoint or breakpoint lo...
void CopyOverSetOptions(const BreakpointOptions &rhs)
Copy over only the options set in the incoming BreakpointOptions.
"lldb/Breakpoint/BreakpointResolverAddress.h" This class sets breakpoints on a given Address.
"lldb/Breakpoint/BreakpointResolverFileLine.h" This class sets breakpoints by file and line.
"lldb/Breakpoint/BreakpointResolverFileRegex.h" This class sets breakpoints by file and line.
"lldb/Breakpoint/BreakpointResolverName.h" This class sets breakpoints on a given function name,...
"lldb/Breakpoint/BreakpointResolverScripted.h" This class sets breakpoints on a given Address.
General Outline: A breakpoint has four main parts, a filter, a resolver, the list of breakpoint locat...
Definition: Breakpoint.h:81
virtual StructuredData::ObjectSP SerializeToStructuredData()
Definition: Breakpoint.cpp:74
static lldb::BreakpointSP CreateFromStructuredData(lldb::TargetSP target_sp, StructuredData::ObjectSP &data_object_sp, Status &error)
Definition: Breakpoint.cpp:122
static lldb::BreakpointSP CopyFromBreakpoint(lldb::TargetSP new_target, const Breakpoint &bp_to_copy_from)
Definition: Breakpoint.cpp:61
static const char * GetSerializationKey()
Definition: Breakpoint.h:160
static bool SerializedBreakpointMatchesNames(StructuredData::ObjectSP &bkpt_object_sp, std::vector< std::string > &names)
Definition: Breakpoint.cpp:215
An event broadcasting class.
Definition: Broadcaster.h:146
void SetEventName(uint32_t event_mask, const char *name)
Set the name for an event bit.
Definition: Broadcaster.h:243
void BroadcastEvent(lldb::EventSP &event_sp)
Broadcast an event which has no associated data.
Definition: Broadcaster.h:168
A class that implements CRTP-based "virtual constructor" idiom.
Definition: Cloneable.h:40
void SetStopOnContinue(bool stop_on_continue)
void HandleCommands(const StringList &commands, const ExecutionContext &context, const CommandInterpreterRunOptions &options, CommandReturnObject &result)
Execute a list of commands in sequence.
void SetImmediateOutputStream(const lldb::StreamSP &stream_sp)
lldb::ReturnStatus GetStatus() const
Generic representation of a type in a programming language.
Definition: CompilerType.h:36
A uniqued constant string class.
Definition: ConstString.h:40
const char * AsCString(const char *value_if_empty=nullptr) const
Get the string value as a C string.
Definition: ConstString.h:188
bool IsEmpty() const
Test for empty string.
Definition: ConstString.h:304
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
Definition: ConstString.h:197
const char * GetCString() const
Get the string value as a C string.
Definition: ConstString.h:216
An data extractor class.
Definition: DataExtractor.h:48
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:80
lldb::StreamSP GetAsyncOutputStream()
Definition: Debugger.cpp:1324
void SetAsyncExecution(bool async)
Definition: Debugger.cpp:1018
CommandInterpreter & GetCommandInterpreter()
Definition: Debugger.h:168
StreamFile & GetErrorStream()
Definition: Debugger.h:148
TargetList & GetTargetList()
Get accessor for the target list.
Definition: Debugger.h:198
static llvm::ThreadPoolInterface & GetThreadPool()
Shared thread pool. Use only with ThreadPoolTaskGroup.
Definition: Debugger.cpp:2271
static void ReportError(std::string message, std::optional< lldb::user_id_t > debugger_id=std::nullopt, std::once_flag *once=nullptr)
Report error events.
Definition: Debugger.cpp:1628
PlatformList & GetPlatformList()
Definition: Debugger.h:200
lldb::ListenerSP GetListener()
Definition: Debugger.h:177
lldb::LanguageType GetREPLLanguage() const
Definition: Debugger.cpp:357
llvm::Error GetAsError(lldb::ExpressionResults result, llvm::Twine message={}) const
Returns an ExpressionError with arg as error code.
A class that measures elapsed time in an exception safe way.
Definition: Statistics.h:76
static constexpr std::chrono::milliseconds default_timeout
Definition: Target.h:313
virtual llvm::StringRef GetFlavor() const =0
EventData * GetData()
Definition: Event.h:200
"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.
Target * GetTargetPtr() const
Returns a pointer to the target object.
Thread & GetThreadRef() const
Returns a reference to the thread object.
llvm::StringRef GetPath() const
Definition: FileAction.cpp:28
A file collection class.
Definition: FileSpecList.h:91
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:447
void SetDirectory(ConstString directory)
Directory string set accessor.
Definition: FileSpec.cpp:335
const ConstString & GetFilename() const
Filename string const get accessor.
Definition: FileSpec.h:240
const ConstString & GetDirectory() const
Directory string const get accessor.
Definition: FileSpec.h:223
void SetPath(llvm::StringRef p)
Temporary helper for FileSystem change.
Definition: FileSpec.h:279
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition: FileSpec.cpp:367
bool IsSourceImplementationFile() const
Returns true if the filespec represents an implementation source file (files with a "....
Definition: FileSpec.cpp:494
void SetFilename(ConstString filename)
Filename string set accessor.
Definition: FileSpec.cpp:345
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
bool IsDirectory(const FileSpec &file_spec) const
Returns whether the given path is a directory.
static FileSystem & Instance()
@ eOpenOptionWriteOnly
Definition: File.h:52
@ eOpenOptionCanCreate
Definition: File.h:56
@ eOpenOptionCloseOnExec
Definition: File.h:63
@ eOpenOptionTruncate
Definition: File.h:57
bool IsValid() const override
IsValid.
Definition: File.cpp:113
A class to manage flags.
Definition: Flags.h:22
ValueType Clear(ValueType mask=~static_cast< ValueType >(0))
Clear one or more flags.
Definition: Flags.h:61
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:432
static Language * FindPlugin(lldb::LanguageType language)
Definition: Language.cpp:84
static const char * GetNameForLanguageType(lldb::LanguageType language)
Definition: Language.cpp:266
static LanguageSet GetLanguagesSupportingTypeSystemsForExpressions()
Definition: Language.cpp:428
virtual llvm::StringRef GetUserEntryPointName() const
Definition: Language.h:174
static std::set< lldb::LanguageType > GetSupportedLanguages()
Definition: Language.cpp:415
static lldb::ListenerSP MakeListener(const char *name)
Definition: Listener.cpp:376
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
Definition: ModuleChild.cpp:24
A collection class for Module objects.
Definition: ModuleList.h:103
bool ReplaceModule(const lldb::ModuleSP &old_module_sp, const lldb::ModuleSP &new_module_sp)
Definition: ModuleList.cpp:338
void ForEach(std::function< bool(const lldb::ModuleSP &module_sp)> const &callback) const
Applies 'callback' to each module in this ModuleList.
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.
size_t GetIndexForModule(const Module *module) const
Definition: ModuleList.cpp:725
lldb::ModuleSP FindFirstModule(const ModuleSpec &module_spec) const
Definition: ModuleList.cpp:626
void Clear()
Clear the object's state.
Definition: ModuleList.cpp:411
void Dump(Stream *s) const
Dump the description of each module contained in this list.
Definition: ModuleList.cpp:647
static bool RemoveSharedModuleIfOrphaned(const Module *module_ptr)
bool AppendIfNeeded(const lldb::ModuleSP &new_module, bool notify=true)
Append a module to the module list, if it is not already there.
Definition: ModuleList.cpp:280
static Status GetSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, const FileSpecList *module_search_paths_ptr, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr, bool always_create=false)
Definition: ModuleList.cpp:789
void FindModules(const ModuleSpec &module_spec, ModuleList &matching_module_list) const
Finds the first module whose file specification matches file_spec.
Definition: ModuleList.cpp:543
bool Remove(const lldb::ModuleSP &module_sp, bool notify=true)
Remove a module from the module list.
Definition: ModuleList.cpp:334
lldb::ModuleSP GetModuleAtIndex(size_t idx) const
Get the module shared pointer for the module at index idx.
Definition: ModuleList.cpp:429
void Append(const lldb::ModuleSP &module_sp, bool notify=true)
Append a module to the module list.
Definition: ModuleList.cpp:247
bool ResolveFileAddress(lldb::addr_t vm_addr, Address &so_addr) const
Definition: ModuleList.cpp:670
size_t GetSize() const
Gets the size of the module list.
Definition: ModuleList.cpp:638
FileSpec & GetFileSpec()
Definition: ModuleSpec.h:53
A class that describes an executable image and its associated object and symbol files.
Definition: Module.h:89
virtual ObjectFile * GetObjectFile()
Get the object file representation for the current architecture.
Definition: Module.cpp:1199
bool FileHasChanged() const
Definition: Module.cpp:1075
const FileSpec & GetFileSpec() const
Get const accessor for the module file specification.
Definition: Module.h:453
A plug-in interface definition class for object file parsers.
Definition: ObjectFile.h:44
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:470
@ eTypeExecutable
A normal executable.
Definition: ObjectFile.h:53
@ eTypeDebugInfo
An object file that contains only debug information.
Definition: ObjectFile.h:55
@ eTypeStubLibrary
A library that can be linked against but not used for execution.
Definition: ObjectFile.h:63
@ eTypeObjectFile
An intermediate object file.
Definition: ObjectFile.h:59
@ eTypeDynamicLinker
The platform's dynamic linker executable.
Definition: ObjectFile.h:57
@ eTypeCoreFile
A core file that has a checkpoint of a program's execution state.
Definition: ObjectFile.h:51
@ eTypeSharedLibrary
A shared library that can be used during execution.
Definition: ObjectFile.h:61
virtual size_t ReadSectionData(Section *section, lldb::offset_t section_offset, void *dst, size_t dst_len)
Definition: ObjectFile.cpp:488
void AppendCurrentValue(const FileSpec &value)
const lldb::DataBufferSP & GetFileContents()
auto GetPropertyAtIndexAs(size_t idx, const ExecutionContext *exe_ctx=nullptr) const
Property * ProtectedGetPropertyAtIndex(size_t idx)
bool SetPropertyAtIndex(size_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
static lldb::OptionValuePropertiesSP CreateLocalCopy(const Properties &global_properties)
bool RemapPath(ConstString path, ConstString &new_path) const
std::optional< llvm::StringRef > ReverseRemapPath(const FileSpec &file, FileSpec &fixed) const
Perform reverse source path remap for input file.
lldb::PlatformSP GetSelectedPlatform()
Select the active platform.
Definition: Platform.h:1100
static std::unique_ptr< Architecture > CreateArchitectureInstance(const ArchSpec &arch)
static lldb::RegisterTypeBuilderSP GetRegisterTypeBuilder(Target &target)
bool ProcessInfoSpecified() const
Definition: Process.h:175
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition: Process.cpp:2936
llvm::StringRef GetProcessPluginName() const
Definition: Process.h:158
void SetHijackListener(const lldb::ListenerSP &listener_sp)
Definition: ProcessInfo.h:110
void SetExecutableFile(const FileSpec &exe_file, bool add_exe_file_as_first_arg)
Definition: ProcessInfo.cpp:65
lldb::ScriptedMetadataSP GetScriptedMetadata() const
Definition: ProcessInfo.h:93
lldb::ListenerSP GetHijackListener() const
Definition: ProcessInfo.h:108
void SetArg0(llvm::StringRef arg)
Definition: ProcessInfo.cpp:82
llvm::StringRef GetArg0() const
Definition: ProcessInfo.cpp:80
void SetScriptedMetadata(lldb::ScriptedMetadataSP metadata_sp)
Definition: ProcessInfo.h:97
FileSpec & GetExecutableFile()
Definition: ProcessInfo.h:43
lldb::ListenerSP GetListener() const
Definition: ProcessInfo.h:102
lldb::ListenerSP GetShadowListener() const
Definition: ProcessInfo.h:114
Environment & GetEnvironment()
Definition: ProcessInfo.h:88
bool IsScriptedProcess() const
ArchSpec & GetArchitecture()
Definition: ProcessInfo.h:62
llvm::StringRef GetProcessPluginName() const
const FileSpec & GetShell() const
bool AppendOpenFileAction(int fd, const FileSpec &file_spec, bool read, bool write)
bool AppendSuppressFileAction(int fd, bool read, bool write)
const FileAction * GetFileActionForFD(int fd) const
void SetProcessPluginName(llvm::StringRef plugin)
static void SettingsInitialize()
Definition: Process.cpp:4819
static constexpr llvm::StringRef AttachSynchronousHijackListenerName
Definition: Process.h:388
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:372
static constexpr llvm::StringRef LaunchSynchronousHijackListenerName
Definition: Process.h:390
static ProcessProperties & GetGlobalProperties()
Definition: Process.cpp:520
static void SettingsTerminate()
Definition: Process.cpp:4821
lldb::OptionValuePropertiesSP m_collection_sp
static llvm::StringRef GetExperimentalSettingsName()
bool SetPropertyAtIndex(uint32_t idx, T t, const ExecutionContext *exe_ctx=nullptr) const
virtual lldb::OptionValuePropertiesSP GetValueProperties() const
const lldb::OptionValueSP & GetValue() const
Definition: Property.h:45
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:745
unsigned long long ULongLong(unsigned long long fail_value=0) const
Definition: Scalar.cpp:335
virtual lldb::ScriptedStopHookInterfaceSP CreateScriptedStopHookInterface()
"lldb/Core/SearchFilter.h" This is a SearchFilter that searches through all modules.
Definition: SearchFilter.h:289
size_t GetNumSections(uint32_t depth) const
Definition: Section.cpp:539
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition: Section.cpp:550
bool ResolveLoadAddress(uint32_t stop_id, lldb::addr_t load_addr, Address &so_addr)
bool SetSectionLoadAddress(uint32_t stop_id, const lldb::SectionSP &section_sp, lldb::addr_t load_addr, bool warn_multiple=false)
lldb::addr_t GetSectionLoadAddress(uint32_t stop_id, const lldb::SectionSP &section_sp)
bool SetSectionUnloaded(uint32_t stop_id, const lldb::SectionSP &section_sp, lldb::addr_t load_addr)
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, bool allow_section_end=false) const
"lldb/Core/SourceLocationSpec.h" A source location specifier class.
Class that provides a registry of known stack frame recognizers.
const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
Definition: StackFrame.cpp:301
An error handling class.
Definition: Status.h:115
void Clear()
Clear the object state.
Definition: Status.cpp:215
static Status FromErrorStringWithFormat(const char *format,...) __attribute__((format(printf
Definition: Status.cpp:106
static Status FromErrorString(const char *str)
Definition: Status.h:138
bool Fail() const
Test for error condition.
Definition: Status.cpp:270
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition: Status.h:148
static Status FromError(llvm::Error error)
Avoid using this in new code. Migrate APIs to llvm::Expected instead.
Definition: Status.cpp:137
bool Success() const
Test for success condition.
Definition: Status.cpp:280
const char * GetData() const
Definition: StreamString.h:45
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)
Definition: Stream.h:353
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition: Stream.h:401
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:65
size_t PutChar(char ch)
Definition: Stream.cpp:131
void SetIndentLevel(unsigned level)
Set the current indentation level.
Definition: Stream.cpp:190
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition: Stream.cpp:198
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition: Stream.cpp:195
unsigned GetIndentLevel() const
Get the current indentation level.
Definition: Stream.cpp:187
void AddItem(const ObjectSP &item)
ObjectSP GetItemAtIndex(size_t idx) const
ObjectSP GetValueForKey(llvm::StringRef key) const
void ForEach(std::function< bool(llvm::StringRef key, Object *object)> const &callback) const
void Dump(lldb_private::Stream &s, bool pretty_print=true) const
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:237
SummaryStatisticsSP GetSummaryStatisticsForProvider(lldb_private::TypeSummaryImpl &provider)
Get the SummaryStatistics object for a given provider name, or insert if statistics for that provider...
Definition: Statistics.h:242
Defines a symbol context baton that can be handed other debug core functions.
Definition: SymbolContext.h:34
lldb::TargetSP target_sp
The Target for a given query.
lldb::TargetSP GetTargetAtIndex(uint32_t index) const
Definition: TargetList.cpp:500
size_t GetNumTargets() const
Definition: TargetList.cpp:495
uint32_t GetMaximumSizeOfStringSummary() const
Definition: Target.cpp:4798
FileSpecList GetDebugFileSearchPaths()
Definition: Target.cpp:4679
llvm::StringRef GetLaunchWorkingDirectory() const
Definition: Target.cpp:4491
bool GetDisplayRecognizedArguments() const
Definition: Target.cpp:4956
ImportStdModule GetImportStdModule() const
Definition: Target.cpp:4695
bool GetMoveToNearestCode() const
Definition: Target.cpp:4415
void AppendExecutableSearchPaths(const FileSpec &)
Definition: Target.cpp:4666
bool GetEnableSyntheticValue() const
Definition: Target.cpp:4765
ProcessLaunchInfo m_launch_info
Definition: Target.h:298
uint64_t GetExprAllocAlign() const
Definition: Target.cpp:4877
MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const
Definition: Target.cpp:4928
llvm::StringRef GetArg0() const
Definition: Target.cpp:4538
uint32_t GetMaximumMemReadSize() const
Definition: Target.cpp:4804
void SetRunArguments(const Args &args)
Definition: Target.cpp:4555
FileSpec GetStandardErrorPath() const
Definition: Target.cpp:4830
bool GetEnableNotifyAboutFixIts() const
Definition: Target.cpp:4721
bool SetPreferDynamicValue(lldb::DynamicValueType d)
Definition: Target.cpp:4428
void SetDisplayRecognizedArguments(bool b)
Definition: Target.cpp:4962
std::optional< bool > GetExperimentalPropertyValue(size_t prop_idx, ExecutionContext *exe_ctx=nullptr) const
Definition: Target.cpp:4367
const ProcessLaunchInfo & GetProcessLaunchInfo() const
Definition: Target.cpp:4967
Environment ComputeEnvironment() const
Definition: Target.cpp:4561
bool GetUserSpecifiedTrapHandlerNames(Args &args) const
Definition: Target.cpp:4935
uint64_t GetExprErrorLimit() const
Definition: Target.cpp:4859
bool GetEnableAutoImportClangModules() const
Definition: Target.cpp:4689
bool GetDebugUtilityExpression() const
Definition: Target.cpp:5073
DynamicClassInfoHelper GetDynamicClassInfoHelper() const
Definition: Target.cpp:4702
FileSpec GetStandardOutputPath() const
Definition: Target.cpp:4820
void SetDisplayRuntimeSupportValues(bool b)
Definition: Target.cpp:4951
uint32_t GetMaximumNumberOfChildrenToDisplay() const
Definition: Target.cpp:4783
void SetRequireHardwareBreakpoints(bool b)
Definition: Target.cpp:5005
bool GetAutoInstallMainExecutable() const
Definition: Target.cpp:5010
const char * GetDisassemblyFeatures() const
Definition: Target.cpp:4517
RealpathPrefixes GetSourceRealpathPrefixes() const
Definition: Target.cpp:4533
uint64_t GetNumberOfRetriesWithFixits() const
Definition: Target.cpp:4715
uint64_t GetExprAllocSize() const
Definition: Target.cpp:4871
llvm::StringRef GetExpressionPrefixContents()
Definition: Target.cpp:4845
PathMappingList & GetObjectPathMap() const
Definition: Target.cpp:4652
const char * GetDisassemblyFlavor() const
Definition: Target.cpp:4497
FileSpec GetStandardInputPath() const
Definition: Target.cpp:4810
lldb::DynamicValueType GetPreferDynamicValue() const
Definition: Target.cpp:4421
InlineStrategy GetInlineStrategy() const
Definition: Target.cpp:4524
Environment GetTargetEnvironment() const
Definition: Target.cpp:4621
bool GetDisplayRuntimeSupportValues() const
Definition: Target.cpp:4945
void SetUserSpecifiedTrapHandlerNames(const Args &args)
Definition: Target.cpp:4940
bool GetUseHexImmediates() const
Definition: Target.cpp:4889
uint32_t GetMaxZeroPaddingInFloatFormat() const
Definition: Target.cpp:4777
uint64_t GetExprAllocAddress() const
Definition: Target.cpp:4865
LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const
Definition: Target.cpp:4914
Environment GetInheritedEnvironment() const
Definition: Target.cpp:4593
void SetArg0(llvm::StringRef arg)
Definition: Target.cpp:4544
bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const
Definition: Target.cpp:4378
bool ShowHexVariableValuesWithLeadingZeroes() const
Definition: Target.cpp:4771
SourceLanguage GetLanguage() const
Definition: Target.cpp:4840
Environment GetEnvironment() const
Definition: Target.cpp:4589
void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
Definition: Target.cpp:4971
FileSpec GetSaveJITObjectsDir() const
Definition: Target.cpp:4727
void SetEnvironment(Environment env)
Definition: Target.cpp:4632
LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const
Definition: Target.cpp:4907
const char * GetDisassemblyCPU() const
Definition: Target.cpp:4510
void SetStandardErrorPath(llvm::StringRef path)
Definition: Target.cpp:4835
bool GetRunArguments(Args &args) const
Definition: Target.cpp:4550
bool GetBreakpointsConsultPlatformAvoidList()
Definition: Target.cpp:4883
FileSpecList GetExecutableSearchPaths()
Definition: Target.cpp:4674
ArchSpec GetDefaultArchitecture() const
Definition: Target.cpp:4405
Disassembler::HexImmediateStyle GetHexImmediateStyle() const
Definition: Target.cpp:4921
void SetUseDIL(ExecutionContext *exe_ctx, bool b)
Definition: Target.cpp:4396
std::unique_ptr< TargetExperimentalProperties > m_experimental_properties_up
Definition: Target.h:299
FileSpecList GetClangModuleSearchPaths()
Definition: Target.cpp:4684
void SetStandardOutputPath(llvm::StringRef path)
Definition: Target.cpp:4825
bool GetRequireHardwareBreakpoints() const
Definition: Target.cpp:4999
PathMappingList & GetSourcePathMap() const
Definition: Target.cpp:4644
bool GetAutoSourceMapRelative() const
Definition: Target.cpp:4660
bool GetUseDIL(ExecutionContext *exe_ctx) const
Definition: Target.cpp:4384
void SetDefaultArchitecture(const ArchSpec &arch)
Definition: Target.cpp:4410
void SetStandardInputPath(llvm::StringRef path)
Definition: Target.cpp:4815
TargetProperties(Target *target)
Definition: Target.cpp:4291
bool GetDisplayExpressionsInCrashlogs() const
Definition: Target.cpp:4901
bool GetEnableAutoApplyFixIts() const
Definition: Target.cpp:4709
void SetDebugUtilityExpression(bool debug)
Definition: Target.cpp:5079
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:4790
void Reset(Target &target)
Definition: Statistics.cpp:204
llvm::json::Value ToJSON(Target &target, const lldb_private::StatisticsOptions &options)
Definition: Statistics.cpp:106
StatsDuration & GetCreateTime()
Definition: Statistics.h:277
StatsSuccessFail & GetExpressionStats()
Definition: Statistics.h:278
const ArchSpec & GetSpec() const
Definition: Target.h:1551
const Arch & operator=(const ArchSpec &spec)
Definition: Target.cpp:160
Arch(const ArchSpec &spec)
Definition: Target.cpp:156
void SetActionFromString(const std::string &strings)
Definition: Target.cpp:3910
void SetActionFromStrings(const std::vector< std::string > &strings)
Definition: Target.cpp:3914
StopHookResult HandleStop(ExecutionContext &exc_ctx, lldb::StreamSP output_sp) override
Definition: Target.cpp:3921
void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition: Target.cpp:3891
Status SetScriptCallback(std::string class_name, StructuredData::ObjectSP extra_args_sp)
Definition: Target.cpp:3955
StopHookResult HandleStop(ExecutionContext &exc_ctx, lldb::StreamSP output) override
Definition: Target.cpp:3995
void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition: Target.cpp:4014
void SetSpecifier(SymbolContextSpecifier *specifier)
Definition: Target.cpp:3825
std::unique_ptr< ThreadSpec > m_thread_spec_up
Definition: Target.h:1358
void SetThreadSpecifier(ThreadSpec *specifier)
Definition: Target.cpp:3829
StopHook(const StopHook &rhs)
Definition: Target.cpp:3817
bool ExecutionContextPasses(const ExecutionContext &exe_ctx)
Definition: Target.cpp:3833
void GetDescription(Stream &s, lldb::DescriptionLevel level) const
Definition: Target.cpp:3849
void Dump(Stream *s) const override
Definition: Target.cpp:5099
static llvm::StringRef GetFlavorString()
Definition: Target.cpp:5095
static ModuleList GetModuleListFromEvent(const Event *event_ptr)
Definition: Target.cpp:5128
static const TargetEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition: Target.cpp:5109
TargetEventData(const lldb::TargetSP &target_sp)
Definition: Target.cpp:5086
static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr)
Definition: Target.cpp:5119
void ModulesDidLoad(ModuleList &module_list)
Definition: Target.cpp:1814
lldb::ThreadSP CalculateThread() override
Definition: Target.cpp:2531
REPLMap m_repl_map
Definition: Target.h:1594
StopHookCollection m_stop_hooks
Definition: Target.h:1599
Module * GetExecutableModulePointer()
Definition: Target.cpp:1518
void Dump(Stream *s, lldb::DescriptionLevel description_level)
Dump a description of this object to a Stream.
Definition: Target.cpp:234
bool m_suppress_stop_hooks
Definition: Target.h:1604
void DisableAllBreakpoints(bool internal_also=false)
Definition: Target.cpp:1052
lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size, const CompilerType *type, uint32_t kind, Status &error)
Definition: Target.cpp:934
void ApplyNameToBreakpoints(BreakpointName &bp_name)
Definition: Target.cpp:888
StopHookSP CreateStopHook(StopHook::StopHookKind kind)
Add an empty stop hook to the Target's stop hook list, and returns a shared pointer to it in new_hook...
Definition: Target.cpp:2957
lldb::TraceSP GetTrace()
Get the Trace object containing processor trace information of this target.
Definition: Target.cpp:3489
PathMappingList & GetImageSearchPathList()
Definition: Target.cpp:2540
void FinalizeFileActions(ProcessLaunchInfo &info)
Definition: Target.cpp:3609
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:2931
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:2939
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:740
static Target * GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
Definition: Target.cpp:2776
lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr)
Definition: Target.cpp:2946
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:3757
static void ImageSearchPathsChanged(const PathMappingList &path_list, void *baton)
Definition: Target.cpp:2544
llvm::Expected< lldb_private::Address > GetEntryPointAddress()
This method will return the address of the starting function for this binary, e.g.
Definition: Target.cpp:2897
bool IgnoreWatchpointByID(lldb::watch_id_t watch_id, uint32_t ignore_count)
Definition: Target.cpp:1488
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:706
lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id)
Definition: Target.cpp:405
std::shared_ptr< StopHook > StopHookSP
Definition: Target.h:1415
void SymbolsDidLoad(ModuleList &module_list)
Definition: Target.cpp:1834
bool ClearAllWatchpointHistoricValues()
Definition: Target.cpp:1402
void SetTrace(const lldb::TraceSP &trace_sp)
Set the Trace object containing processor trace information of this target.
Definition: Target.cpp:3487
BreakpointList & GetBreakpointList(bool internal=false)
Definition: Target.cpp:391
CompilerType GetRegisterType(const std::string &name, const lldb_private::RegisterFlags &flags, uint32_t byte_size)
Definition: Target.cpp:2579
BreakpointNameList m_breakpoint_names
Definition: Target.h:1580
lldb_private::SummaryStatisticsCache & GetSummaryStatisticsCache()
Definition: Target.cpp:3308
llvm::StringRef GetABIName() const
Returns the name of the target's ABI plugin.
Definition: Target.cpp:380
SourceManager & GetSourceManager()
Definition: Target.cpp:2951
lldb::SearchFilterSP GetSearchFilterForModuleList(const FileSpecList *containingModuleList)
Definition: Target.cpp:669
StopHookSP GetStopHookByID(lldb::user_id_t uid)
Definition: Target.cpp:2986
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:1615
lldb::ProcessSP m_process_sp
Definition: Target.h:1588
lldb::SearchFilterSP m_search_filter_sp
Definition: Target.h:1589
PersistentExpressionState * GetPersistentExpressionStateForLanguage(lldb::LanguageType language)
Definition: Target.cpp:2623
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:3745
bool m_is_dummy_target
Used to not run stop hooks for expressions.
Definition: Target.h:1605
static bool UpdateSignalFromDummy(lldb::UnixSignalsSP signals_sp, const DummySignalElement &element)
Definition: Target.cpp:3703
PathMappingList m_image_search_paths
Definition: Target.h:1590
bool ModuleIsExcludedForUnconstrainedSearches(const FileSpec &module_spec)
Return whether this FileSpec corresponds to a module that should be considered for general searches.
Definition: Target.cpp:1890
lldb::StackFrameSP CalculateStackFrame() override
Definition: Target.cpp:2533
SectionLoadList & GetSectionLoadList()
Definition: Target.h:1154
lldb::addr_t GetPersistentSymbol(ConstString name)
Definition: Target.cpp:2877
void PrimeFromDummyTarget(Target &target)
Definition: Target.cpp:212
static void SettingsTerminate()
Definition: Target.cpp:2735
bool EnableWatchpointByID(lldb::watch_id_t watch_id)
Definition: Target.cpp:1453
bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr)
Definition: Target.cpp:3224
Debugger & GetDebugger()
Definition: Target.h:1080
bool ClearAllWatchpointHitCounts()
Definition: Target.cpp:1388
size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len, Status &error)
Definition: Target.cpp:1922
void ClearAllLoadedSections()
Definition: Target.cpp:3300
std::vector< lldb::TypeSystemSP > GetScratchTypeSystems(bool create_on_demand=true)
Definition: Target.cpp:2588
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:2216
void AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name, Status &error)
Definition: Target.cpp:808
void DeleteCurrentProcess()
Definition: Target.cpp:269
BreakpointList m_internal_breakpoint_list
Definition: Target.h:1577
void DisableAllowedBreakpoints()
Definition: Target.cpp:1062
bool SetSectionUnloaded(const lldb::SectionSP &section_sp)
Definition: Target.cpp:3278
lldb::TargetSP CalculateTarget() override
Definition: Target.cpp:2527
const lldb::ProcessSP & GetProcessSP() const
Definition: Target.cpp:297
void ClearModules(bool delete_locations)
Definition: Target.cpp:1540
bool RemoveBreakpointByID(lldb::break_id_t break_id)
Definition: Target.cpp:1086
lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec, bool notify, Status *error_ptr=nullptr)
Find a binary on the system and return its Module, or return an existing Module that is already in th...
Definition: Target.cpp:2286
static bool ResetSignalFromDummy(lldb::UnixSignalsSP signals_sp, const DummySignalElement &element)
Definition: Target.cpp:3730
Architecture * GetArchitecturePlugin() const
Definition: Target.h:1078
llvm::json::Value ReportStatistics(const lldb_private::StatisticsOptions &options)
Get metrics associated with this target in JSON format.
Definition: Target.cpp:5145
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:2676
void EnableAllBreakpoints(bool internal_also=false)
Definition: Target.cpp:1069
Status Launch(ProcessLaunchInfo &launch_info, Stream *stream)
Definition: Target.cpp:3323
bool DisableBreakpointByID(lldb::break_id_t break_id)
Definition: Target.cpp:1106
lldb::BreakpointSP CreateBreakpointAtUserEntry(Status &error)
Definition: Target.cpp:417
BreakpointName * FindBreakpointName(ConstString name, bool can_create, Status &error)
Definition: Target.cpp:840
llvm::Expected< lldb::TraceSP > CreateTrace()
Create a Trace object for the current target using the using the default supported tracing technology...
Definition: Target.cpp:3491
lldb::TraceSP m_trace_sp
An optional lldb_private::Trace object containing processor trace information of this target.
Definition: Target.h:1609
bool RemoveAllWatchpoints(bool end_to_end=true)
Definition: Target.cpp:1306
bool ReadPointerFromMemory(const Address &addr, Status &error, Address &pointer_addr, bool force_live_memory=false)
Definition: Target.cpp:2256
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:2972
WatchpointList m_watchpoint_list
Definition: Target.h:1583
BreakpointList m_breakpoint_list
Definition: Target.h:1576
lldb::SourceManagerUP m_source_manager_up
Definition: Target.h:1596
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)
Definition: Target.cpp:1956
bool RemoveWatchpointByID(lldb::watch_id_t watch_id)
Definition: Target.cpp:1472
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:2167
void DeleteBreakpointName(ConstString name)
Definition: Target.cpp:864
void NotifyWillClearList(const ModuleList &module_list) override
Definition: Target.cpp:1776
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition: Target.cpp:1662
void NotifyModuleAdded(const ModuleList &module_list, const lldb::ModuleSP &module_sp) override
Implementing of ModuleList::Notifier.
Definition: Target.cpp:1778
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
Definition: Target.cpp:2553
void ConfigureBreakpointName(BreakpointName &bp_name, const BreakpointOptions &options, const BreakpointName::Permissions &permissions)
Definition: Target.cpp:880
lldb_private::SummaryStatisticsSP GetSummaryStatisticsSPForProviderName(lldb_private::TypeSummaryImpl &summary_provider)
Definition: Target.cpp:3302
lldb::SearchFilterSP GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules, const FileSpecList *containingSourceFiles)
Definition: Target.cpp:686
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition: Target.cpp:1504
bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state)
Definition: Target.cpp:2996
const lldb::ProcessSP & CreateProcess(lldb::ListenerSP listener_sp, llvm::StringRef plugin_name, const FileSpec *crash_file, bool can_connect)
Definition: Target.cpp:285
void SetAllStopHooksActiveState(bool active_state)
Definition: Target.cpp:3007
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition: Target.cpp:2858
void NotifyModulesRemoved(lldb_private::ModuleList &module_list) override
Definition: Target.cpp:1810
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error, bool force_live_memory=false)
Definition: Target.cpp:2077
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:1562
void ModulesDidUnload(ModuleList &module_list, bool delete_locations)
Definition: Target.cpp:1850
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition: Target.cpp:2535
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:3516
void NotifyModuleUpdated(const ModuleList &module_list, const lldb::ModuleSP &old_module_sp, const lldb::ModuleSP &new_module_sp) override
Definition: Target.cpp:1798
SummaryStatisticsCache m_summary_statistics_cache
Definition: Target.h:1574
Status SerializeBreakpointsToFile(const FileSpec &file, const BreakpointIDList &bp_ids, bool append)
Definition: Target.cpp:1147
void DidExec()
Called as the last function in Process::DidExec().
Definition: Target.cpp:1547
void SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info)
Definition: Target.cpp:3312
std::string m_label
Definition: Target.h:1571
lldb::user_id_t m_stop_hook_next_id
Definition: Target.h:1600
void RemoveAllStopHooks()
Definition: Target.cpp:2984
static FileSpecList GetDefaultExecutableSearchPaths()
Definition: Target.cpp:2737
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:723
lldb::SearchFilterSP GetSearchFilterForModule(const FileSpec *containingModule)
Definition: Target.cpp:651
llvm::StringMapEntry< DummySignalValues > DummySignalElement
Definition: Target.h:1505
std::recursive_mutex & GetAPIMutex()
Definition: Target.cpp:5136
static llvm::StringRef GetStaticBroadcasterClass()
Definition: Target.cpp:166
static FileSpecList GetDefaultDebugFileSearchPaths()
Definition: Target.cpp:2741
void EnableAllowedBreakpoints()
Definition: Target.cpp:1079
llvm::Error SetLabel(llvm::StringRef label)
Set a label for a target.
Definition: Target.cpp:2756
uint32_t m_latest_stop_hook_id
Definition: Target.h:1601
@ eBroadcastBitModulesLoaded
Definition: Target.h:518
@ eBroadcastBitSymbolsLoaded
Definition: Target.h:521
@ eBroadcastBitModulesUnloaded
Definition: Target.h:519
@ eBroadcastBitWatchpointChanged
Definition: Target.h:520
@ eBroadcastBitBreakpointChanged
Definition: Target.h:517
void RemoveAllowedBreakpoints()
Definition: Target.cpp:1031
bool DisableAllWatchpoints(bool end_to_end=true)
Definition: Target.cpp:1335
lldb::addr_t GetReasonableReadSize(const Address &addr)
Return a recommended size for memory reads at addr, optimizing for cache usage.
Definition: Target.cpp:2154
lldb::PlatformSP m_platform_sp
The platform for this target.
Definition: Target.h:1561
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:2706
static TargetProperties & GetGlobalProperties()
Definition: Target.cpp:3183
Status Install(ProcessLaunchInfo *launch_info)
Definition: Target.cpp:3191
lldb::PlatformSP GetPlatform()
Definition: Target.h:1463
void NotifyModuleRemoved(const ModuleList &module_list, const lldb::ModuleSP &module_sp) override
Definition: Target.cpp:1788
lldb::BreakpointSP CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal, const FileSpec &file_spec, bool request_hardware)
Definition: Target.cpp:560
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:472
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow)
Definition: Target.cpp:3219
void RemoveAllBreakpoints(bool internal_also=false)
Definition: Target.cpp:1040
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:455
static ArchSpec GetDefaultArchitecture()
Definition: Target.cpp:2745
void ResetBreakpointHitCounts()
Resets the hit count of all breakpoints.
Definition: Target.cpp:1143
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition: Target.h:997
const ArchSpec & GetArchitecture() const
Definition: Target.h:1039
WatchpointList & GetWatchpointList()
Definition: Target.h:790
bool EnableBreakpointByID(lldb::break_id_t break_id)
Definition: Target.cpp:1124
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:2245
TargetStats m_stats
Definition: Target.h:1623
bool IgnoreAllWatchpoints(uint32_t ignore_count)
Definition: Target.cpp:1417
void AddBreakpoint(lldb::BreakpointSP breakpoint_sp, bool internal)
Definition: Target.cpp:785
TypeSystemMap m_scratch_type_system_map
Definition: Target.h:1591
void AddBreakpointName(std::unique_ptr< BreakpointName > bp_name)
Definition: Target.cpp:835
SectionLoadHistory m_section_load_history
Definition: Target.h:1575
void GetBreakpointNames(std::vector< std::string > &names)
Definition: Target.cpp:902
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:171
size_t UnloadModuleSections(const lldb::ModuleSP &module_sp)
Definition: Target.cpp:3259
bool m_valid
This records the last natural stop at which we ran a stop-hook.
Definition: Target.h:1603
bool DisableWatchpointByID(lldb::watch_id_t watch_id)
Definition: Target.cpp:1434
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:3688
lldb::WatchpointSP m_last_created_watchpoint
Definition: Target.h:1584
Status CreateBreakpointsFromFile(const FileSpec &file, BreakpointIDList &new_bps)
Definition: Target.cpp:1239
Debugger & m_debugger
Definition: Target.h:1560
void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp)
Definition: Target.cpp:350
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition: Target.cpp:1553
lldb::StackFrameRecognizerManagerUP m_frame_recognizer_manager_up
Stores the frame recognizers of this target.
Definition: Target.h:1611
lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language, const char *repl_options, bool can_create)
Definition: Target.cpp:299
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:2643
ModuleList m_images
The list of images for this process (shared libraries and anything dynamically loaded).
Definition: Target.h:1572
lldb::ProcessSP CalculateProcess() override
Definition: Target.cpp:2529
void PrintDummySignals(Stream &strm, Args &signals)
Print all the signals set in this target.
Definition: Target.cpp:3782
void SetPlatform(const lldb::PlatformSP &platform_sp)
Definition: Target.h:1465
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition: Target.cpp:3229
Status Attach(ProcessAttachInfo &attach_info, Stream *stream)
Definition: Target.cpp:3522
static void SetDefaultArchitecture(const ArchSpec &arch)
Definition: Target.cpp:2749
lldb::BreakpointSP m_last_created_breakpoint
Definition: Target.h:1582
void RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp, ConstString name)
Definition: Target.cpp:875
bool RemoveStopHookByID(lldb::user_id_t uid)
Definition: Target.cpp:2979
static void SettingsInitialize()
Definition: Target.cpp:2733
~Target() override
Definition: Target.cpp:206
bool EnableAllWatchpoints(bool end_to_end=true)
Definition: Target.cpp:1362
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:1569
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:2790
bool MergeArchitecture(const ArchSpec &arch_spec)
Definition: Target.cpp:1751
uint32_t GetSize(bool can_update=true)
Definition: ThreadList.cpp:82
lldb::ThreadSP GetThreadAtIndex(uint32_t idx, bool can_update=true)
Definition: ThreadList.cpp:90
static llvm::Expected< lldb::TraceSP > FindPluginForLiveProcess(llvm::StringRef plugin_name, Process &process)
Find a trace plug-in to trace a live process.
Definition: Trace.cpp:134
llvm::Expected< lldb::TypeSystemSP > GetTypeSystemForLanguage(lldb::LanguageType language, Module *module, bool can_create)
Definition: TypeSystem.cpp:320
void ForEach(std::function< bool(lldb::TypeSystemSP)> const &callback)
Definition: TypeSystem.cpp:242
void Dump(Stream &s) const
Definition: UUID.cpp:63
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...
lldb::watch_id_t Add(const lldb::WatchpointSP &wp_sp, bool notify)
Add a Watchpoint to the list.
void SetEnabledAll(bool enabled)
lldb::WatchpointSP FindByID(lldb::watch_id_t watchID) const
Returns a shared pointer to the watchpoint with id watchID, const version.
void GetListMutex(std::unique_lock< std::recursive_mutex > &lock)
Sets the passed in Locker to hold the Watchpoint List mutex.
WatchpointIterable Watchpoints() const
bool Remove(lldb::watch_id_t watchID, bool notify)
Removes the watchpoint given by watchID from this list.
const lldb::WatchpointSP FindByAddress(lldb::addr_t addr) const
Returns a shared pointer to the watchpoint at address addr - const version.
#define LLDB_WATCH_TYPE_WRITE
Definition: lldb-defines.h:46
#define LLDB_INVALID_BREAK_ID
Definition: lldb-defines.h:37
#define LLDB_INVALID_SIGNAL_NUMBER
Definition: lldb-defines.h:92
#define LLDB_INVALID_INDEX32
Definition: lldb-defines.h:83
#define LLDB_WATCH_TYPE_IS_VALID(type)
Definition: lldb-defines.h:48
#define LLDB_BREAK_ID_IS_INTERNAL(bid)
Definition: lldb-defines.h:40
#define LLDB_WATCH_TYPE_MODIFY
Definition: lldb-defines.h:47
#define LLDB_WATCH_TYPE_READ
Definition: lldb-defines.h:45
#define LLDB_INVALID_ADDRESS
Definition: lldb-defines.h:82
@ SelectMostRelevantFrame
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition: Log.h:332
std::shared_ptr< SummaryStatistics > SummaryStatisticsSP
Definition: Statistics.h:33
LoadScriptFromSymFile
Definition: Target.h:52
@ eLoadScriptFromSymFileTrue
Definition: Target.h:53
@ eLoadScriptFromSymFileFalse
Definition: Target.h:54
@ eLoadScriptFromSymFileWarn
Definition: Target.h:55
DynamicClassInfoHelper
Definition: Target.h:70
@ eDynamicClassInfoHelperCopyRealizedClassList
Definition: Target.h:73
@ eDynamicClassInfoHelperGetRealizedClassList
Definition: Target.h:74
@ eDynamicClassInfoHelperAuto
Definition: Target.h:71
@ eDynamicClassInfoHelperRealizedClassesStruct
Definition: Target.h:72
OptionEnumValues GetDynamicValueTypes()
Definition: Target.cpp:4074
ImportStdModule
Definition: Target.h:64
@ eImportStdModuleFalse
Definition: Target.h:65
@ eImportStdModuleFallback
Definition: Target.h:66
@ eImportStdModuleTrue
Definition: Target.h:67
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:58
@ eLoadCWDlldbinitTrue
Definition: Target.h:59
@ eLoadCWDlldbinitFalse
Definition: Target.h:60
@ eLoadCWDlldbinitWarn
Definition: Target.h:61
llvm::ArrayRef< OptionEnumValueElement > OptionEnumValues
void LoadFormattersForModule(lldb::ModuleSP module_sp)
Load data formatters embedded in the binary.
InlineStrategy
Definition: Target.h:46
@ eInlineBreakpointsNever
Definition: Target.h:47
@ eInlineBreakpointsAlways
Definition: Target.h:49
@ eInlineBreakpointsHeaders
Definition: Target.h:48
Definition: SBAddress.h:15
std::shared_ptr< lldb_private::OptionValueProperties > OptionValuePropertiesSP
Definition: lldb-forward.h:387
std::shared_ptr< lldb_private::Trace > TraceSP
Definition: lldb-forward.h:458
std::shared_ptr< lldb_private::TypeSystem > TypeSystemSP
Definition: lldb-forward.h:469
std::shared_ptr< lldb_private::ABI > ABISP
Definition: lldb-forward.h:317
std::shared_ptr< lldb_private::StackFrame > StackFrameSP
Definition: lldb-forward.h:424
std::shared_ptr< lldb_private::SearchFilter > SearchFilterSP
Definition: lldb-forward.h:422
std::shared_ptr< lldb_private::BreakpointResolver > BreakpointResolverSP
Definition: lldb-forward.h:328
DescriptionLevel
Description levels for "void GetDescription(Stream *, DescriptionLevel)" calls.
@ eDescriptionLevelBrief
@ eDescriptionLevelVerbose
std::shared_ptr< lldb_private::Thread > ThreadSP
Definition: lldb-forward.h:450
std::shared_ptr< lldb_private::ValueObject > ValueObjectSP
Definition: lldb-forward.h:484
std::shared_ptr< lldb_private::ExpressionVariable > ExpressionVariableSP
Definition: lldb-forward.h:351
std::shared_ptr< lldb_private::UnixSignals > UnixSignalsSP
Definition: lldb-forward.h:480
std::shared_ptr< lldb_private::Platform > PlatformSP
Definition: lldb-forward.h:388
uint64_t offset_t
Definition: lldb-types.h:85
StateType
Process and Thread States.
@ eStateConnected
Process is connected to remote debug services, but not launched or attached to anything yet.
@ eStateStopped
Process or thread is stopped and can be examined.
@ eStateAttaching
Process is currently trying to attach.
@ eStateExited
Process has exited and can't be examined.
std::shared_ptr< lldb_private::RegisterTypeBuilder > RegisterTypeBuilderSP
Definition: lldb-forward.h:396
LanguageType
Programming language type.
@ eLanguageTypeMipsAssembler
Mips_Assembler.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC
Non-standardized C, such as K&R.
std::shared_ptr< lldb_private::Stream > StreamSP
Definition: lldb-forward.h:432
std::shared_ptr< lldb_private::Breakpoint > BreakpointSP
Definition: lldb-forward.h:321
ExpressionResults
The results of expression evaluation.
@ eExpressionCompleted
@ eExpressionSetupError
int32_t break_id_t
Definition: lldb-types.h:86
std::shared_ptr< lldb_private::Process > ProcessSP
Definition: lldb-forward.h:389
std::shared_ptr< lldb_private::BreakpointPrecondition > BreakpointPreconditionSP
Definition: lldb-forward.h:327
std::shared_ptr< lldb_private::Event > EventSP
Definition: lldb-forward.h:345
ReturnStatus
Command Return Status Types.
@ eReturnStatusSuccessContinuingResult
@ eReturnStatusSuccessContinuingNoResult
std::shared_ptr< lldb_private::Watchpoint > WatchpointSP
Definition: lldb-forward.h:489
std::shared_ptr< lldb_private::Listener > ListenerSP
Definition: lldb-forward.h:368
int32_t watch_id_t
Definition: lldb-types.h:87
@ eSearchDepthTarget
uint64_t user_id_t
Definition: lldb-types.h:82
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
Definition: lldb-forward.h:336
std::shared_ptr< lldb_private::Section > SectionSP
Definition: lldb-forward.h:418
uint64_t addr_t
Definition: lldb-types.h:80
std::shared_ptr< lldb_private::Target > TargetSP
Definition: lldb-forward.h:448
@ eDynamicDontRunTarget
@ eDynamicCanRunTarget
@ eNoDynamicValues
std::shared_ptr< lldb_private::Module > ModuleSP
Definition: lldb-forward.h:373
std::shared_ptr< lldb_private::REPL > REPLSP
Definition: lldb-forward.h:401
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.
Definition: TypeSystem.cpp:28
A type-erased pair of llvm::dwarf::SourceLanguageName and version.
lldb::LanguageType AsLanguageType() const
Definition: Language.cpp:554
llvm::StringRef GetDescription() const
Definition: Language.cpp:561
A mix in class that contains a generic user ID.
Definition: UserID.h:31
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition: UserID.h:47