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