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