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