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