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