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