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