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