LLDB mainline
Target.cpp
Go to the documentation of this file.
1//===-- Target.cpp --------------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
19#include "lldb/Core/Debugger.h"
20#include "lldb/Core/Module.h"
24#include "lldb/Core/Section.h"
27#include "lldb/Core/Telemetry.h"
34#include "lldb/Host/Host.h"
35#include "lldb/Host/PosixApi.h"
46#include "lldb/Symbol/Symbol.h"
47#include "lldb/Target/ABI.h"
51#include "lldb/Target/Process.h"
57#include "lldb/Target/Thread.h"
60#include "lldb/Utility/Event.h"
64#include "lldb/Utility/Log.h"
66#include "lldb/Utility/State.h"
68#include "lldb/Utility/Timer.h"
69
70#include "llvm/ADT/ScopeExit.h"
71#include "llvm/ADT/SetVector.h"
72#include "llvm/Support/ThreadPool.h"
73
74#include <memory>
75#include <mutex>
76#include <optional>
77#include <sstream>
78
79using namespace lldb;
80using namespace lldb_private;
81
82namespace {
83
84struct ExecutableInstaller {
85
86 ExecutableInstaller(PlatformSP platform, ModuleSP module)
87 : m_platform{platform}, m_module{module},
88 m_local_file{m_module->GetFileSpec()},
89 m_remote_file{m_module->GetRemoteInstallFileSpec()} {}
90
91 void setupRemoteFile() const { m_module->SetPlatformFileSpec(m_remote_file); }
92
93 PlatformSP m_platform;
94 ModuleSP m_module;
95 const FileSpec m_local_file;
96 const FileSpec m_remote_file;
97};
98
99struct MainExecutableInstaller {
100
101 MainExecutableInstaller(PlatformSP platform, ModuleSP module, TargetSP target,
102 ProcessLaunchInfo &launch_info)
103 : m_platform{platform}, m_module{module},
104 m_local_file{m_module->GetFileSpec()},
105 m_remote_file{
106 getRemoteFileSpec(m_platform, target, m_module, m_local_file)},
107 m_launch_info{launch_info} {}
108
109 void setupRemoteFile() const {
110 m_module->SetPlatformFileSpec(m_remote_file);
111 m_launch_info.SetExecutableFile(m_remote_file,
112 /*add_exe_file_as_first_arg=*/false);
113 m_platform->SetFilePermissions(m_remote_file, 0700 /*-rwx------*/);
114 }
115
116 PlatformSP m_platform;
117 ModuleSP m_module;
118 const FileSpec m_local_file;
119 const FileSpec m_remote_file;
120
121private:
122 static FileSpec getRemoteFileSpec(PlatformSP platform, TargetSP target,
123 ModuleSP module,
124 const FileSpec &local_file) {
125 FileSpec remote_file = module->GetRemoteInstallFileSpec();
126 if (remote_file || !target->GetAutoInstallMainExecutable())
127 return remote_file;
128
129 if (!local_file)
130 return {};
131
132 remote_file = platform->GetRemoteWorkingDirectory();
133 remote_file.AppendPathComponent(local_file.GetFilename().GetCString());
134
135 return remote_file;
136 }
137
138 ProcessLaunchInfo &m_launch_info;
139};
140} // namespace
141
142static std::atomic<lldb::user_id_t> g_target_unique_id{1};
143
144template <typename Installer>
145static Status installExecutable(const Installer &installer) {
146 if (!installer.m_local_file || !installer.m_remote_file)
147 return Status();
148
149 Status error = installer.m_platform->Install(installer.m_local_file,
150 installer.m_remote_file);
151 if (error.Fail())
152 return error;
153
154 installer.setupRemoteFile();
155 return Status();
156}
157
158constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
159
161 : m_spec(spec),
162 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
163
165 m_spec = spec;
167 return *this;
168}
169
171 static constexpr llvm::StringLiteral class_name("lldb.target");
172 return class_name;
173}
174
175Target::Target(Debugger &debugger, const ArchSpec &target_arch,
176 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
177 : TargetProperties(this),
178 Broadcaster(debugger.GetBroadcasterManager(),
180 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
181 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
187 m_suppress_stop_hooks(false), m_is_dummy_target(is_dummy_target),
190 std::make_unique<StackFrameRecognizerManager>()) {
191 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
192 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
193 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
194 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
195 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
196
198
199 LLDB_LOG(GetLog(LLDBLog::Object), "{0} Target::Target()",
200 static_cast<void *>(this));
201 if (target_arch.IsValid()) {
203 "Target::Target created with architecture {0} ({1})",
204 target_arch.GetArchitectureName(),
205 target_arch.GetTriple().getTriple().c_str());
206 }
207
209}
210
212 Log *log = GetLog(LLDBLog::Object);
213 LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this));
215}
216
218 m_stop_hooks = target.m_stop_hooks;
221
222 for (const auto &breakpoint_sp : target.m_breakpoint_list.Breakpoints()) {
223 if (breakpoint_sp->IsInternal())
224 continue;
225
226 BreakpointSP new_bp(
227 Breakpoint::CopyFromBreakpoint(shared_from_this(), *breakpoint_sp));
228 AddBreakpoint(std::move(new_bp), false);
229 }
230
231 for (const auto &bp_name_entry : target.m_breakpoint_names) {
232 AddBreakpointName(std::make_unique<BreakpointName>(*bp_name_entry.second));
233 }
234
235 m_frame_recognizer_manager_up = std::make_unique<StackFrameRecognizerManager>(
237
239}
240
241void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
242 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
243 if (description_level != lldb::eDescriptionLevelBrief) {
244 s->Indent();
245 s->PutCString("Target\n");
246 s->IndentMore();
247 m_images.Dump(s);
248 m_breakpoint_list.Dump(s);
250 s->IndentLess();
251 } else {
252 Module *exe_module = GetExecutableModulePointer();
253 if (exe_module)
254 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
255 else
256 s->PutCString("No executable module.");
257 }
258}
259
261 // Do any cleanup of the target we need to do between process instances.
262 // NB It is better to do this before destroying the process in case the
263 // clean up needs some help from the process.
264 m_breakpoint_list.ClearAllBreakpointSites();
265 m_internal_breakpoint_list.ClearAllBreakpointSites();
267 // Disable watchpoints just on the debugger side.
268 std::unique_lock<std::recursive_mutex> lock;
269 this->GetWatchpointList().GetListMutex(lock);
274}
275
277 if (m_process_sp) {
278 // We dispose any active tracing sessions on the current process
279 m_trace_sp.reset();
280
281 if (m_process_sp->IsAlive())
282 m_process_sp->Destroy(false);
283
284 m_process_sp->Finalize(false /* not destructing */);
285
286 // Let the process finalize itself first, then clear the section load
287 // history. Some objects owned by the process might end up calling
288 // SectionLoadHistory::SetSectionUnloaded() which can create entries in
289 // the section load history that can mess up subsequent processes.
291
293
294 m_process_sp.reset();
295 }
296}
297
299 llvm::StringRef plugin_name,
300 const FileSpec *crash_file,
301 bool can_connect) {
302 if (!listener_sp)
303 listener_sp = GetDebugger().GetListener();
305 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
306 listener_sp, crash_file, can_connect);
307 return m_process_sp;
308}
309
311
313 const char *repl_options, bool can_create) {
314 if (language == eLanguageTypeUnknown)
315 language = m_debugger.GetREPLLanguage();
316
317 if (language == eLanguageTypeUnknown) {
319
320 if (auto single_lang = repl_languages.GetSingularLanguage()) {
321 language = *single_lang;
322 } else if (repl_languages.Empty()) {
324 "LLDB isn't configured with REPL support for any languages.");
325 return REPLSP();
326 } else {
328 "Multiple possible REPL languages. Please specify a language.");
329 return REPLSP();
330 }
331 }
332
333 REPLMap::iterator pos = m_repl_map.find(language);
334
335 if (pos != m_repl_map.end()) {
336 return pos->second;
337 }
338
339 if (!can_create) {
341 "Couldn't find an existing REPL for %s, and can't create a new one",
343 return lldb::REPLSP();
344 }
345
346 Debugger *const debugger = nullptr;
347 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
348
349 if (ret) {
350 m_repl_map[language] = ret;
351 return m_repl_map[language];
352 }
353
354 if (err.Success()) {
356 "Couldn't create a REPL for %s",
358 }
359
360 return lldb::REPLSP();
361}
362
364 lldbassert(!m_repl_map.count(language));
365
366 m_repl_map[language] = repl_sp;
367}
368
370 std::lock_guard<std::recursive_mutex> guard(m_mutex);
371 m_valid = false;
373 m_platform_sp.reset();
374 m_arch = ArchSpec();
375 ClearModules(true);
377 const bool notify = false;
378 m_breakpoint_list.RemoveAll(notify);
379 m_internal_breakpoint_list.RemoveAll(notify);
381 m_watchpoint_list.RemoveAll(notify);
383 m_search_filter_sp.reset();
384 m_image_search_paths.Clear(notify);
385 m_stop_hooks.clear();
387 m_internal_stop_hooks.clear();
388 m_suppress_stop_hooks = false;
389 m_repl_map.clear();
390 Args signal_args;
391 ClearDummySignals(signal_args);
392}
393
394llvm::StringRef Target::GetABIName() const {
395 lldb::ABISP abi_sp;
396 if (m_process_sp)
397 abi_sp = m_process_sp->GetABI();
398 if (!abi_sp)
400 if (abi_sp)
401 return abi_sp->GetPluginName();
402 return {};
403}
404
406 if (internal)
408 else
409 return m_breakpoint_list;
410}
411
412const BreakpointList &Target::GetBreakpointList(bool internal) const {
413 if (internal)
415 else
416 return m_breakpoint_list;
417}
418
420 BreakpointSP bp_sp;
421
422 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
423 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
424 else
425 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
426
427 return bp_sp;
428}
429
432 ModuleSP main_module_sp = GetExecutableModule();
433 FileSpecList shared_lib_filter;
434 shared_lib_filter.Append(main_module_sp->GetFileSpec());
435 llvm::SetVector<std::string, std::vector<std::string>,
436 std::unordered_set<std::string>>
437 entryPointNamesSet;
439 Language *lang = Language::FindPlugin(lang_type);
440 if (!lang) {
441 error = Status::FromErrorString("Language not found\n");
442 return lldb::BreakpointSP();
443 }
444 std::string entryPointName = lang->GetUserEntryPointName().str();
445 if (!entryPointName.empty())
446 entryPointNamesSet.insert(entryPointName);
447 }
448 if (entryPointNamesSet.empty()) {
449 error = Status::FromErrorString("No entry point name found\n");
450 return lldb::BreakpointSP();
451 }
453 &shared_lib_filter,
454 /*containingSourceFiles=*/nullptr, entryPointNamesSet.takeVector(),
455 /*func_name_type_mask=*/eFunctionNameTypeFull,
456 /*language=*/eLanguageTypeUnknown,
457 /*offset=*/0,
458 /*skip_prologue=*/eLazyBoolNo,
459 /*internal=*/false,
460 /*hardware=*/false);
461 if (!bp_sp) {
462 error = Status::FromErrorString("Breakpoint creation failed.\n");
463 return lldb::BreakpointSP();
464 }
465 bp_sp->SetOneShot(true);
466 return bp_sp;
467}
468
470 const FileSpecList *containingModules,
471 const FileSpecList *source_file_spec_list,
472 const std::unordered_set<std::string> &function_names,
473 RegularExpression source_regex, bool internal, bool hardware,
474 LazyBool move_to_nearest_code) {
476 containingModules, source_file_spec_list));
477 if (move_to_nearest_code == eLazyBoolCalculate)
478 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
480 nullptr, std::move(source_regex), function_names,
481 !static_cast<bool>(move_to_nearest_code)));
482
483 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
484}
485
487 const FileSpec &file, uint32_t line_no,
488 uint32_t column, lldb::addr_t offset,
489 LazyBool check_inlines,
490 LazyBool skip_prologue, bool internal,
491 bool hardware,
492 LazyBool move_to_nearest_code) {
493 FileSpec remapped_file;
494 std::optional<llvm::StringRef> removed_prefix_opt =
495 GetSourcePathMap().ReverseRemapPath(file, remapped_file);
496 if (!removed_prefix_opt)
497 remapped_file = file;
498
499 if (check_inlines == eLazyBoolCalculate) {
500 const InlineStrategy inline_strategy = GetInlineStrategy();
501 switch (inline_strategy) {
503 check_inlines = eLazyBoolNo;
504 break;
505
507 if (remapped_file.IsSourceImplementationFile())
508 check_inlines = eLazyBoolNo;
509 else
510 check_inlines = eLazyBoolYes;
511 break;
512
514 check_inlines = eLazyBoolYes;
515 break;
516 }
517 }
518 SearchFilterSP filter_sp;
519 if (check_inlines == eLazyBoolNo) {
520 // Not checking for inlines, we are looking only for matching compile units
521 FileSpecList compile_unit_list;
522 compile_unit_list.Append(remapped_file);
523 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
524 &compile_unit_list);
525 } else {
526 filter_sp = GetSearchFilterForModuleList(containingModules);
527 }
528 if (skip_prologue == eLazyBoolCalculate)
529 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
530 if (move_to_nearest_code == eLazyBoolCalculate)
531 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
532
533 SourceLocationSpec location_spec(remapped_file, line_no, column,
534 check_inlines,
535 !static_cast<bool>(move_to_nearest_code));
536 if (!location_spec)
537 return nullptr;
538
540 nullptr, offset, skip_prologue, location_spec, removed_prefix_opt));
541 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
542}
543
545 bool hardware) {
546 Address so_addr;
547
548 // Check for any reason we want to move this breakpoint to other address.
549 addr = GetBreakableLoadAddress(addr);
550
551 // Attempt to resolve our load address if possible, though it is ok if it
552 // doesn't resolve to section/offset.
553
554 // Try and resolve as a load address if possible
555 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
556 if (!so_addr.IsValid()) {
557 // The address didn't resolve, so just set this as an absolute address
558 so_addr.SetOffset(addr);
559 }
560 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
561 return bp_sp;
562}
563
565 bool hardware) {
566 SearchFilterSP filter_sp =
567 std::make_shared<SearchFilterForUnconstrainedSearches>(
568 shared_from_this());
569 BreakpointResolverSP resolver_sp =
570 std::make_shared<BreakpointResolverAddress>(nullptr, addr);
571 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
572}
573
576 const FileSpec &file_spec,
577 bool request_hardware) {
578 SearchFilterSP filter_sp =
579 std::make_shared<SearchFilterForUnconstrainedSearches>(
580 shared_from_this());
581 BreakpointResolverSP resolver_sp =
582 std::make_shared<BreakpointResolverAddress>(nullptr, file_addr,
583 file_spec);
584 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
585 false);
586}
587
589 const FileSpecList *containingModules,
590 const FileSpecList *containingSourceFiles, const char *func_name,
591 FunctionNameType func_name_type_mask, LanguageType language,
592 lldb::addr_t offset, bool offset_is_insn_count, LazyBool skip_prologue,
593 bool internal, bool hardware) {
594 BreakpointSP bp_sp;
595 if (func_name) {
597 containingModules, containingSourceFiles));
598
599 if (skip_prologue == eLazyBoolCalculate)
600 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
601 if (language == lldb::eLanguageTypeUnknown)
602 language = GetLanguage().AsLanguageType();
603
605 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
606 offset, offset_is_insn_count, skip_prologue));
607 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
608 }
609 return bp_sp;
610}
611
613Target::CreateBreakpoint(const FileSpecList *containingModules,
614 const FileSpecList *containingSourceFiles,
615 const std::vector<std::string> &func_names,
616 FunctionNameType func_name_type_mask,
617 LanguageType language, lldb::addr_t offset,
618 LazyBool skip_prologue, bool internal, bool hardware) {
619 BreakpointSP bp_sp;
620 size_t num_names = func_names.size();
621 if (num_names > 0) {
623 containingModules, containingSourceFiles));
624
625 if (skip_prologue == eLazyBoolCalculate)
626 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
627 if (language == lldb::eLanguageTypeUnknown)
628 language = GetLanguage().AsLanguageType();
629
630 BreakpointResolverSP resolver_sp(
631 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
632 language, offset, skip_prologue));
633 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
634 }
635 return bp_sp;
636}
637
639Target::CreateBreakpoint(const FileSpecList *containingModules,
640 const FileSpecList *containingSourceFiles,
641 const char *func_names[], size_t num_names,
642 FunctionNameType func_name_type_mask,
643 LanguageType language, lldb::addr_t offset,
644 LazyBool skip_prologue, bool internal, bool hardware) {
645 BreakpointSP bp_sp;
646 if (num_names > 0) {
648 containingModules, containingSourceFiles));
649
650 if (skip_prologue == eLazyBoolCalculate) {
651 if (offset == 0)
652 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
653 else
654 skip_prologue = eLazyBoolNo;
655 }
656 if (language == lldb::eLanguageTypeUnknown)
657 language = GetLanguage().AsLanguageType();
658
659 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
660 nullptr, func_names, num_names, func_name_type_mask, language, offset,
661 skip_prologue));
662 resolver_sp->SetOffset(offset);
663 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
664 }
665 return bp_sp;
666}
667
670 SearchFilterSP filter_sp;
671 if (containingModule != nullptr) {
672 // TODO: We should look into sharing module based search filters
673 // across many breakpoints like we do for the simple target based one
674 filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(),
675 *containingModule);
676 } else {
679 std::make_shared<SearchFilterForUnconstrainedSearches>(
680 shared_from_this());
681 filter_sp = m_search_filter_sp;
682 }
683 return filter_sp;
684}
685
688 SearchFilterSP filter_sp;
689 if (containingModules && containingModules->GetSize() != 0) {
690 // TODO: We should look into sharing module based search filters
691 // across many breakpoints like we do for the simple target based one
692 filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(),
693 *containingModules);
694 } else {
697 std::make_shared<SearchFilterForUnconstrainedSearches>(
698 shared_from_this());
699 filter_sp = m_search_filter_sp;
700 }
701 return filter_sp;
702}
703
705 const FileSpecList *containingModules,
706 const FileSpecList *containingSourceFiles) {
707 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
708 return GetSearchFilterForModuleList(containingModules);
709
710 SearchFilterSP filter_sp;
711 if (containingModules == nullptr) {
712 // We could make a special "CU List only SearchFilter". Better yet was if
713 // these could be composable, but that will take a little reworking.
714
715 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
716 shared_from_this(), FileSpecList(), *containingSourceFiles);
717 } else {
718 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
719 shared_from_this(), *containingModules, *containingSourceFiles);
720 }
721 return filter_sp;
722}
723
725 const FileSpecList *containingModules,
726 const FileSpecList *containingSourceFiles, RegularExpression func_regex,
727 lldb::LanguageType requested_language, LazyBool skip_prologue,
728 bool internal, bool hardware) {
730 containingModules, containingSourceFiles));
731 bool skip = (skip_prologue == eLazyBoolCalculate)
733 : static_cast<bool>(skip_prologue);
735 nullptr, std::move(func_regex), requested_language, 0, skip));
736
737 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
738}
739
742 bool catch_bp, bool throw_bp, bool internal,
743 Args *additional_args, Status *error) {
745 *this, language, catch_bp, throw_bp, internal);
746 if (exc_bkpt_sp && additional_args) {
747 BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
748 if (precondition_sp && additional_args) {
749 if (error)
750 *error = precondition_sp->ConfigurePrecondition(*additional_args);
751 else
752 precondition_sp->ConfigurePrecondition(*additional_args);
753 }
754 }
755 return exc_bkpt_sp;
756}
757
759 const llvm::StringRef class_name, const FileSpecList *containingModules,
760 const FileSpecList *containingSourceFiles, bool internal,
761 bool request_hardware, StructuredData::ObjectSP extra_args_sp,
762 Status *creation_error) {
763 SearchFilterSP filter_sp;
764
766 bool has_files =
767 containingSourceFiles && containingSourceFiles->GetSize() > 0;
768 bool has_modules = containingModules && containingModules->GetSize() > 0;
769
770 if (has_files && has_modules) {
771 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
772 containingSourceFiles);
773 } else if (has_files) {
774 filter_sp =
775 GetSearchFilterForModuleAndCUList(nullptr, containingSourceFiles);
776 } else if (has_modules) {
777 filter_sp = GetSearchFilterForModuleList(containingModules);
778 } else {
779 filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
780 shared_from_this());
781 }
782
784 nullptr, class_name, depth, StructuredDataImpl(extra_args_sp)));
785 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
786}
787
789 BreakpointResolverSP &resolver_sp,
790 bool internal, bool request_hardware,
791 bool resolve_indirect_symbols) {
792 BreakpointSP bp_sp;
793 if (filter_sp && resolver_sp) {
794 const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
795 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
796 resolve_indirect_symbols));
797 resolver_sp->SetBreakpoint(bp_sp);
798 AddBreakpoint(bp_sp, internal);
799 }
800 return bp_sp;
801}
802
803void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
804 if (!bp_sp)
805 return;
806 if (internal)
807 m_internal_breakpoint_list.Add(bp_sp, false);
808 else
809 m_breakpoint_list.Add(bp_sp, true);
810
812 if (log) {
813 StreamString s;
814 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
815 LLDB_LOGF(log, "Target::%s (internal = %s) => break_id = %s\n",
816 __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
817 }
818
819 bp_sp->ResolveBreakpoint();
820
821 if (!internal) {
823 }
824}
825
826void Target::AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name,
827 Status &error) {
828 BreakpointSP bp_sp =
829 m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
830 if (!bp_sp) {
831 StreamString s;
832 id.GetDescription(&s, eDescriptionLevelBrief);
833 error = Status::FromErrorStringWithFormat("Could not find breakpoint %s",
834 s.GetData());
835 return;
836 }
837 AddNameToBreakpoint(bp_sp, name, error);
838}
839
840void Target::AddNameToBreakpoint(BreakpointSP &bp_sp, llvm::StringRef name,
841 Status &error) {
842 if (!bp_sp)
843 return;
844
845 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
846 if (!bp_name)
847 return;
848
849 bp_name->ConfigureBreakpoint(bp_sp);
850 bp_sp->AddName(name);
851}
852
853void Target::AddBreakpointName(std::unique_ptr<BreakpointName> bp_name) {
854 m_breakpoint_names.insert(
855 std::make_pair(bp_name->GetName(), std::move(bp_name)));
856}
857
859 Status &error) {
861 if (!error.Success())
862 return nullptr;
863
864 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
865 if (iter != m_breakpoint_names.end()) {
866 return iter->second.get();
867 }
868
869 if (!can_create) {
871 "Breakpoint name \"%s\" doesn't exist and "
872 "can_create is false.",
873 name.AsCString());
874 return nullptr;
875 }
876
877 return m_breakpoint_names
878 .insert(std::make_pair(name, std::make_unique<BreakpointName>(name)))
879 .first->second.get();
880}
881
883 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
884
885 if (iter != m_breakpoint_names.end()) {
886 const char *name_cstr = name.AsCString();
887 m_breakpoint_names.erase(iter);
888 for (auto bp_sp : m_breakpoint_list.Breakpoints())
889 bp_sp->RemoveName(name_cstr);
890 }
891}
892
894 ConstString name) {
895 bp_sp->RemoveName(name.AsCString());
896}
897
899 BreakpointName &bp_name, const BreakpointOptions &new_options,
900 const BreakpointName::Permissions &new_permissions) {
901 bp_name.GetOptions().CopyOverSetOptions(new_options);
902 bp_name.GetPermissions().MergeInto(new_permissions);
903 ApplyNameToBreakpoints(bp_name);
904}
905
907 llvm::Expected<std::vector<BreakpointSP>> expected_vector =
908 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString());
909
910 if (!expected_vector) {
911 LLDB_LOG(GetLog(LLDBLog::Breakpoints), "invalid breakpoint name: {}",
912 llvm::toString(expected_vector.takeError()));
913 return;
914 }
915
916 for (auto bp_sp : *expected_vector)
917 bp_name.ConfigureBreakpoint(bp_sp);
918}
919
920void Target::GetBreakpointNames(std::vector<std::string> &names) {
921 names.clear();
922 for (const auto& bp_name_entry : m_breakpoint_names) {
923 names.push_back(bp_name_entry.first.AsCString());
924 }
925 llvm::sort(names);
926}
927
929 return (m_process_sp && m_process_sp->IsAlive());
930}
931
933 std::optional<uint32_t> num_supported_hardware_watchpoints =
934 target->GetProcessSP()->GetWatchpointSlotCount();
935
936 // If unable to determine the # of watchpoints available,
937 // assume they are supported.
938 if (!num_supported_hardware_watchpoints)
939 return true;
940
941 if (*num_supported_hardware_watchpoints == 0) {
943 "Target supports (%u) hardware watchpoint slots.\n",
944 *num_supported_hardware_watchpoints);
945 return false;
946 }
947 return true;
948}
949
950// See also Watchpoint::SetWatchpointType(uint32_t type) and the
951// OptionGroupWatchpoint::WatchType enum type.
953 const CompilerType *type, uint32_t kind,
954 Status &error) {
956 LLDB_LOGF(log,
957 "Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
958 " type = %u)\n",
959 __FUNCTION__, addr, (uint64_t)size, kind);
960
961 WatchpointSP wp_sp;
962 if (!ProcessIsValid()) {
963 error = Status::FromErrorString("process is not alive");
964 return wp_sp;
965 }
966
967 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
968 if (size == 0)
970 "cannot set a watchpoint with watch_size of 0");
971 else
973 "invalid watch address: %" PRIu64, addr);
974 return wp_sp;
975 }
976
977 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
978 error =
979 Status::FromErrorStringWithFormat("invalid watchpoint type: %d", kind);
980 }
981
983 return wp_sp;
984
985 // Currently we only support one watchpoint per address, with total number of
986 // watchpoints limited by the hardware which the inferior is running on.
987
988 // Grab the list mutex while doing operations.
989 const bool notify = false; // Don't notify about all the state changes we do
990 // on creating the watchpoint.
991
992 // Mask off ignored bits from watchpoint address.
993 if (ABISP abi = m_process_sp->GetABI())
994 addr = abi->FixDataAddress(addr);
995
996 // LWP_TODO this sequence is looking for an existing watchpoint
997 // at the exact same user-specified address, disables the new one
998 // if addr/size/type match. If type/size differ, disable old one.
999 // This isn't correct, we need both watchpoints to use a shared
1000 // WatchpointResource in the target, and expand the WatchpointResource
1001 // to handle the needs of both Watchpoints.
1002 // Also, even if the addresses don't match, they may need to be
1003 // supported by the same WatchpointResource, e.g. a watchpoint
1004 // watching 1 byte at 0x102 and a watchpoint watching 1 byte at 0x103.
1005 // They're in the same word and must be watched by a single hardware
1006 // watchpoint register.
1007
1008 std::unique_lock<std::recursive_mutex> lock;
1009 this->GetWatchpointList().GetListMutex(lock);
1010 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
1011 if (matched_sp) {
1012 size_t old_size = matched_sp->GetByteSize();
1013 uint32_t old_type =
1014 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
1015 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0) |
1016 (matched_sp->WatchpointModify() ? LLDB_WATCH_TYPE_MODIFY : 0);
1017 // Return the existing watchpoint if both size and type match.
1018 if (size == old_size && kind == old_type) {
1019 wp_sp = matched_sp;
1020 wp_sp->SetEnabled(false, notify);
1021 } else {
1022 // Nil the matched watchpoint; we will be creating a new one.
1023 m_process_sp->DisableWatchpoint(matched_sp, notify);
1024 m_watchpoint_list.Remove(matched_sp->GetID(), true);
1025 }
1026 }
1027
1028 if (!wp_sp) {
1029 wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type);
1030 wp_sp->SetWatchpointType(kind, notify);
1031 m_watchpoint_list.Add(wp_sp, true);
1032 }
1033
1034 error = m_process_sp->EnableWatchpoint(wp_sp, notify);
1035 LLDB_LOGF(log, "Target::%s (creation of watchpoint %s with id = %u)\n",
1036 __FUNCTION__, error.Success() ? "succeeded" : "failed",
1037 wp_sp->GetID());
1038
1039 if (error.Fail()) {
1040 // Enabling the watchpoint on the device side failed. Remove the said
1041 // watchpoint from the list maintained by the target instance.
1042 m_watchpoint_list.Remove(wp_sp->GetID(), true);
1043 wp_sp.reset();
1044 } else
1046 return wp_sp;
1047}
1048
1051 LLDB_LOGF(log, "Target::%s \n", __FUNCTION__);
1052
1053 m_breakpoint_list.RemoveAllowed(true);
1054
1056}
1057
1058void Target::RemoveAllBreakpoints(bool internal_also) {
1060 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1061 internal_also ? "yes" : "no");
1062
1063 m_breakpoint_list.RemoveAll(true);
1064 if (internal_also)
1065 m_internal_breakpoint_list.RemoveAll(false);
1066
1068}
1069
1070void Target::DisableAllBreakpoints(bool internal_also) {
1072 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1073 internal_also ? "yes" : "no");
1074
1075 m_breakpoint_list.SetEnabledAll(false);
1076 if (internal_also)
1077 m_internal_breakpoint_list.SetEnabledAll(false);
1078}
1079
1082 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
1083
1084 m_breakpoint_list.SetEnabledAllowed(false);
1085}
1086
1087void Target::EnableAllBreakpoints(bool internal_also) {
1089 LLDB_LOGF(log, "Target::%s (internal_also = %s)\n", __FUNCTION__,
1090 internal_also ? "yes" : "no");
1091
1092 m_breakpoint_list.SetEnabledAll(true);
1093 if (internal_also)
1094 m_internal_breakpoint_list.SetEnabledAll(true);
1095}
1096
1099 LLDB_LOGF(log, "Target::%s", __FUNCTION__);
1100
1101 m_breakpoint_list.SetEnabledAllowed(true);
1102}
1103
1106 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1107 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1108
1109 if (DisableBreakpointByID(break_id)) {
1110 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1111 m_internal_breakpoint_list.Remove(break_id, false);
1112 else {
1114 if (m_last_created_breakpoint->GetID() == break_id)
1116 }
1117 m_breakpoint_list.Remove(break_id, true);
1118 }
1119 return true;
1120 }
1121 return false;
1122}
1123
1126 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1127 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1128
1129 BreakpointSP bp_sp;
1130
1131 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1132 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
1133 else
1134 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1135 if (bp_sp) {
1136 bp_sp->SetEnabled(false);
1137 return true;
1138 }
1139 return false;
1140}
1141
1144 LLDB_LOGF(log, "Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
1145 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
1146
1147 BreakpointSP bp_sp;
1148
1149 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
1150 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
1151 else
1152 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
1153
1154 if (bp_sp) {
1155 bp_sp->SetEnabled(true);
1156 return true;
1157 }
1158 return false;
1159}
1160
1164
1166 const BreakpointIDList &bp_ids,
1167 bool append) {
1168 Status error;
1169
1170 if (!file) {
1171 error = Status::FromErrorString("Invalid FileSpec.");
1172 return error;
1173 }
1174
1175 std::string path(file.GetPath());
1176 StructuredData::ObjectSP input_data_sp;
1177
1178 StructuredData::ArraySP break_store_sp;
1179 StructuredData::Array *break_store_ptr = nullptr;
1180
1181 if (append) {
1182 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1183 if (error.Success()) {
1184 break_store_ptr = input_data_sp->GetAsArray();
1185 if (!break_store_ptr) {
1187 "Tried to append to invalid input file %s", path.c_str());
1188 return error;
1189 }
1190 }
1191 }
1192
1193 if (!break_store_ptr) {
1194 break_store_sp = std::make_shared<StructuredData::Array>();
1195 break_store_ptr = break_store_sp.get();
1196 }
1197
1198 StreamFile out_file(path.c_str(),
1202 lldb::eFilePermissionsFileDefault);
1203 if (!out_file.GetFile().IsValid()) {
1204 error = Status::FromErrorStringWithFormat("Unable to open output file: %s.",
1205 path.c_str());
1206 return error;
1207 }
1208
1209 std::unique_lock<std::recursive_mutex> lock;
1211
1212 if (bp_ids.GetSize() == 0) {
1213 const BreakpointList &breakpoints = GetBreakpointList();
1214
1215 size_t num_breakpoints = breakpoints.GetSize();
1216 for (size_t i = 0; i < num_breakpoints; i++) {
1217 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1219 // If a breakpoint can't serialize it, just ignore it for now:
1220 if (bkpt_save_sp)
1221 break_store_ptr->AddItem(bkpt_save_sp);
1222 }
1223 } else {
1224
1225 std::unordered_set<lldb::break_id_t> processed_bkpts;
1226 const size_t count = bp_ids.GetSize();
1227 for (size_t i = 0; i < count; ++i) {
1228 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1229 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1230
1231 if (bp_id != LLDB_INVALID_BREAK_ID) {
1232 // Only do each breakpoint once:
1233 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1234 insert_result = processed_bkpts.insert(bp_id);
1235 if (!insert_result.second)
1236 continue;
1237
1238 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1240 // If the user explicitly asked to serialize a breakpoint, and we
1241 // can't, then raise an error:
1242 if (!bkpt_save_sp) {
1244 "Unable to serialize breakpoint %d", bp_id);
1245 return error;
1246 }
1247 break_store_ptr->AddItem(bkpt_save_sp);
1248 }
1249 }
1250 }
1251
1252 break_store_ptr->Dump(out_file, false);
1253 out_file.PutChar('\n');
1254 return error;
1255}
1256
1258 BreakpointIDList &new_bps) {
1259 std::vector<std::string> no_names;
1260 return CreateBreakpointsFromFile(file, no_names, new_bps);
1261}
1262
1264 std::vector<std::string> &names,
1265 BreakpointIDList &new_bps) {
1266 std::unique_lock<std::recursive_mutex> lock;
1268
1269 Status error;
1270 StructuredData::ObjectSP input_data_sp =
1272 if (!error.Success()) {
1273 return error;
1274 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1276 "Invalid JSON from input file: %s.", file.GetPath().c_str());
1277 return error;
1278 }
1279
1280 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1281 if (!bkpt_array) {
1283 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1284 return error;
1285 }
1286
1287 size_t num_bkpts = bkpt_array->GetSize();
1288 size_t num_names = names.size();
1289
1290 for (size_t i = 0; i < num_bkpts; i++) {
1291 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1292 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1293 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1294 if (!bkpt_dict) {
1296 "Invalid breakpoint data for element %zu from input file: %s.", i,
1297 file.GetPath().c_str());
1298 return error;
1299 }
1300 StructuredData::ObjectSP bkpt_data_sp =
1302 if (num_names &&
1304 continue;
1305
1307 shared_from_this(), bkpt_data_sp, error);
1308 if (!error.Success()) {
1310 "Error restoring breakpoint %zu from %s: %s.", i,
1311 file.GetPath().c_str(), error.AsCString());
1312 return error;
1313 }
1314 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1315 }
1316 return error;
1317}
1318
1319// The flag 'end_to_end', default to true, signifies that the operation is
1320// performed end to end, for both the debugger and the debuggee.
1321
1322// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1323// to end operations.
1324bool Target::RemoveAllWatchpoints(bool end_to_end) {
1326 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1327
1328 if (!end_to_end) {
1329 m_watchpoint_list.RemoveAll(true);
1330 return true;
1331 }
1332
1333 // Otherwise, it's an end to end operation.
1334
1335 if (!ProcessIsValid())
1336 return false;
1337
1338 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1339 if (!wp_sp)
1340 return false;
1341
1342 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1343 if (rc.Fail())
1344 return false;
1345 }
1346 m_watchpoint_list.RemoveAll(true);
1348 return true; // Success!
1349}
1350
1351// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1352// to end operations.
1353bool Target::DisableAllWatchpoints(bool end_to_end) {
1355 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1356
1357 if (!end_to_end) {
1358 m_watchpoint_list.SetEnabledAll(false);
1359 return true;
1360 }
1361
1362 // Otherwise, it's an end to end operation.
1363
1364 if (!ProcessIsValid())
1365 return false;
1366
1367 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1368 if (!wp_sp)
1369 return false;
1370
1371 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1372 if (rc.Fail())
1373 return false;
1374 }
1375 return true; // Success!
1376}
1377
1378// Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1379// to end operations.
1380bool Target::EnableAllWatchpoints(bool end_to_end) {
1382 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1383
1384 if (!end_to_end) {
1385 m_watchpoint_list.SetEnabledAll(true);
1386 return true;
1387 }
1388
1389 // Otherwise, it's an end to end operation.
1390
1391 if (!ProcessIsValid())
1392 return false;
1393
1394 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1395 if (!wp_sp)
1396 return false;
1397
1398 Status rc = m_process_sp->EnableWatchpoint(wp_sp);
1399 if (rc.Fail())
1400 return false;
1401 }
1402 return true; // Success!
1403}
1404
1405// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1408 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1409
1410 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1411 if (!wp_sp)
1412 return false;
1413
1414 wp_sp->ResetHitCount();
1415 }
1416 return true; // Success!
1417}
1418
1419// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1422 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1423
1424 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1425 if (!wp_sp)
1426 return false;
1427
1428 wp_sp->ResetHistoricValues();
1429 }
1430 return true; // Success!
1431}
1432
1433// Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1434// these operations.
1435bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1437 LLDB_LOGF(log, "Target::%s\n", __FUNCTION__);
1438
1439 if (!ProcessIsValid())
1440 return false;
1441
1442 for (WatchpointSP wp_sp : m_watchpoint_list.Watchpoints()) {
1443 if (!wp_sp)
1444 return false;
1445
1446 wp_sp->SetIgnoreCount(ignore_count);
1447 }
1448 return true; // Success!
1449}
1450
1451// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1454 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1455
1456 if (!ProcessIsValid())
1457 return false;
1458
1459 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1460 if (wp_sp) {
1461 Status rc = m_process_sp->DisableWatchpoint(wp_sp);
1462 if (rc.Success())
1463 return true;
1464
1465 // Else, fallthrough.
1466 }
1467 return false;
1468}
1469
1470// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1473 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1474
1475 if (!ProcessIsValid())
1476 return false;
1477
1478 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1479 if (wp_sp) {
1480 Status rc = m_process_sp->EnableWatchpoint(wp_sp);
1481 if (rc.Success())
1482 return true;
1483
1484 // Else, fallthrough.
1485 }
1486 return false;
1487}
1488
1489// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1492 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1493
1494 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1495 if (watch_to_remove_sp == m_last_created_watchpoint)
1497
1498 if (DisableWatchpointByID(watch_id)) {
1499 m_watchpoint_list.Remove(watch_id, true);
1500 return true;
1501 }
1502 return false;
1503}
1504
1505// Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1507 uint32_t ignore_count) {
1509 LLDB_LOGF(log, "Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1510
1511 if (!ProcessIsValid())
1512 return false;
1513
1514 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1515 if (wp_sp) {
1516 wp_sp->SetIgnoreCount(ignore_count);
1517 return true;
1518 }
1519 return false;
1520}
1521
1523 std::lock_guard<std::recursive_mutex> lock(m_images.GetMutex());
1524
1525 // Search for the first executable in the module list.
1526 for (ModuleSP module_sp : m_images.ModulesNoLocking()) {
1527 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1528 if (obj == nullptr)
1529 continue;
1531 return module_sp;
1532 }
1533
1534 // If there is none, fall back return the first module loaded.
1535 return m_images.GetModuleAtIndex(0);
1536}
1537
1541
1542static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1543 Target *target) {
1544 Status error;
1545 StreamString feedback_stream;
1546 if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error,
1547 feedback_stream)) {
1548 if (error.AsCString())
1549 target->GetDebugger().GetAsyncErrorStream()->Printf(
1550 "unable to load scripting data for module %s - error reported was "
1551 "%s\n",
1552 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1553 error.AsCString());
1554 }
1555 if (feedback_stream.GetSize())
1556 target->GetDebugger().GetAsyncErrorStream()->Printf(
1557 "%s\n", feedback_stream.GetData());
1558}
1559
1560void Target::ClearModules(bool delete_locations) {
1561 ModulesDidUnload(m_images, delete_locations);
1562 m_section_load_history.Clear();
1563 m_images.Clear();
1565}
1566
1568 // When a process exec's we need to know about it so we can do some cleanup.
1569 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1570 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1571}
1572
1574 LoadDependentFiles load_dependent_files) {
1576 &m_debugger);
1577 Log *log = GetLog(LLDBLog::Target);
1578 ClearModules(false);
1579
1580 if (executable_sp) {
1582 if (ProcessSP proc = GetProcessSP())
1583 pid = proc->GetID();
1584
1586 info->exec_mod = executable_sp;
1587 info->uuid = executable_sp->GetUUID();
1588 info->pid = pid;
1589 info->triple = executable_sp->GetArchitecture().GetTriple().getTriple();
1590 info->is_start_entry = true;
1591 });
1592
1593 helper.DispatchOnExit([&, pid](telemetry::ExecutableModuleInfo *info) {
1594 info->exec_mod = executable_sp;
1595 info->uuid = executable_sp->GetUUID();
1596 info->pid = pid;
1597 });
1598
1599 ElapsedTime elapsed(m_stats.GetCreateTime());
1600 LLDB_SCOPED_TIMERF("Target::SetExecutableModule (executable = '%s')",
1601 executable_sp->GetFileSpec().GetPath().c_str());
1602
1603 const bool notify = true;
1604 m_images.Append(executable_sp,
1605 notify); // The first image is our executable file
1606
1607 // If we haven't set an architecture yet, reset our architecture based on
1608 // what we found in the executable module.
1609 if (!m_arch.GetSpec().IsValid()) {
1610 m_arch = executable_sp->GetArchitecture();
1611 LLDB_LOG(log,
1612 "Target::SetExecutableModule setting architecture to {0} ({1}) "
1613 "based on executable file",
1614 m_arch.GetSpec().GetArchitectureName(),
1615 m_arch.GetSpec().GetTriple().getTriple());
1616 }
1617
1618 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1619 bool load_dependents = true;
1620 switch (load_dependent_files) {
1622 load_dependents = executable_sp->IsExecutable();
1623 break;
1624 case eLoadDependentsYes:
1625 load_dependents = true;
1626 break;
1627 case eLoadDependentsNo:
1628 load_dependents = false;
1629 break;
1630 }
1631
1632 if (executable_objfile && load_dependents) {
1633 // FileSpecList is not thread safe and needs to be synchronized.
1634 FileSpecList dependent_files;
1635 std::mutex dependent_files_mutex;
1636
1637 // ModuleList is thread safe.
1638 ModuleList added_modules;
1639
1640 auto GetDependentModules = [&](FileSpec dependent_file_spec) {
1641 FileSpec platform_dependent_file_spec;
1642 if (m_platform_sp)
1643 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1644 platform_dependent_file_spec);
1645 else
1646 platform_dependent_file_spec = dependent_file_spec;
1647
1648 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1649 ModuleSP image_module_sp(
1650 GetOrCreateModule(module_spec, false /* notify */));
1651 if (image_module_sp) {
1652 added_modules.AppendIfNeeded(image_module_sp, false);
1653 ObjectFile *objfile = image_module_sp->GetObjectFile();
1654 if (objfile) {
1655 // Create a local copy of the dependent file list so we don't have
1656 // to lock for the whole duration of GetDependentModules.
1657 FileSpecList dependent_files_copy;
1658 {
1659 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1660 dependent_files_copy = dependent_files;
1661 }
1662
1663 // Remember the size of the local copy so we can append only the
1664 // modules that have been added by GetDependentModules.
1665 const size_t previous_dependent_files =
1666 dependent_files_copy.GetSize();
1667
1668 objfile->GetDependentModules(dependent_files_copy);
1669
1670 {
1671 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1672 for (size_t i = previous_dependent_files;
1673 i < dependent_files_copy.GetSize(); ++i)
1674 dependent_files.AppendIfUnique(
1675 dependent_files_copy.GetFileSpecAtIndex(i));
1676 }
1677 }
1678 }
1679 };
1680
1681 executable_objfile->GetDependentModules(dependent_files);
1682
1683 llvm::ThreadPoolTaskGroup task_group(Debugger::GetThreadPool());
1684 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1685 // Process all currently known dependencies in parallel in the innermost
1686 // loop. This may create newly discovered dependencies to be appended to
1687 // dependent_files. We'll deal with these files during the next
1688 // iteration of the outermost loop.
1689 {
1690 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1691 for (; i < dependent_files.GetSize(); i++)
1692 task_group.async(GetDependentModules,
1693 dependent_files.GetFileSpecAtIndex(i));
1694 }
1695 task_group.wait();
1696 }
1697 ModulesDidLoad(added_modules);
1698 }
1699 }
1700}
1701
1702bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform,
1703 bool merge) {
1704 Log *log = GetLog(LLDBLog::Target);
1705 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1706 bool replace_local_arch = true;
1707 bool compatible_local_arch = false;
1708 ArchSpec other(arch_spec);
1709
1710 // Changing the architecture might mean that the currently selected platform
1711 // isn't compatible. Set the platform correctly if we are asked to do so,
1712 // otherwise assume the user will set the platform manually.
1713 if (set_platform) {
1714 if (other.IsValid()) {
1715 auto platform_sp = GetPlatform();
1716 if (!platform_sp || !platform_sp->IsCompatibleArchitecture(
1717 other, {}, ArchSpec::CompatibleMatch, nullptr)) {
1718 ArchSpec platform_arch;
1719 if (PlatformSP arch_platform_sp =
1720 GetDebugger().GetPlatformList().GetOrCreate(other, {},
1721 &platform_arch)) {
1722 arch_platform_sp->SetLocateModuleCallback(
1723 platform_sp->GetLocateModuleCallback());
1724 SetPlatform(arch_platform_sp);
1725 if (platform_arch.IsValid())
1726 other = platform_arch;
1727 }
1728 }
1729 }
1730 }
1731
1732 if (!missing_local_arch) {
1733 if (merge && m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1734 other.MergeFrom(m_arch.GetSpec());
1735
1736 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1737 compatible_local_arch = true;
1738
1739 if (m_arch.GetSpec().GetTriple() == other.GetTriple())
1740 replace_local_arch = false;
1741 }
1742 }
1743 }
1744
1745 if (compatible_local_arch || missing_local_arch) {
1746 // If we haven't got a valid arch spec, or the architectures are compatible
1747 // update the architecture, unless the one we already have is more
1748 // specified
1749 if (replace_local_arch)
1750 m_arch = other;
1751 LLDB_LOG(log,
1752 "Target::SetArchitecture merging compatible arch; arch "
1753 "is now {0} ({1})",
1754 m_arch.GetSpec().GetArchitectureName(),
1755 m_arch.GetSpec().GetTriple().getTriple());
1756 return true;
1757 }
1758
1759 // If we have an executable file, try to reset the executable to the desired
1760 // architecture
1761 LLDB_LOGF(
1762 log,
1763 "Target::SetArchitecture changing architecture to %s (%s) from %s (%s)",
1764 arch_spec.GetArchitectureName(),
1765 arch_spec.GetTriple().getTriple().c_str(),
1766 m_arch.GetSpec().GetArchitectureName(),
1767 m_arch.GetSpec().GetTriple().getTriple().c_str());
1768 m_arch = other;
1769 ModuleSP executable_sp = GetExecutableModule();
1770
1771 ClearModules(true);
1772 // Need to do something about unsetting breakpoints.
1773
1774 if (executable_sp) {
1775 LLDB_LOGF(log,
1776 "Target::SetArchitecture Trying to select executable file "
1777 "architecture %s (%s)",
1778 arch_spec.GetArchitectureName(),
1779 arch_spec.GetTriple().getTriple().c_str());
1780 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1781 FileSpecList search_paths = GetExecutableSearchPaths();
1782 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1783 &search_paths, nullptr, nullptr);
1784
1785 if (!error.Fail() && executable_sp) {
1787 return true;
1788 }
1789 }
1790 return false;
1791}
1792
1793bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1794 Log *log = GetLog(LLDBLog::Target);
1795 if (arch_spec.IsValid()) {
1796 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1797 // The current target arch is compatible with "arch_spec", see if we can
1798 // improve our current architecture using bits from "arch_spec"
1799
1800 LLDB_LOGF(log,
1801 "Target::MergeArchitecture target has arch %s, merging with "
1802 "arch %s",
1803 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1804 arch_spec.GetTriple().getTriple().c_str());
1805
1806 // Merge bits from arch_spec into "merged_arch" and set our architecture
1807 ArchSpec merged_arch(m_arch.GetSpec());
1808 merged_arch.MergeFrom(arch_spec);
1809 return SetArchitecture(merged_arch);
1810 } else {
1811 // The new architecture is different, we just need to replace it
1812 return SetArchitecture(arch_spec);
1813 }
1814 }
1815 return false;
1816}
1817
1818void Target::NotifyWillClearList(const ModuleList &module_list) {}
1819
1821 const ModuleSP &module_sp) {
1822 // A module is being added to this target for the first time
1823 if (m_valid) {
1824 ModuleList my_module_list;
1825 my_module_list.Append(module_sp);
1826 ModulesDidLoad(my_module_list);
1827 }
1828}
1829
1831 const ModuleSP &module_sp) {
1832 // A module is being removed from this target.
1833 if (m_valid) {
1834 ModuleList my_module_list;
1835 my_module_list.Append(module_sp);
1836 ModulesDidUnload(my_module_list, false);
1837 }
1838}
1839
1841 const ModuleSP &old_module_sp,
1842 const ModuleSP &new_module_sp) {
1843 // A module is replacing an already added module
1844 if (m_valid) {
1845 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1846 new_module_sp);
1847 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1848 old_module_sp, new_module_sp);
1849 }
1850}
1851
1853 ModulesDidUnload(module_list, false);
1854}
1855
1857 const size_t num_images = module_list.GetSize();
1858 if (m_valid && num_images) {
1859 for (size_t idx = 0; idx < num_images; ++idx) {
1860 ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1861 LoadScriptingResourceForModule(module_sp, this);
1862 LoadTypeSummariesForModule(module_sp);
1863 LoadFormattersForModule(module_sp);
1864 }
1865 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1866 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1867 if (m_process_sp) {
1868 m_process_sp->ModulesDidLoad(module_list);
1869 }
1870 auto data_sp =
1871 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1873 }
1874}
1875
1877 if (m_valid && module_list.GetSize()) {
1878 if (m_process_sp) {
1879 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1880 runtime->SymbolsDidLoad(module_list);
1881 }
1882 }
1883
1884 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1885 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1886 auto data_sp =
1887 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1889 }
1890}
1891
1892void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1893 if (m_valid && module_list.GetSize()) {
1894 UnloadModuleSections(module_list);
1895 auto data_sp =
1896 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1898 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1899 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1900 delete_locations);
1901
1902 // If a module was torn down it will have torn down the 'TypeSystemClang's
1903 // that we used as source 'ASTContext's for the persistent variables in
1904 // the current target. Those would now be unsafe to access because the
1905 // 'DeclOrigin' are now possibly stale. Thus clear all persistent
1906 // variables. We only want to flush 'TypeSystem's if the module being
1907 // unloaded was capable of describing a source type. JITted module unloads
1908 // happen frequently for Objective-C utility functions or the REPL and rely
1909 // on the persistent variables to stick around.
1910 const bool should_flush_type_systems =
1911 module_list.AnyOf([](lldb_private::Module &module) {
1912 auto *object_file = module.GetObjectFile();
1913
1914 if (!object_file)
1915 return false;
1916
1917 auto type = object_file->GetType();
1918
1919 // eTypeExecutable: when debugged binary was rebuilt
1920 // eTypeSharedLibrary: if dylib was re-loaded
1921 return module.FileHasChanged() &&
1922 (type == ObjectFile::eTypeObjectFile ||
1923 type == ObjectFile::eTypeExecutable ||
1924 type == ObjectFile::eTypeSharedLibrary);
1925 });
1926
1927 if (should_flush_type_systems)
1929 }
1930}
1931
1933 const FileSpec &module_file_spec) {
1935 ModuleList matchingModules;
1936 ModuleSpec module_spec(module_file_spec);
1937 GetImages().FindModules(module_spec, matchingModules);
1938 size_t num_modules = matchingModules.GetSize();
1939
1940 // If there is more than one module for this file spec, only
1941 // return true if ALL the modules are on the black list.
1942 if (num_modules > 0) {
1943 for (size_t i = 0; i < num_modules; i++) {
1945 matchingModules.GetModuleAtIndex(i)))
1946 return false;
1947 }
1948 return true;
1949 }
1950 }
1951 return false;
1952}
1953
1955 const lldb::ModuleSP &module_sp) {
1957 if (m_platform_sp)
1958 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1959 module_sp);
1960 }
1961 return false;
1962}
1963
1964size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1965 size_t dst_len, Status &error) {
1966 SectionSP section_sp(addr.GetSection());
1967 if (section_sp) {
1968 // If the contents of this section are encrypted, the on-disk file is
1969 // unusable. Read only from live memory.
1970 if (section_sp->IsEncrypted()) {
1971 error = Status::FromErrorString("section is encrypted");
1972 return 0;
1973 }
1974 ModuleSP module_sp(section_sp->GetModule());
1975 if (module_sp) {
1976 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1977 if (objfile) {
1978 size_t bytes_read = objfile->ReadSectionData(
1979 section_sp.get(), addr.GetOffset(), dst, dst_len);
1980 if (bytes_read > 0)
1981 return bytes_read;
1982 else
1984 "error reading data from section %s",
1985 section_sp->GetName().GetCString());
1986 } else
1987 error = Status::FromErrorString("address isn't from a object file");
1988 } else
1989 error = Status::FromErrorString("address isn't in a module");
1990 } else
1992 "address doesn't contain a section that points to a "
1993 "section in a object file");
1994
1995 return 0;
1996}
1997
1998size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len,
1999 Status &error, bool force_live_memory,
2000 lldb::addr_t *load_addr_ptr,
2001 bool *did_read_live_memory) {
2002 error.Clear();
2003 if (did_read_live_memory)
2004 *did_read_live_memory = false;
2005
2006 Address fixed_addr = addr;
2007 if (ProcessIsValid())
2008 if (const ABISP &abi = m_process_sp->GetABI())
2009 fixed_addr.SetLoadAddress(abi->FixAnyAddress(addr.GetLoadAddress(this)),
2010 this);
2011
2012 // if we end up reading this from process memory, we will fill this with the
2013 // actual load address
2014 if (load_addr_ptr)
2015 *load_addr_ptr = LLDB_INVALID_ADDRESS;
2016
2017 size_t bytes_read = 0;
2018
2019 addr_t load_addr = LLDB_INVALID_ADDRESS;
2020 addr_t file_addr = LLDB_INVALID_ADDRESS;
2021 Address resolved_addr;
2022 if (!fixed_addr.IsSectionOffset()) {
2023 SectionLoadList &section_load_list = GetSectionLoadList();
2024 if (section_load_list.IsEmpty()) {
2025 // No sections are loaded, so we must assume we are not running yet and
2026 // anything we are given is a file address.
2027 file_addr =
2028 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
2029 // its offset is the file address
2030 m_images.ResolveFileAddress(file_addr, resolved_addr);
2031 } else {
2032 // We have at least one section loaded. This can be because we have
2033 // manually loaded some sections with "target modules load ..." or
2034 // because we have a live process that has sections loaded through
2035 // the dynamic loader
2036 load_addr =
2037 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
2038 // its offset is the load address
2039 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
2040 }
2041 }
2042 if (!resolved_addr.IsValid())
2043 resolved_addr = fixed_addr;
2044
2045 // If we read from the file cache but can't get as many bytes as requested,
2046 // we keep the result around in this buffer, in case this result is the
2047 // best we can do.
2048 std::unique_ptr<uint8_t[]> file_cache_read_buffer;
2049 size_t file_cache_bytes_read = 0;
2050
2051 // Read from file cache if read-only section.
2052 if (!force_live_memory && resolved_addr.IsSectionOffset()) {
2053 SectionSP section_sp(resolved_addr.GetSection());
2054 if (section_sp) {
2055 auto permissions = Flags(section_sp->GetPermissions());
2056 bool is_readonly = !permissions.Test(ePermissionsWritable) &&
2057 permissions.Test(ePermissionsReadable);
2058 if (is_readonly) {
2059 file_cache_bytes_read =
2060 ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2061 if (file_cache_bytes_read == dst_len)
2062 return file_cache_bytes_read;
2063 else if (file_cache_bytes_read > 0) {
2064 file_cache_read_buffer =
2065 std::make_unique<uint8_t[]>(file_cache_bytes_read);
2066 std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read);
2067 }
2068 }
2069 }
2070 }
2071
2072 if (ProcessIsValid()) {
2073 if (load_addr == LLDB_INVALID_ADDRESS)
2074 load_addr = resolved_addr.GetLoadAddress(this);
2075
2076 if (load_addr == LLDB_INVALID_ADDRESS) {
2077 ModuleSP addr_module_sp(resolved_addr.GetModule());
2078 if (addr_module_sp && addr_module_sp->GetFileSpec())
2080 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
2081 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
2082 else
2084 "0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
2085 } else {
2086 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
2087 if (bytes_read != dst_len) {
2088 if (error.Success()) {
2089 if (bytes_read == 0)
2091 "read memory from 0x%" PRIx64 " failed", load_addr);
2092 else
2094 "only %" PRIu64 " of %" PRIu64
2095 " bytes were read from memory at 0x%" PRIx64,
2096 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
2097 }
2098 }
2099 if (bytes_read) {
2100 if (load_addr_ptr)
2101 *load_addr_ptr = load_addr;
2102 if (did_read_live_memory)
2103 *did_read_live_memory = true;
2104 return bytes_read;
2105 }
2106 }
2107 }
2108
2109 if (file_cache_read_buffer && file_cache_bytes_read > 0) {
2110 // Reading from the process failed. If we've previously succeeded in reading
2111 // something from the file cache, then copy that over and return that.
2112 std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read);
2113 return file_cache_bytes_read;
2114 }
2115
2116 if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) {
2117 // If we didn't already try and read from the object file cache, then try
2118 // it after failing to read from the process.
2119 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2120 }
2121 return 0;
2122}
2123
2124size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
2125 Status &error, bool force_live_memory) {
2126 char buf[256];
2127 out_str.clear();
2128 addr_t curr_addr = addr.GetLoadAddress(this);
2129 Address address(addr);
2130 while (true) {
2131 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error,
2132 force_live_memory);
2133 if (length == 0)
2134 break;
2135 out_str.append(buf, length);
2136 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2137 // to read some more characters
2138 if (length == sizeof(buf) - 1)
2139 curr_addr += length;
2140 else
2141 break;
2142 address = Address(curr_addr);
2143 }
2144 return out_str.size();
2145}
2146
2147size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
2148 size_t dst_max_len, Status &result_error,
2149 bool force_live_memory) {
2150 size_t total_cstr_len = 0;
2151 if (dst && dst_max_len) {
2152 result_error.Clear();
2153 // NULL out everything just to be safe
2154 memset(dst, 0, dst_max_len);
2155 addr_t curr_addr = addr.GetLoadAddress(this);
2156 Address address(addr);
2157
2158 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
2159 // this really needs to be tied to the memory cache subsystem's cache line
2160 // size, so leave this as a fixed constant.
2161 const size_t cache_line_size = 512;
2162
2163 size_t bytes_left = dst_max_len - 1;
2164 char *curr_dst = dst;
2165
2166 while (bytes_left > 0) {
2167 addr_t cache_line_bytes_left =
2168 cache_line_size - (curr_addr % cache_line_size);
2169 addr_t bytes_to_read =
2170 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2171 Status error;
2172 size_t bytes_read = ReadMemory(address, curr_dst, bytes_to_read, error,
2173 force_live_memory);
2174
2175 if (bytes_read == 0) {
2176 result_error = std::move(error);
2177 dst[total_cstr_len] = '\0';
2178 break;
2179 }
2180 const size_t len = strlen(curr_dst);
2181
2182 total_cstr_len += len;
2183
2184 if (len < bytes_to_read)
2185 break;
2186
2187 curr_dst += bytes_read;
2188 curr_addr += bytes_read;
2189 bytes_left -= bytes_read;
2190 address = Address(curr_addr);
2191 }
2192 } else {
2193 if (dst == nullptr)
2194 result_error = Status::FromErrorString("invalid arguments");
2195 else
2196 result_error.Clear();
2197 }
2198 return total_cstr_len;
2199}
2200
2202 addr_t load_addr = addr.GetLoadAddress(this);
2203 if (load_addr != LLDB_INVALID_ADDRESS && m_process_sp) {
2204 // Avoid crossing cache line boundaries.
2205 addr_t cache_line_size = m_process_sp->GetMemoryCacheLineSize();
2206 return cache_line_size - (load_addr % cache_line_size);
2207 }
2208
2209 // The read is going to go to the file cache, so we can just pick a largish
2210 // value.
2211 return 0x1000;
2212}
2213
2214size_t Target::ReadStringFromMemory(const Address &addr, char *dst,
2215 size_t max_bytes, Status &error,
2216 size_t type_width, bool force_live_memory) {
2217 if (!dst || !max_bytes || !type_width || max_bytes < type_width)
2218 return 0;
2219
2220 size_t total_bytes_read = 0;
2221
2222 // Ensure a null terminator independent of the number of bytes that is
2223 // read.
2224 memset(dst, 0, max_bytes);
2225 size_t bytes_left = max_bytes - type_width;
2226
2227 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2228 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2229 "string with more than 4 bytes "
2230 "per character!");
2231
2232 Address address = addr;
2233 char *curr_dst = dst;
2234
2235 error.Clear();
2236 while (bytes_left > 0 && error.Success()) {
2237 addr_t bytes_to_read =
2238 std::min<addr_t>(bytes_left, GetReasonableReadSize(address));
2239 size_t bytes_read =
2240 ReadMemory(address, curr_dst, bytes_to_read, error, force_live_memory);
2241
2242 if (bytes_read == 0)
2243 break;
2244
2245 // Search for a null terminator of correct size and alignment in
2246 // bytes_read
2247 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2248 for (size_t i = aligned_start;
2249 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2250 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2251 error.Clear();
2252 return i;
2253 }
2254
2255 total_bytes_read += bytes_read;
2256 curr_dst += bytes_read;
2257 address.Slide(bytes_read);
2258 bytes_left -= bytes_read;
2259 }
2260 return total_bytes_read;
2261}
2262
2263size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
2264 bool is_signed, Scalar &scalar,
2265 Status &error,
2266 bool force_live_memory) {
2267 uint64_t uval;
2268
2269 if (byte_size <= sizeof(uval)) {
2270 size_t bytes_read =
2271 ReadMemory(addr, &uval, byte_size, error, force_live_memory);
2272 if (bytes_read == byte_size) {
2273 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
2274 m_arch.GetSpec().GetAddressByteSize());
2275 lldb::offset_t offset = 0;
2276 if (byte_size <= 4)
2277 scalar = data.GetMaxU32(&offset, byte_size);
2278 else
2279 scalar = data.GetMaxU64(&offset, byte_size);
2280
2281 if (is_signed)
2282 scalar.SignExtend(byte_size * 8);
2283 return bytes_read;
2284 }
2285 } else {
2287 "byte size of %u is too large for integer scalar type", byte_size);
2288 }
2289 return 0;
2290}
2291
2293 size_t integer_byte_size,
2294 int64_t fail_value, Status &error,
2295 bool force_live_memory) {
2296 Scalar scalar;
2297 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
2298 force_live_memory))
2299 return scalar.SLongLong(fail_value);
2300 return fail_value;
2301}
2302
2304 size_t integer_byte_size,
2305 uint64_t fail_value, Status &error,
2306 bool force_live_memory) {
2307 Scalar scalar;
2308 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
2309 force_live_memory))
2310 return scalar.ULongLong(fail_value);
2311 return fail_value;
2312}
2313
2315 Address &pointer_addr,
2316 bool force_live_memory) {
2317 Scalar scalar;
2318 if (ReadScalarIntegerFromMemory(addr, m_arch.GetSpec().GetAddressByteSize(),
2319 false, scalar, error, force_live_memory)) {
2320 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
2321 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
2322 SectionLoadList &section_load_list = GetSectionLoadList();
2323 if (section_load_list.IsEmpty()) {
2324 // No sections are loaded, so we must assume we are not running yet and
2325 // anything we are given is a file address.
2326 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
2327 } else {
2328 // We have at least one section loaded. This can be because we have
2329 // manually loaded some sections with "target modules load ..." or
2330 // because we have a live process that has sections loaded through
2331 // the dynamic loader
2332 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
2333 }
2334 // We weren't able to resolve the pointer value, so just return an
2335 // address with no section
2336 if (!pointer_addr.IsValid())
2337 pointer_addr.SetOffset(pointer_vm_addr);
2338 return true;
2339 }
2340 }
2341 return false;
2342}
2343
2345 bool notify, Status *error_ptr) {
2346 ModuleSP module_sp;
2347
2348 Status error;
2349
2350 // Apply any remappings specified in target.object-map:
2351 ModuleSpec module_spec(orig_module_spec);
2352 PathMappingList &obj_mapping = GetObjectPathMap();
2353 if (std::optional<FileSpec> remapped_obj_file =
2354 obj_mapping.RemapPath(orig_module_spec.GetFileSpec().GetPath(),
2355 true /* only_if_exists */)) {
2356 module_spec.GetFileSpec().SetPath(remapped_obj_file->GetPath());
2357 }
2358
2359 // First see if we already have this module in our module list. If we do,
2360 // then we're done, we don't need to consult the shared modules list. But
2361 // only do this if we are passed a UUID.
2362
2363 if (module_spec.GetUUID().IsValid())
2364 module_sp = m_images.FindFirstModule(module_spec);
2365
2366 if (!module_sp) {
2367 llvm::SmallVector<ModuleSP, 1>
2368 old_modules; // This will get filled in if we have a new version
2369 // of the library
2370 bool did_create_module = false;
2371 FileSpecList search_paths = GetExecutableSearchPaths();
2372 FileSpec symbol_file_spec;
2373
2374 // Call locate module callback if set. This allows users to implement their
2375 // own module cache system. For example, to leverage build system artifacts,
2376 // to bypass pulling files from remote platform, or to search symbol files
2377 // from symbol servers.
2378 if (m_platform_sp)
2379 m_platform_sp->CallLocateModuleCallbackIfSet(
2380 module_spec, module_sp, symbol_file_spec, &did_create_module);
2381
2382 // The result of this CallLocateModuleCallbackIfSet is one of the following.
2383 // 1. module_sp:loaded, symbol_file_spec:set
2384 // The callback found a module file and a symbol file for the
2385 // module_spec. We will call module_sp->SetSymbolFileFileSpec with
2386 // the symbol_file_spec later.
2387 // 2. module_sp:loaded, symbol_file_spec:empty
2388 // The callback only found a module file for the module_spec.
2389 // 3. module_sp:empty, symbol_file_spec:set
2390 // The callback only found a symbol file for the module. We continue
2391 // to find a module file for this module_spec and we will call
2392 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
2393 // 4. module_sp:empty, symbol_file_spec:empty
2394 // Platform does not exist, the callback is not set, the callback did
2395 // not find any module files nor any symbol files, the callback failed,
2396 // or something went wrong. We continue to find a module file for this
2397 // module_spec.
2398
2399 if (!module_sp) {
2400 // If there are image search path entries, try to use them to acquire a
2401 // suitable image.
2402 if (m_image_search_paths.GetSize()) {
2403 ModuleSpec transformed_spec(module_spec);
2404 ConstString transformed_dir;
2405 if (m_image_search_paths.RemapPath(
2406 module_spec.GetFileSpec().GetDirectory(), transformed_dir)) {
2407 transformed_spec.GetFileSpec().SetDirectory(transformed_dir);
2408 transformed_spec.GetFileSpec().SetFilename(
2409 module_spec.GetFileSpec().GetFilename());
2410 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2411 &search_paths, &old_modules,
2412 &did_create_module);
2413 }
2414 }
2415 }
2416
2417 if (!module_sp) {
2418 // If we have a UUID, we can check our global shared module list in case
2419 // we already have it. If we don't have a valid UUID, then we can't since
2420 // the path in "module_spec" will be a platform path, and we will need to
2421 // let the platform find that file. For example, we could be asking for
2422 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2423 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2424 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2425 // cache.
2426 if (module_spec.GetUUID().IsValid()) {
2427 // We have a UUID, it is OK to check the global module list...
2428 error =
2429 ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
2430 &old_modules, &did_create_module);
2431 }
2432
2433 if (!module_sp) {
2434 // The platform is responsible for finding and caching an appropriate
2435 // module in the shared module cache.
2436 if (m_platform_sp) {
2437 error = m_platform_sp->GetSharedModule(
2438 module_spec, m_process_sp.get(), module_sp, &search_paths,
2439 &old_modules, &did_create_module);
2440 } else {
2441 error = Status::FromErrorString("no platform is currently set");
2442 }
2443 }
2444 }
2445
2446 // We found a module that wasn't in our target list. Let's make sure that
2447 // there wasn't an equivalent module in the list already, and if there was,
2448 // let's remove it.
2449 if (module_sp) {
2450 ObjectFile *objfile = module_sp->GetObjectFile();
2451 if (objfile) {
2452 switch (objfile->GetType()) {
2453 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2454 /// a program's execution state
2455 case ObjectFile::eTypeExecutable: /// A normal executable
2456 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2457 /// executable
2458 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2459 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2460 /// used during execution
2461 break;
2462 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2463 /// debug information
2464 if (error_ptr)
2465 *error_ptr = Status::FromErrorString(
2466 "debug info files aren't valid target "
2467 "modules, please specify an executable");
2468 return ModuleSP();
2469 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2470 /// against but not used for
2471 /// execution
2472 if (error_ptr)
2473 *error_ptr = Status::FromErrorString(
2474 "stub libraries aren't valid target "
2475 "modules, please specify an executable");
2476 return ModuleSP();
2477 default:
2478 if (error_ptr)
2479 *error_ptr = Status::FromErrorString(
2480 "unsupported file type, please specify an executable");
2481 return ModuleSP();
2482 }
2483 // GetSharedModule is not guaranteed to find the old shared module, for
2484 // instance in the common case where you pass in the UUID, it is only
2485 // going to find the one module matching the UUID. In fact, it has no
2486 // good way to know what the "old module" relevant to this target is,
2487 // since there might be many copies of a module with this file spec in
2488 // various running debug sessions, but only one of them will belong to
2489 // this target. So let's remove the UUID from the module list, and look
2490 // in the target's module list. Only do this if there is SOMETHING else
2491 // in the module spec...
2492 if (module_spec.GetUUID().IsValid() &&
2493 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2494 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2495 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2496 module_spec_copy.GetUUID().Clear();
2497
2498 ModuleList found_modules;
2499 m_images.FindModules(module_spec_copy, found_modules);
2500 found_modules.ForEach([&](const ModuleSP &found_module) {
2501 old_modules.push_back(found_module);
2503 });
2504 }
2505
2506 // If the locate module callback had found a symbol file, set it to the
2507 // module_sp before preloading symbols.
2508 if (symbol_file_spec)
2509 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
2510
2511 // Preload symbols outside of any lock, so hopefully we can do this for
2512 // each library in parallel.
2513 if (GetPreloadSymbols())
2514 module_sp->PreloadSymbols();
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 for (auto cur_hook_sp : active_hooks) {
3210 bool any_thread_matched = false;
3211 for (auto exc_ctx : exc_ctx_with_reasons) {
3212 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
3213 continue;
3214
3215 bool suppress_output = cur_hook_sp->GetSuppressOutput();
3216 if (print_hook_header && !any_thread_matched && !suppress_output) {
3217 StreamString s;
3218 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
3219 if (s.GetSize() != 0)
3220 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
3221 s.GetData());
3222 else
3223 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
3224 any_thread_matched = true;
3225 }
3226
3227 if (print_thread_header && !suppress_output)
3228 output_sp->Printf("-- Thread %d\n",
3229 exc_ctx.GetThreadPtr()->GetIndexID());
3230
3231 auto result = cur_hook_sp->HandleStop(exc_ctx, output_sp);
3232 switch (result) {
3234 if (cur_hook_sp->GetAutoContinue())
3235 requested_continue = true;
3236 else
3237 should_stop = true;
3238 break;
3240 requested_continue = true;
3241 break;
3243 // Do nothing
3244 break;
3246 // We don't have a good way to prohibit people from restarting the
3247 // target willy nilly in a stop hook. If the hook did so, give a
3248 // gentle suggestion here and back out of the hook processing.
3249 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3250 " set the program running.\n"
3251 " Consider using '-G true' to make "
3252 "stop hooks auto-continue.\n",
3253 cur_hook_sp->GetID());
3254 // FIXME: if we are doing non-stop mode for real, we would have to
3255 // check that OUR thread was restarted, otherwise we should keep
3256 // processing stop hooks.
3257 return true;
3258 }
3259 }
3260 }
3261
3262 // Resume iff at least one hook requested to continue and no hook asked to
3263 // stop.
3264 if (requested_continue && !should_stop) {
3265 Log *log = GetLog(LLDBLog::Process);
3266 Status error = m_process_sp->PrivateResume();
3267 if (error.Success()) {
3268 LLDB_LOG(log, "Resuming from RunStopHooks");
3269 return true;
3270 } else {
3271 LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
3272 return false;
3273 }
3274 }
3275
3276 return false;
3277}
3278
3280 // NOTE: intentional leak so we don't crash if global destructor chain gets
3281 // called as other threads still use the result of this function
3282 static TargetProperties *g_settings_ptr =
3283 new TargetProperties(nullptr);
3284 return *g_settings_ptr;
3285}
3286
3288 Status error;
3289 PlatformSP platform_sp(GetPlatform());
3290 if (!platform_sp || !platform_sp->IsRemote() || !platform_sp->IsConnected())
3291 return error;
3292
3293 // Install all files that have an install path when connected to a
3294 // remote platform. If target.auto-install-main-executable is set then
3295 // also install the main executable even if it does not have an explicit
3296 // install path specified.
3297
3298 for (auto module_sp : GetImages().Modules()) {
3299 if (module_sp == GetExecutableModule()) {
3300 MainExecutableInstaller installer{platform_sp, module_sp,
3301 shared_from_this(), *launch_info};
3302 error = installExecutable(installer);
3303 } else {
3304 ExecutableInstaller installer{platform_sp, module_sp};
3305 error = installExecutable(installer);
3306 }
3307
3308 if (error.Fail())
3309 return error;
3310 }
3311
3312 return error;
3313}
3314
3316 uint32_t stop_id, bool allow_section_end) {
3317 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr,
3318 allow_section_end);
3319}
3320
3322 Address &resolved_addr) {
3323 return m_images.ResolveFileAddress(file_addr, resolved_addr);
3324}
3325
3327 addr_t new_section_load_addr,
3328 bool warn_multiple) {
3329 const addr_t old_section_load_addr =
3330 m_section_load_history.GetSectionLoadAddress(
3331 SectionLoadHistory::eStopIDNow, section_sp);
3332 if (old_section_load_addr != new_section_load_addr) {
3333 uint32_t stop_id = 0;
3334 ProcessSP process_sp(GetProcessSP());
3335 if (process_sp)
3336 stop_id = process_sp->GetStopID();
3337 else
3338 stop_id = m_section_load_history.GetLastStopID();
3339 if (m_section_load_history.SetSectionLoadAddress(
3340 stop_id, section_sp, new_section_load_addr, warn_multiple))
3341 return true; // Return true if the section load address was changed...
3342 }
3343 return false; // Return false to indicate nothing changed
3344}
3345
3346size_t Target::UnloadModuleSections(const ModuleList &module_list) {
3347 size_t section_unload_count = 0;
3348 size_t num_modules = module_list.GetSize();
3349 for (size_t i = 0; i < num_modules; ++i) {
3350 section_unload_count +=
3351 UnloadModuleSections(module_list.GetModuleAtIndex(i));
3352 }
3353 return section_unload_count;
3354}
3355
3357 uint32_t stop_id = 0;
3358 ProcessSP process_sp(GetProcessSP());
3359 if (process_sp)
3360 stop_id = process_sp->GetStopID();
3361 else
3362 stop_id = m_section_load_history.GetLastStopID();
3363 SectionList *sections = module_sp->GetSectionList();
3364 size_t section_unload_count = 0;
3365 if (sections) {
3366 const uint32_t num_sections = sections->GetNumSections(0);
3367 for (uint32_t i = 0; i < num_sections; ++i) {
3368 section_unload_count += m_section_load_history.SetSectionUnloaded(
3369 stop_id, sections->GetSectionAtIndex(i));
3370 }
3371 }
3372 return section_unload_count;
3373}
3374
3376 uint32_t stop_id = 0;
3377 ProcessSP process_sp(GetProcessSP());
3378 if (process_sp)
3379 stop_id = process_sp->GetStopID();
3380 else
3381 stop_id = m_section_load_history.GetLastStopID();
3382 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
3383}
3384
3386 addr_t load_addr) {
3387 uint32_t stop_id = 0;
3388 ProcessSP process_sp(GetProcessSP());
3389 if (process_sp)
3390 stop_id = process_sp->GetStopID();
3391 else
3392 stop_id = m_section_load_history.GetLastStopID();
3393 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
3394 load_addr);
3395}
3396
3398
3400 lldb_private::TypeSummaryImpl &summary_provider) {
3401 return m_summary_statistics_cache.GetSummaryStatisticsForProvider(
3402 summary_provider);
3403}
3404
3408
3410 if (process_info.IsScriptedProcess()) {
3411 // Only copy scripted process launch options.
3412 ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>(
3414 default_launch_info.SetProcessPluginName("ScriptedProcess");
3415 default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata());
3416 SetProcessLaunchInfo(default_launch_info);
3417 }
3418}
3419
3421 m_stats.SetLaunchOrAttachTime();
3422 Status error;
3423 Log *log = GetLog(LLDBLog::Target);
3424
3425 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
3426 launch_info.GetExecutableFile().GetPath().c_str());
3427
3428 StateType state = eStateInvalid;
3429
3430 // Scope to temporarily get the process state in case someone has manually
3431 // remotely connected already to a process and we can skip the platform
3432 // launching.
3433 {
3434 ProcessSP process_sp(GetProcessSP());
3435
3436 if (process_sp) {
3437 state = process_sp->GetState();
3438 LLDB_LOGF(log,
3439 "Target::%s the process exists, and its current state is %s",
3440 __FUNCTION__, StateAsCString(state));
3441 } else {
3442 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
3443 __FUNCTION__);
3444 }
3445 }
3446
3447 launch_info.GetFlags().Set(eLaunchFlagDebug);
3448
3449 SaveScriptedLaunchInfo(launch_info);
3450
3451 // Get the value of synchronous execution here. If you wait till after you
3452 // have started to run, then you could have hit a breakpoint, whose command
3453 // might switch the value, and then you'll pick up that incorrect value.
3454 Debugger &debugger = GetDebugger();
3455 const bool synchronous_execution =
3457
3458 PlatformSP platform_sp(GetPlatform());
3459
3460 FinalizeFileActions(launch_info);
3461
3462 if (state == eStateConnected) {
3463 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY))
3465 "can't launch in tty when launching through a remote connection");
3466 }
3467
3468 if (!launch_info.GetArchitecture().IsValid())
3469 launch_info.GetArchitecture() = GetArchitecture();
3470
3471 // Hijacking events of the process to be created to be sure that all events
3472 // until the first stop are intercepted (in case if platform doesn't define
3473 // its own hijacking listener or if the process is created by the target
3474 // manually, without the platform).
3475 if (!launch_info.GetHijackListener())
3478
3479 // If we're not already connected to the process, and if we have a platform
3480 // that can launch a process for debugging, go ahead and do that here.
3481 if (state != eStateConnected && platform_sp &&
3482 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) {
3483 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
3484 __FUNCTION__);
3485
3486 // If there was a previous process, delete it before we make the new one.
3487 // One subtle point, we delete the process before we release the reference
3488 // to m_process_sp. That way even if we are the last owner, the process
3489 // will get Finalized before it gets destroyed.
3491
3492 m_process_sp =
3493 GetPlatform()->DebugProcess(launch_info, debugger, *this, error);
3494
3495 } else {
3496 LLDB_LOGF(log,
3497 "Target::%s the platform doesn't know how to debug a "
3498 "process, getting a process plugin to do this for us.",
3499 __FUNCTION__);
3500
3501 if (state == eStateConnected) {
3502 assert(m_process_sp);
3503 } else {
3504 // Use a Process plugin to construct the process.
3505 CreateProcess(launch_info.GetListener(),
3506 launch_info.GetProcessPluginName(), nullptr, false);
3507 }
3508
3509 // Since we didn't have a platform launch the process, launch it here.
3510 if (m_process_sp) {
3511 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener());
3512 m_process_sp->SetShadowListener(launch_info.GetShadowListener());
3513 error = m_process_sp->Launch(launch_info);
3514 }
3515 }
3516
3517 if (!error.Success())
3518 return error;
3519
3520 if (!m_process_sp)
3521 return Status::FromErrorString("failed to launch or debug process");
3522
3523 bool rebroadcast_first_stop =
3524 !synchronous_execution &&
3525 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry);
3526
3527 assert(launch_info.GetHijackListener());
3528
3529 EventSP first_stop_event_sp;
3530 state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp,
3531 rebroadcast_first_stop,
3532 launch_info.GetHijackListener());
3533 m_process_sp->RestoreProcessEvents();
3534
3535 if (rebroadcast_first_stop) {
3536 // We don't need to run the stop hooks by hand here, they will get
3537 // triggered when this rebroadcast event gets fetched.
3538 assert(first_stop_event_sp);
3539 m_process_sp->BroadcastEvent(first_stop_event_sp);
3540 return error;
3541 }
3542 // Run the stop hooks that want to run at entry.
3543 RunStopHooks(true /* at entry point */);
3544
3545 switch (state) {
3546 case eStateStopped: {
3547 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3548 break;
3549 if (synchronous_execution)
3550 // Now we have handled the stop-from-attach, and we are just
3551 // switching to a synchronous resume. So we should switch to the
3552 // SyncResume hijacker.
3553 m_process_sp->ResumeSynchronous(stream);
3554 else
3555 error = m_process_sp->Resume();
3556 if (!error.Success()) {
3558 "process resume at entry point failed: %s", error.AsCString());
3559 }
3560 } break;
3561 case eStateExited: {
3562 bool with_shell = !!launch_info.GetShell();
3563 const int exit_status = m_process_sp->GetExitStatus();
3564 const char *exit_desc = m_process_sp->GetExitDescription();
3565 std::string desc;
3566 if (exit_desc && exit_desc[0])
3567 desc = " (" + std::string(exit_desc) + ')';
3568 if (with_shell)
3570 "process exited with status %i%s\n"
3571 "'r' and 'run' are aliases that default to launching through a "
3572 "shell.\n"
3573 "Try launching without going through a shell by using "
3574 "'process launch'.",
3575 exit_status, desc.c_str());
3576 else
3578 "process exited with status %i%s", exit_status, desc.c_str());
3579 } break;
3580 default:
3582 "initial process state wasn't stopped: %s", StateAsCString(state));
3583 break;
3584 }
3585 return error;
3586}
3587
3588void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3589
3591
3592llvm::Expected<TraceSP> Target::CreateTrace() {
3593 if (!m_process_sp)
3594 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3595 "A process is required for tracing");
3596 if (m_trace_sp)
3597 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3598 "A trace already exists for the target");
3599
3600 llvm::Expected<TraceSupportedResponse> trace_type =
3601 m_process_sp->TraceSupported();
3602 if (!trace_type)
3603 return llvm::createStringError(
3604 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3605 llvm::toString(trace_type.takeError()).c_str());
3606 if (llvm::Expected<TraceSP> trace_sp =
3608 m_trace_sp = *trace_sp;
3609 else
3610 return llvm::createStringError(
3611 llvm::inconvertibleErrorCode(),
3612 "Couldn't create a Trace object for the process. %s",
3613 llvm::toString(trace_sp.takeError()).c_str());
3614 return m_trace_sp;
3615}
3616
3617llvm::Expected<TraceSP> Target::GetTraceOrCreate() {
3618 if (m_trace_sp)
3619 return m_trace_sp;
3620 return CreateTrace();
3621}
3622
3624 Progress attach_progress("Waiting to attach to process");
3625 m_stats.SetLaunchOrAttachTime();
3626 auto state = eStateInvalid;
3627 auto process_sp = GetProcessSP();
3628 if (process_sp) {
3629 state = process_sp->GetState();
3630 if (process_sp->IsAlive() && state != eStateConnected) {
3631 if (state == eStateAttaching)
3632 return Status::FromErrorString("process attach is in progress");
3633 return Status::FromErrorString("a process is already being debugged");
3634 }
3635 }
3636
3637 const ModuleSP old_exec_module_sp = GetExecutableModule();
3638
3639 // If no process info was specified, then use the target executable name as
3640 // the process to attach to by default
3641 if (!attach_info.ProcessInfoSpecified()) {
3642 if (old_exec_module_sp)
3643 attach_info.GetExecutableFile().SetFilename(
3644 old_exec_module_sp->GetPlatformFileSpec().GetFilename());
3645
3646 if (!attach_info.ProcessInfoSpecified()) {
3648 "no process specified, create a target with a file, or "
3649 "specify the --pid or --name");
3650 }
3651 }
3652
3653 const auto platform_sp =
3655 ListenerSP hijack_listener_sp;
3656 const bool async = attach_info.GetAsync();
3657 if (!async) {
3658 hijack_listener_sp = Listener::MakeListener(
3660 attach_info.SetHijackListener(hijack_listener_sp);
3661 }
3662
3663 Status error;
3664 if (state != eStateConnected && platform_sp != nullptr &&
3665 platform_sp->CanDebugProcess() && !attach_info.IsScriptedProcess()) {
3666 SetPlatform(platform_sp);
3667 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3668 } else {
3669 if (state != eStateConnected) {
3670 SaveScriptedLaunchInfo(attach_info);
3671 llvm::StringRef plugin_name = attach_info.GetProcessPluginName();
3672 process_sp =
3674 plugin_name, nullptr, false);
3675 if (!process_sp) {
3677 "failed to create process using plugin '{0}'",
3678 plugin_name.empty() ? "<empty>" : plugin_name);
3679 return error;
3680 }
3681 }
3682 if (hijack_listener_sp)
3683 process_sp->HijackProcessEvents(hijack_listener_sp);
3684 error = process_sp->Attach(attach_info);
3685 }
3686
3687 if (error.Success() && process_sp) {
3688 if (async) {
3689 process_sp->RestoreProcessEvents();
3690 } else {
3691 // We are stopping all the way out to the user, so update selected frames.
3692 state = process_sp->WaitForProcessToStop(
3693 std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
3695 process_sp->RestoreProcessEvents();
3696
3697 // Run the stop hooks here. Since we were hijacking the events, they
3698 // wouldn't have gotten run as part of event delivery.
3699 RunStopHooks(/* at_initial_stop= */ true);
3700
3701 if (state != eStateStopped) {
3702 const char *exit_desc = process_sp->GetExitDescription();
3703 if (exit_desc)
3704 error = Status::FromErrorStringWithFormat("%s", exit_desc);
3705 else
3707 "process did not stop (no such process or permission problem?)");
3708 process_sp->Destroy(false);
3709 }
3710 }
3711 }
3712 return error;
3713}
3714
3716 Log *log = GetLog(LLDBLog::Process);
3717
3718 // Finalize the file actions, and if none were given, default to opening up a
3719 // pseudo terminal
3720 PlatformSP platform_sp = GetPlatform();
3721 const bool default_to_use_pty =
3722 m_platform_sp ? m_platform_sp->IsHost() : false;
3723 LLDB_LOG(
3724 log,
3725 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3726 bool(platform_sp),
3727 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3728 default_to_use_pty);
3729
3730 // If nothing for stdin or stdout or stderr was specified, then check the
3731 // process for any default settings that were set with "settings set"
3732 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3733 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3734 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3735 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3736 "default handling");
3737
3738 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3739 // Do nothing, if we are launching in a remote terminal no file actions
3740 // should be done at all.
3741 return;
3742 }
3743
3744 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3745 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3746 "for stdin, stdout and stderr");
3747 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3748 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3749 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3750 } else {
3751 // Check for any values that might have gotten set with any of: (lldb)
3752 // settings set target.input-path (lldb) settings set target.output-path
3753 // (lldb) settings set target.error-path
3754 FileSpec in_file_spec;
3755 FileSpec out_file_spec;
3756 FileSpec err_file_spec;
3757 // Only override with the target settings if we don't already have an
3758 // action for in, out or error
3759 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3760 in_file_spec = GetStandardInputPath();
3761 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3762 out_file_spec = GetStandardOutputPath();
3763 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3764 err_file_spec = GetStandardErrorPath();
3765
3766 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{2}'",
3767 in_file_spec, out_file_spec, err_file_spec);
3768
3769 if (in_file_spec) {
3770 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3771 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3772 }
3773
3774 if (out_file_spec) {
3775 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3776 LLDB_LOG(log, "appended stdout open file action for {0}",
3777 out_file_spec);
3778 }
3779
3780 if (err_file_spec) {
3781 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3782 LLDB_LOG(log, "appended stderr open file action for {0}",
3783 err_file_spec);
3784 }
3785
3786 if (default_to_use_pty) {
3787 llvm::Error Err = info.SetUpPtyRedirection();
3788 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3789 }
3790 }
3791 }
3792}
3793
3794void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify,
3795 LazyBool stop) {
3796 if (name.empty())
3797 return;
3798 // Don't add a signal if all the actions are trivial:
3799 if (pass == eLazyBoolCalculate && notify == eLazyBoolCalculate
3800 && stop == eLazyBoolCalculate)
3801 return;
3802
3803 auto& elem = m_dummy_signals[name];
3804 elem.pass = pass;
3805 elem.notify = notify;
3806 elem.stop = stop;
3807}
3808
3810 const DummySignalElement &elem) {
3811 if (!signals_sp)
3812 return false;
3813
3814 int32_t signo
3815 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3816 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3817 return false;
3818
3819 if (elem.second.pass == eLazyBoolYes)
3820 signals_sp->SetShouldSuppress(signo, false);
3821 else if (elem.second.pass == eLazyBoolNo)
3822 signals_sp->SetShouldSuppress(signo, true);
3823
3824 if (elem.second.notify == eLazyBoolYes)
3825 signals_sp->SetShouldNotify(signo, true);
3826 else if (elem.second.notify == eLazyBoolNo)
3827 signals_sp->SetShouldNotify(signo, false);
3828
3829 if (elem.second.stop == eLazyBoolYes)
3830 signals_sp->SetShouldStop(signo, true);
3831 else if (elem.second.stop == eLazyBoolNo)
3832 signals_sp->SetShouldStop(signo, false);
3833 return true;
3834}
3835
3837 const DummySignalElement &elem) {
3838 if (!signals_sp)
3839 return false;
3840 int32_t signo
3841 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3842 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3843 return false;
3844 bool do_pass = elem.second.pass != eLazyBoolCalculate;
3845 bool do_stop = elem.second.stop != eLazyBoolCalculate;
3846 bool do_notify = elem.second.notify != eLazyBoolCalculate;
3847 signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass);
3848 return true;
3849}
3850
3852 StreamSP warning_stream_sp) {
3853 if (!signals_sp)
3854 return;
3855
3856 for (const auto &elem : m_dummy_signals) {
3857 if (!UpdateSignalFromDummy(signals_sp, elem))
3858 warning_stream_sp->Printf("Target signal '%s' not found in process\n",
3859 elem.first().str().c_str());
3860 }
3861}
3862
3863void Target::ClearDummySignals(Args &signal_names) {
3864 ProcessSP process_sp = GetProcessSP();
3865 // The simplest case, delete them all with no process to update.
3866 if (signal_names.GetArgumentCount() == 0 && !process_sp) {
3867 m_dummy_signals.clear();
3868 return;
3869 }
3870 UnixSignalsSP signals_sp;
3871 if (process_sp)
3872 signals_sp = process_sp->GetUnixSignals();
3873
3874 for (const Args::ArgEntry &entry : signal_names) {
3875 const char *signal_name = entry.c_str();
3876 auto elem = m_dummy_signals.find(signal_name);
3877 // If we didn't find it go on.
3878 // FIXME: Should I pipe error handling through here?
3879 if (elem == m_dummy_signals.end()) {
3880 continue;
3881 }
3882 if (signals_sp)
3883 ResetSignalFromDummy(signals_sp, *elem);
3884 m_dummy_signals.erase(elem);
3885 }
3886}
3887
3888void Target::PrintDummySignals(Stream &strm, Args &signal_args) {
3889 strm.Printf("NAME PASS STOP NOTIFY\n");
3890 strm.Printf("=========== ======= ======= =======\n");
3891
3892 auto str_for_lazy = [] (LazyBool lazy) -> const char * {
3893 switch (lazy) {
3894 case eLazyBoolCalculate: return "not set";
3895 case eLazyBoolYes: return "true ";
3896 case eLazyBoolNo: return "false ";
3897 }
3898 llvm_unreachable("Fully covered switch above!");
3899 };
3900 size_t num_args = signal_args.GetArgumentCount();
3901 for (const auto &elem : m_dummy_signals) {
3902 bool print_it = false;
3903 for (size_t idx = 0; idx < num_args; idx++) {
3904 if (elem.first() == signal_args.GetArgumentAtIndex(idx)) {
3905 print_it = true;
3906 break;
3907 }
3908 }
3909 if (print_it) {
3910 strm.Printf("%-11s ", elem.first().str().c_str());
3911 strm.Printf("%s %s %s\n", str_for_lazy(elem.second.pass),
3912 str_for_lazy(elem.second.stop),
3913 str_for_lazy(elem.second.notify));
3914 }
3915 }
3916}
3917
3918// Target::StopHook
3922
3924 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3927 if (rhs.m_thread_spec_up)
3928 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3929}
3930
3932 m_specifier_sp.reset(specifier);
3933}
3934
3936 m_thread_spec_up.reset(specifier);
3937}
3938
3940 SymbolContextSpecifier *specifier = GetSpecifier();
3941 if (!specifier)
3942 return true;
3943
3944 bool will_run = true;
3945 if (exc_ctx.GetFramePtr())
3946 will_run = GetSpecifier()->SymbolContextMatches(
3947 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
3948 if (will_run && GetThreadSpecifier() != nullptr)
3949 will_run =
3950 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
3951
3952 return will_run;
3953}
3954
3956 lldb::DescriptionLevel level) const {
3957
3958 // For brief descriptions, only print the subclass description:
3959 if (level == eDescriptionLevelBrief) {
3960 GetSubclassDescription(s, level);
3961 return;
3962 }
3963
3964 unsigned indent_level = s.GetIndentLevel();
3965
3966 s.SetIndentLevel(indent_level + 2);
3967
3968 s.Printf("Hook: %" PRIu64 "\n", GetID());
3969 if (m_active)
3970 s.Indent("State: enabled\n");
3971 else
3972 s.Indent("State: disabled\n");
3973
3974 if (m_auto_continue)
3975 s.Indent("AutoContinue on\n");
3976
3977 if (m_specifier_sp) {
3978 s.Indent();
3979 s.PutCString("Specifier:\n");
3980 s.SetIndentLevel(indent_level + 4);
3981 m_specifier_sp->GetDescription(&s, level);
3982 s.SetIndentLevel(indent_level + 2);
3983 }
3984
3985 if (m_thread_spec_up) {
3986 StreamString tmp;
3987 s.Indent("Thread:\n");
3988 m_thread_spec_up->GetDescription(&tmp, level);
3989 s.SetIndentLevel(indent_level + 4);
3990 s.Indent(tmp.GetString());
3991 s.PutCString("\n");
3992 s.SetIndentLevel(indent_level + 2);
3993 }
3994 GetSubclassDescription(s, level);
3995}
3996
3998 Stream &s, lldb::DescriptionLevel level) const {
3999 // The brief description just prints the first command.
4000 if (level == eDescriptionLevelBrief) {
4001 if (m_commands.GetSize() == 1)
4002 s.PutCString(m_commands.GetStringAtIndex(0));
4003 return;
4004 }
4005 s.Indent("Commands: \n");
4006 s.SetIndentLevel(s.GetIndentLevel() + 4);
4007 uint32_t num_commands = m_commands.GetSize();
4008 for (uint32_t i = 0; i < num_commands; i++) {
4009 s.Indent(m_commands.GetStringAtIndex(i));
4010 s.PutCString("\n");
4011 }
4012 s.SetIndentLevel(s.GetIndentLevel() - 4);
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 s.SetIndentLevel(s.GetIndentLevel() + 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 s.SetIndentLevel(s.GetIndentLevel() - 4);
4159}
4160
4162 {
4164 "no-dynamic-values",
4165 "Don't calculate the dynamic type of values",
4166 },
4167 {
4169 "run-target",
4170 "Calculate the dynamic type of values "
4171 "even if you have to run the target.",
4172 },
4173 {
4175 "no-run-target",
4176 "Calculate the dynamic type of values, but don't run the target.",
4177 },
4178};
4179
4183
4185 {
4187 "never",
4188 "Never look for inline breakpoint locations (fastest). This setting "
4189 "should only be used if you know that no inlining occurs in your"
4190 "programs.",
4191 },
4192 {
4194 "headers",
4195 "Only check for inline breakpoint locations when setting breakpoints "
4196 "in header files, but not when setting breakpoint in implementation "
4197 "source files (default).",
4198 },
4199 {
4201 "always",
4202 "Always look for inline breakpoint locations when setting file and "
4203 "line breakpoints (slower but most accurate).",
4204 },
4205};
4206
4212
4214 {
4216 "default",
4217 "Disassembler default (currently att).",
4218 },
4219 {
4221 "intel",
4222 "Intel disassembler flavor.",
4223 },
4224 {
4226 "att",
4227 "AT&T disassembler flavor.",
4228 },
4229};
4230
4232 {
4234 "false",
4235 "Never import the 'std' C++ module in the expression parser.",
4236 },
4237 {
4239 "fallback",
4240 "Retry evaluating expressions with an imported 'std' C++ module if they"
4241 " failed to parse without the module. This allows evaluating more "
4242 "complex expressions involving C++ standard library types."
4243 },
4244 {
4246 "true",
4247 "Always import the 'std' C++ module. This allows evaluating more "
4248 "complex expressions involving C++ standard library types. This feature"
4249 " is experimental."
4250 },
4251};
4252
4253static constexpr OptionEnumValueElement
4255 {
4257 "auto",
4258 "Automatically determine the most appropriate method for the "
4259 "target OS.",
4260 },
4261 {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct",
4262 "Prefer using the realized classes struct."},
4263 {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList",
4264 "Prefer using the CopyRealizedClassList API."},
4265 {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList",
4266 "Prefer using the GetRealizedClassList API."},
4267};
4268
4270 {
4272 "c",
4273 "C-style (0xffff).",
4274 },
4275 {
4277 "asm",
4278 "Asm-style (0ffffh).",
4279 },
4280};
4281
4283 {
4285 "true",
4286 "Load debug scripts inside symbol files",
4287 },
4288 {
4290 "false",
4291 "Do not load debug scripts inside symbol files.",
4292 },
4293 {
4295 "warn",
4296 "Warn about debug scripts inside symbol files but do not load them.",
4297 },
4298};
4299
4301 {
4303 "true",
4304 "Load .lldbinit files from current directory",
4305 },
4306 {
4308 "false",
4309 "Do not load .lldbinit files from current directory",
4310 },
4311 {
4313 "warn",
4314 "Warn about loading .lldbinit files from current directory",
4315 },
4316};
4317
4319 {
4321 "minimal",
4322 "Load minimal information when loading modules from memory. Currently "
4323 "this setting loads sections only.",
4324 },
4325 {
4327 "partial",
4328 "Load partial information when loading modules from memory. Currently "
4329 "this setting loads sections and function bounds.",
4330 },
4331 {
4333 "complete",
4334 "Load complete information when loading modules from memory. Currently "
4335 "this setting loads sections and all symbols.",
4336 },
4337};
4338
4339#define LLDB_PROPERTIES_target
4340#include "TargetProperties.inc"
4341
4342enum {
4343#define LLDB_PROPERTIES_target
4344#include "TargetPropertiesEnum.inc"
4346};
4347
4349 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
4350public:
4351 TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
4352
4353 const Property *
4355 const ExecutionContext *exe_ctx = nullptr) const override {
4356 // When getting the value for a key from the target options, we will always
4357 // try and grab the setting from the current target if there is one. Else
4358 // we just use the one from this instance.
4359 if (exe_ctx) {
4360 Target *target = exe_ctx->GetTargetPtr();
4361 if (target) {
4362 TargetOptionValueProperties *target_properties =
4363 static_cast<TargetOptionValueProperties *>(
4364 target->GetValueProperties().get());
4365 if (this != target_properties)
4366 return target_properties->ProtectedGetPropertyAtIndex(idx);
4367 }
4368 }
4369 return ProtectedGetPropertyAtIndex(idx);
4370 }
4371};
4372
4373// TargetProperties
4374#define LLDB_PROPERTIES_target_experimental
4375#include "TargetProperties.inc"
4376
4377enum {
4378#define LLDB_PROPERTIES_target_experimental
4379#include "TargetPropertiesEnum.inc"
4380};
4381
4383 : public Cloneable<TargetExperimentalOptionValueProperties,
4384 OptionValueProperties> {
4385public:
4387 : Cloneable(Properties::GetExperimentalSettingsName()) {}
4388};
4389
4395
4396// TargetProperties
4398 : Properties(), m_launch_info(), m_target(target) {
4399 if (target) {
4402
4403 // Set callbacks to update launch_info whenever "settins set" updated any
4404 // of these properties
4405 m_collection_sp->SetValueChangedCallback(
4406 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
4407 m_collection_sp->SetValueChangedCallback(
4408 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
4409 m_collection_sp->SetValueChangedCallback(
4410 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
4411 m_collection_sp->SetValueChangedCallback(
4412 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
4413 m_collection_sp->SetValueChangedCallback(
4414 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
4415 m_collection_sp->SetValueChangedCallback(
4416 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
4417 m_collection_sp->SetValueChangedCallback(
4418 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
4419 m_collection_sp->SetValueChangedCallback(
4420 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
4421 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
4423 });
4424 m_collection_sp->SetValueChangedCallback(
4425 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
4426 m_collection_sp->SetValueChangedCallback(
4427 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
4428 m_collection_sp->SetValueChangedCallback(
4429 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
4430
4431 m_collection_sp->SetValueChangedCallback(
4432 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4434 std::make_unique<TargetExperimentalProperties>();
4435 m_collection_sp->AppendProperty(
4437 "Experimental settings - setting these won't produce "
4438 "errors if the setting is not present.",
4439 true, m_experimental_properties_up->GetValueProperties());
4440 } else {
4441 m_collection_sp = std::make_shared<TargetOptionValueProperties>("target");
4442 m_collection_sp->Initialize(g_target_properties);
4444 std::make_unique<TargetExperimentalProperties>();
4445 m_collection_sp->AppendProperty(
4447 "Experimental settings - setting these won't produce "
4448 "errors if the setting is not present.",
4449 true, m_experimental_properties_up->GetValueProperties());
4450 m_collection_sp->AppendProperty(
4451 "process", "Settings specific to processes.", true,
4453 m_collection_sp->SetValueChangedCallback(
4454 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4455 }
4456}
4457
4459
4472
4474 size_t prop_idx, ExecutionContext *exe_ctx) const {
4475 const Property *exp_property =
4476 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4477 OptionValueProperties *exp_values =
4478 exp_property->GetValue()->GetAsProperties();
4479 if (exp_values)
4480 return exp_values->GetPropertyAtIndexAs<bool>(prop_idx, exe_ctx);
4481 return std::nullopt;
4482}
4483
4485 ExecutionContext *exe_ctx) const {
4486 return GetExperimentalPropertyValue(ePropertyInjectLocalVars, exe_ctx)
4487 .value_or(true);
4488}
4489
4491 const Property *exp_property =
4492 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4493 OptionValueProperties *exp_values =
4494 exp_property->GetValue()->GetAsProperties();
4495 if (exp_values)
4496 return exp_values->GetPropertyAtIndexAs<bool>(ePropertyUseDIL, exe_ctx)
4497 .value_or(false);
4498 else
4499 return true;
4500}
4501
4503 const Property *exp_property =
4504 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4505 OptionValueProperties *exp_values =
4506 exp_property->GetValue()->GetAsProperties();
4507 if (exp_values)
4508 exp_values->SetPropertyAtIndex(ePropertyUseDIL, true, exe_ctx);
4509}
4510
4512 const uint32_t idx = ePropertyDefaultArch;
4513 return GetPropertyAtIndexAs<ArchSpec>(idx, {});
4514}
4515
4517 const uint32_t idx = ePropertyDefaultArch;
4518 SetPropertyAtIndex(idx, arch);
4519}
4520
4522 const uint32_t idx = ePropertyMoveToNearestCode;
4524 idx, g_target_properties[idx].default_uint_value != 0);
4525}
4526
4528 const uint32_t idx = ePropertyPreferDynamic;
4530 idx, static_cast<lldb::DynamicValueType>(
4531 g_target_properties[idx].default_uint_value));
4532}
4533
4535 const uint32_t idx = ePropertyPreferDynamic;
4536 return SetPropertyAtIndex(idx, d);
4537}
4538
4540 if (INTERRUPT_REQUESTED(m_target->GetDebugger(),
4541 "Interrupted checking preload symbols")) {
4542 return false;
4543 }
4544 const uint32_t idx = ePropertyPreloadSymbols;
4546 idx, g_target_properties[idx].default_uint_value != 0);
4547}
4548
4550 const uint32_t idx = ePropertyPreloadSymbols;
4551 SetPropertyAtIndex(idx, b);
4552}
4553
4555 const uint32_t idx = ePropertyDisableASLR;
4557 idx, g_target_properties[idx].default_uint_value != 0);
4558}
4559
4561 const uint32_t idx = ePropertyDisableASLR;
4562 SetPropertyAtIndex(idx, b);
4563}
4564
4566 const uint32_t idx = ePropertyInheritTCC;
4568 idx, g_target_properties[idx].default_uint_value != 0);
4569}
4570
4572 const uint32_t idx = ePropertyInheritTCC;
4573 SetPropertyAtIndex(idx, b);
4574}
4575
4577 const uint32_t idx = ePropertyDetachOnError;
4579 idx, g_target_properties[idx].default_uint_value != 0);
4580}
4581
4583 const uint32_t idx = ePropertyDetachOnError;
4584 SetPropertyAtIndex(idx, b);
4585}
4586
4588 const uint32_t idx = ePropertyDisableSTDIO;
4590 idx, g_target_properties[idx].default_uint_value != 0);
4591}
4592
4594 const uint32_t idx = ePropertyDisableSTDIO;
4595 SetPropertyAtIndex(idx, b);
4596}
4598 const uint32_t idx = ePropertyLaunchWorkingDir;
4600 idx, g_target_properties[idx].default_cstr_value);
4601}
4602
4604 const uint32_t idx = ePropertyParallelModuleLoad;
4606 idx, g_target_properties[idx].default_uint_value != 0);
4607}
4608
4610 const uint32_t idx = ePropertyDisassemblyFlavor;
4611 const char *return_value;
4612
4613 x86DisassemblyFlavor flavor_value =
4615 idx, static_cast<x86DisassemblyFlavor>(
4616 g_target_properties[idx].default_uint_value));
4617
4618 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
4619 return return_value;
4620}
4621
4623 const uint32_t idx = ePropertyDisassemblyCPU;
4624 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
4625 idx, g_target_properties[idx].default_cstr_value);
4626 return str.empty() ? nullptr : str.data();
4627}
4628
4630 const uint32_t idx = ePropertyDisassemblyFeatures;
4631 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
4632 idx, g_target_properties[idx].default_cstr_value);
4633 return str.empty() ? nullptr : str.data();
4634}
4635
4637 const uint32_t idx = ePropertyInlineStrategy;
4639 idx,
4640 static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value));
4641}
4642
4643// Returning RealpathPrefixes, but the setting's type is FileSpecList. We do
4644// this because we want the FileSpecList to normalize the file paths for us.
4646 const uint32_t idx = ePropertySourceRealpathPrefixes;
4648}
4649
4650llvm::StringRef TargetProperties::GetArg0() const {
4651 const uint32_t idx = ePropertyArg0;
4653 idx, g_target_properties[idx].default_cstr_value);
4654}
4655
4656void TargetProperties::SetArg0(llvm::StringRef arg) {
4657 const uint32_t idx = ePropertyArg0;
4658 SetPropertyAtIndex(idx, arg);
4659 m_launch_info.SetArg0(arg);
4660}
4661
4663 const uint32_t idx = ePropertyRunArgs;
4664 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4665}
4666
4668 const uint32_t idx = ePropertyRunArgs;
4669 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4670 m_launch_info.GetArguments() = args;
4671}
4672
4674 Environment env;
4675
4676 if (m_target &&
4678 ePropertyInheritEnv,
4679 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
4680 if (auto platform_sp = m_target->GetPlatform()) {
4681 Environment platform_env = platform_sp->GetEnvironment();
4682 for (const auto &KV : platform_env)
4683 env[KV.first()] = KV.second;
4684 }
4685 }
4686
4687 Args property_unset_env;
4688 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4689 property_unset_env);
4690 for (const auto &var : property_unset_env)
4691 env.erase(var.ref());
4692
4693 Args property_env;
4694 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env);
4695 for (const auto &KV : Environment(property_env))
4696 env[KV.first()] = KV.second;
4697
4698 return env;
4699}
4700
4704
4706 Environment environment;
4707
4708 if (m_target == nullptr)
4709 return environment;
4710
4712 ePropertyInheritEnv,
4713 g_target_properties[ePropertyInheritEnv].default_uint_value != 0))
4714 return environment;
4715
4716 PlatformSP platform_sp = m_target->GetPlatform();
4717 if (platform_sp == nullptr)
4718 return environment;
4719
4720 Environment platform_environment = platform_sp->GetEnvironment();
4721 for (const auto &KV : platform_environment)
4722 environment[KV.first()] = KV.second;
4723
4724 Args property_unset_environment;
4725 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4726 property_unset_environment);
4727 for (const auto &var : property_unset_environment)
4728 environment.erase(var.ref());
4729
4730 return environment;
4731}
4732
4734 Args property_environment;
4735 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars,
4736 property_environment);
4737 Environment environment;
4738 for (const auto &KV : Environment(property_environment))
4739 environment[KV.first()] = KV.second;
4740
4741 return environment;
4742}
4743
4745 // TODO: Get rid of the Args intermediate step
4746 const uint32_t idx = ePropertyEnvVars;
4747 m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env));
4748}
4749
4751 const uint32_t idx = ePropertySkipPrologue;
4753 idx, g_target_properties[idx].default_uint_value != 0);
4754}
4755
4757 const uint32_t idx = ePropertySourceMap;
4758 OptionValuePathMappings *option_value =
4759 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4760 assert(option_value);
4761 return option_value->GetCurrentValue();
4762}
4763
4765 const uint32_t idx = ePropertyObjectMap;
4766 OptionValuePathMappings *option_value =
4767 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4768 assert(option_value);
4769 return option_value->GetCurrentValue();
4770}
4771
4773 const uint32_t idx = ePropertyAutoSourceMapRelative;
4775 idx, g_target_properties[idx].default_uint_value != 0);
4776}
4777
4779 const uint32_t idx = ePropertyExecutableSearchPaths;
4780 OptionValueFileSpecList *option_value =
4781 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
4782 assert(option_value);
4783 option_value->AppendCurrentValue(dir);
4784}
4785
4787 const uint32_t idx = ePropertyExecutableSearchPaths;
4788 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4789}
4790
4792 const uint32_t idx = ePropertyDebugFileSearchPaths;
4793 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4794}
4795
4797 const uint32_t idx = ePropertyClangModuleSearchPaths;
4798 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4799}
4800
4802 const uint32_t idx = ePropertyAutoImportClangModules;
4804 idx, g_target_properties[idx].default_uint_value != 0);
4805}
4806
4808 const uint32_t idx = ePropertyImportStdModule;
4810 idx, static_cast<ImportStdModule>(
4811 g_target_properties[idx].default_uint_value));
4812}
4813
4815 const uint32_t idx = ePropertyDynamicClassInfoHelper;
4817 idx, static_cast<DynamicClassInfoHelper>(
4818 g_target_properties[idx].default_uint_value));
4819}
4820
4822 const uint32_t idx = ePropertyAutoApplyFixIts;
4824 idx, g_target_properties[idx].default_uint_value != 0);
4825}
4826
4828 const uint32_t idx = ePropertyRetriesWithFixIts;
4830 idx, g_target_properties[idx].default_uint_value);
4831}
4832
4834 const uint32_t idx = ePropertyNotifyAboutFixIts;
4836 idx, g_target_properties[idx].default_uint_value != 0);
4837}
4838
4840 const uint32_t idx = ePropertySaveObjectsDir;
4841 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4842}
4843
4845 FileSpec new_dir = GetSaveJITObjectsDir();
4846 if (!new_dir)
4847 return;
4848
4849 const FileSystem &instance = FileSystem::Instance();
4850 bool exists = instance.Exists(new_dir);
4851 bool is_directory = instance.IsDirectory(new_dir);
4852 std::string path = new_dir.GetPath(true);
4853 bool writable = llvm::sys::fs::can_write(path);
4854 if (exists && is_directory && writable)
4855 return;
4856
4857 m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir)
4858 ->GetValue()
4859 ->Clear();
4860
4861 std::string buffer;
4862 llvm::raw_string_ostream os(buffer);
4863 os << "JIT object dir '" << path << "' ";
4864 if (!exists)
4865 os << "does not exist";
4866 else if (!is_directory)
4867 os << "is not a directory";
4868 else if (!writable)
4869 os << "is not writable";
4870
4871 std::optional<lldb::user_id_t> debugger_id;
4872 if (m_target)
4873 debugger_id = m_target->GetDebugger().GetID();
4874 Debugger::ReportError(buffer, debugger_id);
4875}
4876
4878 const uint32_t idx = ePropertyEnableSynthetic;
4880 idx, g_target_properties[idx].default_uint_value != 0);
4881}
4882
4884 const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes;
4886 idx, g_target_properties[idx].default_uint_value != 0);
4887}
4888
4890 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
4892 idx, g_target_properties[idx].default_uint_value);
4893}
4894
4896 const uint32_t idx = ePropertyMaxChildrenCount;
4898 idx, g_target_properties[idx].default_uint_value);
4899}
4900
4901std::pair<uint32_t, bool>
4903 const uint32_t idx = ePropertyMaxChildrenDepth;
4904 auto *option_value =
4905 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx);
4906 bool is_default = !option_value->OptionWasSet();
4907 return {option_value->GetCurrentValue(), is_default};
4908}
4909
4911 const uint32_t idx = ePropertyMaxSummaryLength;
4913 idx, g_target_properties[idx].default_uint_value);
4914}
4915
4917 const uint32_t idx = ePropertyMaxMemReadSize;
4919 idx, g_target_properties[idx].default_uint_value);
4920}
4921
4923 const uint32_t idx = ePropertyInputPath;
4924 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4925}
4926
4927void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4928 const uint32_t idx = ePropertyInputPath;
4929 SetPropertyAtIndex(idx, path);
4930}
4931
4933 const uint32_t idx = ePropertyOutputPath;
4934 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4935}
4936
4938 const uint32_t idx = ePropertyOutputPath;
4939 SetPropertyAtIndex(idx, path);
4940}
4941
4943 const uint32_t idx = ePropertyErrorPath;
4944 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4945}
4946
4947void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4948 const uint32_t idx = ePropertyErrorPath;
4949 SetPropertyAtIndex(idx, path);
4950}
4951
4953 const uint32_t idx = ePropertyLanguage;
4954 return {GetPropertyAtIndexAs<LanguageType>(idx, {})};
4955}
4956
4958 const uint32_t idx = ePropertyExprPrefix;
4959 OptionValueFileSpec *file =
4960 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx);
4961 if (file) {
4962 DataBufferSP data_sp(file->GetFileContents());
4963 if (data_sp)
4964 return llvm::StringRef(
4965 reinterpret_cast<const char *>(data_sp->GetBytes()),
4966 data_sp->GetByteSize());
4967 }
4968 return "";
4969}
4970
4972 const uint32_t idx = ePropertyExprErrorLimit;
4974 idx, g_target_properties[idx].default_uint_value);
4975}
4976
4978 const uint32_t idx = ePropertyExprAllocAddress;
4980 idx, g_target_properties[idx].default_uint_value);
4981}
4982
4984 const uint32_t idx = ePropertyExprAllocSize;
4986 idx, g_target_properties[idx].default_uint_value);
4987}
4988
4990 const uint32_t idx = ePropertyExprAllocAlign;
4992 idx, g_target_properties[idx].default_uint_value);
4993}
4994
4996 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4998 idx, g_target_properties[idx].default_uint_value != 0);
4999}
5000
5002 const uint32_t idx = ePropertyUseHexImmediates;
5004 idx, g_target_properties[idx].default_uint_value != 0);
5005}
5006
5008 const uint32_t idx = ePropertyUseFastStepping;
5010 idx, g_target_properties[idx].default_uint_value != 0);
5011}
5012
5014 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
5016 idx, g_target_properties[idx].default_uint_value != 0);
5017}
5018
5020 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
5022 idx, static_cast<LoadScriptFromSymFile>(
5023 g_target_properties[idx].default_uint_value));
5024}
5025
5027 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
5029 idx, static_cast<LoadCWDlldbinitFile>(
5030 g_target_properties[idx].default_uint_value));
5031}
5032
5034 const uint32_t idx = ePropertyHexImmediateStyle;
5036 idx, static_cast<Disassembler::HexImmediateStyle>(
5037 g_target_properties[idx].default_uint_value));
5038}
5039
5041 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
5043 idx, static_cast<MemoryModuleLoadLevel>(
5044 g_target_properties[idx].default_uint_value));
5045}
5046
5048 const uint32_t idx = ePropertyTrapHandlerNames;
5049 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
5050}
5051
5053 const uint32_t idx = ePropertyTrapHandlerNames;
5054 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
5055}
5056
5058 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
5060 idx, g_target_properties[idx].default_uint_value != 0);
5061}
5062
5064 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
5065 SetPropertyAtIndex(idx, b);
5066}
5067
5069 const uint32_t idx = ePropertyDisplayRecognizedArguments;
5071 idx, g_target_properties[idx].default_uint_value != 0);
5072}
5073
5075 const uint32_t idx = ePropertyDisplayRecognizedArguments;
5076 SetPropertyAtIndex(idx, b);
5077}
5078
5082
5084 const ProcessLaunchInfo &launch_info) {
5085 m_launch_info = launch_info;
5086 SetArg0(launch_info.GetArg0());
5087 SetRunArguments(launch_info.GetArguments());
5088 SetEnvironment(launch_info.GetEnvironment());
5089 const FileAction *input_file_action =
5090 launch_info.GetFileActionForFD(STDIN_FILENO);
5091 if (input_file_action) {
5092 SetStandardInputPath(input_file_action->GetPath());
5093 }
5094 const FileAction *output_file_action =
5095 launch_info.GetFileActionForFD(STDOUT_FILENO);
5096 if (output_file_action) {
5097 SetStandardOutputPath(output_file_action->GetPath());
5098 }
5099 const FileAction *error_file_action =
5100 launch_info.GetFileActionForFD(STDERR_FILENO);
5101 if (error_file_action) {
5102 SetStandardErrorPath(error_file_action->GetPath());
5103 }
5104 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
5105 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
5107 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
5108 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
5109}
5110
5112 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5114 idx, g_target_properties[idx].default_uint_value != 0);
5115}
5116
5118 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5119 m_collection_sp->SetPropertyAtIndex(idx, b);
5120}
5121
5123 const uint32_t idx = ePropertyAutoInstallMainExecutable;
5125 idx, g_target_properties[idx].default_uint_value != 0);
5126}
5127
5131
5133 Args args;
5134 if (GetRunArguments(args))
5135 m_launch_info.GetArguments() = args;
5136}
5137
5141
5143 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
5144 false);
5145}
5146
5148 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
5149 false, true);
5150}
5151
5153 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
5154 false, true);
5155}
5156
5158 if (GetDetachOnError())
5159 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
5160 else
5161 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
5162}
5163
5165 if (GetDisableASLR())
5166 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
5167 else
5168 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
5169}
5170
5172 if (GetInheritTCC())
5173 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
5174 else
5175 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
5176}
5177
5179 if (GetDisableSTDIO())
5180 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
5181 else
5182 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
5183}
5184
5186 const uint32_t idx = ePropertyDebugUtilityExpression;
5188 idx, g_target_properties[idx].default_uint_value != 0);
5189}
5190
5192 const uint32_t idx = ePropertyDebugUtilityExpression;
5193 SetPropertyAtIndex(idx, debug);
5194}
5195
5196// Target::TargetEventData
5197
5200
5202 const ModuleList &module_list)
5203 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
5204
5206
5208 return "Target::TargetEventData";
5209}
5210
5212 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
5213 if (i != 0)
5214 *s << ", ";
5215 m_module_list.GetModuleAtIndex(i)->GetDescription(
5217 }
5218}
5219
5222 if (event_ptr) {
5223 const EventData *event_data = event_ptr->GetData();
5224 if (event_data &&
5226 return static_cast<const TargetEventData *>(event_ptr->GetData());
5227 }
5228 return nullptr;
5229}
5230
5232 TargetSP target_sp;
5233 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
5234 if (event_data)
5235 target_sp = event_data->m_target_sp;
5236 return target_sp;
5237}
5238
5241 ModuleList module_list;
5242 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
5243 if (event_data)
5244 module_list = event_data->m_module_list;
5245 return module_list;
5246}
5247
5248std::recursive_mutex &Target::GetAPIMutex() {
5249 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
5250 return m_private_mutex;
5251 else
5252 return m_mutex;
5253}
5254
5255/// Get metrics associated with this target in JSON format.
5256llvm::json::Value
5258 return m_stats.ToJSON(*this, options);
5259}
5260
5261void Target::ResetStatistics() { m_stats.Reset(*this); }
5262
5264
5268
5270
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:127
static double elapsed(const StatsTimepoint &start, const StatsTimepoint &end)
static Status installExecutable(const Installer &installer)
Definition Target.cpp:145
static constexpr OptionEnumValueElement g_dynamic_class_info_helper_value_types[]
Definition Target.cpp:4254
static bool CheckIfWatchpointsSupported(Target *target, Status &error)
Definition Target.cpp:932
static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[]
Definition Target.cpp:4300
x86DisassemblyFlavor
Definition Target.cpp:4207
@ eX86DisFlavorDefault
Definition Target.cpp:4208
@ eX86DisFlavorIntel
Definition Target.cpp:4209
@ eX86DisFlavorATT
Definition Target.cpp:4210
static void LoadScriptingResourceForModule(const ModuleSP &module_sp, Target *target)
Definition Target.cpp:1542
static constexpr OptionEnumValueElement g_dynamic_value_types[]
Definition Target.cpp:4161
static constexpr OptionEnumValueElement g_memory_module_load_level_values[]
Definition Target.cpp:4318
static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[]
Definition Target.cpp:4282
static std::atomic< lldb::user_id_t > g_target_unique_id
Definition Target.cpp:142
static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[]
Definition Target.cpp:4213
static constexpr OptionEnumValueElement g_hex_immediate_style_values[]
Definition Target.cpp:4269
static constexpr OptionEnumValueElement g_inline_breakpoint_enums[]
Definition Target.cpp:4184
static constexpr OptionEnumValueElement g_import_std_module_value_types[]
Definition Target.cpp:4231
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:86
const Property * GetPropertyAtIndex(size_t idx, const ExecutionContext *exe_ctx=nullptr) const override
Definition Target.cpp:4354
TargetOptionValueProperties(llvm::StringRef name)
Definition Target.cpp:4351
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)
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)
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, const FileSpecList *module_search_paths_ptr, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr, bool always_create=false)
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:53
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:1177
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:177
lldb::ListenerSP GetListenerForProcess(Debugger &debugger)
Definition Process.cpp:2973
llvm::StringRef GetProcessPluginName() const
Definition Process.h:160
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:4876
static constexpr llvm::StringRef AttachSynchronousHijackListenerName
Definition Process.h:402
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:381
static constexpr llvm::StringRef LaunchSynchronousHijackListenerName
Definition Process.h:404
static ProcessProperties & GetGlobalProperties()
Definition Process.cpp:530
static void SettingsTerminate()
Definition Process.cpp:4878
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:540
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:551
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:344
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:392
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
size_t PutChar(char ch)
Definition Stream.cpp:131
void SetIndentLevel(unsigned level)
Set the current indentation level.
Definition Stream.cpp:190
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:198
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:195
unsigned GetIndentLevel() const
Get the current indentation level.
Definition Stream.cpp:187
void AddItem(const ObjectSP &item)
ObjectSP GetItemAtIndex(size_t idx) const
ObjectSP GetValueForKey(llvm::StringRef key) const
void ForEach(std::function< bool(llvm::StringRef key, Object *object)> const &callback) const
void Dump(lldb_private::Stream &s, bool pretty_print=true) const
std::shared_ptr< Object > ObjectSP
std::shared_ptr< Array > ArraySP
static ObjectSP ParseJSONFromFile(const FileSpec &file, Status &error)
A class that wraps a std::map of SummaryStatistics objects behind a mutex.
Definition Statistics.h: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:4910
FileSpecList GetDebugFileSearchPaths()
Definition Target.cpp:4791
llvm::StringRef GetLaunchWorkingDirectory() const
Definition Target.cpp:4597
bool GetDisplayRecognizedArguments() const
Definition Target.cpp:5068
ImportStdModule GetImportStdModule() const
Definition Target.cpp:4807
void AppendExecutableSearchPaths(const FileSpec &)
Definition Target.cpp:4778
bool GetEnableSyntheticValue() const
Definition Target.cpp:4877
ProcessLaunchInfo m_launch_info
Definition Target.h:302
uint64_t GetExprAllocAlign() const
Definition Target.cpp:4989
MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const
Definition Target.cpp:5040
llvm::StringRef GetArg0() const
Definition Target.cpp:4650
uint32_t GetMaximumMemReadSize() const
Definition Target.cpp:4916
void SetRunArguments(const Args &args)
Definition Target.cpp:4667
FileSpec GetStandardErrorPath() const
Definition Target.cpp:4942
bool GetEnableNotifyAboutFixIts() const
Definition Target.cpp:4833
bool SetPreferDynamicValue(lldb::DynamicValueType d)
Definition Target.cpp:4534
void SetDisplayRecognizedArguments(bool b)
Definition Target.cpp:5074
std::optional< bool > GetExperimentalPropertyValue(size_t prop_idx, ExecutionContext *exe_ctx=nullptr) const
Definition Target.cpp:4473
const ProcessLaunchInfo & GetProcessLaunchInfo() const
Definition Target.cpp:5079
Environment ComputeEnvironment() const
Definition Target.cpp:4673
bool GetUserSpecifiedTrapHandlerNames(Args &args) const
Definition Target.cpp:5047
uint64_t GetExprErrorLimit() const
Definition Target.cpp:4971
bool GetEnableAutoImportClangModules() const
Definition Target.cpp:4801
bool GetDebugUtilityExpression() const
Definition Target.cpp:5185
DynamicClassInfoHelper GetDynamicClassInfoHelper() const
Definition Target.cpp:4814
FileSpec GetStandardOutputPath() const
Definition Target.cpp:4932
void SetDisplayRuntimeSupportValues(bool b)
Definition Target.cpp:5063
uint32_t GetMaximumNumberOfChildrenToDisplay() const
Definition Target.cpp:4895
void SetRequireHardwareBreakpoints(bool b)
Definition Target.cpp:5117
bool GetAutoInstallMainExecutable() const
Definition Target.cpp:5122
const char * GetDisassemblyFeatures() const
Definition Target.cpp:4629
RealpathPrefixes GetSourceRealpathPrefixes() const
Definition Target.cpp:4645
uint64_t GetNumberOfRetriesWithFixits() const
Definition Target.cpp:4827
uint64_t GetExprAllocSize() const
Definition Target.cpp:4983
llvm::StringRef GetExpressionPrefixContents()
Definition Target.cpp:4957
PathMappingList & GetObjectPathMap() const
Definition Target.cpp:4764
const char * GetDisassemblyFlavor() const
Definition Target.cpp:4609
FileSpec GetStandardInputPath() const
Definition Target.cpp:4922
lldb::DynamicValueType GetPreferDynamicValue() const
Definition Target.cpp:4527
InlineStrategy GetInlineStrategy() const
Definition Target.cpp:4636
Environment GetTargetEnvironment() const
Definition Target.cpp:4733
bool GetDisplayRuntimeSupportValues() const
Definition Target.cpp:5057
void SetUserSpecifiedTrapHandlerNames(const Args &args)
Definition Target.cpp:5052
uint32_t GetMaxZeroPaddingInFloatFormat() const
Definition Target.cpp:4889
uint64_t GetExprAllocAddress() const
Definition Target.cpp:4977
LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const
Definition Target.cpp:5026
Environment GetInheritedEnvironment() const
Definition Target.cpp:4705
void SetArg0(llvm::StringRef arg)
Definition Target.cpp:4656
bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const
Definition Target.cpp:4484
bool ShowHexVariableValuesWithLeadingZeroes() const
Definition Target.cpp:4883
SourceLanguage GetLanguage() const
Definition Target.cpp:4952
Environment GetEnvironment() const
Definition Target.cpp:4701
void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
Definition Target.cpp:5083
FileSpec GetSaveJITObjectsDir() const
Definition Target.cpp:4839
void SetEnvironment(Environment env)
Definition Target.cpp:4744
LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const
Definition Target.cpp:5019
const char * GetDisassemblyCPU() const
Definition Target.cpp:4622
void SetStandardErrorPath(llvm::StringRef path)
Definition Target.cpp:4947
bool GetRunArguments(Args &args) const
Definition Target.cpp:4662
FileSpecList GetExecutableSearchPaths()
Definition Target.cpp:4786
ArchSpec GetDefaultArchitecture() const
Definition Target.cpp:4511
Disassembler::HexImmediateStyle GetHexImmediateStyle() const
Definition Target.cpp:5033
void SetUseDIL(ExecutionContext *exe_ctx, bool b)
Definition Target.cpp:4502
std::unique_ptr< TargetExperimentalProperties > m_experimental_properties_up
Definition Target.h:303
FileSpecList GetClangModuleSearchPaths()
Definition Target.cpp:4796
void SetStandardOutputPath(llvm::StringRef path)
Definition Target.cpp:4937
bool GetRequireHardwareBreakpoints() const
Definition Target.cpp:5111
PathMappingList & GetSourcePathMap() const
Definition Target.cpp:4756
bool GetAutoSourceMapRelative() const
Definition Target.cpp:4772
bool GetUseDIL(ExecutionContext *exe_ctx) const
Definition Target.cpp:4490
void SetDefaultArchitecture(const ArchSpec &arch)
Definition Target.cpp:4516
void SetStandardInputPath(llvm::StringRef path)
Definition Target.cpp:4927
TargetProperties(Target *target)
Definition Target.cpp:4397
bool GetDisplayExpressionsInCrashlogs() const
Definition Target.cpp:5013
bool GetEnableAutoApplyFixIts() const
Definition Target.cpp:4821
void SetDebugUtilityExpression(bool debug)
Definition Target.cpp:5191
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:4902
std::unique_ptr< Architecture > m_plugin_up
Definition Target.h:1648
const Arch & operator=(const ArchSpec &spec)
Definition Target.cpp:164
Arch(const ArchSpec &spec)
Definition Target.cpp:160
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:3997
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:1471
lldb::ScriptedStopHookInterfaceSP m_interface_sp
Definition Target.h:1472
SymbolContextSpecifier * GetSpecifier()
Definition Target.h:1377
void SetSpecifier(SymbolContextSpecifier *specifier)
Definition Target.cpp:3931
std::unique_ptr< ThreadSpec > m_thread_spec_up
Definition Target.h:1423
void SetThreadSpecifier(ThreadSpec *specifier)
Definition Target.cpp:3935
ThreadSpec * GetThreadSpecifier()
Definition Target.h:1392
StopHook(const StopHook &rhs)
Definition Target.cpp:3923
bool ExecutionContextPasses(const ExecutionContext &exe_ctx)
Definition Target.cpp:3939
lldb::TargetSP & GetTarget()
Definition Target.h:1371
lldb::SymbolContextSpecifierSP m_specifier_sp
Definition Target.h:1422
virtual void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const =0
void GetDescription(Stream &s, lldb::DescriptionLevel level) const
Definition Target.cpp:3955
void Dump(Stream *s) const override
Definition Target.cpp:5211
static llvm::StringRef GetFlavorString()
Definition Target.cpp:5207
static ModuleList GetModuleListFromEvent(const Event *event_ptr)
Definition Target.cpp:5240
static const TargetEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Target.cpp:5221
TargetEventData(const lldb::TargetSP &target_sp)
Definition Target.cpp:5198
static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr)
Definition Target.cpp:5231
void ModulesDidLoad(ModuleList &module_list)
Definition Target.cpp:1856
lldb::ThreadSP CalculateThread() override
Definition Target.cpp:2589
StopHookCollection m_stop_hooks
Definition Target.h:1691
Module * GetExecutableModulePointer()
Definition Target.cpp:1538
void Dump(Stream *s, lldb::DescriptionLevel description_level)
Dump a description of this object to a Stream.
Definition Target.cpp:241
void DisableAllBreakpoints(bool internal_also=false)
Definition Target.cpp:1070
lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size, const CompilerType *type, uint32_t kind, Status &error)
Definition Target.cpp:952
void ApplyNameToBreakpoints(BreakpointName &bp_name)
Definition Target.cpp:906
lldb::TraceSP GetTrace()
Get the Trace object containing processor trace information of this target.
Definition Target.cpp:3590
PathMappingList & GetImageSearchPathList()
Definition Target.cpp:2598
void FinalizeFileActions(ProcessLaunchInfo &info)
Definition Target.cpp:3715
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:758
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:3863
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:1506
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:724
lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:419
std::shared_ptr< StopHook > StopHookSP
Definition Target.h:1519
void SymbolsDidLoad(ModuleList &module_list)
Definition Target.cpp:1876
bool ClearAllWatchpointHistoricValues()
Definition Target.cpp:1420
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:3588
BreakpointList & GetBreakpointList(bool internal=false)
Definition Target.cpp:405
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:1672
lldb_private::SummaryStatisticsCache & GetSummaryStatisticsCache()
Definition Target.cpp:3405
lldb::addr_t GetSectionLoadAddress(const lldb::SectionSP &section_sp)
Definition Target.cpp:5265
llvm::StringRef GetABIName() const
Returns the name of the target's ABI plugin.
Definition Target.cpp:394
SourceManager & GetSourceManager()
Definition Target.cpp:3040
lldb::SearchFilterSP GetSearchFilterForModuleList(const FileSpecList *containingModuleList)
Definition Target.cpp:687
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:1711
lldb::ProcessSP m_process_sp
Definition Target.h:1680
Debugger & GetDebugger() const
Definition Target.h:1108
lldb::SearchFilterSP m_search_filter_sp
Definition Target.h:1681
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:3851
bool m_is_dummy_target
Used to not run stop hooks for expressions.
Definition Target.h:1698
static bool UpdateSignalFromDummy(lldb::UnixSignalsSP signals_sp, const DummySignalElement &element)
Definition Target.cpp:3809
PathMappingList m_image_search_paths
Definition Target.h:1682
bool ModuleIsExcludedForUnconstrainedSearches(const FileSpec &module_spec)
Return whether this FileSpec corresponds to a module that should be considered for general searches.
Definition Target.cpp:1932
lldb::StackFrameSP CalculateStackFrame() override
Definition Target.cpp:2591
SectionLoadList & GetSectionLoadList()
Definition Target.h:1766
lldb::addr_t GetPersistentSymbol(ConstString name)
Definition Target.cpp:2934
void PrimeFromDummyTarget(Target &target)
Definition Target.cpp:217
static void SettingsTerminate()
Definition Target.cpp:2792
bool EnableWatchpointByID(lldb::watch_id_t watch_id)
Definition Target.cpp:1471
bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr)
Definition Target.cpp:3321
bool ClearAllWatchpointHitCounts()
Definition Target.cpp:1406
size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len, Status &error)
Definition Target.cpp:1964
void ClearAllLoadedSections()
Definition Target.cpp:3397
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:2263
void AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name, Status &error)
Definition Target.cpp:826
void DumpSectionLoadList(Stream &s)
Definition Target.cpp:5271
void DeleteCurrentProcess()
Definition Target.cpp:276
BreakpointList m_internal_breakpoint_list
Definition Target.h:1669
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:2292
void DisableAllowedBreakpoints()
Definition Target.cpp:1080
bool SetSectionUnloaded(const lldb::SectionSP &section_sp)
Definition Target.cpp:3375
lldb::TargetSP CalculateTarget() override
Definition Target.cpp:2585
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:310
void ClearModules(bool delete_locations)
Definition Target.cpp:1560
bool RemoveBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:1104
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:2344
static bool ResetSignalFromDummy(lldb::UnixSignalsSP signals_sp, const DummySignalElement &element)
Definition Target.cpp:3836
Architecture * GetArchitecturePlugin() const
Definition Target.h:1106
llvm::json::Value ReportStatistics(const lldb_private::StatisticsOptions &options)
Get metrics associated with this target in JSON format.
Definition Target.cpp:5257
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:1087
Status Launch(ProcessLaunchInfo &launch_info, Stream *stream)
Definition Target.cpp:3420
bool DisableBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:1124
lldb::BreakpointSP CreateBreakpointAtUserEntry(Status &error)
Definition Target.cpp:431
BreakpointName * FindBreakpointName(ConstString name, bool can_create, Status &error)
Definition Target.cpp:858
llvm::Expected< lldb::TraceSP > CreateTrace()
Create a Trace object for the current target using the using the default supported tracing technology...
Definition Target.cpp:3592
lldb::TraceSP m_trace_sp
The globally unique ID assigned to this target.
Definition Target.h:1705
bool RemoveAllWatchpoints(bool end_to_end=true)
Definition Target.cpp:1324
bool ReadPointerFromMemory(const Address &addr, Status &error, Address &pointer_addr, bool force_live_memory=false)
Definition Target.cpp:2314
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:1675
BreakpointList m_breakpoint_list
Definition Target.h:1668
lldb::SourceManagerUP m_source_manager_up
Definition Target.h:1688
bool RemoveWatchpointByID(lldb::watch_id_t watch_id)
Definition Target.cpp:1490
bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr, uint32_t stop_id=SectionLoadHistory::eStopIDNow, bool allow_section_end=false)
Definition Target.cpp:3315
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:2214
void DeleteBreakpointName(ConstString name)
Definition Target.cpp:882
void NotifyWillClearList(const ModuleList &module_list) override
Definition Target.cpp:1818
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1702
void NotifyModuleAdded(const ModuleList &module_list, const lldb::ModuleSP &module_sp) override
Implementing of ModuleList::Notifier.
Definition Target.cpp:1820
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:898
lldb_private::SummaryStatisticsSP GetSummaryStatisticsSPForProviderName(lldb_private::TypeSummaryImpl &summary_provider)
Definition Target.cpp:3399
lldb::SearchFilterSP GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules, const FileSpecList *containingSourceFiles)
Definition Target.cpp:704
lldb::ModuleSP GetExecutableModule()
Gets the module for the main executable.
Definition Target.cpp:1522
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:298
void SetAllStopHooksActiveState(bool active_state)
Definition Target.cpp:3103
std::vector< StopHookSP > m_internal_stop_hooks
Definition Target.h:1693
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition Target.cpp:2915
void NotifyModulesRemoved(lldb_private::ModuleList &module_list) override
Definition Target.cpp:1852
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:2124
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:1654
lldb::user_id_t m_target_unique_id
Definition Target.h:1700
void ModulesDidUnload(ModuleList &module_list, bool delete_locations)
Definition Target.cpp:1892
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:3617
void NotifyModuleUpdated(const ModuleList &module_list, const lldb::ModuleSP &old_module_sp, const lldb::ModuleSP &new_module_sp) override
Definition Target.cpp:1840
SummaryStatisticsCache m_summary_statistics_cache
Definition Target.h:1666
Status SerializeBreakpointsToFile(const FileSpec &file, const BreakpointIDList &bp_ids, bool append)
Definition Target.cpp:1165
void DidExec()
Called as the last function in Process::DidExec().
Definition Target.cpp:1567
void SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info)
Definition Target.cpp:3409
std::string m_label
Definition Target.h:1663
lldb::user_id_t m_stop_hook_next_id
Definition Target.h:1692
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:741
lldb::SearchFilterSP GetSearchFilterForModule(const FileSpec *containingModule)
Definition Target.cpp:669
llvm::StringMapEntry< DummySignalValues > DummySignalElement
Definition Target.h:1597
std::recursive_mutex & GetAPIMutex()
Definition Target.cpp:5248
static llvm::StringRef GetStaticBroadcasterClass()
Definition Target.cpp:170
static FileSpecList GetDefaultDebugFileSearchPaths()
Definition Target.cpp:2798
void EnableAllowedBreakpoints()
Definition Target.cpp:1097
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:1998
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:1694
void RemoveAllowedBreakpoints()
Definition Target.cpp:1049
bool DisableAllWatchpoints(bool end_to_end=true)
Definition Target.cpp:1353
bool RunStopHooks(bool at_initial_stop=false)
Definition Target.cpp:3127
void ClearSectionLoadList()
Definition Target.cpp:5269
lldb::addr_t GetReasonableReadSize(const Address &addr)
Return a recommended size for memory reads at addr, optimizing for cache usage.
Definition Target.cpp:2201
lldb::PlatformSP m_platform_sp
The platform for this target.
Definition Target.h:1653
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:3279
Status Install(ProcessLaunchInfo *launch_info)
Definition Target.cpp:3287
lldb::PlatformSP GetPlatform()
Definition Target.h:1555
void NotifyModuleRemoved(const ModuleList &module_list, const lldb::ModuleSP &module_sp) override
Definition Target.cpp:1830
lldb::BreakpointSP CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal, const FileSpec &file_spec, bool request_hardware)
Definition Target.cpp:575
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:486
void RemoveAllBreakpoints(bool internal_also=false)
Definition Target.cpp:1058
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:469
static ArchSpec GetDefaultArchitecture()
Definition Target.cpp:2802
void ResetBreakpointHitCounts()
Resets the hit count of all breakpoints.
Definition Target.cpp:1161
const ModuleList & GetImages() const
Get accessor for the images for this process.
Definition Target.h:1025
const ArchSpec & GetArchitecture() const
Definition Target.h:1067
WatchpointList & GetWatchpointList()
Definition Target.h:818
@ eBroadcastBitWatchpointChanged
Definition Target.h:537
@ eBroadcastBitBreakpointChanged
Definition Target.h:534
bool EnableBreakpointByID(lldb::break_id_t break_id)
Definition Target.cpp:1142
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:2303
TargetStats m_stats
Definition Target.h:1719
bool IgnoreAllWatchpoints(uint32_t ignore_count)
Definition Target.cpp:1435
void AddBreakpoint(lldb::BreakpointSP breakpoint_sp, bool internal)
Definition Target.cpp:803
TypeSystemMap m_scratch_type_system_map
Definition Target.h:1683
void AddBreakpointName(std::unique_ptr< BreakpointName > bp_name)
Definition Target.cpp:853
SectionLoadHistory m_section_load_history
Definition Target.h:1667
void GetBreakpointNames(std::vector< std::string > &names)
Definition Target.cpp:920
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:175
size_t UnloadModuleSections(const lldb::ModuleSP &module_sp)
Definition Target.cpp:3356
bool m_valid
This records the last natural stop at which we ran a stop-hook.
Definition Target.h:1696
bool DisableWatchpointByID(lldb::watch_id_t watch_id)
Definition Target.cpp:1452
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:3794
lldb::WatchpointSP m_last_created_watchpoint
Definition Target.h:1676
Status CreateBreakpointsFromFile(const FileSpec &file, BreakpointIDList &new_bps)
Definition Target.cpp:1257
Debugger & m_debugger
Definition Target.h:1652
void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp)
Definition Target.cpp:363
void SetExecutableModule(lldb::ModuleSP &module_sp, LoadDependentFiles load_dependent_files=eLoadDependentsDefault)
Set the main executable module.
Definition Target.cpp:1573
lldb::StackFrameRecognizerManagerUP m_frame_recognizer_manager_up
Stores the frame recognizers of this target.
Definition Target.h:1707
lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language, const char *repl_options, bool can_create)
Definition Target.cpp:312
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:1664
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:3888
void SetPlatform(const lldb::PlatformSP &platform_sp)
Definition Target.h:1557
bool SetSectionLoadAddress(const lldb::SectionSP &section, lldb::addr_t load_addr, bool warn_multiple=false)
Definition Target.cpp:3326
Status Attach(ProcessAttachInfo &attach_info, Stream *stream)
Definition Target.cpp:3623
static void SetDefaultArchitecture(const ArchSpec &arch)
Definition Target.cpp:2806
lldb::BreakpointSP m_last_created_breakpoint
Definition Target.h:1674
void RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp, ConstString name)
Definition Target.cpp:893
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:211
bool EnableAllWatchpoints(bool end_to_end=true)
Definition Target.cpp:1380
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:1661
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:1793
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:4180
@ 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::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