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