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