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, Address(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.GetString());
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
1545void Target::ClearModules(bool delete_locations) {
1546 ModulesDidUnload(m_images, delete_locations);
1547 m_section_load_history.Clear();
1548 m_images.Clear();
1550}
1551
1553 // When a process exec's we need to know about it so we can do some cleanup.
1554 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1555 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1556}
1557
1559 LoadDependentFiles load_dependent_files) {
1561 &m_debugger);
1562 Log *log = GetLog(LLDBLog::Target);
1563 ClearModules(false);
1564
1565 if (executable_sp) {
1567 if (ProcessSP proc = GetProcessSP())
1568 pid = proc->GetID();
1569
1571 info->exec_mod = executable_sp;
1572 info->uuid = executable_sp->GetUUID();
1573 info->pid = pid;
1574 info->triple = executable_sp->GetArchitecture().GetTriple().getTriple();
1575 info->is_start_entry = true;
1576 });
1577
1578 helper.DispatchOnExit([&, pid](telemetry::ExecutableModuleInfo *info) {
1579 info->exec_mod = executable_sp;
1580 info->uuid = executable_sp->GetUUID();
1581 info->pid = pid;
1582 });
1583
1584 ElapsedTime elapsed(m_stats.GetCreateTime());
1585 LLDB_SCOPED_TIMERF("Target::SetExecutableModule (executable = '%s')",
1586 executable_sp->GetFileSpec().GetPath().c_str());
1587
1588 const bool notify = true;
1589 m_images.Append(executable_sp,
1590 notify); // The first image is our executable file
1591
1592 // If we haven't set an architecture yet, reset our architecture based on
1593 // what we found in the executable module.
1594 if (!m_arch.GetSpec().IsValid()) {
1595 m_arch = executable_sp->GetArchitecture();
1596 LLDB_LOG(log,
1597 "Target::SetExecutableModule setting architecture to {0} ({1}) "
1598 "based on executable file",
1599 m_arch.GetSpec().GetArchitectureName(),
1600 m_arch.GetSpec().GetTriple().getTriple());
1601 }
1602
1603 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1604 bool load_dependents = true;
1605 switch (load_dependent_files) {
1607 load_dependents = executable_sp->IsExecutable();
1608 break;
1609 case eLoadDependentsYes:
1610 load_dependents = true;
1611 break;
1612 case eLoadDependentsNo:
1613 load_dependents = false;
1614 break;
1615 }
1616
1617 if (executable_objfile && load_dependents) {
1618 // FileSpecList is not thread safe and needs to be synchronized.
1619 FileSpecList dependent_files;
1620 std::mutex dependent_files_mutex;
1621
1622 // ModuleList is thread safe.
1623 ModuleList added_modules;
1624
1625 auto GetDependentModules = [&](FileSpec dependent_file_spec) {
1626 FileSpec platform_dependent_file_spec;
1627 if (m_platform_sp)
1628 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1629 platform_dependent_file_spec);
1630 else
1631 platform_dependent_file_spec = dependent_file_spec;
1632
1633 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1634 ModuleSP image_module_sp(
1635 GetOrCreateModule(module_spec, false /* notify */));
1636 if (image_module_sp) {
1637 added_modules.AppendIfNeeded(image_module_sp, false);
1638 ObjectFile *objfile = image_module_sp->GetObjectFile();
1639 if (objfile) {
1640 // Create a local copy of the dependent file list so we don't have
1641 // to lock for the whole duration of GetDependentModules.
1642 FileSpecList dependent_files_copy;
1643 {
1644 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1645 dependent_files_copy = dependent_files;
1646 }
1647
1648 // Remember the size of the local copy so we can append only the
1649 // modules that have been added by GetDependentModules.
1650 const size_t previous_dependent_files =
1651 dependent_files_copy.GetSize();
1652
1653 objfile->GetDependentModules(dependent_files_copy);
1654
1655 {
1656 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1657 for (size_t i = previous_dependent_files;
1658 i < dependent_files_copy.GetSize(); ++i)
1659 dependent_files.AppendIfUnique(
1660 dependent_files_copy.GetFileSpecAtIndex(i));
1661 }
1662 }
1663 }
1664 };
1665
1666 executable_objfile->GetDependentModules(dependent_files);
1667
1668 llvm::ThreadPoolTaskGroup task_group(Debugger::GetThreadPool());
1669 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1670 // Process all currently known dependencies in parallel in the innermost
1671 // loop. This may create newly discovered dependencies to be appended to
1672 // dependent_files. We'll deal with these files during the next
1673 // iteration of the outermost loop.
1674 {
1675 std::lock_guard<std::mutex> guard(dependent_files_mutex);
1676 for (; i < dependent_files.GetSize(); i++)
1677 task_group.async(GetDependentModules,
1678 dependent_files.GetFileSpecAtIndex(i));
1679 }
1680 task_group.wait();
1681 }
1682 ModulesDidLoad(added_modules);
1683 }
1684 }
1685}
1686
1687bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform,
1688 bool merge) {
1689 Log *log = GetLog(LLDBLog::Target);
1690 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1691 bool replace_local_arch = true;
1692 bool compatible_local_arch = false;
1693 ArchSpec other(arch_spec);
1694
1695 // Changing the architecture might mean that the currently selected platform
1696 // isn't compatible. Set the platform correctly if we are asked to do so,
1697 // otherwise assume the user will set the platform manually.
1698 if (set_platform) {
1699 if (other.IsValid()) {
1700 auto platform_sp = GetPlatform();
1701 if (!platform_sp || !platform_sp->IsCompatibleArchitecture(
1702 other, {}, ArchSpec::CompatibleMatch, nullptr)) {
1703 ArchSpec platform_arch;
1704 if (PlatformSP arch_platform_sp =
1705 GetDebugger().GetPlatformList().GetOrCreate(other, {},
1706 &platform_arch)) {
1707 arch_platform_sp->SetLocateModuleCallback(
1708 platform_sp->GetLocateModuleCallback());
1709 SetPlatform(arch_platform_sp);
1710 if (platform_arch.IsValid())
1711 other = platform_arch;
1712 }
1713 }
1714 }
1715 }
1716
1717 if (!missing_local_arch) {
1718 if (merge && m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1719 other.MergeFrom(m_arch.GetSpec());
1720
1721 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1722 compatible_local_arch = true;
1723
1724 if (m_arch.GetSpec().GetTriple() == other.GetTriple())
1725 replace_local_arch = false;
1726 }
1727 }
1728 }
1729
1730 if (compatible_local_arch || missing_local_arch) {
1731 // If we haven't got a valid arch spec, or the architectures are compatible
1732 // update the architecture, unless the one we already have is more
1733 // specified
1734 if (replace_local_arch)
1735 m_arch = other;
1736 LLDB_LOG(log,
1737 "Target::SetArchitecture merging compatible arch; arch "
1738 "is now {0} ({1})",
1739 m_arch.GetSpec().GetArchitectureName(),
1740 m_arch.GetSpec().GetTriple().getTriple());
1741 return true;
1742 }
1743
1744 // If we have an executable file, try to reset the executable to the desired
1745 // architecture
1746 LLDB_LOGF(
1747 log,
1748 "Target::SetArchitecture changing architecture to %s (%s) from %s (%s)",
1749 arch_spec.GetArchitectureName(),
1750 arch_spec.GetTriple().getTriple().c_str(),
1751 m_arch.GetSpec().GetArchitectureName(),
1752 m_arch.GetSpec().GetTriple().getTriple().c_str());
1753 m_arch = other;
1754 ModuleSP executable_sp = GetExecutableModule();
1755
1756 ClearModules(true);
1757 // Need to do something about unsetting breakpoints.
1758
1759 if (executable_sp) {
1760 LLDB_LOGF(log,
1761 "Target::SetArchitecture Trying to select executable file "
1762 "architecture %s (%s)",
1763 arch_spec.GetArchitectureName(),
1764 arch_spec.GetTriple().getTriple().c_str());
1765 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1766 module_spec.SetTarget(shared_from_this());
1767 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1768 nullptr, nullptr);
1769
1770 if (!error.Fail() && executable_sp) {
1772 return true;
1773 }
1774 }
1775 return false;
1776}
1777
1778bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1779 Log *log = GetLog(LLDBLog::Target);
1780 if (arch_spec.IsValid()) {
1781 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1782 // The current target arch is compatible with "arch_spec", see if we can
1783 // improve our current architecture using bits from "arch_spec"
1784
1785 LLDB_LOGF(log,
1786 "Target::MergeArchitecture target has arch %s, merging with "
1787 "arch %s",
1788 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1789 arch_spec.GetTriple().getTriple().c_str());
1790
1791 // Merge bits from arch_spec into "merged_arch" and set our architecture
1792 ArchSpec merged_arch(m_arch.GetSpec());
1793 merged_arch.MergeFrom(arch_spec);
1794 return SetArchitecture(merged_arch);
1795 } else {
1796 // The new architecture is different, we just need to replace it
1797 return SetArchitecture(arch_spec);
1798 }
1799 }
1800 return false;
1801}
1802
1803void Target::NotifyWillClearList(const ModuleList &module_list) {}
1804
1806 const ModuleSP &module_sp) {
1807 // A module is being added to this target for the first time
1808 if (m_valid) {
1809 ModuleList my_module_list;
1810 my_module_list.Append(module_sp);
1811 ModulesDidLoad(my_module_list);
1812 }
1813}
1814
1816 const ModuleSP &module_sp) {
1817 // A module is being removed from this target.
1818 if (m_valid) {
1819 ModuleList my_module_list;
1820 my_module_list.Append(module_sp);
1821 ModulesDidUnload(my_module_list, false);
1822 }
1823}
1824
1826 const ModuleSP &old_module_sp,
1827 const ModuleSP &new_module_sp) {
1828 // A module is replacing an already added module
1829 if (m_valid) {
1830 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1831 new_module_sp);
1832 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1833 old_module_sp, new_module_sp);
1834 }
1835}
1836
1838 ModulesDidUnload(module_list, false);
1839}
1840
1842 if (GetPreloadSymbols())
1844
1845 const size_t num_images = module_list.GetSize();
1846 if (m_valid && num_images) {
1847 std::list<Status> errors;
1848 module_list.LoadScriptingResourcesInTarget(this, errors);
1849 for (const auto &err : errors)
1850 GetDebugger().GetAsyncErrorStream()->PutCString(err.AsCString());
1851
1852 for (size_t idx = 0; idx < num_images; ++idx) {
1853 ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1854 LoadTypeSummariesForModule(module_sp);
1855 LoadFormattersForModule(module_sp);
1856 }
1857 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1858 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1859 if (m_process_sp) {
1860 m_process_sp->ModulesDidLoad(module_list);
1861 }
1862 auto data_sp =
1863 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1865 }
1866}
1867
1869 if (m_valid && module_list.GetSize()) {
1870 if (m_process_sp) {
1871 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1872 runtime->SymbolsDidLoad(module_list);
1873 }
1874 }
1875
1876 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1877 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1878 auto data_sp =
1879 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1881 }
1882}
1883
1884void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1885 if (m_valid && module_list.GetSize()) {
1886 UnloadModuleSections(module_list);
1887 auto data_sp =
1888 std::make_shared<TargetEventData>(shared_from_this(), module_list);
1890 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1891 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1892 delete_locations);
1893
1894 // If a module was torn down it will have torn down the 'TypeSystemClang's
1895 // that we used as source 'ASTContext's for the persistent variables in
1896 // the current target. Those would now be unsafe to access because the
1897 // 'DeclOrigin' are now possibly stale. Thus clear all persistent
1898 // variables. We only want to flush 'TypeSystem's if the module being
1899 // unloaded was capable of describing a source type. JITted module unloads
1900 // happen frequently for Objective-C utility functions or the REPL and rely
1901 // on the persistent variables to stick around.
1902 const bool should_flush_type_systems =
1903 module_list.AnyOf([](lldb_private::Module &module) {
1904 auto *object_file = module.GetObjectFile();
1905
1906 if (!object_file)
1907 return false;
1908
1909 auto type = object_file->GetType();
1910
1911 // eTypeExecutable: when debugged binary was rebuilt
1912 // eTypeSharedLibrary: if dylib was re-loaded
1913 return module.FileHasChanged() &&
1914 (type == ObjectFile::eTypeObjectFile ||
1915 type == ObjectFile::eTypeExecutable ||
1916 type == ObjectFile::eTypeSharedLibrary);
1917 });
1918
1919 if (should_flush_type_systems)
1921 }
1922}
1923
1925 const FileSpec &module_file_spec) {
1927 ModuleList matchingModules;
1928 ModuleSpec module_spec(module_file_spec);
1929 GetImages().FindModules(module_spec, matchingModules);
1930 size_t num_modules = matchingModules.GetSize();
1931
1932 // If there is more than one module for this file spec, only
1933 // return true if ALL the modules are on the black list.
1934 if (num_modules > 0) {
1935 for (size_t i = 0; i < num_modules; i++) {
1937 matchingModules.GetModuleAtIndex(i)))
1938 return false;
1939 }
1940 return true;
1941 }
1942 }
1943 return false;
1944}
1945
1947 const lldb::ModuleSP &module_sp) {
1949 if (m_platform_sp)
1950 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1951 module_sp);
1952 }
1953 return false;
1954}
1955
1956size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1957 size_t dst_len, Status &error) {
1958 SectionSP section_sp(addr.GetSection());
1959 if (section_sp) {
1960 // If the contents of this section are encrypted, the on-disk file is
1961 // unusable. Read only from live memory.
1962 if (section_sp->IsEncrypted()) {
1963 error = Status::FromErrorString("section is encrypted");
1964 return 0;
1965 }
1966 ModuleSP module_sp(section_sp->GetModule());
1967 if (module_sp) {
1968 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1969 if (objfile) {
1970 size_t bytes_read = objfile->ReadSectionData(
1971 section_sp.get(), addr.GetOffset(), dst, dst_len);
1972 if (bytes_read > 0)
1973 return bytes_read;
1974 else
1976 "error reading data from section %s",
1977 section_sp->GetName().GetCString());
1978 } else
1979 error = Status::FromErrorString("address isn't from a object file");
1980 } else
1981 error = Status::FromErrorString("address isn't in a module");
1982 } else
1984 "address doesn't contain a section that points to a "
1985 "section in a object file");
1986
1987 return 0;
1988}
1989
1990size_t Target::ReadMemory(const Address &addr, void *dst, size_t dst_len,
1991 Status &error, bool force_live_memory,
1992 lldb::addr_t *load_addr_ptr,
1993 bool *did_read_live_memory) {
1994 error.Clear();
1995 if (did_read_live_memory)
1996 *did_read_live_memory = false;
1997
1998 Address fixed_addr = addr;
1999 if (ProcessIsValid())
2000 if (const ABISP &abi = m_process_sp->GetABI())
2001 fixed_addr.SetLoadAddress(abi->FixAnyAddress(addr.GetLoadAddress(this)),
2002 this);
2003
2004 // if we end up reading this from process memory, we will fill this with the
2005 // actual load address
2006 if (load_addr_ptr)
2007 *load_addr_ptr = LLDB_INVALID_ADDRESS;
2008
2009 size_t bytes_read = 0;
2010
2011 addr_t load_addr = LLDB_INVALID_ADDRESS;
2012 addr_t file_addr = LLDB_INVALID_ADDRESS;
2013 Address resolved_addr;
2014 if (!fixed_addr.IsSectionOffset()) {
2015 SectionLoadList &section_load_list = GetSectionLoadList();
2016 if (section_load_list.IsEmpty()) {
2017 // No sections are loaded, so we must assume we are not running yet and
2018 // anything we are given is a file address.
2019 file_addr =
2020 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
2021 // its offset is the file address
2022 m_images.ResolveFileAddress(file_addr, resolved_addr);
2023 } else {
2024 // We have at least one section loaded. This can be because we have
2025 // manually loaded some sections with "target modules load ..." or
2026 // because we have a live process that has sections loaded through
2027 // the dynamic loader
2028 load_addr =
2029 fixed_addr.GetOffset(); // "fixed_addr" doesn't have a section, so
2030 // its offset is the load address
2031 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
2032 }
2033 }
2034 if (!resolved_addr.IsValid())
2035 resolved_addr = fixed_addr;
2036
2037 // If we read from the file cache but can't get as many bytes as requested,
2038 // we keep the result around in this buffer, in case this result is the
2039 // best we can do.
2040 std::unique_ptr<uint8_t[]> file_cache_read_buffer;
2041 size_t file_cache_bytes_read = 0;
2042
2043 // Read from file cache if read-only section.
2044 if (!force_live_memory && resolved_addr.IsSectionOffset()) {
2045 SectionSP section_sp(resolved_addr.GetSection());
2046 if (section_sp) {
2047 auto permissions = Flags(section_sp->GetPermissions());
2048 bool is_readonly = !permissions.Test(ePermissionsWritable) &&
2049 permissions.Test(ePermissionsReadable);
2050 if (is_readonly) {
2051 file_cache_bytes_read =
2052 ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2053 if (file_cache_bytes_read == dst_len)
2054 return file_cache_bytes_read;
2055 else if (file_cache_bytes_read > 0) {
2056 file_cache_read_buffer =
2057 std::make_unique<uint8_t[]>(file_cache_bytes_read);
2058 std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read);
2059 }
2060 }
2061 }
2062 }
2063
2064 if (ProcessIsValid()) {
2065 if (load_addr == LLDB_INVALID_ADDRESS)
2066 load_addr = resolved_addr.GetLoadAddress(this);
2067
2068 if (load_addr == LLDB_INVALID_ADDRESS) {
2069 ModuleSP addr_module_sp(resolved_addr.GetModule());
2070 if (addr_module_sp && addr_module_sp->GetFileSpec())
2072 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
2073 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
2074 else
2076 "0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
2077 } else {
2078 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
2079 if (bytes_read != dst_len) {
2080 if (error.Success()) {
2081 if (bytes_read == 0)
2083 "read memory from 0x%" PRIx64 " failed", load_addr);
2084 else
2086 "only %" PRIu64 " of %" PRIu64
2087 " bytes were read from memory at 0x%" PRIx64,
2088 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
2089 }
2090 }
2091 if (bytes_read) {
2092 if (load_addr_ptr)
2093 *load_addr_ptr = load_addr;
2094 if (did_read_live_memory)
2095 *did_read_live_memory = true;
2096 return bytes_read;
2097 }
2098 }
2099 }
2100
2101 if (file_cache_read_buffer && file_cache_bytes_read > 0) {
2102 // Reading from the process failed. If we've previously succeeded in reading
2103 // something from the file cache, then copy that over and return that.
2104 std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read);
2105 return file_cache_bytes_read;
2106 }
2107
2108 if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) {
2109 // If we didn't already try and read from the object file cache, then try
2110 // it after failing to read from the process.
2111 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
2112 }
2113 return 0;
2114}
2115
2116size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
2117 Status &error, bool force_live_memory) {
2118 char buf[256];
2119 out_str.clear();
2120 addr_t curr_addr = addr.GetLoadAddress(this);
2121 Address address(addr);
2122 while (true) {
2123 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error,
2124 force_live_memory);
2125 if (length == 0)
2126 break;
2127 out_str.append(buf, length);
2128 // If we got "length - 1" bytes, we didn't get the whole C string, we need
2129 // to read some more characters
2130 if (length == sizeof(buf) - 1)
2131 curr_addr += length;
2132 else
2133 break;
2134 address = Address(curr_addr);
2135 }
2136 return out_str.size();
2137}
2138
2139size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
2140 size_t dst_max_len, Status &result_error,
2141 bool force_live_memory) {
2142 size_t total_cstr_len = 0;
2143 if (dst && dst_max_len) {
2144 result_error.Clear();
2145 // NULL out everything just to be safe
2146 memset(dst, 0, dst_max_len);
2147 addr_t curr_addr = addr.GetLoadAddress(this);
2148 Address address(addr);
2149
2150 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
2151 // this really needs to be tied to the memory cache subsystem's cache line
2152 // size, so leave this as a fixed constant.
2153 const size_t cache_line_size = 512;
2154
2155 size_t bytes_left = dst_max_len - 1;
2156 char *curr_dst = dst;
2157
2158 while (bytes_left > 0) {
2159 addr_t cache_line_bytes_left =
2160 cache_line_size - (curr_addr % cache_line_size);
2161 addr_t bytes_to_read =
2162 std::min<addr_t>(bytes_left, cache_line_bytes_left);
2163 Status error;
2164 size_t bytes_read = ReadMemory(address, curr_dst, bytes_to_read, error,
2165 force_live_memory);
2166
2167 if (bytes_read == 0) {
2168 result_error = std::move(error);
2169 dst[total_cstr_len] = '\0';
2170 break;
2171 }
2172 const size_t len = strlen(curr_dst);
2173
2174 total_cstr_len += len;
2175
2176 if (len < bytes_to_read)
2177 break;
2178
2179 curr_dst += bytes_read;
2180 curr_addr += bytes_read;
2181 bytes_left -= bytes_read;
2182 address = Address(curr_addr);
2183 }
2184 } else {
2185 if (dst == nullptr)
2186 result_error = Status::FromErrorString("invalid arguments");
2187 else
2188 result_error.Clear();
2189 }
2190 return total_cstr_len;
2191}
2192
2194 addr_t load_addr = addr.GetLoadAddress(this);
2195 if (load_addr != LLDB_INVALID_ADDRESS && m_process_sp) {
2196 // Avoid crossing cache line boundaries.
2197 addr_t cache_line_size = m_process_sp->GetMemoryCacheLineSize();
2198 return cache_line_size - (load_addr % cache_line_size);
2199 }
2200
2201 // The read is going to go to the file cache, so we can just pick a largish
2202 // value.
2203 return 0x1000;
2204}
2205
2206size_t Target::ReadStringFromMemory(const Address &addr, char *dst,
2207 size_t max_bytes, Status &error,
2208 size_t type_width, bool force_live_memory) {
2209 if (!dst || !max_bytes || !type_width || max_bytes < type_width)
2210 return 0;
2211
2212 size_t total_bytes_read = 0;
2213
2214 // Ensure a null terminator independent of the number of bytes that is
2215 // read.
2216 memset(dst, 0, max_bytes);
2217 size_t bytes_left = max_bytes - type_width;
2218
2219 const char terminator[4] = {'\0', '\0', '\0', '\0'};
2220 assert(sizeof(terminator) >= type_width && "Attempting to validate a "
2221 "string with more than 4 bytes "
2222 "per character!");
2223
2224 Address address = addr;
2225 char *curr_dst = dst;
2226
2227 error.Clear();
2228 while (bytes_left > 0 && error.Success()) {
2229 addr_t bytes_to_read =
2230 std::min<addr_t>(bytes_left, GetReasonableReadSize(address));
2231 size_t bytes_read =
2232 ReadMemory(address, curr_dst, bytes_to_read, error, force_live_memory);
2233
2234 if (bytes_read == 0)
2235 break;
2236
2237 // Search for a null terminator of correct size and alignment in
2238 // bytes_read
2239 size_t aligned_start = total_bytes_read - total_bytes_read % type_width;
2240 for (size_t i = aligned_start;
2241 i + type_width <= total_bytes_read + bytes_read; i += type_width)
2242 if (::memcmp(&dst[i], terminator, type_width) == 0) {
2243 error.Clear();
2244 return i;
2245 }
2246
2247 total_bytes_read += bytes_read;
2248 curr_dst += bytes_read;
2249 address.Slide(bytes_read);
2250 bytes_left -= bytes_read;
2251 }
2252 return total_bytes_read;
2253}
2254
2255size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
2256 bool is_signed, Scalar &scalar,
2257 Status &error,
2258 bool force_live_memory) {
2259 uint64_t uval;
2260
2261 if (byte_size <= sizeof(uval)) {
2262 size_t bytes_read =
2263 ReadMemory(addr, &uval, byte_size, error, force_live_memory);
2264 if (bytes_read == byte_size) {
2265 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
2266 m_arch.GetSpec().GetAddressByteSize());
2267 lldb::offset_t offset = 0;
2268 if (byte_size <= 4)
2269 scalar = data.GetMaxU32(&offset, byte_size);
2270 else
2271 scalar = data.GetMaxU64(&offset, byte_size);
2272
2273 if (is_signed) {
2274 scalar.MakeSigned();
2275 scalar.SignExtend(byte_size * 8);
2276 }
2277 return bytes_read;
2278 }
2279 } else {
2281 "byte size of %u is too large for integer scalar type", byte_size);
2282 }
2283 return 0;
2284}
2285
2287 size_t integer_byte_size,
2288 int64_t fail_value, Status &error,
2289 bool force_live_memory) {
2290 Scalar scalar;
2291 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, true, scalar, error,
2292 force_live_memory))
2293 return scalar.SLongLong(fail_value);
2294 return fail_value;
2295}
2296
2298 size_t integer_byte_size,
2299 uint64_t fail_value, Status &error,
2300 bool force_live_memory) {
2301 Scalar scalar;
2302 if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
2303 force_live_memory))
2304 return scalar.ULongLong(fail_value);
2305 return fail_value;
2306}
2307
2309 Address &pointer_addr,
2310 bool force_live_memory) {
2311 Scalar scalar;
2312 if (ReadScalarIntegerFromMemory(addr, m_arch.GetSpec().GetAddressByteSize(),
2313 false, scalar, error, force_live_memory)) {
2314 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
2315 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
2316 SectionLoadList &section_load_list = GetSectionLoadList();
2317 if (section_load_list.IsEmpty()) {
2318 // No sections are loaded, so we must assume we are not running yet and
2319 // anything we are given is a file address.
2320 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
2321 } else {
2322 // We have at least one section loaded. This can be because we have
2323 // manually loaded some sections with "target modules load ..." or
2324 // because we have a live process that has sections loaded through
2325 // the dynamic loader
2326 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
2327 }
2328 // We weren't able to resolve the pointer value, so just return an
2329 // address with no section
2330 if (!pointer_addr.IsValid())
2331 pointer_addr.SetOffset(pointer_vm_addr);
2332 return true;
2333 }
2334 }
2335 return false;
2336}
2337
2339 bool notify, Status *error_ptr) {
2340 ModuleSP module_sp;
2341
2342 Status error;
2343
2344 // Apply any remappings specified in target.object-map:
2345 ModuleSpec module_spec(orig_module_spec);
2346 module_spec.SetTarget(shared_from_this());
2347 PathMappingList &obj_mapping = GetObjectPathMap();
2348 if (std::optional<FileSpec> remapped_obj_file =
2349 obj_mapping.RemapPath(orig_module_spec.GetFileSpec().GetPath(),
2350 true /* only_if_exists */)) {
2351 module_spec.GetFileSpec().SetPath(remapped_obj_file->GetPath());
2352 }
2353
2354 // First see if we already have this module in our module list. If we do,
2355 // then we're done, we don't need to consult the shared modules list. But
2356 // only do this if we are passed a UUID.
2357
2358 if (module_spec.GetUUID().IsValid())
2359 module_sp = m_images.FindFirstModule(module_spec);
2360
2361 if (!module_sp) {
2362 llvm::SmallVector<ModuleSP, 1>
2363 old_modules; // This will get filled in if we have a new version
2364 // of the library
2365 bool did_create_module = false;
2366 FileSpecList search_paths = GetExecutableSearchPaths();
2367 FileSpec symbol_file_spec;
2368
2369 // Call locate module callback if set. This allows users to implement their
2370 // own module cache system. For example, to leverage build system artifacts,
2371 // to bypass pulling files from remote platform, or to search symbol files
2372 // from symbol servers.
2373 if (m_platform_sp)
2374 m_platform_sp->CallLocateModuleCallbackIfSet(
2375 module_spec, module_sp, symbol_file_spec, &did_create_module);
2376
2377 // The result of this CallLocateModuleCallbackIfSet is one of the following.
2378 // 1. module_sp:loaded, symbol_file_spec:set
2379 // The callback found a module file and a symbol file for the
2380 // module_spec. We will call module_sp->SetSymbolFileFileSpec with
2381 // the symbol_file_spec later.
2382 // 2. module_sp:loaded, symbol_file_spec:empty
2383 // The callback only found a module file for the module_spec.
2384 // 3. module_sp:empty, symbol_file_spec:set
2385 // The callback only found a symbol file for the module. We continue
2386 // to find a module file for this module_spec and we will call
2387 // module_sp->SetSymbolFileFileSpec with the symbol_file_spec later.
2388 // 4. module_sp:empty, symbol_file_spec:empty
2389 // Platform does not exist, the callback is not set, the callback did
2390 // not find any module files nor any symbol files, the callback failed,
2391 // or something went wrong. We continue to find a module file for this
2392 // module_spec.
2393
2394 if (!module_sp) {
2395 // If there are image search path entries, try to use them to acquire a
2396 // suitable image.
2397 if (m_image_search_paths.GetSize()) {
2398 ModuleSpec transformed_spec(module_spec);
2399 ConstString transformed_dir;
2400 if (m_image_search_paths.RemapPath(
2401 module_spec.GetFileSpec().GetDirectory(), transformed_dir)) {
2402 transformed_spec.GetFileSpec().SetDirectory(transformed_dir);
2403 transformed_spec.GetFileSpec().SetFilename(
2404 module_spec.GetFileSpec().GetFilename());
2405 transformed_spec.SetTarget(shared_from_this());
2406 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2407 &old_modules, &did_create_module);
2408 }
2409 }
2410 }
2411
2412 if (!module_sp) {
2413 // If we have a UUID, we can check our global shared module list in case
2414 // we already have it. If we don't have a valid UUID, then we can't since
2415 // the path in "module_spec" will be a platform path, and we will need to
2416 // let the platform find that file. For example, we could be asking for
2417 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2418 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2419 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2420 // cache.
2421 if (module_spec.GetUUID().IsValid()) {
2422 // We have a UUID, it is OK to check the global module list...
2423 error = ModuleList::GetSharedModule(module_spec, module_sp,
2424 &old_modules, &did_create_module);
2425 }
2426
2427 if (!module_sp) {
2428 // The platform is responsible for finding and caching an appropriate
2429 // module in the shared module cache.
2430 if (m_platform_sp) {
2431 error = m_platform_sp->GetSharedModule(
2432 module_spec, m_process_sp.get(), module_sp, &old_modules,
2433 &did_create_module);
2434 } else {
2435 error = Status::FromErrorString("no platform is currently set");
2436 }
2437 }
2438 }
2439
2440 // We found a module that wasn't in our target list. Let's make sure that
2441 // there wasn't an equivalent module in the list already, and if there was,
2442 // let's remove it.
2443 if (module_sp) {
2444 ObjectFile *objfile = module_sp->GetObjectFile();
2445 if (objfile) {
2446 switch (objfile->GetType()) {
2447 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2448 /// a program's execution state
2449 case ObjectFile::eTypeExecutable: /// A normal executable
2450 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2451 /// executable
2452 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2453 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2454 /// used during execution
2455 break;
2456 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2457 /// debug information
2458 if (error_ptr)
2459 *error_ptr = Status::FromErrorString(
2460 "debug info files aren't valid target "
2461 "modules, please specify an executable");
2462 return ModuleSP();
2463 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2464 /// against but not used for
2465 /// execution
2466 if (error_ptr)
2467 *error_ptr = Status::FromErrorString(
2468 "stub libraries aren't valid target "
2469 "modules, please specify an executable");
2470 return ModuleSP();
2471 default:
2472 if (error_ptr)
2473 *error_ptr = Status::FromErrorString(
2474 "unsupported file type, please specify an executable");
2475 return ModuleSP();
2476 }
2477 // GetSharedModule is not guaranteed to find the old shared module, for
2478 // instance in the common case where you pass in the UUID, it is only
2479 // going to find the one module matching the UUID. In fact, it has no
2480 // good way to know what the "old module" relevant to this target is,
2481 // since there might be many copies of a module with this file spec in
2482 // various running debug sessions, but only one of them will belong to
2483 // this target. So let's remove the UUID from the module list, and look
2484 // in the target's module list. Only do this if there is SOMETHING else
2485 // in the module spec...
2486 if (module_spec.GetUUID().IsValid() &&
2487 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2488 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2489 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2490 module_spec_copy.GetUUID().Clear();
2491
2492 ModuleList found_modules;
2493 m_images.FindModules(module_spec_copy, found_modules);
2494 found_modules.ForEach([&](const ModuleSP &found_module) {
2495 old_modules.push_back(found_module);
2497 });
2498 }
2499
2500 // If the locate module callback had found a symbol file, set it to the
2501 // module_sp before preloading symbols.
2502 if (symbol_file_spec)
2503 module_sp->SetSymbolFileFileSpec(symbol_file_spec);
2504
2505 llvm::SmallVector<ModuleSP, 1> replaced_modules;
2506 for (ModuleSP &old_module_sp : old_modules) {
2507 if (m_images.GetIndexForModule(old_module_sp.get()) !=
2509 if (replaced_modules.empty())
2510 m_images.ReplaceModule(old_module_sp, module_sp);
2511 else
2512 m_images.Remove(old_module_sp);
2513
2514 replaced_modules.push_back(std::move(old_module_sp));
2515 }
2516 }
2517
2518 if (replaced_modules.size() > 1) {
2519 // The same new module replaced multiple old modules
2520 // simultaneously. It's not clear this should ever
2521 // happen (if we always replace old modules as we add
2522 // new ones, presumably we should never have more than
2523 // one old one). If there are legitimate cases where
2524 // this happens, then the ModuleList::Notifier interface
2525 // may need to be adjusted to allow reporting this.
2526 // In the meantime, just log that this has happened; just
2527 // above we called ReplaceModule on the first one, and Remove
2528 // on the rest.
2530 StreamString message;
2531 auto dump = [&message](Module &dump_module) -> void {
2532 UUID dump_uuid = dump_module.GetUUID();
2533
2534 message << '[';
2535 dump_module.GetDescription(message.AsRawOstream());
2536 message << " (uuid ";
2537
2538 if (dump_uuid.IsValid())
2539 dump_uuid.Dump(message);
2540 else
2541 message << "not specified";
2542
2543 message << ")]";
2544 };
2545
2546 message << "New module ";
2547 dump(*module_sp);
2548 message.AsRawOstream()
2549 << llvm::formatv(" simultaneously replaced {0} old modules: ",
2550 replaced_modules.size());
2551 for (ModuleSP &replaced_module_sp : replaced_modules)
2552 dump(*replaced_module_sp);
2553
2554 log->PutString(message.GetString());
2555 }
2556 }
2557
2558 if (replaced_modules.empty())
2559 m_images.Append(module_sp, notify);
2560
2561 for (ModuleSP &old_module_sp : replaced_modules) {
2562 auto old_module_wp = old_module_sp->weak_from_this();
2563 old_module_sp.reset();
2565 }
2566 } else
2567 module_sp.reset();
2568 }
2569 }
2570 if (error_ptr)
2571 *error_ptr = std::move(error);
2572 return module_sp;
2573}
2574
2575TargetSP Target::CalculateTarget() { return shared_from_this(); }
2576
2578
2580
2582
2584 exe_ctx.Clear();
2585 exe_ctx.SetTargetPtr(this);
2586}
2587
2591
2593 void *baton) {
2594 Target *target = (Target *)baton;
2595 ModuleSP exe_module_sp(target->GetExecutableModule());
2596 if (exe_module_sp)
2597 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2598}
2599
2600llvm::Expected<lldb::TypeSystemSP>
2602 bool create_on_demand) {
2603 if (!m_valid)
2604 return llvm::createStringError("Invalid Target");
2605
2606 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2607 // assembly code
2608 || language == eLanguageTypeAssembly ||
2609 language == eLanguageTypeUnknown) {
2610 LanguageSet languages_for_expressions =
2612
2613 if (languages_for_expressions[eLanguageTypeC]) {
2614 language = eLanguageTypeC; // LLDB's default. Override by setting the
2615 // target language.
2616 } else {
2617 if (languages_for_expressions.Empty())
2618 return llvm::createStringError(
2619 "No expression support for any languages");
2620 language = (LanguageType)languages_for_expressions.bitvector.find_first();
2621 }
2622 }
2623
2624 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2625 create_on_demand);
2626}
2627
2629 const lldb_private::RegisterFlags &flags,
2630 uint32_t byte_size) {
2634 return m_register_type_builder_sp->GetRegisterType(name, flags, byte_size);
2635}
2636
2637std::vector<lldb::TypeSystemSP>
2638Target::GetScratchTypeSystems(bool create_on_demand) {
2639 if (!m_valid)
2640 return {};
2641
2642 // Some TypeSystem instances are associated with several LanguageTypes so
2643 // they will show up several times in the loop below. The SetVector filters
2644 // out all duplicates as they serve no use for the caller.
2645 std::vector<lldb::TypeSystemSP> scratch_type_systems;
2646
2647 LanguageSet languages_for_expressions =
2649
2650 for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2651 auto language = (LanguageType)bit;
2652 auto type_system_or_err =
2653 GetScratchTypeSystemForLanguage(language, create_on_demand);
2654 if (!type_system_or_err)
2656 GetLog(LLDBLog::Target), type_system_or_err.takeError(),
2657 "Language '{1}' has expression support but no scratch type "
2658 "system available: {0}",
2660 else
2661 if (auto ts = *type_system_or_err)
2662 scratch_type_systems.push_back(ts);
2663 }
2664
2665 std::sort(scratch_type_systems.begin(), scratch_type_systems.end());
2666 scratch_type_systems.erase(llvm::unique(scratch_type_systems),
2667 scratch_type_systems.end());
2668 return scratch_type_systems;
2669}
2670
2673 auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2674
2675 if (auto err = type_system_or_err.takeError()) {
2677 GetLog(LLDBLog::Target), std::move(err),
2678 "Unable to get persistent expression state for language {1}: {0}",
2680 return nullptr;
2681 }
2682
2683 if (auto ts = *type_system_or_err)
2684 return ts->GetPersistentExpressionState();
2685
2687 "Unable to get persistent expression state for language {1}: {0}",
2689 return nullptr;
2690}
2691
2693 llvm::StringRef expr, llvm::StringRef prefix, SourceLanguage language,
2694 Expression::ResultType desired_type,
2695 const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2696 Status &error) {
2697 auto type_system_or_err =
2699 if (auto err = type_system_or_err.takeError()) {
2701 "Could not find type system for language %s: %s",
2703 llvm::toString(std::move(err)).c_str());
2704 return nullptr;
2705 }
2706
2707 auto ts = *type_system_or_err;
2708 if (!ts) {
2710 "Type system for language %s is no longer live",
2711 language.GetDescription().data());
2712 return nullptr;
2713 }
2714
2715 auto *user_expr = ts->GetUserExpression(expr, prefix, language, desired_type,
2716 options, ctx_obj);
2717 if (!user_expr)
2719 "Could not create an expression for language %s",
2720 language.GetDescription().data());
2721
2722 return user_expr;
2723}
2724
2726 lldb::LanguageType language, const CompilerType &return_type,
2727 const Address &function_address, const ValueList &arg_value_list,
2728 const char *name, Status &error) {
2729 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2730 if (auto err = type_system_or_err.takeError()) {
2732 "Could not find type system for language %s: %s",
2734 llvm::toString(std::move(err)).c_str());
2735 return nullptr;
2736 }
2737 auto ts = *type_system_or_err;
2738 if (!ts) {
2740 "Type system for language %s is no longer live",
2742 return nullptr;
2743 }
2744 auto *persistent_fn = ts->GetFunctionCaller(return_type, function_address,
2745 arg_value_list, name);
2746 if (!persistent_fn)
2748 "Could not create an expression for language %s",
2750
2751 return persistent_fn;
2752}
2753
2754llvm::Expected<std::unique_ptr<UtilityFunction>>
2755Target::CreateUtilityFunction(std::string expression, std::string name,
2756 lldb::LanguageType language,
2757 ExecutionContext &exe_ctx) {
2758 auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2759 if (!type_system_or_err)
2760 return type_system_or_err.takeError();
2761 auto ts = *type_system_or_err;
2762 if (!ts)
2763 return llvm::createStringError(
2764 llvm::StringRef("Type system for language ") +
2766 llvm::StringRef(" is no longer live"));
2767 std::unique_ptr<UtilityFunction> utility_fn =
2768 ts->CreateUtilityFunction(std::move(expression), std::move(name));
2769 if (!utility_fn)
2770 return llvm::createStringError(
2771 llvm::StringRef("Could not create an expression for language") +
2773
2774 DiagnosticManager diagnostics;
2775 if (!utility_fn->Install(diagnostics, exe_ctx))
2776 return diagnostics.GetAsError(lldb::eExpressionSetupError,
2777 "Could not install utility function:");
2778
2779 return std::move(utility_fn);
2780}
2781
2783
2785
2789
2793
2797
2800 "setting target's default architecture to {0} ({1})",
2801 arch.GetArchitectureName(), arch.GetTriple().getTriple());
2803}
2804
2805llvm::Error Target::SetLabel(llvm::StringRef label) {
2806 size_t n = LLDB_INVALID_INDEX32;
2807 if (llvm::to_integer(label, n))
2808 return llvm::createStringError("Cannot use integer as target label.");
2809 TargetList &targets = GetDebugger().GetTargetList();
2810 for (size_t i = 0; i < targets.GetNumTargets(); i++) {
2811 TargetSP target_sp = targets.GetTargetAtIndex(i);
2812 if (target_sp && target_sp->GetLabel() == label) {
2813 return llvm::createStringErrorV(
2814 "Cannot use label '{0}' since it's set in target #{1}.", label, i);
2815 }
2816 }
2817
2818 m_label = label.str();
2819 return llvm::Error::success();
2820}
2821
2823 const SymbolContext *sc_ptr) {
2824 // The target can either exist in the "process" of ExecutionContext, or in
2825 // the "target_sp" member of SymbolContext. This accessor helper function
2826 // will get the target from one of these locations.
2827
2828 Target *target = nullptr;
2829 if (sc_ptr != nullptr)
2830 target = sc_ptr->target_sp.get();
2831 if (target == nullptr && exe_ctx_ptr)
2832 target = exe_ctx_ptr->GetTargetPtr();
2833 return target;
2834}
2835
2837 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2838 lldb::ValueObjectSP &result_valobj_sp,
2839 const EvaluateExpressionOptions &options, std::string *fixed_expression,
2840 ValueObject *ctx_obj) {
2841 result_valobj_sp.reset();
2842
2843 ExpressionResults execution_results = eExpressionSetupError;
2844
2845 if (expr.empty()) {
2846 m_stats.GetExpressionStats().NotifyFailure();
2847 return execution_results;
2848 }
2849
2850 // We shouldn't run stop hooks in expressions.
2851 bool old_suppress_value = m_suppress_stop_hooks;
2852 m_suppress_stop_hooks = true;
2853 llvm::scope_exit on_exit([this, old_suppress_value]() {
2854 m_suppress_stop_hooks = old_suppress_value;
2855 });
2856
2857 ExecutionContext exe_ctx;
2858
2859 if (exe_scope) {
2860 exe_scope->CalculateExecutionContext(exe_ctx);
2861 } else if (m_process_sp) {
2862 m_process_sp->CalculateExecutionContext(exe_ctx);
2863 } else {
2865 }
2866
2867 // Make sure we aren't just trying to see the value of a persistent variable
2868 // (something like "$0")
2869 // Only check for persistent variables the expression starts with a '$'
2870 lldb::ExpressionVariableSP persistent_var_sp;
2871 if (expr[0] == '$') {
2872 auto type_system_or_err =
2874 if (auto err = type_system_or_err.takeError()) {
2875 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2876 "Unable to get scratch type system");
2877 } else {
2878 auto ts = *type_system_or_err;
2879 if (!ts)
2880 LLDB_LOG_ERROR(GetLog(LLDBLog::Target), std::move(err),
2881 "Scratch type system is no longer live: {0}");
2882 else
2883 persistent_var_sp =
2884 ts->GetPersistentExpressionState()->GetVariable(expr);
2885 }
2886 }
2887 if (persistent_var_sp) {
2888 result_valobj_sp = persistent_var_sp->GetValueObject();
2889 execution_results = eExpressionCompleted;
2890 } else {
2891 // If this expression is being evaluated from inside a frame provider,
2892 // force single-thread execution. Resuming all threads while a provider
2893 // is mid-construction could cause unwanted process state changes.
2894 EvaluateExpressionOptions effective_options = options;
2895 if (ThreadSP thread_sp = exe_ctx.GetThreadSP()) {
2896 if (thread_sp->IsAnyProviderActive()) {
2897 effective_options.SetStopOthers(true);
2898 effective_options.SetTryAllThreads(false);
2899 }
2900 }
2901 llvm::StringRef prefix = GetExpressionPrefixContents();
2902 execution_results =
2903 UserExpression::Evaluate(exe_ctx, effective_options, expr, prefix,
2904 result_valobj_sp, fixed_expression, ctx_obj);
2905 }
2906
2907 if (execution_results == eExpressionCompleted)
2908 m_stats.GetExpressionStats().NotifySuccess();
2909 else
2910 m_stats.GetExpressionStats().NotifyFailure();
2911 return execution_results;
2912}
2913
2915 lldb::ExpressionVariableSP variable_sp;
2917 [name, &variable_sp](TypeSystemSP type_system) -> bool {
2918 auto ts = type_system.get();
2919 if (!ts)
2920 return true;
2921 if (PersistentExpressionState *persistent_state =
2922 ts->GetPersistentExpressionState()) {
2923 variable_sp = persistent_state->GetVariable(name);
2924
2925 if (variable_sp)
2926 return false; // Stop iterating the ForEach
2927 }
2928 return true; // Keep iterating the ForEach
2929 });
2930 return variable_sp;
2931}
2932
2935
2937 [name, &address](lldb::TypeSystemSP type_system) -> bool {
2938 auto ts = type_system.get();
2939 if (!ts)
2940 return true;
2941
2942 if (PersistentExpressionState *persistent_state =
2943 ts->GetPersistentExpressionState()) {
2944 address = persistent_state->LookupSymbol(name);
2945 if (address != LLDB_INVALID_ADDRESS)
2946 return false; // Stop iterating the ForEach
2947 }
2948 return true; // Keep iterating the ForEach
2949 });
2950 return address;
2951}
2952
2953llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2954 Module *exe_module = GetExecutableModulePointer();
2955
2956 // Try to find the entry point address in the primary executable.
2957 const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2958 if (has_primary_executable) {
2959 Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2960 if (entry_addr.IsValid())
2961 return entry_addr;
2962 }
2963
2964 const ModuleList &modules = GetImages();
2965 const size_t num_images = modules.GetSize();
2966 for (size_t idx = 0; idx < num_images; ++idx) {
2967 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2968 if (!module_sp || !module_sp->GetObjectFile())
2969 continue;
2970
2971 Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2972 if (entry_addr.IsValid())
2973 return entry_addr;
2974 }
2975
2976 // We haven't found the entry point address. Return an appropriate error.
2977 if (!has_primary_executable)
2978 return llvm::createStringError(
2979 "No primary executable found and could not find entry point address in "
2980 "any executable module");
2981
2982 return llvm::createStringError(
2983 "Could not find entry point address for primary executable module \"" +
2984 exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"");
2985}
2986
2988 AddressClass addr_class) const {
2989 auto arch_plugin = GetArchitecturePlugin();
2990 return arch_plugin
2991 ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2992 : load_addr;
2993}
2994
2996 AddressClass addr_class) const {
2997 auto arch_plugin = GetArchitecturePlugin();
2998 return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2999 : load_addr;
3000}
3001
3003 auto arch_plugin = GetArchitecturePlugin();
3004 return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
3005}
3006
3007llvm::Expected<lldb::DisassemblerSP>
3008Target::ReadInstructions(const Address &start_addr, uint32_t count,
3009 const char *flavor_string) {
3010 DataBufferHeap data(GetArchitecture().GetMaximumOpcodeByteSize() * count, 0);
3011 bool force_live_memory = true;
3014 const size_t bytes_read =
3015 ReadMemory(start_addr, data.GetBytes(), data.GetByteSize(), error,
3016 force_live_memory, &load_addr);
3017
3018 if (error.Fail())
3019 return llvm::createStringError(
3020 error.AsCString("Target::ReadInstructions failed to read memory at %s"),
3021 start_addr.GetLoadAddress(this));
3022
3023 const bool data_from_file = load_addr == LLDB_INVALID_ADDRESS;
3024 if (!flavor_string || flavor_string[0] == '\0') {
3025 // FIXME - we don't have the mechanism in place to do per-architecture
3026 // settings. But since we know that for now we only support flavors on
3027 // x86 & x86_64,
3028 const llvm::Triple::ArchType arch = GetArchitecture().GetTriple().getArch();
3029 if (arch == llvm::Triple::x86 || arch == llvm::Triple::x86_64)
3030 flavor_string = GetDisassemblyFlavor();
3031 }
3032
3034 GetArchitecture(), nullptr, flavor_string, GetDisassemblyCPU(),
3035 GetDisassemblyFeatures(), start_addr, data.GetBytes(), bytes_read, count,
3036 data_from_file);
3037}
3038
3041 m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
3042 return *m_source_manager_up;
3043}
3044
3046 bool internal) {
3047 user_id_t new_uid = (internal ? LLDB_INVALID_UID : ++m_stop_hook_next_id);
3048 Target::StopHookSP stop_hook_sp;
3049 switch (kind) {
3051 stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
3052 break;
3054 stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
3055 break;
3057 stop_hook_sp.reset(new StopHookCoded(shared_from_this(), new_uid));
3058 break;
3059 }
3060 if (internal)
3061 m_internal_stop_hooks.push_back(stop_hook_sp);
3062 else
3063 m_stop_hooks[new_uid] = stop_hook_sp;
3064 return stop_hook_sp;
3065}
3066
3068 if (!RemoveStopHookByID(user_id))
3069 return;
3070 if (user_id == m_stop_hook_next_id)
3072}
3073
3075 size_t num_removed = m_stop_hooks.erase(user_id);
3076 return (num_removed != 0);
3077}
3078
3080
3082 StopHookSP found_hook;
3083
3084 StopHookCollection::iterator specified_hook_iter;
3085 specified_hook_iter = m_stop_hooks.find(user_id);
3086 if (specified_hook_iter != m_stop_hooks.end())
3087 found_hook = (*specified_hook_iter).second;
3088 return found_hook;
3089}
3090
3092 bool active_state) {
3093 StopHookCollection::iterator specified_hook_iter;
3094 specified_hook_iter = m_stop_hooks.find(user_id);
3095 if (specified_hook_iter == m_stop_hooks.end())
3096 return false;
3097
3098 (*specified_hook_iter).second->SetIsActive(active_state);
3099 return true;
3100}
3101
3102void Target::SetAllStopHooksActiveState(bool active_state) {
3103 StopHookCollection::iterator pos, end = m_stop_hooks.end();
3104 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
3105 (*pos).second->SetIsActive(active_state);
3106 }
3107}
3108
3109// FIXME: Ideally we would like to return a `const &` (const reference) instead
3110// of creating copy here, but that is not possible due to different container
3111// types. In C++20, we should be able to use `std::ranges::views::values` to
3112// adapt the key-pair entries in the `std::map` (behind `StopHookCollection`)
3113// to avoid creating the copy.
3114const std::vector<Target::StopHookSP>
3115Target::GetStopHooks(bool internal) const {
3116 if (internal)
3117 return m_internal_stop_hooks;
3118
3119 std::vector<StopHookSP> stop_hooks;
3120 for (auto &[_, hook] : m_stop_hooks)
3121 stop_hooks.push_back(hook);
3122
3123 return stop_hooks;
3124}
3125
3126bool Target::RunStopHooks(bool at_initial_stop) {
3128 return false;
3129
3130 if (!m_process_sp)
3131 return false;
3132
3133 // Somebody might have restarted the process:
3134 // Still return false, the return value is about US restarting the target.
3135 lldb::StateType state = m_process_sp->GetState();
3136 if (!(state == eStateStopped || state == eStateAttaching))
3137 return false;
3138
3139 auto is_active = [at_initial_stop](StopHookSP hook) {
3140 bool should_run_now = (!at_initial_stop || hook->GetRunAtInitialStop());
3141 return hook->IsActive() && should_run_now;
3142 };
3143
3144 // Create list of active internal and user stop hooks.
3145 std::vector<StopHookSP> active_hooks;
3146 llvm::copy_if(m_internal_stop_hooks, std::back_inserter(active_hooks),
3147 is_active);
3148 for (auto &[_, hook] : m_stop_hooks) {
3149 if (is_active(hook))
3150 active_hooks.push_back(hook);
3151 }
3152 if (active_hooks.empty())
3153 return false;
3154
3155 // Make sure we check that we are not stopped because of us running a user
3156 // expression since in that case we do not want to run the stop-hooks. Note,
3157 // you can't just check whether the last stop was for a User Expression,
3158 // because breakpoint commands get run before stop hooks, and one of them
3159 // might have run an expression. You have to ensure you run the stop hooks
3160 // once per natural stop.
3161 uint32_t last_natural_stop = m_process_sp->GetModIDRef().GetLastNaturalStopID();
3162 if (last_natural_stop != 0 && m_latest_stop_hook_id == last_natural_stop)
3163 return false;
3164
3165 m_latest_stop_hook_id = last_natural_stop;
3166
3167 std::vector<ExecutionContext> exc_ctx_with_reasons;
3168
3169 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
3170 size_t num_threads = cur_threadlist.GetSize();
3171 for (size_t i = 0; i < num_threads; i++) {
3172 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
3173 if (cur_thread_sp->ThreadStoppedForAReason()) {
3174 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
3175 exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
3176 cur_frame_sp.get());
3177 }
3178 }
3179
3180 // If no threads stopped for a reason, don't run the stop-hooks.
3181 // However, if this is the FIRST stop for this process, then we are in the
3182 // state where an attach or a core file load was completed without designating
3183 // a particular thread as responsible for the stop. In that case, we do
3184 // want to run the stop hooks, but do so just on one thread.
3185 size_t num_exe_ctx = exc_ctx_with_reasons.size();
3186 if (num_exe_ctx == 0) {
3187 if (at_initial_stop && num_threads > 0) {
3188 lldb::ThreadSP thread_to_use_sp = cur_threadlist.GetThreadAtIndex(0);
3189 exc_ctx_with_reasons.emplace_back(
3190 m_process_sp.get(), thread_to_use_sp.get(),
3191 thread_to_use_sp->GetStackFrameAtIndex(0).get());
3192 num_exe_ctx = 1;
3193 } else {
3194 return false;
3195 }
3196 }
3197
3198 StreamSP output_sp = m_debugger.GetAsyncOutputStream();
3199 llvm::scope_exit on_exit([output_sp] { output_sp->Flush(); });
3200
3201 size_t num_hooks_with_output = llvm::count_if(
3202 active_hooks, [](auto h) { return !h->GetSuppressOutput(); });
3203 bool print_hook_header = (num_hooks_with_output > 1);
3204 bool print_thread_header = (num_exe_ctx > 1);
3205 bool should_stop = false;
3206 bool requested_continue = false;
3207
3208 // A stop hook might get deleted while running stop hooks.
3209 // We have to decide what that means. We will follow the rule that deleting
3210 // a stop hook while processing these stop hooks will delete it for FUTURE
3211 // stops but not this stop. Fortunately, copying the m_stop_hooks to the
3212 // active_hooks list before iterating over the hooks has this effect.
3213 for (auto cur_hook_sp : active_hooks) {
3214 bool any_thread_matched = false;
3215 for (auto exc_ctx : exc_ctx_with_reasons) {
3216 if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
3217 continue;
3218
3219 bool suppress_output = cur_hook_sp->GetSuppressOutput();
3220 if (print_hook_header && !any_thread_matched && !suppress_output) {
3221 StreamString s;
3222 cur_hook_sp->GetDescription(s, eDescriptionLevelBrief);
3223 if (s.GetSize() != 0)
3224 output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
3225 s.GetData());
3226 else
3227 output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
3228 any_thread_matched = true;
3229 }
3230
3231 if (print_thread_header && !suppress_output)
3232 output_sp->Printf("-- Thread %d\n",
3233 exc_ctx.GetThreadPtr()->GetIndexID());
3234
3235 auto result = cur_hook_sp->HandleStop(exc_ctx, output_sp);
3236 switch (result) {
3238 if (cur_hook_sp->GetAutoContinue())
3239 requested_continue = true;
3240 else
3241 should_stop = true;
3242 break;
3244 requested_continue = true;
3245 break;
3247 // Do nothing
3248 break;
3250 // We don't have a good way to prohibit people from restarting the
3251 // target willy nilly in a stop hook. If the hook did so, give a
3252 // gentle suggestion here and back out of the hook processing.
3253 output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
3254 " set the program running.\n"
3255 " Consider using '-G true' to make "
3256 "stop hooks auto-continue.\n",
3257 cur_hook_sp->GetID());
3258 // FIXME: if we are doing non-stop mode for real, we would have to
3259 // check that OUR thread was restarted, otherwise we should keep
3260 // processing stop hooks.
3261 return true;
3262 }
3263 }
3264 }
3265
3266 // Resume iff at least one hook requested to continue and no hook asked to
3267 // stop.
3268 if (requested_continue && !should_stop) {
3269 Log *log = GetLog(LLDBLog::Process);
3270 Status error = m_process_sp->PrivateResume();
3271 if (error.Success()) {
3272 LLDB_LOG(log, "Resuming from RunStopHooks");
3273 return true;
3274 } else {
3275 LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
3276 return false;
3277 }
3278 }
3279
3280 return false;
3281}
3282
3284 // NOTE: intentional leak so we don't crash if global destructor chain gets
3285 // called as other threads still use the result of this function
3286 static TargetProperties *g_settings_ptr =
3287 new TargetProperties(nullptr);
3288 return *g_settings_ptr;
3289}
3290
3292 Status error;
3293 PlatformSP platform_sp(GetPlatform());
3294 if (!platform_sp || !platform_sp->IsRemote() || !platform_sp->IsConnected())
3295 return error;
3296
3297 // Install all files that have an install path when connected to a
3298 // remote platform. If target.auto-install-main-executable is set then
3299 // also install the main executable even if it does not have an explicit
3300 // install path specified.
3301
3302 for (auto module_sp : GetImages().Modules()) {
3303 if (module_sp == GetExecutableModule()) {
3304 MainExecutableInstaller installer{platform_sp, module_sp,
3305 shared_from_this(), *launch_info};
3306 error = installExecutable(installer);
3307 } else {
3308 ExecutableInstaller installer{platform_sp, module_sp};
3309 error = installExecutable(installer);
3310 }
3311
3312 if (error.Fail())
3313 return error;
3314 }
3315
3316 return error;
3317}
3318
3320 uint32_t stop_id, bool allow_section_end) {
3321 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr,
3322 allow_section_end);
3323}
3324
3326 Address &resolved_addr) {
3327 return m_images.ResolveFileAddress(file_addr, resolved_addr);
3328}
3329
3331 addr_t new_section_load_addr,
3332 bool warn_multiple) {
3333 const addr_t old_section_load_addr =
3334 m_section_load_history.GetSectionLoadAddress(
3335 SectionLoadHistory::eStopIDNow, section_sp);
3336 if (old_section_load_addr != new_section_load_addr) {
3337 uint32_t stop_id = 0;
3338 ProcessSP process_sp(GetProcessSP());
3339 if (process_sp)
3340 stop_id = process_sp->GetStopID();
3341 else
3342 stop_id = m_section_load_history.GetLastStopID();
3343 if (m_section_load_history.SetSectionLoadAddress(
3344 stop_id, section_sp, new_section_load_addr, warn_multiple))
3345 return true; // Return true if the section load address was changed...
3346 }
3347 return false; // Return false to indicate nothing changed
3348}
3349
3350size_t Target::UnloadModuleSections(const ModuleList &module_list) {
3351 size_t section_unload_count = 0;
3352 size_t num_modules = module_list.GetSize();
3353 for (size_t i = 0; i < num_modules; ++i) {
3354 section_unload_count +=
3355 UnloadModuleSections(module_list.GetModuleAtIndex(i));
3356 }
3357 return section_unload_count;
3358}
3359
3361 uint32_t stop_id = 0;
3362 ProcessSP process_sp(GetProcessSP());
3363 if (process_sp)
3364 stop_id = process_sp->GetStopID();
3365 else
3366 stop_id = m_section_load_history.GetLastStopID();
3367 SectionList *sections = module_sp->GetSectionList();
3368 size_t section_unload_count = 0;
3369 if (sections) {
3370 const uint32_t num_sections = sections->GetNumSections(0);
3371 for (uint32_t i = 0; i < num_sections; ++i) {
3372 section_unload_count += m_section_load_history.SetSectionUnloaded(
3373 stop_id, sections->GetSectionAtIndex(i));
3374 }
3375 }
3376 return section_unload_count;
3377}
3378
3380 uint32_t stop_id = 0;
3381 ProcessSP process_sp(GetProcessSP());
3382 if (process_sp)
3383 stop_id = process_sp->GetStopID();
3384 else
3385 stop_id = m_section_load_history.GetLastStopID();
3386 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
3387}
3388
3390 addr_t load_addr) {
3391 uint32_t stop_id = 0;
3392 ProcessSP process_sp(GetProcessSP());
3393 if (process_sp)
3394 stop_id = process_sp->GetStopID();
3395 else
3396 stop_id = m_section_load_history.GetLastStopID();
3397 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
3398 load_addr);
3399}
3400
3402
3404 lldb_private::TypeSummaryImpl &summary_provider) {
3405 return m_summary_statistics_cache.GetSummaryStatisticsForProvider(
3406 summary_provider);
3407}
3408
3412
3414 if (process_info.IsScriptedProcess()) {
3415 // Only copy scripted process launch options.
3416 ProcessLaunchInfo &default_launch_info = const_cast<ProcessLaunchInfo &>(
3418 default_launch_info.SetProcessPluginName("ScriptedProcess");
3419 default_launch_info.SetScriptedMetadata(process_info.GetScriptedMetadata());
3420 SetProcessLaunchInfo(default_launch_info);
3421 }
3422}
3423
3425 m_stats.SetLaunchOrAttachTime();
3426 Status error;
3427 Log *log = GetLog(LLDBLog::Target);
3428
3429 LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
3430 launch_info.GetExecutableFile().GetPath().c_str());
3431
3432 StateType state = eStateInvalid;
3433
3434 // Scope to temporarily get the process state in case someone has manually
3435 // remotely connected already to a process and we can skip the platform
3436 // launching.
3437 {
3438 ProcessSP process_sp(GetProcessSP());
3439
3440 if (process_sp) {
3441 state = process_sp->GetState();
3442 LLDB_LOGF(log,
3443 "Target::%s the process exists, and its current state is %s",
3444 __FUNCTION__, StateAsCString(state));
3445 } else {
3446 LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
3447 __FUNCTION__);
3448 }
3449 }
3450
3451 launch_info.GetFlags().Set(eLaunchFlagDebug);
3452
3453 SaveScriptedLaunchInfo(launch_info);
3454
3455 // Get the value of synchronous execution here. If you wait till after you
3456 // have started to run, then you could have hit a breakpoint, whose command
3457 // might switch the value, and then you'll pick up that incorrect value.
3458 Debugger &debugger = GetDebugger();
3459 const bool synchronous_execution =
3461
3462 PlatformSP platform_sp(GetPlatform());
3463
3464 FinalizeFileActions(launch_info);
3465
3466 if (state == eStateConnected) {
3467 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY))
3469 "can't launch in tty when launching through a remote connection");
3470 }
3471
3472 if (!launch_info.GetArchitecture().IsValid())
3473 launch_info.GetArchitecture() = GetArchitecture();
3474
3475 // Hijacking events of the process to be created to be sure that all events
3476 // until the first stop are intercepted (in case if platform doesn't define
3477 // its own hijacking listener or if the process is created by the target
3478 // manually, without the platform).
3479 if (!launch_info.GetHijackListener())
3482
3483 // If we're not already connected to the process, and if we have a platform
3484 // that can launch a process for debugging, go ahead and do that here.
3485 if (state != eStateConnected && platform_sp &&
3486 platform_sp->CanDebugProcess() && !launch_info.IsScriptedProcess()) {
3487 LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
3488 __FUNCTION__);
3489
3490 // If there was a previous process, delete it before we make the new one.
3491 // One subtle point, we delete the process before we release the reference
3492 // to m_process_sp. That way even if we are the last owner, the process
3493 // will get Finalized before it gets destroyed.
3495
3496 m_process_sp =
3497 GetPlatform()->DebugProcess(launch_info, debugger, *this, error);
3498
3499 } else {
3500 LLDB_LOGF(log,
3501 "Target::%s the platform doesn't know how to debug a "
3502 "process, getting a process plugin to do this for us.",
3503 __FUNCTION__);
3504
3505 if (state == eStateConnected) {
3506 assert(m_process_sp);
3507 } else {
3508 // Use a Process plugin to construct the process.
3509 CreateProcess(launch_info.GetListener(),
3510 launch_info.GetProcessPluginName(), nullptr, false);
3511 }
3512
3513 // Since we didn't have a platform launch the process, launch it here.
3514 if (m_process_sp) {
3515 m_process_sp->HijackProcessEvents(launch_info.GetHijackListener());
3516 m_process_sp->SetShadowListener(launch_info.GetShadowListener());
3517 error = m_process_sp->Launch(launch_info);
3518 }
3519 }
3520
3521 if (!error.Success())
3522 return error;
3523
3524 if (!m_process_sp)
3525 return Status::FromErrorString("failed to launch or debug process");
3526
3527 bool rebroadcast_first_stop =
3528 !synchronous_execution &&
3529 launch_info.GetFlags().Test(eLaunchFlagStopAtEntry);
3530
3531 assert(launch_info.GetHijackListener());
3532
3533 EventSP first_stop_event_sp;
3534 state = m_process_sp->WaitForProcessToStop(std::nullopt, &first_stop_event_sp,
3535 rebroadcast_first_stop,
3536 launch_info.GetHijackListener());
3537 m_process_sp->RestoreProcessEvents();
3538
3539 if (rebroadcast_first_stop) {
3540 // We don't need to run the stop hooks by hand here, they will get
3541 // triggered when this rebroadcast event gets fetched.
3542 assert(first_stop_event_sp);
3543 m_process_sp->BroadcastEvent(first_stop_event_sp);
3544 return error;
3545 }
3546 // Run the stop hooks that want to run at entry.
3547 RunStopHooks(true /* at entry point */);
3548
3549 switch (state) {
3550 case eStateStopped: {
3551 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3552 break;
3553 if (synchronous_execution)
3554 // Now we have handled the stop-from-attach, and we are just
3555 // switching to a synchronous resume. So we should switch to the
3556 // SyncResume hijacker.
3557 m_process_sp->ResumeSynchronous(stream);
3558 else
3559 error = m_process_sp->Resume();
3560 if (!error.Success()) {
3562 "process resume at entry point failed: %s", error.AsCString());
3563 }
3564 } break;
3565 case eStateExited: {
3566 bool with_shell = !!launch_info.GetShell();
3567 const int exit_status = m_process_sp->GetExitStatus();
3568 const char *exit_desc = m_process_sp->GetExitDescription();
3569 std::string desc;
3570 if (exit_desc && exit_desc[0])
3571 desc = " (" + std::string(exit_desc) + ')';
3572 if (with_shell)
3574 "process exited with status %i%s\n"
3575 "'r' and 'run' are aliases that default to launching through a "
3576 "shell.\n"
3577 "Try launching without going through a shell by using "
3578 "'process launch'.",
3579 exit_status, desc.c_str());
3580 else
3582 "process exited with status %i%s", exit_status, desc.c_str());
3583 } break;
3584 default:
3586 "initial process state wasn't stopped: %s", StateAsCString(state));
3587 break;
3588 }
3589 return error;
3590}
3591
3592void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3593
3595
3596llvm::Expected<TraceSP> Target::CreateTrace() {
3597 if (!m_process_sp)
3598 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3599 "A process is required for tracing");
3600 if (m_trace_sp)
3601 return llvm::createStringError(llvm::inconvertibleErrorCode(),
3602 "A trace already exists for the target");
3603
3604 llvm::Expected<TraceSupportedResponse> trace_type =
3605 m_process_sp->TraceSupported();
3606 if (!trace_type)
3607 return llvm::createStringError(
3608 llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3609 llvm::toString(trace_type.takeError()).c_str());
3610 if (llvm::Expected<TraceSP> trace_sp =
3612 m_trace_sp = *trace_sp;
3613 else
3614 return llvm::createStringError(
3615 llvm::inconvertibleErrorCode(),
3616 "Couldn't create a Trace object for the process. %s",
3617 llvm::toString(trace_sp.takeError()).c_str());
3618 return m_trace_sp;
3619}
3620
3621llvm::Expected<TraceSP> Target::GetTraceOrCreate() {
3622 if (m_trace_sp)
3623 return m_trace_sp;
3624 return CreateTrace();
3625}
3626
3628 Progress attach_progress("Waiting to attach to process");
3629 m_stats.SetLaunchOrAttachTime();
3630 auto state = eStateInvalid;
3631 auto process_sp = GetProcessSP();
3632 if (process_sp) {
3633 state = process_sp->GetState();
3634 if (process_sp->IsAlive() && state != eStateConnected) {
3635 if (state == eStateAttaching)
3636 return Status::FromErrorString("process attach is in progress");
3637 return Status::FromErrorString("a process is already being debugged");
3638 }
3639 }
3640
3641 const ModuleSP old_exec_module_sp = GetExecutableModule();
3642
3643 // If no process info was specified, then use the target executable name as
3644 // the process to attach to by default
3645 if (!attach_info.ProcessInfoSpecified()) {
3646 if (old_exec_module_sp)
3647 attach_info.GetExecutableFile().SetFilename(
3648 old_exec_module_sp->GetPlatformFileSpec().GetFilename());
3649
3650 if (!attach_info.ProcessInfoSpecified()) {
3652 "no process specified, create a target with a file, or "
3653 "specify the --pid or --name");
3654 }
3655 }
3656
3657 const auto platform_sp =
3659 ListenerSP hijack_listener_sp;
3660 const bool async = attach_info.GetAsync();
3661 if (!async) {
3662 hijack_listener_sp = Listener::MakeListener(
3664 attach_info.SetHijackListener(hijack_listener_sp);
3665 }
3666
3667 Status error;
3668 if (state != eStateConnected && platform_sp != nullptr &&
3669 platform_sp->CanDebugProcess() && !attach_info.IsScriptedProcess()) {
3670 SetPlatform(platform_sp);
3671 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3672 } else {
3673 if (state != eStateConnected) {
3674 SaveScriptedLaunchInfo(attach_info);
3675 llvm::StringRef plugin_name = attach_info.GetProcessPluginName();
3676 process_sp =
3678 plugin_name, nullptr, false);
3679 if (!process_sp) {
3681 "failed to create process using plugin '{0}'",
3682 plugin_name.empty() ? "<empty>" : plugin_name);
3683 return error;
3684 }
3685 }
3686 if (hijack_listener_sp)
3687 process_sp->HijackProcessEvents(hijack_listener_sp);
3688 error = process_sp->Attach(attach_info);
3689 }
3690
3691 if (error.Success() && process_sp) {
3692 if (async) {
3693 process_sp->RestoreProcessEvents();
3694 } else {
3695 // We are stopping all the way out to the user, so update selected frames.
3696 state = process_sp->WaitForProcessToStop(
3697 std::nullopt, nullptr, false, attach_info.GetHijackListener(), stream,
3699 process_sp->RestoreProcessEvents();
3700
3701 // Run the stop hooks here. Since we were hijacking the events, they
3702 // wouldn't have gotten run as part of event delivery.
3703 RunStopHooks(/* at_initial_stop= */ true);
3704
3705 if (state != eStateStopped) {
3706 const char *exit_desc = process_sp->GetExitDescription();
3707 if (exit_desc)
3708 error = Status::FromErrorStringWithFormat("%s", exit_desc);
3709 else
3711 "process did not stop (no such process or permission problem?)");
3712 process_sp->Destroy(false);
3713 }
3714 }
3715 }
3716 return error;
3717}
3718
3720 const ScriptedFrameProviderDescriptor &descriptor) {
3721 if (!descriptor.IsValid())
3722 return llvm::createStringError("invalid frame provider descriptor");
3723
3724 uint32_t descriptor_id = descriptor.GetID();
3725
3726 llvm::StringRef name = descriptor.GetName();
3727 if (name.empty())
3728 return llvm::createStringError(
3729 "frame provider descriptor has no class name");
3730
3731 {
3732 std::unique_lock<std::recursive_mutex> guard(
3734 m_frame_provider_descriptors[descriptor_id] = descriptor;
3735 }
3736
3738
3739 return descriptor_id;
3740}
3741
3743 bool removed = false;
3744 {
3745 std::lock_guard<std::recursive_mutex> guard(
3747 removed = m_frame_provider_descriptors.erase(id);
3748 }
3749
3750 if (removed)
3752 return removed;
3753}
3754
3756 {
3757 std::lock_guard<std::recursive_mutex> guard(
3760 }
3761
3763}
3764
3765const llvm::DenseMap<uint32_t, ScriptedFrameProviderDescriptor> &
3767 std::lock_guard<std::recursive_mutex> guard(
3770}
3771
3773 ProcessSP process_sp = GetProcessSP();
3774 if (!process_sp)
3775 return;
3776 for (ThreadSP thread_sp : process_sp->Threads()) {
3777 // Clear frame providers on existing threads so they reload with new config.
3778 thread_sp->ClearScriptedFrameProvider();
3779 // Notify threads that the stack traces might have changed.
3780 if (thread_sp->EventTypeHasListeners(Thread::eBroadcastBitStackChanged)) {
3781 auto data_sp = std::make_shared<Thread::ThreadEventData>(thread_sp);
3782 thread_sp->BroadcastEvent(Thread::eBroadcastBitStackChanged, data_sp);
3783 }
3784 }
3785}
3786
3788 Log *log = GetLog(LLDBLog::Process);
3789
3790 // Finalize the file actions, and if none were given, default to opening up a
3791 // pseudo terminal
3792 PlatformSP platform_sp = GetPlatform();
3793 const bool default_to_use_pty =
3794 m_platform_sp ? m_platform_sp->IsHost() : false;
3795 LLDB_LOG(
3796 log,
3797 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3798 bool(platform_sp),
3799 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3800 default_to_use_pty);
3801
3802 // If nothing for stdin or stdout or stderr was specified, then check the
3803 // process for any default settings that were set with "settings set"
3804 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3805 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3806 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3807 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3808 "default handling");
3809
3810 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3811 // Do nothing, if we are launching in a remote terminal no file actions
3812 // should be done at all.
3813 return;
3814 }
3815
3816 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3817 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3818 "for stdin, stdout and stderr");
3819 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3820 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3821 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3822 } else {
3823 // Check for any values that might have gotten set with any of: (lldb)
3824 // settings set target.input-path (lldb) settings set target.output-path
3825 // (lldb) settings set target.error-path
3826 FileSpec in_file_spec;
3827 FileSpec out_file_spec;
3828 FileSpec err_file_spec;
3829 // Only override with the target settings if we don't already have an
3830 // action for in, out or error
3831 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3832 in_file_spec = GetStandardInputPath();
3833 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3834 out_file_spec = GetStandardOutputPath();
3835 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3836 err_file_spec = GetStandardErrorPath();
3837
3838 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{2}'",
3839 in_file_spec, out_file_spec, err_file_spec);
3840
3841 if (in_file_spec) {
3842 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3843 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3844 }
3845
3846 if (out_file_spec) {
3847 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3848 LLDB_LOG(log, "appended stdout open file action for {0}",
3849 out_file_spec);
3850 }
3851
3852 if (err_file_spec) {
3853 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3854 LLDB_LOG(log, "appended stderr open file action for {0}",
3855 err_file_spec);
3856 }
3857
3858 if (default_to_use_pty) {
3859#ifdef _WIN32
3860 if (info.GetFlags().Test(eLaunchFlagUsePipes)) {
3861 llvm::Error Err = info.SetUpPipeRedirection();
3862 LLDB_LOG_ERROR(log, std::move(Err),
3863 "SetUpPipeRedirection failed: {0}");
3864 } else {
3865#endif
3866 llvm::Error Err = info.SetUpPtyRedirection();
3867 LLDB_LOG_ERROR(log, std::move(Err),
3868 "SetUpPtyRedirection failed: {0}");
3869#ifdef _WIN32
3870 }
3871#endif
3872 }
3873 }
3874 }
3875}
3876
3877void Target::AddDummySignal(llvm::StringRef name, LazyBool pass, LazyBool notify,
3878 LazyBool stop) {
3879 if (name.empty())
3880 return;
3881 // Don't add a signal if all the actions are trivial:
3882 if (pass == eLazyBoolCalculate && notify == eLazyBoolCalculate
3883 && stop == eLazyBoolCalculate)
3884 return;
3885
3886 auto& elem = m_dummy_signals[name];
3887 elem.pass = pass;
3888 elem.notify = notify;
3889 elem.stop = stop;
3890}
3891
3893 const DummySignalElement &elem) {
3894 if (!signals_sp)
3895 return false;
3896
3897 int32_t signo
3898 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3899 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3900 return false;
3901
3902 if (elem.second.pass == eLazyBoolYes)
3903 signals_sp->SetShouldSuppress(signo, false);
3904 else if (elem.second.pass == eLazyBoolNo)
3905 signals_sp->SetShouldSuppress(signo, true);
3906
3907 if (elem.second.notify == eLazyBoolYes)
3908 signals_sp->SetShouldNotify(signo, true);
3909 else if (elem.second.notify == eLazyBoolNo)
3910 signals_sp->SetShouldNotify(signo, false);
3911
3912 if (elem.second.stop == eLazyBoolYes)
3913 signals_sp->SetShouldStop(signo, true);
3914 else if (elem.second.stop == eLazyBoolNo)
3915 signals_sp->SetShouldStop(signo, false);
3916 return true;
3917}
3918
3920 const DummySignalElement &elem) {
3921 if (!signals_sp)
3922 return false;
3923 int32_t signo
3924 = signals_sp->GetSignalNumberFromName(elem.first().str().c_str());
3925 if (signo == LLDB_INVALID_SIGNAL_NUMBER)
3926 return false;
3927 bool do_pass = elem.second.pass != eLazyBoolCalculate;
3928 bool do_stop = elem.second.stop != eLazyBoolCalculate;
3929 bool do_notify = elem.second.notify != eLazyBoolCalculate;
3930 signals_sp->ResetSignal(signo, do_stop, do_notify, do_pass);
3931 return true;
3932}
3933
3935 StreamSP warning_stream_sp) {
3936 if (!signals_sp)
3937 return;
3938
3939 for (const auto &elem : m_dummy_signals) {
3940 if (!UpdateSignalFromDummy(signals_sp, elem))
3941 warning_stream_sp->Printf("Target signal '%s' not found in process\n",
3942 elem.first().str().c_str());
3943 }
3944}
3945
3946void Target::ClearDummySignals(Args &signal_names) {
3947 ProcessSP process_sp = GetProcessSP();
3948 // The simplest case, delete them all with no process to update.
3949 if (signal_names.GetArgumentCount() == 0 && !process_sp) {
3950 m_dummy_signals.clear();
3951 return;
3952 }
3953 UnixSignalsSP signals_sp;
3954 if (process_sp)
3955 signals_sp = process_sp->GetUnixSignals();
3956
3957 for (const Args::ArgEntry &entry : signal_names) {
3958 const char *signal_name = entry.c_str();
3959 auto elem = m_dummy_signals.find(signal_name);
3960 // If we didn't find it go on.
3961 // FIXME: Should I pipe error handling through here?
3962 if (elem == m_dummy_signals.end()) {
3963 continue;
3964 }
3965 if (signals_sp)
3966 ResetSignalFromDummy(signals_sp, *elem);
3967 m_dummy_signals.erase(elem);
3968 }
3969}
3970
3971void Target::PrintDummySignals(Stream &strm, Args &signal_args) {
3972 strm.Printf("NAME PASS STOP NOTIFY\n");
3973 strm.Printf("=========== ======= ======= =======\n");
3974
3975 auto str_for_lazy = [] (LazyBool lazy) -> const char * {
3976 switch (lazy) {
3977 case eLazyBoolCalculate: return "not set";
3978 case eLazyBoolYes: return "true ";
3979 case eLazyBoolNo: return "false ";
3980 }
3981 llvm_unreachable("Fully covered switch above!");
3982 };
3983 size_t num_args = signal_args.GetArgumentCount();
3984 for (const auto &elem : m_dummy_signals) {
3985 bool print_it = false;
3986 for (size_t idx = 0; idx < num_args; idx++) {
3987 if (elem.first() == signal_args.GetArgumentAtIndex(idx)) {
3988 print_it = true;
3989 break;
3990 }
3991 }
3992 if (print_it) {
3993 strm.Printf("%-11s ", elem.first().str().c_str());
3994 strm.Printf("%s %s %s\n", str_for_lazy(elem.second.pass),
3995 str_for_lazy(elem.second.stop),
3996 str_for_lazy(elem.second.notify));
3997 }
3998 }
3999}
4000
4001// Target::StopHook
4005
4007 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
4010 if (rhs.m_thread_spec_up)
4011 m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
4012}
4013
4015 m_specifier_sp.reset(specifier);
4016}
4017
4019 m_thread_spec_up.reset(specifier);
4020}
4021
4023 SymbolContextSpecifier *specifier = GetSpecifier();
4024 if (!specifier)
4025 return true;
4026
4027 bool will_run = true;
4028 if (exc_ctx.GetFramePtr())
4029 will_run = GetSpecifier()->SymbolContextMatches(
4030 exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
4031 if (will_run && GetThreadSpecifier() != nullptr)
4032 will_run =
4033 GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
4034
4035 return will_run;
4036}
4037
4039 lldb::DescriptionLevel level) const {
4040
4041 // For brief descriptions, only print the subclass description:
4042 if (level == eDescriptionLevelBrief) {
4043 GetSubclassDescription(s, level);
4044 return;
4045 }
4046
4047 auto indent_scope = s.MakeIndentScope();
4048
4049 s.Printf("Hook: %" PRIu64 "\n", GetID());
4050 if (m_active)
4051 s.Indent("State: enabled\n");
4052 else
4053 s.Indent("State: disabled\n");
4054
4055 if (m_auto_continue)
4056 s.Indent("AutoContinue on\n");
4057
4058 if (m_specifier_sp) {
4059 s.Indent();
4060 s.PutCString("Specifier:\n");
4061 auto indent_scope = s.MakeIndentScope();
4062 m_specifier_sp->GetDescription(&s, level);
4063 }
4064
4065 if (m_thread_spec_up) {
4066 StreamString tmp;
4067 s.Indent("Thread:\n");
4068 m_thread_spec_up->GetDescription(&tmp, level);
4069 auto indent_scope = s.MakeIndentScope();
4070 s.Indent(tmp.GetString());
4071 s.PutCString("\n");
4072 }
4073 GetSubclassDescription(s, level);
4074}
4075
4077 Stream &s, lldb::DescriptionLevel level) const {
4078 // The brief description just prints the first command.
4079 if (level == eDescriptionLevelBrief) {
4080 if (m_commands.GetSize() == 1)
4081 s.PutCString(m_commands.GetStringAtIndex(0));
4082 return;
4083 }
4084 s.Indent("Commands:\n");
4085 auto indent_scope = s.MakeIndentScope(4);
4086 uint32_t num_commands = m_commands.GetSize();
4087 for (uint32_t i = 0; i < num_commands; i++) {
4088 s.Indent(m_commands.GetStringAtIndex(i));
4089 s.PutCString("\n");
4090 }
4091}
4092
4093// Target::StopHookCommandLine
4095 GetCommands().SplitIntoLines(string);
4096}
4097
4099 const std::vector<std::string> &strings) {
4100 for (auto string : strings)
4101 GetCommands().AppendString(string.c_str());
4102}
4103
4106 StreamSP output_sp) {
4107 assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
4108 "with no target");
4109
4110 if (!m_commands.GetSize())
4112
4113 CommandReturnObject result(false);
4114 result.SetImmediateOutputStream(output_sp);
4115 result.SetInteractive(false);
4116 Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
4118 options.SetStopOnContinue(true);
4119 options.SetStopOnError(true);
4120 options.SetEchoCommands(false);
4121 options.SetPrintResults(true);
4122 options.SetPrintErrors(true);
4123 options.SetAddToHistory(false);
4124
4125 // Force Async:
4126 bool old_async = debugger.GetAsyncExecution();
4127 debugger.SetAsyncExecution(true);
4128 debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
4129 options, result);
4130 debugger.SetAsyncExecution(old_async);
4131 lldb::ReturnStatus status = result.GetStatus();
4136}
4137
4138// Target::StopHookScripted
4140 std::string class_name, StructuredData::ObjectSP extra_args_sp) {
4141 Status error;
4142
4143 ScriptInterpreter *script_interp =
4144 GetTarget()->GetDebugger().GetScriptInterpreter();
4145 if (!script_interp) {
4146 error = Status::FromErrorString("No script interpreter installed.");
4147 return error;
4148 }
4149
4151 if (!m_interface_sp) {
4153 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__,
4154 "Script interpreter couldn't create Scripted Stop Hook Interface");
4155 return error;
4156 }
4157
4158 m_class_name = class_name;
4159 m_extra_args.SetObjectSP(extra_args_sp);
4160
4161 auto obj_or_err = m_interface_sp->CreatePluginObject(
4163 if (!obj_or_err) {
4164 return Status::FromError(obj_or_err.takeError());
4165 }
4166
4167 StructuredData::ObjectSP object_sp = *obj_or_err;
4168 if (!object_sp || !object_sp->IsValid()) {
4170 "ScriptedStopHook::%s () - ERROR: %s", __FUNCTION__,
4171 "Failed to create valid script object");
4172 return error;
4173 }
4174
4175 return {};
4176}
4177
4180 StreamSP output_sp) {
4181 assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
4182 "with no target");
4183
4184 if (!m_interface_sp)
4186
4187 lldb::StreamSP stream = std::make_shared<lldb_private::StreamString>();
4188 auto should_stop_or_err = m_interface_sp->HandleStop(exc_ctx, stream);
4189 output_sp->PutCString(
4190 reinterpret_cast<StreamString *>(stream.get())->GetData());
4191 if (!should_stop_or_err)
4193
4194 return *should_stop_or_err ? StopHookResult::KeepStopped
4196}
4197
4199 Stream &s, lldb::DescriptionLevel level) const {
4200 if (level == eDescriptionLevelBrief) {
4202 return;
4203 }
4204 s.Indent("Class:");
4205 s.Printf("%s\n", m_class_name.c_str());
4206
4207 // Now print the extra args:
4208 // FIXME: We should use StructuredData.GetDescription on the m_extra_args
4209 // but that seems to rely on some printing plugin that doesn't exist.
4210 if (!m_extra_args.IsValid())
4211 return;
4212 StructuredData::ObjectSP object_sp = m_extra_args.GetObjectSP();
4213 if (!object_sp || !object_sp->IsValid())
4214 return;
4215
4216 StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary();
4217 if (!as_dict || !as_dict->IsValid())
4218 return;
4219
4220 uint32_t num_keys = as_dict->GetSize();
4221 if (num_keys == 0)
4222 return;
4223
4224 s.Indent("Args:\n");
4225 auto indent_scope = s.MakeIndentScope(4);
4226
4227 auto print_one_element = [&s](llvm::StringRef key,
4228 StructuredData::Object *object) {
4229 s.Indent();
4230 s.Format("{0} : {1}\n", key, object->GetStringValue());
4231 return true;
4232 };
4233
4234 as_dict->ForEach(print_one_element);
4235}
4236
4238 {
4240 "no-dynamic-values",
4241 "Don't calculate the dynamic type of values",
4242 },
4243 {
4245 "run-target",
4246 "Calculate the dynamic type of values "
4247 "even if you have to run the target.",
4248 },
4249 {
4251 "no-run-target",
4252 "Calculate the dynamic type of values, but don't run the target.",
4253 },
4254};
4255
4259
4261 {
4263 "never",
4264 "Never look for inline breakpoint locations (fastest). This setting "
4265 "should only be used if you know that no inlining occurs in your"
4266 "programs.",
4267 },
4268 {
4270 "headers",
4271 "Only check for inline breakpoint locations when setting breakpoints "
4272 "in header files, but not when setting breakpoint in implementation "
4273 "source files (default).",
4274 },
4275 {
4277 "always",
4278 "Always look for inline breakpoint locations when setting file and "
4279 "line breakpoints (slower but most accurate).",
4280 },
4281};
4282
4288
4290 {
4292 "default",
4293 "Disassembler default (currently att).",
4294 },
4295 {
4297 "intel",
4298 "Intel disassembler flavor.",
4299 },
4300 {
4302 "att",
4303 "AT&T disassembler flavor.",
4304 },
4305};
4306
4308 {
4310 "false",
4311 "Never import the 'std' C++ module in the expression parser.",
4312 },
4313 {
4315 "fallback",
4316 "Retry evaluating expressions with an imported 'std' C++ module if they"
4317 " failed to parse without the module. This allows evaluating more "
4318 "complex expressions involving C++ standard library types."
4319 },
4320 {
4322 "true",
4323 "Always import the 'std' C++ module. This allows evaluating more "
4324 "complex expressions involving C++ standard library types. This feature"
4325 " is experimental."
4326 },
4327};
4328
4329static constexpr OptionEnumValueElement
4331 {
4333 "auto",
4334 "Automatically determine the most appropriate method for the "
4335 "target OS.",
4336 },
4337 {eDynamicClassInfoHelperRealizedClassesStruct, "RealizedClassesStruct",
4338 "Prefer using the realized classes struct."},
4339 {eDynamicClassInfoHelperCopyRealizedClassList, "CopyRealizedClassList",
4340 "Prefer using the CopyRealizedClassList API."},
4341 {eDynamicClassInfoHelperGetRealizedClassList, "GetRealizedClassList",
4342 "Prefer using the GetRealizedClassList API."},
4343};
4344
4346 {
4348 "c",
4349 "C-style (0xffff).",
4350 },
4351 {
4353 "asm",
4354 "Asm-style (0ffffh).",
4355 },
4356};
4357
4359 {
4361 "true",
4362 "Load debug scripts inside symbol files",
4363 },
4364 {
4366 "false",
4367 "Do not load debug scripts inside symbol files.",
4368 },
4369 {
4371 "warn",
4372 "Warn about debug scripts inside symbol files but do not load them.",
4373 },
4374 {
4376 "trusted",
4377 "Load debug scripts inside trusted symbol files, and warn about "
4378 "scripts from untrusted symbol files.",
4379 },
4380};
4381
4383 {
4385 "true",
4386 "Load .lldbinit files from current directory",
4387 },
4388 {
4390 "false",
4391 "Do not load .lldbinit files from current directory",
4392 },
4393 {
4395 "warn",
4396 "Warn about loading .lldbinit files from current directory",
4397 },
4398};
4399
4401 {
4403 "minimal",
4404 "Load minimal information when loading modules from memory. Currently "
4405 "this setting loads sections only.",
4406 },
4407 {
4409 "partial",
4410 "Load partial information when loading modules from memory. Currently "
4411 "this setting loads sections and function bounds.",
4412 },
4413 {
4415 "complete",
4416 "Load complete information when loading modules from memory. Currently "
4417 "this setting loads sections and all symbols.",
4418 },
4419};
4420
4421#define LLDB_PROPERTIES_target
4422#include "TargetProperties.inc"
4423
4424enum {
4425#define LLDB_PROPERTIES_target
4426#include "TargetPropertiesEnum.inc"
4428};
4429
4431 : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
4432public:
4433 TargetOptionValueProperties(llvm::StringRef name) : Cloneable(name) {}
4434
4435 const Property *
4437 const ExecutionContext *exe_ctx = nullptr) const override {
4438 // When getting the value for a key from the target options, we will always
4439 // try and grab the setting from the current target if there is one. Else
4440 // we just use the one from this instance.
4441 if (exe_ctx) {
4442 Target *target = exe_ctx->GetTargetPtr();
4443 if (target) {
4444 TargetOptionValueProperties *target_properties =
4445 static_cast<TargetOptionValueProperties *>(
4446 target->GetValueProperties().get());
4447 if (this != target_properties)
4448 return target_properties->ProtectedGetPropertyAtIndex(idx);
4449 }
4450 }
4451 return ProtectedGetPropertyAtIndex(idx);
4452 }
4453};
4454
4455// TargetProperties
4456#define LLDB_PROPERTIES_target_experimental
4457#include "TargetProperties.inc"
4458
4459enum {
4460#define LLDB_PROPERTIES_target_experimental
4461#include "TargetPropertiesEnum.inc"
4462};
4463
4465 : public Cloneable<TargetExperimentalOptionValueProperties,
4466 OptionValueProperties> {
4467public:
4469 : Cloneable(Properties::GetExperimentalSettingsName()) {}
4470};
4471
4477
4478// TargetProperties
4480 : Properties(), m_launch_info(), m_target(target) {
4481 if (target) {
4484
4485 // Set callbacks to update launch_info whenever "settins set" updated any
4486 // of these properties
4487 m_collection_sp->SetValueChangedCallback(
4488 ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
4489 m_collection_sp->SetValueChangedCallback(
4490 ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
4491 m_collection_sp->SetValueChangedCallback(
4492 ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
4493 m_collection_sp->SetValueChangedCallback(
4494 ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
4495 m_collection_sp->SetValueChangedCallback(
4496 ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
4497 m_collection_sp->SetValueChangedCallback(
4498 ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
4499 m_collection_sp->SetValueChangedCallback(
4500 ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
4501 m_collection_sp->SetValueChangedCallback(
4502 ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
4503 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
4505 });
4506 m_collection_sp->SetValueChangedCallback(
4507 ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
4508 m_collection_sp->SetValueChangedCallback(
4509 ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
4510 m_collection_sp->SetValueChangedCallback(
4511 ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
4512
4513 m_collection_sp->SetValueChangedCallback(
4514 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4516 std::make_unique<TargetExperimentalProperties>();
4517 m_collection_sp->AppendProperty(
4519 "Experimental settings - setting these won't produce "
4520 "errors if the setting is not present.",
4521 true, m_experimental_properties_up->GetValueProperties());
4522 } else {
4523 m_collection_sp = std::make_shared<TargetOptionValueProperties>("target");
4524 m_collection_sp->Initialize(g_target_properties_def);
4526 std::make_unique<TargetExperimentalProperties>();
4527 m_collection_sp->AppendProperty(
4529 "Experimental settings - setting these won't produce "
4530 "errors if the setting is not present.",
4531 true, m_experimental_properties_up->GetValueProperties());
4532 m_collection_sp->AppendProperty(
4533 "process", "Settings specific to processes.", true,
4535 m_collection_sp->SetValueChangedCallback(
4536 ePropertySaveObjectsDir, [this] { CheckJITObjectsDir(); });
4537 }
4538}
4539
4541
4554
4556 size_t prop_idx, ExecutionContext *exe_ctx) const {
4557 const Property *exp_property =
4558 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4559 OptionValueProperties *exp_values =
4560 exp_property->GetValue()->GetAsProperties();
4561 if (exp_values)
4562 return exp_values->GetPropertyAtIndexAs<bool>(prop_idx, exe_ctx);
4563 return std::nullopt;
4564}
4565
4567 ExecutionContext *exe_ctx) const {
4568 return GetExperimentalPropertyValue(ePropertyInjectLocalVars, exe_ctx)
4569 .value_or(true);
4570}
4571
4573 const Property *exp_property =
4574 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4575 OptionValueProperties *exp_values =
4576 exp_property->GetValue()->GetAsProperties();
4577 if (exp_values)
4578 return exp_values->GetPropertyAtIndexAs<bool>(ePropertyUseDIL, exe_ctx)
4579 .value_or(false);
4580 else
4581 return true;
4582}
4583
4585 const Property *exp_property =
4586 m_collection_sp->GetPropertyAtIndex(ePropertyExperimental, exe_ctx);
4587 OptionValueProperties *exp_values =
4588 exp_property->GetValue()->GetAsProperties();
4589 if (exp_values)
4590 exp_values->SetPropertyAtIndex(ePropertyUseDIL, true, exe_ctx);
4591}
4592
4594 const uint32_t idx = ePropertyDefaultArch;
4595 return GetPropertyAtIndexAs<ArchSpec>(idx, {});
4596}
4597
4599 const uint32_t idx = ePropertyDefaultArch;
4600 SetPropertyAtIndex(idx, arch);
4601}
4602
4604 const uint32_t idx = ePropertyMoveToNearestCode;
4606 idx, g_target_properties[idx].default_uint_value != 0);
4607}
4608
4610 const uint32_t idx = ePropertyPreferDynamic;
4612 idx, static_cast<lldb::DynamicValueType>(
4613 g_target_properties[idx].default_uint_value));
4614}
4615
4617 const uint32_t idx = ePropertyPreferDynamic;
4618 return SetPropertyAtIndex(idx, d);
4619}
4620
4622 if (INTERRUPT_REQUESTED(m_target->GetDebugger(),
4623 "Interrupted checking preload symbols")) {
4624 return false;
4625 }
4626 const uint32_t idx = ePropertyPreloadSymbols;
4628 idx, g_target_properties[idx].default_uint_value != 0);
4629}
4630
4632 const uint32_t idx = ePropertyPreloadSymbols;
4633 SetPropertyAtIndex(idx, b);
4634}
4635
4637 const uint32_t idx = ePropertyDisableASLR;
4639 idx, g_target_properties[idx].default_uint_value != 0);
4640}
4641
4643 const uint32_t idx = ePropertyDisableASLR;
4644 SetPropertyAtIndex(idx, b);
4645}
4646
4648 const uint32_t idx = ePropertyInheritTCC;
4650 idx, g_target_properties[idx].default_uint_value != 0);
4651}
4652
4654 const uint32_t idx = ePropertyInheritTCC;
4655 SetPropertyAtIndex(idx, b);
4656}
4657
4659 const uint32_t idx = ePropertyDetachOnError;
4661 idx, g_target_properties[idx].default_uint_value != 0);
4662}
4663
4665 const uint32_t idx = ePropertyDetachOnError;
4666 SetPropertyAtIndex(idx, b);
4667}
4668
4670 const uint32_t idx = ePropertyDisableSTDIO;
4672 idx, g_target_properties[idx].default_uint_value != 0);
4673}
4674
4676 const uint32_t idx = ePropertyDisableSTDIO;
4677 SetPropertyAtIndex(idx, b);
4678}
4680 const uint32_t idx = ePropertyLaunchWorkingDir;
4682 idx, g_target_properties[idx].default_cstr_value);
4683}
4684
4686 const uint32_t idx = ePropertyParallelModuleLoad;
4688 idx, g_target_properties[idx].default_uint_value != 0);
4689}
4690
4692 const uint32_t idx = ePropertyDisassemblyFlavor;
4693 const char *return_value;
4694
4695 x86DisassemblyFlavor flavor_value =
4697 idx, static_cast<x86DisassemblyFlavor>(
4698 g_target_properties[idx].default_uint_value));
4699
4700 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
4701 return return_value;
4702}
4703
4705 const uint32_t idx = ePropertyDisassemblyCPU;
4706 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
4707 idx, g_target_properties[idx].default_cstr_value);
4708 return str.empty() ? nullptr : str.data();
4709}
4710
4712 const uint32_t idx = ePropertyDisassemblyFeatures;
4713 llvm::StringRef str = GetPropertyAtIndexAs<llvm::StringRef>(
4714 idx, g_target_properties[idx].default_cstr_value);
4715 return str.empty() ? nullptr : str.data();
4716}
4717
4719 const uint32_t idx = ePropertyInlineStrategy;
4721 idx,
4722 static_cast<InlineStrategy>(g_target_properties[idx].default_uint_value));
4723}
4724
4725// Returning RealpathPrefixes, but the setting's type is FileSpecList. We do
4726// this because we want the FileSpecList to normalize the file paths for us.
4728 const uint32_t idx = ePropertySourceRealpathPrefixes;
4730}
4731
4732llvm::StringRef TargetProperties::GetArg0() const {
4733 const uint32_t idx = ePropertyArg0;
4735 idx, g_target_properties[idx].default_cstr_value);
4736}
4737
4738void TargetProperties::SetArg0(llvm::StringRef arg) {
4739 const uint32_t idx = ePropertyArg0;
4740 SetPropertyAtIndex(idx, arg);
4741 m_launch_info.SetArg0(arg);
4742}
4743
4745 const uint32_t idx = ePropertyRunArgs;
4746 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
4747}
4748
4750 const uint32_t idx = ePropertyRunArgs;
4751 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
4752 m_launch_info.GetArguments() = args;
4753}
4754
4756 Environment env;
4757
4758 if (m_target &&
4760 ePropertyInheritEnv,
4761 g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
4762 if (auto platform_sp = m_target->GetPlatform()) {
4763 Environment platform_env = platform_sp->GetEnvironment();
4764 for (const auto &KV : platform_env)
4765 env[KV.first()] = KV.second;
4766 }
4767 }
4768
4769 Args property_unset_env;
4770 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4771 property_unset_env);
4772 for (const auto &var : property_unset_env)
4773 env.erase(var.ref());
4774
4775 Args property_env;
4776 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars, property_env);
4777 for (const auto &KV : Environment(property_env))
4778 env[KV.first()] = KV.second;
4779
4780 return env;
4781}
4782
4786
4788 Environment environment;
4789
4790 if (m_target == nullptr)
4791 return environment;
4792
4794 ePropertyInheritEnv,
4795 g_target_properties[ePropertyInheritEnv].default_uint_value != 0))
4796 return environment;
4797
4798 PlatformSP platform_sp = m_target->GetPlatform();
4799 if (platform_sp == nullptr)
4800 return environment;
4801
4802 Environment platform_environment = platform_sp->GetEnvironment();
4803 for (const auto &KV : platform_environment)
4804 environment[KV.first()] = KV.second;
4805
4806 Args property_unset_environment;
4807 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyUnsetEnvVars,
4808 property_unset_environment);
4809 for (const auto &var : property_unset_environment)
4810 environment.erase(var.ref());
4811
4812 return environment;
4813}
4814
4816 Args property_environment;
4817 m_collection_sp->GetPropertyAtIndexAsArgs(ePropertyEnvVars,
4818 property_environment);
4819 Environment environment;
4820 for (const auto &KV : Environment(property_environment))
4821 environment[KV.first()] = KV.second;
4822
4823 return environment;
4824}
4825
4827 // TODO: Get rid of the Args intermediate step
4828 const uint32_t idx = ePropertyEnvVars;
4829 m_collection_sp->SetPropertyAtIndexFromArgs(idx, Args(env));
4830}
4831
4833 const uint32_t idx = ePropertySkipPrologue;
4835 idx, g_target_properties[idx].default_uint_value != 0);
4836}
4837
4839 const uint32_t idx = ePropertySourceMap;
4840 OptionValuePathMappings *option_value =
4841 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4842 assert(option_value);
4843 return option_value->GetCurrentValue();
4844}
4845
4847 const uint32_t idx = ePropertyObjectMap;
4848 OptionValuePathMappings *option_value =
4849 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(idx);
4850 assert(option_value);
4851 return option_value->GetCurrentValue();
4852}
4853
4855 const uint32_t idx = ePropertyAutoSourceMapRelative;
4857 idx, g_target_properties[idx].default_uint_value != 0);
4858}
4859
4861 const uint32_t idx = ePropertyExecutableSearchPaths;
4862 OptionValueFileSpecList *option_value =
4863 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(idx);
4864 assert(option_value);
4865 option_value->AppendCurrentValue(dir);
4866}
4867
4869 const uint32_t idx = ePropertyExecutableSearchPaths;
4870 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4871}
4872
4874 const uint32_t idx = ePropertyDebugFileSearchPaths;
4875 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4876}
4877
4879 const uint32_t idx = ePropertyClangModuleSearchPaths;
4880 return GetPropertyAtIndexAs<FileSpecList>(idx, {});
4881}
4882
4884 const uint32_t idx = ePropertyAutoImportClangModules;
4886 idx, g_target_properties[idx].default_uint_value != 0);
4887}
4888
4890 const uint32_t idx = ePropertyImportStdModule;
4892 idx, static_cast<ImportStdModule>(
4893 g_target_properties[idx].default_uint_value));
4894}
4895
4897 const uint32_t idx = ePropertyDynamicClassInfoHelper;
4899 idx, static_cast<DynamicClassInfoHelper>(
4900 g_target_properties[idx].default_uint_value));
4901}
4902
4904 const uint32_t idx = ePropertyAutoApplyFixIts;
4906 idx, g_target_properties[idx].default_uint_value != 0);
4907}
4908
4910 const uint32_t idx = ePropertyRetriesWithFixIts;
4912 idx, g_target_properties[idx].default_uint_value);
4913}
4914
4916 const uint32_t idx = ePropertyNotifyAboutFixIts;
4918 idx, g_target_properties[idx].default_uint_value != 0);
4919}
4920
4922 const uint32_t idx = ePropertySaveObjectsDir;
4923 return GetPropertyAtIndexAs<FileSpec>(idx, {});
4924}
4925
4927 FileSpec new_dir = GetSaveJITObjectsDir();
4928 if (!new_dir)
4929 return;
4930
4931 const FileSystem &instance = FileSystem::Instance();
4932 bool exists = instance.Exists(new_dir);
4933 bool is_directory = instance.IsDirectory(new_dir);
4934 std::string path = new_dir.GetPath(true);
4935 bool writable = llvm::sys::fs::can_write(path);
4936 if (exists && is_directory && writable)
4937 return;
4938
4939 m_collection_sp->GetPropertyAtIndex(ePropertySaveObjectsDir)
4940 ->GetValue()
4941 ->Clear();
4942
4943 std::string buffer;
4944 llvm::raw_string_ostream os(buffer);
4945 os << "JIT object dir '" << path << "' ";
4946 if (!exists)
4947 os << "does not exist";
4948 else if (!is_directory)
4949 os << "is not a directory";
4950 else if (!writable)
4951 os << "is not writable";
4952
4953 std::optional<lldb::user_id_t> debugger_id;
4954 if (m_target)
4955 debugger_id = m_target->GetDebugger().GetID();
4956 Debugger::ReportError(buffer, debugger_id);
4957}
4958
4960 const uint32_t idx = ePropertyEnableSynthetic;
4962 idx, g_target_properties[idx].default_uint_value != 0);
4963}
4964
4966 const uint32_t idx = ePropertyShowHexVariableValuesWithLeadingZeroes;
4968 idx, g_target_properties[idx].default_uint_value != 0);
4969}
4970
4972 const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
4974 idx, g_target_properties[idx].default_uint_value);
4975}
4976
4978 const uint32_t idx = ePropertyMaxChildrenCount;
4980 idx, g_target_properties[idx].default_uint_value);
4981}
4982
4983std::pair<uint32_t, bool>
4985 const uint32_t idx = ePropertyMaxChildrenDepth;
4986 auto *option_value =
4987 m_collection_sp->GetPropertyAtIndexAsOptionValueUInt64(idx);
4988 bool is_default = !option_value->OptionWasSet();
4989 return {option_value->GetCurrentValue(), is_default};
4990}
4991
4993 const uint32_t idx = ePropertyMaxSummaryLength;
4995 idx, g_target_properties[idx].default_uint_value);
4996}
4997
4999 const uint32_t idx = ePropertyMaxMemReadSize;
5001 idx, g_target_properties[idx].default_uint_value);
5002}
5003
5005 const uint32_t idx = ePropertyInputPath;
5006 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5007}
5008
5009void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
5010 const uint32_t idx = ePropertyInputPath;
5011 SetPropertyAtIndex(idx, path);
5012}
5013
5015 const uint32_t idx = ePropertyOutputPath;
5016 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5017}
5018
5020 const uint32_t idx = ePropertyOutputPath;
5021 SetPropertyAtIndex(idx, path);
5022}
5023
5025 const uint32_t idx = ePropertyErrorPath;
5026 return GetPropertyAtIndexAs<FileSpec>(idx, {});
5027}
5028
5029void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
5030 const uint32_t idx = ePropertyErrorPath;
5031 SetPropertyAtIndex(idx, path);
5032}
5033
5035 const uint32_t idx = ePropertyLanguage;
5037}
5038
5040 const uint32_t idx = ePropertyExprPrefix;
5041 OptionValueFileSpec *file =
5042 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(idx);
5043 if (file) {
5044 DataBufferSP data_sp(file->GetFileContents());
5045 if (data_sp)
5046 return llvm::StringRef(
5047 reinterpret_cast<const char *>(data_sp->GetBytes()),
5048 data_sp->GetByteSize());
5049 }
5050 return "";
5051}
5052
5054 const uint32_t idx = ePropertyExprErrorLimit;
5056 idx, g_target_properties[idx].default_uint_value);
5057}
5058
5060 const uint32_t idx = ePropertyExprAllocAddress;
5062 idx, g_target_properties[idx].default_uint_value);
5063}
5064
5066 const uint32_t idx = ePropertyExprAllocSize;
5068 idx, g_target_properties[idx].default_uint_value);
5069}
5070
5072 const uint32_t idx = ePropertyExprAllocAlign;
5074 idx, g_target_properties[idx].default_uint_value);
5075}
5076
5078 const uint32_t idx = ePropertyBreakpointUseAvoidList;
5080 idx, g_target_properties[idx].default_uint_value != 0);
5081}
5082
5084 const uint32_t idx = ePropertyUseHexImmediates;
5086 idx, g_target_properties[idx].default_uint_value != 0);
5087}
5088
5090 const uint32_t idx = ePropertyUseFastStepping;
5092 idx, g_target_properties[idx].default_uint_value != 0);
5093}
5094
5096 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
5098 idx, g_target_properties[idx].default_uint_value != 0);
5099}
5100
5102 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
5104 idx, static_cast<LoadScriptFromSymFile>(
5105 g_target_properties[idx].default_uint_value));
5106}
5107
5109 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
5111 idx, static_cast<LoadCWDlldbinitFile>(
5112 g_target_properties[idx].default_uint_value));
5113}
5114
5116 const uint32_t idx = ePropertyHexImmediateStyle;
5118 idx, static_cast<Disassembler::HexImmediateStyle>(
5119 g_target_properties[idx].default_uint_value));
5120}
5121
5123 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
5125 idx, static_cast<MemoryModuleLoadLevel>(
5126 g_target_properties[idx].default_uint_value));
5127}
5128
5130 const uint32_t idx = ePropertyTrapHandlerNames;
5131 return m_collection_sp->GetPropertyAtIndexAsArgs(idx, args);
5132}
5133
5135 const uint32_t idx = ePropertyTrapHandlerNames;
5136 m_collection_sp->SetPropertyAtIndexFromArgs(idx, args);
5137}
5138
5140 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
5142 idx, g_target_properties[idx].default_uint_value != 0);
5143}
5144
5146 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
5147 SetPropertyAtIndex(idx, b);
5148}
5149
5151 const uint32_t idx = ePropertyDisplayRecognizedArguments;
5153 idx, g_target_properties[idx].default_uint_value != 0);
5154}
5155
5157 const uint32_t idx = ePropertyDisplayRecognizedArguments;
5158 SetPropertyAtIndex(idx, b);
5159}
5160
5164
5166 const ProcessLaunchInfo &launch_info) {
5167 m_launch_info = launch_info;
5168 SetArg0(launch_info.GetArg0());
5169 SetRunArguments(launch_info.GetArguments());
5170 SetEnvironment(launch_info.GetEnvironment());
5171 const FileAction *input_file_action =
5172 launch_info.GetFileActionForFD(STDIN_FILENO);
5173 if (input_file_action) {
5174 SetStandardInputPath(input_file_action->GetFileSpec().GetPath());
5175 }
5176 const FileAction *output_file_action =
5177 launch_info.GetFileActionForFD(STDOUT_FILENO);
5178 if (output_file_action) {
5179 SetStandardOutputPath(output_file_action->GetFileSpec().GetPath());
5180 }
5181 const FileAction *error_file_action =
5182 launch_info.GetFileActionForFD(STDERR_FILENO);
5183 if (error_file_action) {
5184 SetStandardErrorPath(error_file_action->GetFileSpec().GetPath());
5185 }
5186 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
5187 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
5189 launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
5190 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
5191}
5192
5194 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5196 idx, g_target_properties[idx].default_uint_value != 0);
5197}
5198
5200 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
5201 m_collection_sp->SetPropertyAtIndex(idx, b);
5202}
5203
5205 const uint32_t idx = ePropertyAutoInstallMainExecutable;
5207 idx, g_target_properties[idx].default_uint_value != 0);
5208}
5209
5213
5215 Args args;
5216 if (GetRunArguments(args))
5217 m_launch_info.GetArguments() = args;
5218}
5219
5223
5225 m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
5226 false);
5227}
5228
5230 m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
5231 false, true);
5232}
5233
5235 m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
5236 false, true);
5237}
5238
5240 if (GetDetachOnError())
5241 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
5242 else
5243 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
5244}
5245
5247 if (GetDisableASLR())
5248 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
5249 else
5250 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
5251}
5252
5254 if (GetInheritTCC())
5255 m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
5256 else
5257 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
5258}
5259
5261 if (GetDisableSTDIO())
5262 m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
5263 else
5264 m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
5265}
5266
5268 const uint32_t idx = ePropertyDebugUtilityExpression;
5270 idx, g_target_properties[idx].default_uint_value != 0);
5271}
5272
5274 const uint32_t idx = ePropertyDebugUtilityExpression;
5275 SetPropertyAtIndex(idx, debug);
5276}
5277
5278// Target::TargetEventData
5279
5282
5284 const ModuleList &module_list)
5285 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
5286
5288 const lldb::TargetSP &target_sp, const lldb::TargetSP &created_target_sp)
5289 : EventData(), m_target_sp(target_sp),
5290 m_created_target_sp(created_target_sp), m_module_list() {}
5291
5293
5295 return "Target::TargetEventData";
5296}
5297
5299 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
5300 if (i != 0)
5301 *s << ", ";
5302 m_module_list.GetModuleAtIndex(i)->GetDescription(
5304 }
5305}
5306
5309 if (event_ptr) {
5310 const EventData *event_data = event_ptr->GetData();
5311 if (event_data &&
5313 return static_cast<const TargetEventData *>(event_ptr->GetData());
5314 }
5315 return nullptr;
5316}
5317
5319 TargetSP target_sp;
5320 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
5321 if (event_data)
5322 target_sp = event_data->m_target_sp;
5323 return target_sp;
5324}
5325
5328 TargetSP created_target_sp;
5329 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
5330 if (event_data)
5331 created_target_sp = event_data->m_created_target_sp;
5332 return created_target_sp;
5333}
5334
5337 ModuleList module_list;
5338 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
5339 if (event_data)
5340 module_list = event_data->m_module_list;
5341 return module_list;
5342}
5343
5344std::recursive_mutex &Target::GetAPIMutex() {
5345 if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
5346 return m_private_mutex;
5347 else
5348 return m_mutex;
5349}
5350
5351/// Get metrics associated with this target in JSON format.
5352llvm::json::Value
5354 return m_stats.ToJSON(*this, options);
5355}
5356
5357void Target::ResetStatistics() { m_stats.Reset(*this); }
5358
5360
5364
5366
5370
5372 lldb::BreakpointEventType eventKind) {
5374 std::shared_ptr<Breakpoint::BreakpointEventData> data_sp =
5375 std::make_shared<Breakpoint::BreakpointEventData>(
5376 eventKind, bp.shared_from_this());
5378 }
5379}
5380
5386
5387// FIXME: the language plugin should expression options dynamically and
5388// we should validate here (by asking the language plugin) that the options
5389// being set/retrieved are actually valid options.
5390
5391llvm::Error
5393 bool value) {
5394 if (option_name.empty())
5395 return llvm::createStringError("can't set an option with an empty name");
5396
5397 if (StructuredData::ObjectSP existing_sp =
5398 GetLanguageOptions().GetValueForKey(option_name);
5399 existing_sp && existing_sp->GetType() != eStructuredDataTypeBoolean)
5400 return llvm::createStringErrorV("trying to override existing option '{0}' "
5401 "of type '{1}' with a boolean value",
5402 option_name, existing_sp->GetType());
5403
5404 GetLanguageOptions().AddBooleanItem(option_name, value);
5405
5406 return llvm::Error::success();
5407}
5408
5410 llvm::StringRef option_name) const {
5412
5413 if (!opts.HasKey(option_name))
5414 return llvm::createStringErrorV("option '{0}' does not exist", option_name);
5415
5416 bool result;
5417 if (!opts.GetValueForKeyAsBoolean(option_name, result))
5418 return llvm::createStringErrorV("failed to get option '{0}' as boolean",
5419 option_name);
5420
5421 return result;
5422}
5423
5430
5436
5437// FIXME: this option is C++ plugin specific and should be registered by it,
5438// instead of hard-coding it here.
5439constexpr llvm::StringLiteral s_cpp_ignore_context_qualifiers_option =
5440 "c++-ignore-context-qualifiers";
5441
5446
5451
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:494
#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:383
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:399
@ 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:5439
static constexpr OptionEnumValueElement g_dynamic_class_info_helper_value_types[]
Definition Target.cpp:4330
static bool CheckIfWatchpointsSupported(Target *target, Status &error)
Definition Target.cpp:935
static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[]
Definition Target.cpp:4382
x86DisassemblyFlavor
Definition Target.cpp:4283
@ eX86DisFlavorDefault
Definition Target.cpp:4284
@ eX86DisFlavorIntel
Definition Target.cpp:4285
@ eX86DisFlavorATT
Definition Target.cpp:4286
static constexpr OptionEnumValueElement g_dynamic_value_types[]
Definition Target.cpp:4237
static constexpr OptionEnumValueElement g_memory_module_load_level_values[]
Definition Target.cpp:4400
static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[]
Definition Target.cpp:4358
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:4289
static constexpr OptionEnumValueElement g_hex_immediate_style_values[]
Definition Target.cpp:4345
static constexpr OptionEnumValueElement g_inline_breakpoint_enums[]
Definition Target.cpp:4260
static constexpr OptionEnumValueElement g_import_std_module_value_types[]
Definition Target.cpp:4307
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:86
const Property * GetPropertyAtIndex(size_t idx, const ExecutionContext *exe_ctx=nullptr) const override
Definition Target.cpp:4436
TargetOptionValueProperties(llvm::StringRef name)
Definition Target.cpp:4433
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:1034
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:189
lldb::StreamUP GetAsyncErrorStream()
TargetList & GetTargetList()
Get accessor for the target list.
Definition Debugger.h:227
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:229
lldb::ListenerSP GetListener()
Definition Debugger.h:198
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:5447
const StructuredData::Dictionary & GetLanguageOptions() const
Definition Target.cpp:5425
llvm::Expected< bool > GetBooleanLanguageOption(llvm::StringRef option_name) const
Get the language-plugin specific boolean option called option_name.
Definition Target.cpp:5409
void SetTryAllThreads(bool try_others=true)
Definition Target.h:407
void SetStopOthers(bool stop_others=true)
Definition Target.h:411
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:5392
StructuredData::DictionarySP m_language_options_sp
Dictionary mapping names of language-plugin specific options to values.
Definition Target.h:540
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.
Represents a file descriptor action to be performed during process launch.
Definition FileAction.h:21
const FileSpec & GetFileSpec() const
Get the file specification for open actions.
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:372
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.
bool LoadScriptingResourcesInTarget(Target *target, std::list< Status > &errors, bool continue_on_error=true)
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:1184
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:452
@ 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:1142
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:3014
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:4948
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:527
static void SettingsTerminate()
Definition Process.cpp:4950
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:541
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:552
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)
Forwards the arguments to llvm::formatv and writes to the stream.
Definition Stream.h:367
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:402
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:155
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:132
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:63
size_t PutChar(char ch)
Definition Stream.cpp:129
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:211
void IndentLess(unsigned amount=2)
Decrement the current indentation level.
Definition Stream.cpp:202
void IndentMore(unsigned amount=2)
Increment the current indentation level.
Definition Stream.cpp:199
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:4992
FileSpecList GetDebugFileSearchPaths()
Definition Target.cpp:4873
llvm::StringRef GetLaunchWorkingDirectory() const
Definition Target.cpp:4679
bool GetDisplayRecognizedArguments() const
Definition Target.cpp:5150
ImportStdModule GetImportStdModule() const
Definition Target.cpp:4889
void AppendExecutableSearchPaths(const FileSpec &)
Definition Target.cpp:4860
bool GetEnableSyntheticValue() const
Definition Target.cpp:4959
ProcessLaunchInfo m_launch_info
Definition Target.h:305
uint64_t GetExprAllocAlign() const
Definition Target.cpp:5071
MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const
Definition Target.cpp:5122
llvm::StringRef GetArg0() const
Definition Target.cpp:4732
uint32_t GetMaximumMemReadSize() const
Definition Target.cpp:4998
void SetRunArguments(const Args &args)
Definition Target.cpp:4749
FileSpec GetStandardErrorPath() const
Definition Target.cpp:5024
bool GetEnableNotifyAboutFixIts() const
Definition Target.cpp:4915
bool SetPreferDynamicValue(lldb::DynamicValueType d)
Definition Target.cpp:4616
void SetDisplayRecognizedArguments(bool b)
Definition Target.cpp:5156
std::optional< bool > GetExperimentalPropertyValue(size_t prop_idx, ExecutionContext *exe_ctx=nullptr) const
Definition Target.cpp:4555
const ProcessLaunchInfo & GetProcessLaunchInfo() const
Definition Target.cpp:5161
Environment ComputeEnvironment() const
Definition Target.cpp:4755
bool GetUserSpecifiedTrapHandlerNames(Args &args) const
Definition Target.cpp:5129
uint64_t GetExprErrorLimit() const
Definition Target.cpp:5053
bool GetEnableAutoImportClangModules() const
Definition Target.cpp:4883
bool GetDebugUtilityExpression() const
Definition Target.cpp:5267
DynamicClassInfoHelper GetDynamicClassInfoHelper() const
Definition Target.cpp:4896
FileSpec GetStandardOutputPath() const
Definition Target.cpp:5014
void SetDisplayRuntimeSupportValues(bool b)
Definition Target.cpp:5145
uint32_t GetMaximumNumberOfChildrenToDisplay() const
Definition Target.cpp:4977
void SetRequireHardwareBreakpoints(bool b)
Definition Target.cpp:5199
bool GetAutoInstallMainExecutable() const
Definition Target.cpp:5204
const char * GetDisassemblyFeatures() const
Definition Target.cpp:4711
RealpathPrefixes GetSourceRealpathPrefixes() const
Definition Target.cpp:4727
uint64_t GetNumberOfRetriesWithFixits() const
Definition Target.cpp:4909
uint64_t GetExprAllocSize() const
Definition Target.cpp:5065
llvm::StringRef GetExpressionPrefixContents()
Definition Target.cpp:5039
PathMappingList & GetObjectPathMap() const
Definition Target.cpp:4846
const char * GetDisassemblyFlavor() const
Definition Target.cpp:4691
FileSpec GetStandardInputPath() const
Definition Target.cpp:5004
lldb::DynamicValueType GetPreferDynamicValue() const
Definition Target.cpp:4609
InlineStrategy GetInlineStrategy() const
Definition Target.cpp:4718
Environment GetTargetEnvironment() const
Definition Target.cpp:4815
bool GetDisplayRuntimeSupportValues() const
Definition Target.cpp:5139
void SetUserSpecifiedTrapHandlerNames(const Args &args)
Definition Target.cpp:5134
uint32_t GetMaxZeroPaddingInFloatFormat() const
Definition Target.cpp:4971
uint64_t GetExprAllocAddress() const
Definition Target.cpp:5059
LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const
Definition Target.cpp:5108
Environment GetInheritedEnvironment() const
Definition Target.cpp:4787
void SetArg0(llvm::StringRef arg)
Definition Target.cpp:4738
bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const
Definition Target.cpp:4566
bool ShowHexVariableValuesWithLeadingZeroes() const
Definition Target.cpp:4965
SourceLanguage GetLanguage() const
Definition Target.cpp:5034
Environment GetEnvironment() const
Definition Target.cpp:4783
void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
Definition Target.cpp:5165
FileSpec GetSaveJITObjectsDir() const
Definition Target.cpp:4921
void SetEnvironment(Environment env)
Definition Target.cpp:4826
LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const
Definition Target.cpp:5101
const char * GetDisassemblyCPU() const
Definition Target.cpp:4704
void SetStandardErrorPath(llvm::StringRef path)
Definition Target.cpp:5029
bool GetRunArguments(Args &args) const
Definition Target.cpp:4744
FileSpecList GetExecutableSearchPaths()
Definition Target.cpp:4868
ArchSpec GetDefaultArchitecture() const
Definition Target.cpp:4593
Disassembler::HexImmediateStyle GetHexImmediateStyle() const
Definition Target.cpp:5115
void SetUseDIL(ExecutionContext *exe_ctx, bool b)
Definition Target.cpp:4584
std::unique_ptr< TargetExperimentalProperties > m_experimental_properties_up
Definition Target.h:306
FileSpecList GetClangModuleSearchPaths()
Definition Target.cpp:4878
void SetStandardOutputPath(llvm::StringRef path)
Definition Target.cpp:5019
bool GetRequireHardwareBreakpoints() const
Definition Target.cpp:5193
PathMappingList & GetSourcePathMap() const
Definition Target.cpp:4838
bool GetAutoSourceMapRelative() const
Definition Target.cpp:4854
bool GetUseDIL(ExecutionContext *exe_ctx) const
Definition Target.cpp:4572
void SetDefaultArchitecture(const ArchSpec &arch)
Definition Target.cpp:4598
void SetStandardInputPath(llvm::StringRef path)
Definition Target.cpp:5009
TargetProperties(Target *target)
Definition Target.cpp:4479
bool GetDisplayExpressionsInCrashlogs() const
Definition Target.cpp:5095
bool GetEnableAutoApplyFixIts() const
Definition Target.cpp:4903
void SetDebugUtilityExpression(bool debug)
Definition Target.cpp:5273
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:4984
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:4094
void SetActionFromStrings(const std::vector< std::string > &strings)
Definition Target.cpp:4098
StopHookResult HandleStop(ExecutionContext &exc_ctx, lldb::StreamSP output_sp) override
Definition Target.cpp:4105
void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4076
Status SetScriptCallback(std::string class_name, StructuredData::ObjectSP extra_args_sp)
Definition Target.cpp:4139
StopHookResult HandleStop(ExecutionContext &exc_ctx, lldb::StreamSP output) override
Definition Target.cpp:4179
void GetSubclassDescription(Stream &s, lldb::DescriptionLevel level) const override
Definition Target.cpp:4198
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:4014
std::unique_ptr< ThreadSpec > m_thread_spec_up
Definition Target.h:1546
void SetThreadSpecifier(ThreadSpec *specifier)
Definition Target.cpp:4018
ThreadSpec * GetThreadSpecifier()
Definition Target.h:1515
StopHook(const StopHook &rhs)
Definition Target.cpp:4006
bool ExecutionContextPasses(const ExecutionContext &exe_ctx)
Definition Target.cpp:4022
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:4038
void Dump(Stream *s) const override
Definition Target.cpp:5298
static llvm::StringRef GetFlavorString()
Definition Target.cpp:5294
static lldb::TargetSP GetCreatedTargetFromEvent(const Event *event_ptr)
Definition Target.cpp:5327
static ModuleList GetModuleListFromEvent(const Event *event_ptr)
Definition Target.cpp:5336
static const TargetEventData * GetEventDataFromEvent(const Event *event_ptr)
Definition Target.cpp:5308
TargetEventData(const lldb::TargetSP &target_sp)
Definition Target.cpp:5280
static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr)
Definition Target.cpp:5318
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:1841
lldb::ThreadSP CalculateThread() override
Definition Target.cpp:2579
llvm::Expected< uint32_t > AddScriptedFrameProviderDescriptor(const ScriptedFrameProviderDescriptor &descriptor)
Add or update a scripted frame provider descriptor for this target.
Definition Target.cpp:3719
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:3594
PathMappingList & GetImageSearchPathList()
Definition Target.cpp:2588
void FinalizeFileActions(ProcessLaunchInfo &info)
Definition Target.cpp:3787
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:2987
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:2995
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:2822
lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr)
Definition Target.cpp:3002
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:3946
static void ImageSearchPathsChanged(const PathMappingList &path_list, void *baton)
Definition Target.cpp:2592
llvm::Expected< lldb_private::Address > GetEntryPointAddress()
This method will return the address of the starting function for this binary, e.g.
Definition Target.cpp:2953
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:1868
bool ClearAllWatchpointHistoricValues()
Definition Target.cpp:1423
const std::vector< StopHookSP > GetStopHooks(bool internal=false) const
Definition Target.cpp:3115
void SetTrace(const lldb::TraceSP &trace_sp)
Set the Trace object containing processor trace information of this target.
Definition Target.cpp:3592
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:2628
BreakpointNameList m_breakpoint_names
Definition Target.h:1795
lldb_private::SummaryStatisticsCache & GetSummaryStatisticsCache()
Definition Target.cpp:3409
lldb::addr_t GetSectionLoadAddress(const lldb::SectionSP &section_sp)
Definition Target.cpp:5361
llvm::StringRef GetABIName() const
Returns the name of the target's ABI plugin.
Definition Target.cpp:397
SourceManager & GetSourceManager()
Definition Target.cpp:3039
lldb::SearchFilterSP GetSearchFilterForModuleList(const FileSpecList *containingModuleList)
Definition Target.cpp:690
StopHookSP GetStopHookByID(lldb::user_id_t uid)
Definition Target.cpp:3081
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:2672
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:3934
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:3892
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:1924
lldb::StackFrameSP CalculateStackFrame() override
Definition Target.cpp:2581
SectionLoadList & GetSectionLoadList()
Definition Target.h:1901
lldb::addr_t GetPersistentSymbol(ConstString name)
Definition Target.cpp:2933
void PrimeFromDummyTarget(Target &target)
Definition Target.cpp:220
bool RemoveScriptedFrameProviderDescriptor(uint32_t id)
Remove a scripted frame provider descriptor by id.
Definition Target.cpp:3742
lldb::RegisterTypeBuilderSP m_register_type_builder_sp
Definition Target.h:1846
static void SettingsTerminate()
Definition Target.cpp:2784
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:3325
bool ClearAllWatchpointHitCounts()
Definition Target.cpp:1409
size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len, Status &error)
Definition Target.cpp:1956
void ClearAllLoadedSections()
Definition Target.cpp:3401
std::vector< lldb::TypeSystemSP > GetScratchTypeSystems(bool create_on_demand=true)
Definition Target.cpp:2638
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:2255
void AddNameToBreakpoint(BreakpointID &id, llvm::StringRef name, Status &error)
Definition Target.cpp:829
void DumpSectionLoadList(Stream &s)
Definition Target.cpp:5367
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:2286
void DisableAllowedBreakpoints()
Definition Target.cpp:1083
bool SetSectionUnloaded(const lldb::SectionSP &section_sp)
Definition Target.cpp:3379
lldb::TargetSP CalculateTarget() override
Definition Target.cpp:2575
const lldb::ProcessSP & GetProcessSP() const
Definition Target.cpp:313
void ClearModules(bool delete_locations)
Definition Target.cpp:1545
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:2338
static bool ResetSignalFromDummy(lldb::UnixSignalsSP signals_sp, const DummySignalElement &element)
Definition Target.cpp:3919
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:5353
friend class TargetList
Definition Target.h:555
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:2725
void EnableAllBreakpoints(bool internal_also=false)
Definition Target.cpp:1090
Status Launch(ProcessLaunchInfo &launch_info, Stream *stream)
Definition Target.cpp:3424
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:3596
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:2308
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:3067
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:3319
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:2206
const llvm::DenseMap< uint32_t, ScriptedFrameProviderDescriptor > & GetScriptedFrameProviderDescriptors() const
Get all scripted frame provider descriptors for this target.
Definition Target.cpp:3766
void DeleteBreakpointName(ConstString name)
Definition Target.cpp:885
void NotifyWillClearList(const ModuleList &module_list) override
Definition Target.cpp:1803
bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform=false, bool merge=true)
Set the architecture for this target.
Definition Target.cpp:1687
void NotifyModuleAdded(const ModuleList &module_list, const lldb::ModuleSP &module_sp) override
Implementing of ModuleList::Notifier.
Definition Target.cpp:1805
llvm::Expected< lldb::TypeSystemSP > GetScratchTypeSystemForLanguage(lldb::LanguageType language, bool create_on_demand=true)
Definition Target.cpp:2601
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:3403
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:3091
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:3102
std::vector< StopHookSP > m_internal_stop_hooks
Definition Target.h:1823
lldb::ExpressionVariableSP GetPersistentVariable(ConstString name)
Definition Target.cpp:2914
void NotifyModulesRemoved(lldb_private::ModuleList &module_list) override
Definition Target.cpp:1837
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:3045
size_t ReadCStringFromMemory(const Address &addr, std::string &out_str, Status &error, bool force_live_memory=false)
Definition Target.cpp:2116
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:1884
void CalculateExecutionContext(ExecutionContext &exe_ctx) override
Reconstruct the object's execution context into sc.
Definition Target.cpp:2583
llvm::Expected< lldb::DisassemblerSP > ReadInstructions(const Address &start_addr, uint32_t count, const char *flavor_string=nullptr)
Definition Target.cpp:3008
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:3621
void NotifyModuleUpdated(const ModuleList &module_list, const lldb::ModuleSP &old_module_sp, const lldb::ModuleSP &new_module_sp) override
Definition Target.cpp:1825
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:1552
void SaveScriptedLaunchInfo(lldb_private::ProcessInfo &process_info)
Definition Target.cpp:3413
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:2786
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:5371
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:5344
static llvm::StringRef GetStaticBroadcasterClass()
Definition Target.cpp:170
static FileSpecList GetDefaultDebugFileSearchPaths()
Definition Target.cpp:2790
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:1990
llvm::Error SetLabel(llvm::StringRef label)
Set a label for a target.
Definition Target.cpp:2805
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:3126
void ClearSectionLoadList()
Definition Target.cpp:5365
lldb::addr_t GetReasonableReadSize(const Address &addr)
Return a recommended size for memory reads at addr, optimizing for cache usage.
Definition Target.cpp:2193
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:2755
static TargetProperties & GetGlobalProperties()
Definition Target.cpp:3283
Status Install(ProcessLaunchInfo *launch_info)
Definition Target.cpp:3291
lldb::PlatformSP GetPlatform()
Definition Target.h:1678
void NotifyModuleRemoved(const ModuleList &module_list, const lldb::ModuleSP &module_sp) override
Definition Target.cpp:1815
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:2794
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:928
@ eBroadcastBitWatchpointChanged
Definition Target.h:563
@ eBroadcastBitBreakpointChanged
Definition Target.h:560
@ eBroadcastBitNewTargetCreated
Definition Target.h:566
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:2297
void InvalidateThreadFrameProviders()
Invalidate all potentially cached frame providers for all threads and trigger a stack changed event f...
Definition Target.cpp:3772
TargetStats m_stats
Definition Target.h:1854
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:3360
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:3877
void ClearScriptedFrameProviderDescriptors()
Clear all scripted frame provider descriptors for this target.
Definition Target.cpp:3755
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:1558
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:2692
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:2577
void PrintDummySignals(Stream &strm, Args &signals)
Print all the signals set in this target.
Definition Target.cpp:3971
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:3330
Status Attach(ProcessAttachInfo &attach_info, Stream *stream)
Definition Target.cpp:3627
static void SetDefaultArchitecture(const ArchSpec &arch)
Definition Target.cpp:2798
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:3074
friend class Debugger
Definition Target.h:556
static void SettingsInitialize()
Definition Target.cpp:2782
~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:2836
bool MergeArchitecture(const ArchSpec &arch_spec)
Definition Target.cpp:1778
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
@ eLoadScriptFromSymFileTrusted
Definition Target.h:60
@ 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:75
@ eDynamicClassInfoHelperCopyRealizedClassList
Definition Target.h:78
@ eDynamicClassInfoHelperGetRealizedClassList
Definition Target.h:79
@ eDynamicClassInfoHelperAuto
Definition Target.h:76
@ eDynamicClassInfoHelperRealizedClassesStruct
Definition Target.h:77
OptionEnumValues GetDynamicValueTypes()
Definition Target.cpp:4256
@ eImportStdModuleFalse
Definition Target.h:70
@ eImportStdModuleFallback
Definition Target.h:71
@ eImportStdModuleTrue
Definition Target.h:72
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:63
@ eLoadCWDlldbinitTrue
Definition Target.h:64
@ eLoadCWDlldbinitFalse
Definition Target.h:65
@ eLoadCWDlldbinitWarn
Definition Target.h:66
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.
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