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