1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 // Other libraries and framework includes
15 #include "Plugins/ExpressionParser/Clang/ClangASTSource.h"
16 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
17 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
18 #include "lldb/Breakpoint/BreakpointIDList.h"
19 #include "lldb/Breakpoint/BreakpointResolver.h"
20 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
21 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
22 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
23 #include "lldb/Breakpoint/BreakpointResolverName.h"
24 #include "lldb/Breakpoint/Watchpoint.h"
25 #include "lldb/Core/Debugger.h"
26 #include "lldb/Core/Event.h"
27 #include "lldb/Core/Module.h"
28 #include "lldb/Core/ModuleSpec.h"
29 #include "lldb/Core/PluginManager.h"
30 #include "lldb/Core/Section.h"
31 #include "lldb/Core/SourceManager.h"
32 #include "lldb/Core/State.h"
33 #include "lldb/Core/StreamFile.h"
34 #include "lldb/Core/ValueObject.h"
35 #include "lldb/Expression/REPL.h"
36 #include "lldb/Expression/UserExpression.h"
37 #include "lldb/Host/Host.h"
38 #include "lldb/Host/PosixApi.h"
39 #include "lldb/Interpreter/CommandInterpreter.h"
40 #include "lldb/Interpreter/CommandReturnObject.h"
41 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
42 #include "lldb/Interpreter/OptionValues.h"
43 #include "lldb/Interpreter/Property.h"
44 #include "lldb/Symbol/ClangASTContext.h"
45 #include "lldb/Symbol/Function.h"
46 #include "lldb/Symbol/ObjectFile.h"
47 #include "lldb/Symbol/Symbol.h"
48 #include "lldb/Target/Language.h"
49 #include "lldb/Target/LanguageRuntime.h"
50 #include "lldb/Target/ObjCLanguageRuntime.h"
51 #include "lldb/Target/Process.h"
52 #include "lldb/Target/SectionLoadList.h"
53 #include "lldb/Target/StackFrame.h"
54 #include "lldb/Target/SystemRuntime.h"
55 #include "lldb/Target/Target.h"
56 #include "lldb/Target/Thread.h"
57 #include "lldb/Target/ThreadSpec.h"
58 #include "lldb/Utility/FileSpec.h"
59 #include "lldb/Utility/LLDBAssert.h"
60 #include "lldb/Utility/Log.h"
61 #include "lldb/Utility/StreamString.h"
62 #include "lldb/Utility/Timer.h"
65 using namespace lldb_private;
67 constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
69 Target::Arch::Arch(const ArchSpec &spec)
71 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
73 const Target::Arch& Target::Arch::operator=(const ArchSpec &spec) {
75 m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
79 ConstString &Target::GetStaticBroadcasterClass() {
80 static ConstString class_name("lldb.target");
84 Target::Target(Debugger &debugger, const ArchSpec &target_arch,
85 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
86 : TargetProperties(this),
87 Broadcaster(debugger.GetBroadcasterManager(),
88 Target::GetStaticBroadcasterClass().AsCString()),
89 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
90 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
91 m_breakpoint_list(false), m_internal_breakpoint_list(true),
92 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
93 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
94 m_source_manager_ap(), m_stop_hooks(), m_stop_hook_next_id(0),
95 m_valid(true), m_suppress_stop_hooks(false),
96 m_is_dummy_target(is_dummy_target),
97 m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
100 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
101 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
102 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
103 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
104 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
106 CheckInWithManager();
108 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
110 log->Printf("%p Target::Target()", static_cast<void *>(this));
111 if (target_arch.IsValid()) {
112 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET,
113 "Target::Target created with architecture %s (%s)",
114 target_arch.GetArchitectureName(),
115 target_arch.GetTriple().getTriple().c_str());
120 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
122 log->Printf("%p Target::~Target()", static_cast<void *>(this));
123 DeleteCurrentProcess();
126 void Target::PrimeFromDummyTarget(Target *target) {
130 m_stop_hooks = target->m_stop_hooks;
132 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
133 if (breakpoint_sp->IsInternal())
136 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
137 AddBreakpoint(new_bp, false);
140 for (auto bp_name_entry : target->m_breakpoint_names)
143 BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
144 AddBreakpointName(new_bp_name);
148 void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
149 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
150 if (description_level != lldb::eDescriptionLevelBrief) {
152 s->PutCString("Target\n");
155 m_breakpoint_list.Dump(s);
156 m_internal_breakpoint_list.Dump(s);
159 Module *exe_module = GetExecutableModulePointer();
161 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
163 s->PutCString("No executable module.");
167 void Target::CleanupProcess() {
168 // Do any cleanup of the target we need to do between process instances.
169 // NB It is better to do this before destroying the process in case the
170 // clean up needs some help from the process.
171 m_breakpoint_list.ClearAllBreakpointSites();
172 m_internal_breakpoint_list.ClearAllBreakpointSites();
173 // Disable watchpoints just on the debugger side.
174 std::unique_lock<std::recursive_mutex> lock;
175 this->GetWatchpointList().GetListMutex(lock);
176 DisableAllWatchpoints(false);
177 ClearAllWatchpointHitCounts();
178 ClearAllWatchpointHistoricValues();
181 void Target::DeleteCurrentProcess() {
183 m_section_load_history.Clear();
184 if (m_process_sp->IsAlive())
185 m_process_sp->Destroy(false);
187 m_process_sp->Finalize();
191 m_process_sp.reset();
195 const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
196 llvm::StringRef plugin_name,
197 const FileSpec *crash_file) {
198 DeleteCurrentProcess();
199 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
200 listener_sp, crash_file);
204 const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
206 lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
207 const char *repl_options, bool can_create) {
208 if (language == eLanguageTypeUnknown) {
209 std::set<LanguageType> repl_languages;
211 Language::GetLanguagesSupportingREPLs(repl_languages);
213 if (repl_languages.size() == 1) {
214 language = *repl_languages.begin();
215 } else if (repl_languages.size() == 0) {
216 err.SetErrorStringWithFormat(
217 "LLDB isn't configured with REPL support for any languages.");
220 err.SetErrorStringWithFormat(
221 "Multiple possible REPL languages. Please specify a language.");
226 REPLMap::iterator pos = m_repl_map.find(language);
228 if (pos != m_repl_map.end()) {
233 err.SetErrorStringWithFormat(
234 "Couldn't find an existing REPL for %s, and can't create a new one",
235 Language::GetNameForLanguageType(language));
236 return lldb::REPLSP();
239 Debugger *const debugger = nullptr;
240 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
243 m_repl_map[language] = ret;
244 return m_repl_map[language];
248 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
249 Language::GetNameForLanguageType(language));
252 return lldb::REPLSP();
255 void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
256 lldbassert(!m_repl_map.count(language));
258 m_repl_map[language] = repl_sp;
261 void Target::Destroy() {
262 std::lock_guard<std::recursive_mutex> guard(m_mutex);
264 DeleteCurrentProcess();
265 m_platform_sp.reset();
268 m_section_load_history.Clear();
269 const bool notify = false;
270 m_breakpoint_list.RemoveAll(notify);
271 m_internal_breakpoint_list.RemoveAll(notify);
272 m_last_created_breakpoint.reset();
273 m_last_created_watchpoint.reset();
274 m_search_filter_sp.reset();
275 m_image_search_paths.Clear(notify);
276 m_stop_hooks.clear();
277 m_stop_hook_next_id = 0;
278 m_suppress_stop_hooks = false;
281 BreakpointList &Target::GetBreakpointList(bool internal) {
283 return m_internal_breakpoint_list;
285 return m_breakpoint_list;
288 const BreakpointList &Target::GetBreakpointList(bool internal) const {
290 return m_internal_breakpoint_list;
292 return m_breakpoint_list;
295 BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
298 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
299 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
301 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
306 BreakpointSP Target::CreateSourceRegexBreakpoint(
307 const FileSpecList *containingModules,
308 const FileSpecList *source_file_spec_list,
309 const std::unordered_set<std::string> &function_names,
310 RegularExpression &source_regex, bool internal, bool hardware,
311 LazyBool move_to_nearest_code) {
312 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
313 containingModules, source_file_spec_list));
314 if (move_to_nearest_code == eLazyBoolCalculate)
315 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
316 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
317 nullptr, source_regex, function_names,
318 !static_cast<bool>(move_to_nearest_code)));
320 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
323 BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
324 const FileSpec &file, uint32_t line_no,
326 LazyBool check_inlines,
327 LazyBool skip_prologue, bool internal,
329 LazyBool move_to_nearest_code) {
330 FileSpec remapped_file;
331 if (!GetSourcePathMap().ReverseRemapPath(file, remapped_file))
332 remapped_file = file;
334 if (check_inlines == eLazyBoolCalculate) {
335 const InlineStrategy inline_strategy = GetInlineStrategy();
336 switch (inline_strategy) {
337 case eInlineBreakpointsNever:
338 check_inlines = eLazyBoolNo;
341 case eInlineBreakpointsHeaders:
342 if (remapped_file.IsSourceImplementationFile())
343 check_inlines = eLazyBoolNo;
345 check_inlines = eLazyBoolYes;
348 case eInlineBreakpointsAlways:
349 check_inlines = eLazyBoolYes;
353 SearchFilterSP filter_sp;
354 if (check_inlines == eLazyBoolNo) {
355 // Not checking for inlines, we are looking only for matching compile units
356 FileSpecList compile_unit_list;
357 compile_unit_list.Append(remapped_file);
358 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
361 filter_sp = GetSearchFilterForModuleList(containingModules);
363 if (skip_prologue == eLazyBoolCalculate)
364 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
365 if (move_to_nearest_code == eLazyBoolCalculate)
366 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
368 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
369 nullptr, remapped_file, line_no, offset, check_inlines, skip_prologue,
370 !static_cast<bool>(move_to_nearest_code)));
371 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
374 BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
378 // Check for any reason we want to move this breakpoint to other address.
379 addr = GetBreakableLoadAddress(addr);
381 // Attempt to resolve our load address if possible, though it is ok if it
382 // doesn't resolve to section/offset.
384 // Try and resolve as a load address if possible
385 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
386 if (!so_addr.IsValid()) {
387 // The address didn't resolve, so just set this as an absolute address
388 so_addr.SetOffset(addr);
390 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
394 BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
396 SearchFilterSP filter_sp(
397 new SearchFilterForUnconstrainedSearches(shared_from_this()));
398 BreakpointResolverSP resolver_sp(
399 new BreakpointResolverAddress(nullptr, addr));
400 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
404 Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
405 const FileSpec *file_spec,
406 bool request_hardware) {
407 SearchFilterSP filter_sp(
408 new SearchFilterForUnconstrainedSearches(shared_from_this()));
409 BreakpointResolverSP resolver_sp(
410 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
411 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
416 Target::CreateBreakpoint(const FileSpecList *containingModules,
417 const FileSpecList *containingSourceFiles,
418 const char *func_name, uint32_t func_name_type_mask,
419 LanguageType language, lldb::addr_t offset,
420 LazyBool skip_prologue, bool internal, bool hardware) {
423 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
424 containingModules, containingSourceFiles));
426 if (skip_prologue == eLazyBoolCalculate)
427 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
428 if (language == lldb::eLanguageTypeUnknown)
429 language = GetLanguage();
431 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
432 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
433 offset, skip_prologue));
434 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
440 Target::CreateBreakpoint(const FileSpecList *containingModules,
441 const FileSpecList *containingSourceFiles,
442 const std::vector<std::string> &func_names,
443 uint32_t func_name_type_mask, LanguageType language,
444 lldb::addr_t offset, LazyBool skip_prologue,
445 bool internal, bool hardware) {
447 size_t num_names = func_names.size();
449 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
450 containingModules, containingSourceFiles));
452 if (skip_prologue == eLazyBoolCalculate)
453 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
454 if (language == lldb::eLanguageTypeUnknown)
455 language = GetLanguage();
457 BreakpointResolverSP resolver_sp(
458 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
459 language, offset, skip_prologue));
460 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
465 BreakpointSP Target::CreateBreakpoint(
466 const FileSpecList *containingModules,
467 const FileSpecList *containingSourceFiles, const char *func_names[],
468 size_t num_names, uint32_t func_name_type_mask, LanguageType language,
469 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
472 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
473 containingModules, containingSourceFiles));
475 if (skip_prologue == eLazyBoolCalculate) {
477 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
479 skip_prologue = eLazyBoolNo;
481 if (language == lldb::eLanguageTypeUnknown)
482 language = GetLanguage();
484 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
485 nullptr, func_names, num_names, func_name_type_mask, language, offset,
487 resolver_sp->SetOffset(offset);
488 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
494 Target::GetSearchFilterForModule(const FileSpec *containingModule) {
495 SearchFilterSP filter_sp;
496 if (containingModule != nullptr) {
497 // TODO: We should look into sharing module based search filters
498 // across many breakpoints like we do for the simple target based one
500 new SearchFilterByModule(shared_from_this(), *containingModule));
502 if (!m_search_filter_sp)
503 m_search_filter_sp.reset(
504 new SearchFilterForUnconstrainedSearches(shared_from_this()));
505 filter_sp = m_search_filter_sp;
511 Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
512 SearchFilterSP filter_sp;
513 if (containingModules && containingModules->GetSize() != 0) {
514 // TODO: We should look into sharing module based search filters
515 // across many breakpoints like we do for the simple target based one
517 new SearchFilterByModuleList(shared_from_this(), *containingModules));
519 if (!m_search_filter_sp)
520 m_search_filter_sp.reset(
521 new SearchFilterForUnconstrainedSearches(shared_from_this()));
522 filter_sp = m_search_filter_sp;
527 SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
528 const FileSpecList *containingModules,
529 const FileSpecList *containingSourceFiles) {
530 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
531 return GetSearchFilterForModuleList(containingModules);
533 SearchFilterSP filter_sp;
534 if (containingModules == nullptr) {
535 // We could make a special "CU List only SearchFilter". Better yet was if
536 // these could be composable, but that will take a little reworking.
538 filter_sp.reset(new SearchFilterByModuleListAndCU(
539 shared_from_this(), FileSpecList(), *containingSourceFiles));
541 filter_sp.reset(new SearchFilterByModuleListAndCU(
542 shared_from_this(), *containingModules, *containingSourceFiles));
547 BreakpointSP Target::CreateFuncRegexBreakpoint(
548 const FileSpecList *containingModules,
549 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
550 lldb::LanguageType requested_language, LazyBool skip_prologue,
551 bool internal, bool hardware) {
552 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
553 containingModules, containingSourceFiles));
554 bool skip = (skip_prologue == eLazyBoolCalculate)
556 : static_cast<bool>(skip_prologue);
557 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
558 nullptr, func_regex, requested_language, 0, skip));
560 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
564 Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
565 bool catch_bp, bool throw_bp, bool internal,
566 Args *additional_args, Status *error) {
567 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
568 *this, language, catch_bp, throw_bp, internal);
569 if (exc_bkpt_sp && additional_args) {
570 Breakpoint::BreakpointPreconditionSP precondition_sp =
571 exc_bkpt_sp->GetPrecondition();
572 if (precondition_sp && additional_args) {
574 *error = precondition_sp->ConfigurePrecondition(*additional_args);
576 precondition_sp->ConfigurePrecondition(*additional_args);
582 BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
583 BreakpointResolverSP &resolver_sp,
584 bool internal, bool request_hardware,
585 bool resolve_indirect_symbols) {
587 if (filter_sp && resolver_sp) {
588 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, request_hardware,
589 resolve_indirect_symbols));
590 resolver_sp->SetBreakpoint(bp_sp.get());
591 AddBreakpoint(bp_sp, internal);
596 void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
600 m_internal_breakpoint_list.Add(bp_sp, false);
602 m_breakpoint_list.Add(bp_sp, true);
604 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
607 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
608 log->Printf("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__,
609 bp_sp->IsInternal() ? "yes" : "no", s.GetData());
612 bp_sp->ResolveBreakpoint();
615 m_last_created_breakpoint = bp_sp;
619 void Target::AddNameToBreakpoint(BreakpointID &id,
624 = m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
628 id.GetDescription(&s, eDescriptionLevelBrief);
629 error.SetErrorStringWithFormat("Could not find breakpoint %s",
633 AddNameToBreakpoint(bp_sp, name, error);
636 void Target::AddNameToBreakpoint(BreakpointSP &bp_sp,
643 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
647 bp_name->ConfigureBreakpoint(bp_sp);
648 bp_sp->AddName(name);
651 void Target::AddBreakpointName(BreakpointName *bp_name) {
652 m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name));
655 BreakpointName *Target::FindBreakpointName(const ConstString &name,
659 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
660 if (!error.Success())
663 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
664 if (iter == m_breakpoint_names.end()) {
667 error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
668 "can_create is false.", name.AsCString());
672 iter = m_breakpoint_names.insert(std::make_pair(name,
673 new BreakpointName(name)))
676 return (iter->second);
680 Target::DeleteBreakpointName(const ConstString &name)
682 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
684 if (iter != m_breakpoint_names.end()) {
685 const char *name_cstr = name.AsCString();
686 m_breakpoint_names.erase(iter);
687 for (auto bp_sp : m_breakpoint_list.Breakpoints())
688 bp_sp->RemoveName(name_cstr);
692 void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
693 const ConstString &name)
695 bp_sp->RemoveName(name.AsCString());
698 void Target::ConfigureBreakpointName(BreakpointName &bp_name,
699 const BreakpointOptions &new_options,
700 const BreakpointName::Permissions &new_permissions)
702 bp_name.GetOptions().CopyOverSetOptions(new_options);
703 bp_name.GetPermissions().MergeInto(new_permissions);
704 ApplyNameToBreakpoints(bp_name);
707 void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
708 BreakpointList bkpts_with_name(false);
709 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString(),
712 for (auto bp_sp : bkpts_with_name.Breakpoints())
713 bp_name.ConfigureBreakpoint(bp_sp);
716 void Target::GetBreakpointNames(std::vector<std::string> &names)
719 for (auto bp_name : m_breakpoint_names) {
720 names.push_back(bp_name.first.AsCString());
722 std::sort(names.begin(), names.end());
725 bool Target::ProcessIsValid() {
726 return (m_process_sp && m_process_sp->IsAlive());
729 static bool CheckIfWatchpointsExhausted(Target *target, Status &error) {
730 uint32_t num_supported_hardware_watchpoints;
731 Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
732 num_supported_hardware_watchpoints);
733 if (num_supported_hardware_watchpoints == 0) {
734 error.SetErrorStringWithFormat(
735 "Target supports (%u) hardware watchpoint slots.\n",
736 num_supported_hardware_watchpoints);
742 // See also Watchpoint::SetWatchpointType(uint32_t type) and the
743 // OptionGroupWatchpoint::WatchType enum type.
744 WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
745 const CompilerType *type, uint32_t kind,
747 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
749 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
751 __FUNCTION__, addr, (uint64_t)size, kind);
754 if (!ProcessIsValid()) {
755 error.SetErrorString("process is not alive");
759 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
761 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
763 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
767 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
768 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
771 if (!CheckIfWatchpointsExhausted(this, error))
774 // Currently we only support one watchpoint per address, with total number of
775 // watchpoints limited by the hardware which the inferior is running on.
777 // Grab the list mutex while doing operations.
778 const bool notify = false; // Don't notify about all the state changes we do
779 // on creating the watchpoint.
780 std::unique_lock<std::recursive_mutex> lock;
781 this->GetWatchpointList().GetListMutex(lock);
782 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
784 size_t old_size = matched_sp->GetByteSize();
786 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
787 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
788 // Return the existing watchpoint if both size and type match.
789 if (size == old_size && kind == old_type) {
791 wp_sp->SetEnabled(false, notify);
793 // Nil the matched watchpoint; we will be creating a new one.
794 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
795 m_watchpoint_list.Remove(matched_sp->GetID(), true);
800 wp_sp.reset(new Watchpoint(*this, addr, size, type));
801 wp_sp->SetWatchpointType(kind, notify);
802 m_watchpoint_list.Add(wp_sp, true);
805 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
807 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
808 __FUNCTION__, error.Success() ? "succeeded" : "failed",
812 // Enabling the watchpoint on the device side failed. Remove the said
813 // watchpoint from the list maintained by the target instance.
814 m_watchpoint_list.Remove(wp_sp->GetID(), true);
815 // See if we could provide more helpful error message.
816 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
817 error.SetErrorStringWithFormat(
818 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
822 m_last_created_watchpoint = wp_sp;
826 void Target::RemoveAllowedBreakpoints ()
828 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
830 log->Printf("Target::%s \n", __FUNCTION__);
832 m_breakpoint_list.RemoveAllowed(true);
834 m_last_created_breakpoint.reset();
837 void Target::RemoveAllBreakpoints(bool internal_also) {
838 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
840 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
841 internal_also ? "yes" : "no");
843 m_breakpoint_list.RemoveAll(true);
845 m_internal_breakpoint_list.RemoveAll(false);
847 m_last_created_breakpoint.reset();
850 void Target::DisableAllBreakpoints(bool internal_also) {
851 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
853 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
854 internal_also ? "yes" : "no");
856 m_breakpoint_list.SetEnabledAll(false);
858 m_internal_breakpoint_list.SetEnabledAll(false);
861 void Target::DisableAllowedBreakpoints() {
862 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
864 log->Printf("Target::%s", __FUNCTION__);
866 m_breakpoint_list.SetEnabledAllowed(false);
869 void Target::EnableAllBreakpoints(bool internal_also) {
870 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
872 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
873 internal_also ? "yes" : "no");
875 m_breakpoint_list.SetEnabledAll(true);
877 m_internal_breakpoint_list.SetEnabledAll(true);
880 void Target::EnableAllowedBreakpoints() {
881 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
883 log->Printf("Target::%s", __FUNCTION__);
885 m_breakpoint_list.SetEnabledAllowed(true);
888 bool Target::RemoveBreakpointByID(break_id_t break_id) {
889 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
891 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
892 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
894 if (DisableBreakpointByID(break_id)) {
895 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
896 m_internal_breakpoint_list.Remove(break_id, false);
898 if (m_last_created_breakpoint) {
899 if (m_last_created_breakpoint->GetID() == break_id)
900 m_last_created_breakpoint.reset();
902 m_breakpoint_list.Remove(break_id, true);
909 bool Target::DisableBreakpointByID(break_id_t break_id) {
910 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
912 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
913 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
917 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
918 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
920 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
922 bp_sp->SetEnabled(false);
928 bool Target::EnableBreakpointByID(break_id_t break_id) {
929 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
931 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
932 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
936 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
937 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
939 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
942 bp_sp->SetEnabled(true);
948 Status Target::SerializeBreakpointsToFile(const FileSpec &file,
949 const BreakpointIDList &bp_ids,
954 error.SetErrorString("Invalid FileSpec.");
958 std::string path(file.GetPath());
959 StructuredData::ObjectSP input_data_sp;
961 StructuredData::ArraySP break_store_sp;
962 StructuredData::Array *break_store_ptr = nullptr;
965 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
966 if (error.Success()) {
967 break_store_ptr = input_data_sp->GetAsArray();
968 if (!break_store_ptr) {
969 error.SetErrorStringWithFormat(
970 "Tried to append to invalid input file %s", path.c_str());
976 if (!break_store_ptr) {
977 break_store_sp.reset(new StructuredData::Array());
978 break_store_ptr = break_store_sp.get();
981 StreamFile out_file(path.c_str(),
982 File::OpenOptions::eOpenOptionTruncate |
983 File::OpenOptions::eOpenOptionWrite |
984 File::OpenOptions::eOpenOptionCanCreate |
985 File::OpenOptions::eOpenOptionCloseOnExec,
986 lldb::eFilePermissionsFileDefault);
987 if (!out_file.GetFile().IsValid()) {
988 error.SetErrorStringWithFormat("Unable to open output file: %s.",
993 std::unique_lock<std::recursive_mutex> lock;
994 GetBreakpointList().GetListMutex(lock);
996 if (bp_ids.GetSize() == 0) {
997 const BreakpointList &breakpoints = GetBreakpointList();
999 size_t num_breakpoints = breakpoints.GetSize();
1000 for (size_t i = 0; i < num_breakpoints; i++) {
1001 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1002 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1003 // If a breakpoint can't serialize it, just ignore it for now:
1005 break_store_ptr->AddItem(bkpt_save_sp);
1009 std::unordered_set<lldb::break_id_t> processed_bkpts;
1010 const size_t count = bp_ids.GetSize();
1011 for (size_t i = 0; i < count; ++i) {
1012 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1013 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1015 if (bp_id != LLDB_INVALID_BREAK_ID) {
1016 // Only do each breakpoint once:
1017 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1018 insert_result = processed_bkpts.insert(bp_id);
1019 if (!insert_result.second)
1022 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1023 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1024 // If the user explicitly asked to serialize a breakpoint, and we
1025 // can't, then raise an error:
1026 if (!bkpt_save_sp) {
1027 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1031 break_store_ptr->AddItem(bkpt_save_sp);
1036 break_store_ptr->Dump(out_file, false);
1037 out_file.PutChar('\n');
1041 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1042 BreakpointIDList &new_bps) {
1043 std::vector<std::string> no_names;
1044 return CreateBreakpointsFromFile(file, no_names, new_bps);
1047 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1048 std::vector<std::string> &names,
1049 BreakpointIDList &new_bps) {
1050 std::unique_lock<std::recursive_mutex> lock;
1051 GetBreakpointList().GetListMutex(lock);
1054 StructuredData::ObjectSP input_data_sp =
1055 StructuredData::ParseJSONFromFile(file, error);
1056 if (!error.Success()) {
1058 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1059 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1060 file.GetPath().c_str());
1064 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1066 error.SetErrorStringWithFormat(
1067 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1071 size_t num_bkpts = bkpt_array->GetSize();
1072 size_t num_names = names.size();
1074 for (size_t i = 0; i < num_bkpts; i++) {
1075 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1076 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1077 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1079 error.SetErrorStringWithFormat(
1080 "Invalid breakpoint data for element %zu from input file: %s.", i,
1081 file.GetPath().c_str());
1084 StructuredData::ObjectSP bkpt_data_sp =
1085 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
1087 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1090 BreakpointSP bkpt_sp =
1091 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1092 if (!error.Success()) {
1093 error.SetErrorStringWithFormat(
1094 "Error restoring breakpoint %zu from %s: %s.", i,
1095 file.GetPath().c_str(), error.AsCString());
1098 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1103 // The flag 'end_to_end', default to true, signifies that the operation is
1104 // performed end to end, for both the debugger and the debuggee.
1106 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1107 // to end operations.
1108 bool Target::RemoveAllWatchpoints(bool end_to_end) {
1109 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1111 log->Printf("Target::%s\n", __FUNCTION__);
1114 m_watchpoint_list.RemoveAll(true);
1118 // Otherwise, it's an end to end operation.
1120 if (!ProcessIsValid())
1123 size_t num_watchpoints = m_watchpoint_list.GetSize();
1124 for (size_t i = 0; i < num_watchpoints; ++i) {
1125 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1129 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1133 m_watchpoint_list.RemoveAll(true);
1134 m_last_created_watchpoint.reset();
1135 return true; // Success!
1138 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1139 // to end operations.
1140 bool Target::DisableAllWatchpoints(bool end_to_end) {
1141 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1143 log->Printf("Target::%s\n", __FUNCTION__);
1146 m_watchpoint_list.SetEnabledAll(false);
1150 // Otherwise, it's an end to end operation.
1152 if (!ProcessIsValid())
1155 size_t num_watchpoints = m_watchpoint_list.GetSize();
1156 for (size_t i = 0; i < num_watchpoints; ++i) {
1157 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1161 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1165 return true; // Success!
1168 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1169 // to end operations.
1170 bool Target::EnableAllWatchpoints(bool end_to_end) {
1171 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1173 log->Printf("Target::%s\n", __FUNCTION__);
1176 m_watchpoint_list.SetEnabledAll(true);
1180 // Otherwise, it's an end to end operation.
1182 if (!ProcessIsValid())
1185 size_t num_watchpoints = m_watchpoint_list.GetSize();
1186 for (size_t i = 0; i < num_watchpoints; ++i) {
1187 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1191 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1195 return true; // Success!
1198 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1199 bool Target::ClearAllWatchpointHitCounts() {
1200 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1202 log->Printf("Target::%s\n", __FUNCTION__);
1204 size_t num_watchpoints = m_watchpoint_list.GetSize();
1205 for (size_t i = 0; i < num_watchpoints; ++i) {
1206 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1210 wp_sp->ResetHitCount();
1212 return true; // Success!
1215 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1216 bool Target::ClearAllWatchpointHistoricValues() {
1217 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1219 log->Printf("Target::%s\n", __FUNCTION__);
1221 size_t num_watchpoints = m_watchpoint_list.GetSize();
1222 for (size_t i = 0; i < num_watchpoints; ++i) {
1223 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1227 wp_sp->ResetHistoricValues();
1229 return true; // Success!
1232 // Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1233 // these operations.
1234 bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1235 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1237 log->Printf("Target::%s\n", __FUNCTION__);
1239 if (!ProcessIsValid())
1242 size_t num_watchpoints = m_watchpoint_list.GetSize();
1243 for (size_t i = 0; i < num_watchpoints; ++i) {
1244 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1248 wp_sp->SetIgnoreCount(ignore_count);
1250 return true; // Success!
1253 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1254 bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1255 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1257 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1259 if (!ProcessIsValid())
1262 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1264 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1268 // Else, fallthrough.
1273 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1274 bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1275 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1277 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1279 if (!ProcessIsValid())
1282 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1284 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1288 // Else, fallthrough.
1293 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1294 bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1295 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1297 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1299 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1300 if (watch_to_remove_sp == m_last_created_watchpoint)
1301 m_last_created_watchpoint.reset();
1303 if (DisableWatchpointByID(watch_id)) {
1304 m_watchpoint_list.Remove(watch_id, true);
1310 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1311 bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1312 uint32_t ignore_count) {
1313 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1315 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1317 if (!ProcessIsValid())
1320 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1322 wp_sp->SetIgnoreCount(ignore_count);
1328 ModuleSP Target::GetExecutableModule() {
1329 // search for the first executable in the module list
1330 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1331 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1332 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1335 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1338 // as fall back return the first module loaded
1339 return m_images.GetModuleAtIndex(0);
1342 Module *Target::GetExecutableModulePointer() {
1343 return GetExecutableModule().get();
1346 static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1349 StreamString feedback_stream;
1351 !module_sp->LoadScriptingResourceInTarget(target, error,
1352 &feedback_stream)) {
1353 if (error.AsCString())
1354 target->GetDebugger().GetErrorFile()->Printf(
1355 "unable to load scripting data for module %s - error reported was "
1357 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1360 if (feedback_stream.GetSize())
1361 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1362 feedback_stream.GetData());
1365 void Target::ClearModules(bool delete_locations) {
1366 ModulesDidUnload(m_images, delete_locations);
1367 m_section_load_history.Clear();
1369 m_scratch_type_system_map.Clear();
1370 m_ast_importer_sp.reset();
1373 void Target::DidExec() {
1374 // When a process exec's we need to know about it so we can do some cleanup.
1375 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1376 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1379 void Target::SetExecutableModule(ModuleSP &executable_sp,
1380 bool get_dependent_files) {
1381 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1382 ClearModules(false);
1384 if (executable_sp) {
1385 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1386 Timer scoped_timer(func_cat,
1387 "Target::SetExecutableModule (executable = '%s')",
1388 executable_sp->GetFileSpec().GetPath().c_str());
1390 m_images.Append(executable_sp); // The first image is our executable file
1392 // If we haven't set an architecture yet, reset our architecture based on
1393 // what we found in the executable module.
1394 if (!m_arch.GetSpec().IsValid()) {
1395 m_arch = executable_sp->GetArchitecture();
1397 "setting architecture to {0} ({1}) based on executable file",
1398 m_arch.GetSpec().GetArchitectureName(),
1399 m_arch.GetSpec().GetTriple().getTriple());
1402 FileSpecList dependent_files;
1403 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1405 if (executable_objfile && get_dependent_files) {
1406 executable_objfile->GetDependentModules(dependent_files);
1407 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1408 FileSpec dependent_file_spec(
1409 dependent_files.GetFileSpecPointerAtIndex(i));
1410 FileSpec platform_dependent_file_spec;
1412 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1413 platform_dependent_file_spec);
1415 platform_dependent_file_spec = dependent_file_spec;
1417 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1418 ModuleSP image_module_sp(GetSharedModule(module_spec));
1419 if (image_module_sp) {
1420 ObjectFile *objfile = image_module_sp->GetObjectFile();
1422 objfile->GetDependentModules(dependent_files);
1429 bool Target::SetArchitecture(const ArchSpec &arch_spec) {
1430 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1431 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1432 bool replace_local_arch = true;
1433 bool compatible_local_arch = false;
1434 ArchSpec other(arch_spec);
1436 if (!missing_local_arch) {
1437 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1438 other.MergeFrom(m_arch.GetSpec());
1440 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1441 compatible_local_arch = true;
1442 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1445 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed, vendor_changed,
1446 os_changed, os_ver_changed, env_changed);
1448 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1449 replace_local_arch = false;
1454 if (compatible_local_arch || missing_local_arch) {
1455 // If we haven't got a valid arch spec, or the architectures are compatible
1456 // update the architecture, unless the one we already have is more
1458 if (replace_local_arch)
1460 LLDB_LOG(log, "set architecture to {0} ({1})",
1461 m_arch.GetSpec().GetArchitectureName(),
1462 m_arch.GetSpec().GetTriple().getTriple());
1466 // If we have an executable file, try to reset the executable to the desired
1469 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1470 arch_spec.GetArchitectureName(),
1471 arch_spec.GetTriple().getTriple().c_str());
1473 ModuleSP executable_sp = GetExecutableModule();
1476 // Need to do something about unsetting breakpoints.
1478 if (executable_sp) {
1480 log->Printf("Target::SetArchitecture Trying to select executable file "
1481 "architecture %s (%s)",
1482 arch_spec.GetArchitectureName(),
1483 arch_spec.GetTriple().getTriple().c_str());
1484 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1485 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1486 &GetExecutableSearchPaths(),
1489 if (!error.Fail() && executable_sp) {
1490 SetExecutableModule(executable_sp, true);
1497 bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1498 if (arch_spec.IsValid()) {
1499 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1500 // The current target arch is compatible with "arch_spec", see if we can
1501 // improve our current architecture using bits from "arch_spec"
1503 // Merge bits from arch_spec into "merged_arch" and set our architecture
1504 ArchSpec merged_arch(m_arch.GetSpec());
1505 merged_arch.MergeFrom(arch_spec);
1506 return SetArchitecture(merged_arch);
1508 // The new architecture is different, we just need to replace it
1509 return SetArchitecture(arch_spec);
1515 void Target::WillClearList(const ModuleList &module_list) {}
1517 void Target::ModuleAdded(const ModuleList &module_list,
1518 const ModuleSP &module_sp) {
1519 // A module is being added to this target for the first time
1521 ModuleList my_module_list;
1522 my_module_list.Append(module_sp);
1523 LoadScriptingResourceForModule(module_sp, this);
1524 ModulesDidLoad(my_module_list);
1528 void Target::ModuleRemoved(const ModuleList &module_list,
1529 const ModuleSP &module_sp) {
1530 // A module is being removed from this target.
1532 ModuleList my_module_list;
1533 my_module_list.Append(module_sp);
1534 ModulesDidUnload(my_module_list, false);
1538 void Target::ModuleUpdated(const ModuleList &module_list,
1539 const ModuleSP &old_module_sp,
1540 const ModuleSP &new_module_sp) {
1541 // A module is replacing an already added module
1543 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1545 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1546 old_module_sp, new_module_sp);
1550 void Target::ModulesDidLoad(ModuleList &module_list) {
1551 if (m_valid && module_list.GetSize()) {
1552 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1553 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1555 m_process_sp->ModulesDidLoad(module_list);
1557 BroadcastEvent(eBroadcastBitModulesLoaded,
1558 new TargetEventData(this->shared_from_this(), module_list));
1562 void Target::SymbolsDidLoad(ModuleList &module_list) {
1563 if (m_valid && module_list.GetSize()) {
1565 LanguageRuntime *runtime =
1566 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1568 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1569 objc_runtime->SymbolsDidLoad(module_list);
1573 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1574 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1575 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1576 new TargetEventData(this->shared_from_this(), module_list));
1580 void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1581 if (m_valid && module_list.GetSize()) {
1582 UnloadModuleSections(module_list);
1583 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1584 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1586 BroadcastEvent(eBroadcastBitModulesUnloaded,
1587 new TargetEventData(this->shared_from_this(), module_list));
1591 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1592 const FileSpec &module_file_spec) {
1593 if (GetBreakpointsConsultPlatformAvoidList()) {
1594 ModuleList matchingModules;
1595 ModuleSpec module_spec(module_file_spec);
1596 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1598 // If there is more than one module for this file spec, only return true if
1599 // ALL the modules are on the
1601 if (num_modules > 0) {
1602 for (size_t i = 0; i < num_modules; i++) {
1603 if (!ModuleIsExcludedForUnconstrainedSearches(
1604 matchingModules.GetModuleAtIndex(i)))
1613 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1614 const lldb::ModuleSP &module_sp) {
1615 if (GetBreakpointsConsultPlatformAvoidList()) {
1617 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1623 size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1624 size_t dst_len, Status &error) {
1625 SectionSP section_sp(addr.GetSection());
1627 // If the contents of this section are encrypted, the on-disk file is
1628 // unusable. Read only from live memory.
1629 if (section_sp->IsEncrypted()) {
1630 error.SetErrorString("section is encrypted");
1633 ModuleSP module_sp(section_sp->GetModule());
1635 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1637 size_t bytes_read = objfile->ReadSectionData(
1638 section_sp.get(), addr.GetOffset(), dst, dst_len);
1642 error.SetErrorStringWithFormat("error reading data from section %s",
1643 section_sp->GetName().GetCString());
1645 error.SetErrorString("address isn't from a object file");
1647 error.SetErrorString("address isn't in a module");
1649 error.SetErrorString("address doesn't contain a section that points to a "
1650 "section in a object file");
1655 size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1656 void *dst, size_t dst_len, Status &error,
1657 lldb::addr_t *load_addr_ptr) {
1660 // if we end up reading this from process memory, we will fill this with the
1661 // actual load address
1663 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1665 size_t bytes_read = 0;
1667 addr_t load_addr = LLDB_INVALID_ADDRESS;
1668 addr_t file_addr = LLDB_INVALID_ADDRESS;
1669 Address resolved_addr;
1670 if (!addr.IsSectionOffset()) {
1671 SectionLoadList §ion_load_list = GetSectionLoadList();
1672 if (section_load_list.IsEmpty()) {
1673 // No sections are loaded, so we must assume we are not running yet and
1674 // anything we are given is a file address.
1675 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1676 // offset is the file address
1677 m_images.ResolveFileAddress(file_addr, resolved_addr);
1679 // We have at least one section loaded. This can be because we have
1680 // manually loaded some sections with "target modules load ..." or
1681 // because we have have a live process that has sections loaded through
1682 // the dynamic loader
1683 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1684 // offset is the load address
1685 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1688 if (!resolved_addr.IsValid())
1689 resolved_addr = addr;
1691 if (prefer_file_cache) {
1692 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1697 if (ProcessIsValid()) {
1698 if (load_addr == LLDB_INVALID_ADDRESS)
1699 load_addr = resolved_addr.GetLoadAddress(this);
1701 if (load_addr == LLDB_INVALID_ADDRESS) {
1702 ModuleSP addr_module_sp(resolved_addr.GetModule());
1703 if (addr_module_sp && addr_module_sp->GetFileSpec())
1704 error.SetErrorStringWithFormatv(
1705 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1706 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1708 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1709 resolved_addr.GetFileAddress());
1711 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1712 if (bytes_read != dst_len) {
1713 if (error.Success()) {
1714 if (bytes_read == 0)
1715 error.SetErrorStringWithFormat(
1716 "read memory from 0x%" PRIx64 " failed", load_addr);
1718 error.SetErrorStringWithFormat(
1719 "only %" PRIu64 " of %" PRIu64
1720 " bytes were read from memory at 0x%" PRIx64,
1721 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1726 *load_addr_ptr = load_addr;
1729 // If the address is not section offset we have an address that doesn't
1730 // resolve to any address in any currently loaded shared libraries and we
1731 // failed to read memory so there isn't anything more we can do. If it is
1732 // section offset, we might be able to read cached memory from the object
1734 if (!resolved_addr.IsSectionOffset())
1739 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1740 // If we didn't already try and read from the object file cache, then try
1741 // it after failing to read from the process.
1742 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1747 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1751 addr_t curr_addr = addr.GetLoadAddress(this);
1752 Address address(addr);
1754 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1757 out_str.append(buf, length);
1758 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1759 // to read some more characters
1760 if (length == sizeof(buf) - 1)
1761 curr_addr += length;
1764 address = Address(curr_addr);
1766 return out_str.size();
1769 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1770 size_t dst_max_len, Status &result_error) {
1771 size_t total_cstr_len = 0;
1772 if (dst && dst_max_len) {
1773 result_error.Clear();
1774 // NULL out everything just to be safe
1775 memset(dst, 0, dst_max_len);
1777 addr_t curr_addr = addr.GetLoadAddress(this);
1778 Address address(addr);
1780 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1781 // this really needs to be tied to the memory cache subsystem's cache line
1782 // size, so leave this as a fixed constant.
1783 const size_t cache_line_size = 512;
1785 size_t bytes_left = dst_max_len - 1;
1786 char *curr_dst = dst;
1788 while (bytes_left > 0) {
1789 addr_t cache_line_bytes_left =
1790 cache_line_size - (curr_addr % cache_line_size);
1791 addr_t bytes_to_read =
1792 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1794 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1796 if (bytes_read == 0) {
1797 result_error = error;
1798 dst[total_cstr_len] = '\0';
1801 const size_t len = strlen(curr_dst);
1803 total_cstr_len += len;
1805 if (len < bytes_to_read)
1808 curr_dst += bytes_read;
1809 curr_addr += bytes_read;
1810 bytes_left -= bytes_read;
1811 address = Address(curr_addr);
1815 result_error.SetErrorString("invalid arguments");
1817 result_error.Clear();
1819 return total_cstr_len;
1822 size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1823 bool prefer_file_cache,
1824 uint32_t byte_size, bool is_signed,
1825 Scalar &scalar, Status &error) {
1828 if (byte_size <= sizeof(uval)) {
1830 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1831 if (bytes_read == byte_size) {
1832 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1833 m_arch.GetSpec().GetAddressByteSize());
1834 lldb::offset_t offset = 0;
1836 scalar = data.GetMaxU32(&offset, byte_size);
1838 scalar = data.GetMaxU64(&offset, byte_size);
1841 scalar.SignExtend(byte_size * 8);
1845 error.SetErrorStringWithFormat(
1846 "byte size of %u is too large for integer scalar type", byte_size);
1851 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1852 bool prefer_file_cache,
1853 size_t integer_byte_size,
1854 uint64_t fail_value,
1857 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1858 false, scalar, error))
1859 return scalar.ULongLong(fail_value);
1863 bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1864 Status &error, Address &pointer_addr) {
1866 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1867 m_arch.GetSpec().GetAddressByteSize(), false, scalar,
1869 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1870 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1871 SectionLoadList §ion_load_list = GetSectionLoadList();
1872 if (section_load_list.IsEmpty()) {
1873 // No sections are loaded, so we must assume we are not running yet and
1874 // anything we are given is a file address.
1875 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1877 // We have at least one section loaded. This can be because we have
1878 // manually loaded some sections with "target modules load ..." or
1879 // because we have have a live process that has sections loaded through
1880 // the dynamic loader
1881 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1883 // We weren't able to resolve the pointer value, so just return an
1884 // address with no section
1885 if (!pointer_addr.IsValid())
1886 pointer_addr.SetOffset(pointer_vm_addr);
1893 ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
1894 Status *error_ptr) {
1899 // First see if we already have this module in our module list. If we do,
1900 // then we're done, we don't need to consult the shared modules list. But
1901 // only do this if we are passed a UUID.
1903 if (module_spec.GetUUID().IsValid())
1904 module_sp = m_images.FindFirstModule(module_spec);
1907 ModuleSP old_module_sp; // This will get filled in if we have a new version
1909 bool did_create_module = false;
1911 // If there are image search path entries, try to use them first to acquire
1912 // a suitable image.
1913 if (m_image_search_paths.GetSize()) {
1914 ModuleSpec transformed_spec(module_spec);
1915 if (m_image_search_paths.RemapPath(
1916 module_spec.GetFileSpec().GetDirectory(),
1917 transformed_spec.GetFileSpec().GetDirectory())) {
1918 transformed_spec.GetFileSpec().GetFilename() =
1919 module_spec.GetFileSpec().GetFilename();
1920 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1921 &GetExecutableSearchPaths(),
1922 &old_module_sp, &did_create_module);
1927 // If we have a UUID, we can check our global shared module list in case
1928 // we already have it. If we don't have a valid UUID, then we can't since
1929 // the path in "module_spec" will be a platform path, and we will need to
1930 // let the platform find that file. For example, we could be asking for
1931 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1932 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1933 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1935 if (module_spec.GetUUID().IsValid()) {
1936 // We have a UUID, it is OK to check the global module list...
1937 error = ModuleList::GetSharedModule(module_spec, module_sp,
1938 &GetExecutableSearchPaths(),
1939 &old_module_sp, &did_create_module);
1943 // The platform is responsible for finding and caching an appropriate
1944 // module in the shared module cache.
1945 if (m_platform_sp) {
1946 error = m_platform_sp->GetSharedModule(
1947 module_spec, m_process_sp.get(), module_sp,
1948 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
1950 error.SetErrorString("no platform is currently set");
1955 // We found a module that wasn't in our target list. Let's make sure that
1956 // there wasn't an equivalent module in the list already, and if there was,
1959 ObjectFile *objfile = module_sp->GetObjectFile();
1961 switch (objfile->GetType()) {
1962 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
1963 /// a program's execution state
1964 case ObjectFile::eTypeExecutable: /// A normal executable
1965 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
1967 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1968 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
1969 /// used during execution
1971 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
1972 /// debug information
1974 error_ptr->SetErrorString("debug info files aren't valid target "
1975 "modules, please specify an executable");
1977 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
1978 /// against but not used for
1981 error_ptr->SetErrorString("stub libraries aren't valid target "
1982 "modules, please specify an executable");
1986 error_ptr->SetErrorString(
1987 "unsupported file type, please specify an executable");
1990 // GetSharedModule is not guaranteed to find the old shared module, for
1991 // instance in the common case where you pass in the UUID, it is only
1992 // going to find the one module matching the UUID. In fact, it has no
1993 // good way to know what the "old module" relevant to this target is,
1994 // since there might be many copies of a module with this file spec in
1995 // various running debug sessions, but only one of them will belong to
1996 // this target. So let's remove the UUID from the module list, and look
1997 // in the target's module list. Only do this if there is SOMETHING else
1998 // in the module spec...
1999 if (!old_module_sp) {
2000 if (module_spec.GetUUID().IsValid() &&
2001 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2002 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2003 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2004 module_spec_copy.GetUUID().Clear();
2006 ModuleList found_modules;
2008 m_images.FindModules(module_spec_copy, found_modules);
2009 if (num_found == 1) {
2010 old_module_sp = found_modules.GetModuleAtIndex(0);
2015 // Preload symbols outside of any lock, so hopefully we can do this for
2016 // each library in parallel.
2017 if (GetPreloadSymbols())
2018 module_sp->PreloadSymbols();
2020 if (old_module_sp &&
2021 m_images.GetIndexForModule(old_module_sp.get()) !=
2022 LLDB_INVALID_INDEX32) {
2023 m_images.ReplaceModule(old_module_sp, module_sp);
2024 Module *old_module_ptr = old_module_sp.get();
2025 old_module_sp.reset();
2026 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2028 m_images.Append(module_sp);
2038 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2040 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2042 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2044 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2046 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2048 exe_ctx.SetTargetPtr(this);
2051 PathMappingList &Target::GetImageSearchPathList() {
2052 return m_image_search_paths;
2055 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2057 Target *target = (Target *)baton;
2058 ModuleSP exe_module_sp(target->GetExecutableModule());
2060 target->SetExecutableModule(exe_module_sp, true);
2063 TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error,
2064 lldb::LanguageType language,
2065 bool create_on_demand) {
2073 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2075 || language == eLanguageTypeUnknown) {
2076 std::set<lldb::LanguageType> languages_for_types;
2077 std::set<lldb::LanguageType> languages_for_expressions;
2079 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
2080 languages_for_expressions);
2082 if (languages_for_expressions.count(eLanguageTypeC)) {
2083 language = eLanguageTypeC; // LLDB's default. Override by setting the
2086 if (languages_for_expressions.empty()) {
2089 language = *languages_for_expressions.begin();
2094 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2098 PersistentExpressionState *
2099 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2100 TypeSystem *type_system =
2101 GetScratchTypeSystemForLanguage(nullptr, language, true);
2104 return type_system->GetPersistentExpressionState();
2110 UserExpression *Target::GetUserExpressionForLanguage(
2111 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2112 Expression::ResultType desired_type,
2113 const EvaluateExpressionOptions &options, Status &error) {
2114 Status type_system_error;
2116 TypeSystem *type_system =
2117 GetScratchTypeSystemForLanguage(&type_system_error, language);
2118 UserExpression *user_expr = nullptr;
2121 error.SetErrorStringWithFormat(
2122 "Could not find type system for language %s: %s",
2123 Language::GetNameForLanguageType(language),
2124 type_system_error.AsCString());
2128 user_expr = type_system->GetUserExpression(expr, prefix, language,
2129 desired_type, options);
2131 error.SetErrorStringWithFormat(
2132 "Could not create an expression for language %s",
2133 Language::GetNameForLanguageType(language));
2138 FunctionCaller *Target::GetFunctionCallerForLanguage(
2139 lldb::LanguageType language, const CompilerType &return_type,
2140 const Address &function_address, const ValueList &arg_value_list,
2141 const char *name, Status &error) {
2142 Status type_system_error;
2143 TypeSystem *type_system =
2144 GetScratchTypeSystemForLanguage(&type_system_error, language);
2145 FunctionCaller *persistent_fn = nullptr;
2148 error.SetErrorStringWithFormat(
2149 "Could not find type system for language %s: %s",
2150 Language::GetNameForLanguageType(language),
2151 type_system_error.AsCString());
2152 return persistent_fn;
2155 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2156 arg_value_list, name);
2158 error.SetErrorStringWithFormat(
2159 "Could not create an expression for language %s",
2160 Language::GetNameForLanguageType(language));
2162 return persistent_fn;
2166 Target::GetUtilityFunctionForLanguage(const char *text,
2167 lldb::LanguageType language,
2168 const char *name, Status &error) {
2169 Status type_system_error;
2170 TypeSystem *type_system =
2171 GetScratchTypeSystemForLanguage(&type_system_error, language);
2172 UtilityFunction *utility_fn = nullptr;
2175 error.SetErrorStringWithFormat(
2176 "Could not find type system for language %s: %s",
2177 Language::GetNameForLanguageType(language),
2178 type_system_error.AsCString());
2182 utility_fn = type_system->GetUtilityFunction(text, name);
2184 error.SetErrorStringWithFormat(
2185 "Could not create an expression for language %s",
2186 Language::GetNameForLanguageType(language));
2191 ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2193 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2194 nullptr, eLanguageTypeC, create_on_demand))
2195 return llvm::dyn_cast<ClangASTContext>(type_system);
2200 ClangASTImporterSP Target::GetClangASTImporter() {
2202 if (!m_ast_importer_sp) {
2203 m_ast_importer_sp.reset(new ClangASTImporter());
2205 return m_ast_importer_sp;
2207 return ClangASTImporterSP();
2210 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2212 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2214 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2215 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2217 return properties_sp->GetExecutableSearchPaths();
2218 return FileSpecList();
2221 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2222 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2224 return properties_sp->GetDebugFileSearchPaths();
2225 return FileSpecList();
2228 FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2229 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2231 return properties_sp->GetClangModuleSearchPaths();
2232 return FileSpecList();
2235 ArchSpec Target::GetDefaultArchitecture() {
2236 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2238 return properties_sp->GetDefaultArchitecture();
2242 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2243 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2244 if (properties_sp) {
2245 LogIfAnyCategoriesSet(
2246 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2247 "default architecture to %s (%s)",
2248 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2249 return properties_sp->SetDefaultArchitecture(arch);
2253 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2254 const SymbolContext *sc_ptr) {
2255 // The target can either exist in the "process" of ExecutionContext, or in
2256 // the "target_sp" member of SymbolContext. This accessor helper function
2257 // will get the target from one of these locations.
2259 Target *target = nullptr;
2260 if (sc_ptr != nullptr)
2261 target = sc_ptr->target_sp.get();
2262 if (target == nullptr && exe_ctx_ptr)
2263 target = exe_ctx_ptr->GetTargetPtr();
2267 ExpressionResults Target::EvaluateExpression(
2268 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2269 lldb::ValueObjectSP &result_valobj_sp,
2270 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2271 result_valobj_sp.reset();
2273 ExpressionResults execution_results = eExpressionSetupError;
2276 return execution_results;
2278 // We shouldn't run stop hooks in expressions. Be sure to reset this if you
2279 // return anywhere within this function.
2280 bool old_suppress_value = m_suppress_stop_hooks;
2281 m_suppress_stop_hooks = true;
2283 ExecutionContext exe_ctx;
2286 exe_scope->CalculateExecutionContext(exe_ctx);
2287 } else if (m_process_sp) {
2288 m_process_sp->CalculateExecutionContext(exe_ctx);
2290 CalculateExecutionContext(exe_ctx);
2293 // Make sure we aren't just trying to see the value of a persistent variable
2294 // (something like "$0")
2295 lldb::ExpressionVariableSP persistent_var_sp;
2296 // Only check for persistent variables the expression starts with a '$'
2298 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2299 ->GetPersistentExpressionState()
2300 ->GetVariable(expr);
2302 if (persistent_var_sp) {
2303 result_valobj_sp = persistent_var_sp->GetValueObject();
2304 execution_results = eExpressionCompleted;
2306 llvm::StringRef prefix = GetExpressionPrefixContents();
2308 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2309 result_valobj_sp, error,
2314 m_suppress_stop_hooks = old_suppress_value;
2316 return execution_results;
2319 lldb::ExpressionVariableSP
2320 Target::GetPersistentVariable(const ConstString &name) {
2321 lldb::ExpressionVariableSP variable_sp;
2322 m_scratch_type_system_map.ForEach(
2323 [name, &variable_sp](TypeSystem *type_system) -> bool {
2324 if (PersistentExpressionState *persistent_state =
2325 type_system->GetPersistentExpressionState()) {
2326 variable_sp = persistent_state->GetVariable(name);
2329 return false; // Stop iterating the ForEach
2331 return true; // Keep iterating the ForEach
2336 lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2337 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2339 m_scratch_type_system_map.ForEach(
2340 [name, &address](TypeSystem *type_system) -> bool {
2341 if (PersistentExpressionState *persistent_state =
2342 type_system->GetPersistentExpressionState()) {
2343 address = persistent_state->LookupSymbol(name);
2344 if (address != LLDB_INVALID_ADDRESS)
2345 return false; // Stop iterating the ForEach
2347 return true; // Keep iterating the ForEach
2352 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2353 AddressClass addr_class) const {
2354 addr_t code_addr = load_addr;
2355 switch (m_arch.GetSpec().GetMachine()) {
2356 case llvm::Triple::mips:
2357 case llvm::Triple::mipsel:
2358 case llvm::Triple::mips64:
2359 case llvm::Triple::mips64el:
2360 switch (addr_class) {
2361 case AddressClass::eData:
2362 case AddressClass::eDebug:
2363 return LLDB_INVALID_ADDRESS;
2365 case AddressClass::eUnknown:
2366 case AddressClass::eInvalid:
2367 case AddressClass::eCode:
2368 case AddressClass::eCodeAlternateISA:
2369 case AddressClass::eRuntime:
2370 if ((code_addr & 2ull) || (addr_class == AddressClass::eCodeAlternateISA))
2376 case llvm::Triple::arm:
2377 case llvm::Triple::thumb:
2378 switch (addr_class) {
2379 case AddressClass::eData:
2380 case AddressClass::eDebug:
2381 return LLDB_INVALID_ADDRESS;
2383 case AddressClass::eUnknown:
2384 case AddressClass::eInvalid:
2385 case AddressClass::eCode:
2386 case AddressClass::eCodeAlternateISA:
2387 case AddressClass::eRuntime:
2388 // Check if bit zero it no set?
2389 if ((code_addr & 1ull) == 0) {
2390 // Bit zero isn't set, check if the address is a multiple of 2?
2391 if (code_addr & 2ull) {
2392 // The address is a multiple of 2 so it must be thumb, set bit zero
2394 } else if (addr_class == AddressClass::eCodeAlternateISA) {
2395 // We checked the address and the address claims to be the alternate
2396 // ISA which means thumb, so set bit zero.
2410 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2411 AddressClass addr_class) const {
2412 addr_t opcode_addr = load_addr;
2413 switch (m_arch.GetSpec().GetMachine()) {
2414 case llvm::Triple::mips:
2415 case llvm::Triple::mipsel:
2416 case llvm::Triple::mips64:
2417 case llvm::Triple::mips64el:
2418 case llvm::Triple::arm:
2419 case llvm::Triple::thumb:
2420 switch (addr_class) {
2421 case AddressClass::eData:
2422 case AddressClass::eDebug:
2423 return LLDB_INVALID_ADDRESS;
2425 case AddressClass::eInvalid:
2426 case AddressClass::eUnknown:
2427 case AddressClass::eCode:
2428 case AddressClass::eCodeAlternateISA:
2429 case AddressClass::eRuntime:
2430 opcode_addr &= ~(1ull);
2441 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2442 addr_t breakable_addr = addr;
2443 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2445 switch (m_arch.GetSpec().GetMachine()) {
2448 case llvm::Triple::mips:
2449 case llvm::Triple::mipsel:
2450 case llvm::Triple::mips64:
2451 case llvm::Triple::mips64el: {
2452 addr_t function_start = 0;
2453 addr_t current_offset = 0;
2454 uint32_t loop_count = 0;
2455 Address resolved_addr;
2456 uint32_t arch_flags = m_arch.GetSpec().GetFlags();
2457 bool IsMips16 = arch_flags & ArchSpec::eMIPSAse_mips16;
2458 bool IsMicromips = arch_flags & ArchSpec::eMIPSAse_micromips;
2459 SectionLoadList §ion_load_list = GetSectionLoadList();
2461 if (section_load_list.IsEmpty())
2462 // No sections are loaded, so we must assume we are not running yet and
2463 // need to operate only on file address.
2464 m_images.ResolveFileAddress(addr, resolved_addr);
2466 section_load_list.ResolveLoadAddress(addr, resolved_addr);
2468 // Get the function boundaries to make sure we don't scan back before the
2469 // beginning of the current function.
2470 ModuleSP temp_addr_module_sp(resolved_addr.GetModule());
2471 if (temp_addr_module_sp) {
2473 uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
2474 temp_addr_module_sp->ResolveSymbolContextForAddress(resolved_addr,
2478 sym_addr = sc.function->GetAddressRange().GetBaseAddress();
2480 sym_addr = sc.symbol->GetAddress();
2482 function_start = sym_addr.GetLoadAddress(this);
2483 if (function_start == LLDB_INVALID_ADDRESS)
2484 function_start = sym_addr.GetFileAddress();
2487 current_offset = addr - function_start;
2490 // If breakpoint address is start of function then we dont have to do
2492 if (current_offset == 0)
2493 return breakable_addr;
2495 loop_count = current_offset / 2;
2497 if (loop_count > 3) {
2498 // Scan previous 6 bytes
2499 if (IsMips16 | IsMicromips)
2501 // For mips-only, instructions are always 4 bytes, so scan previous 4
2507 // Create Disassembler Instance
2508 lldb::DisassemblerSP disasm_sp(
2509 Disassembler::FindPlugin(m_arch.GetSpec(), nullptr, nullptr));
2511 ExecutionContext exe_ctx;
2512 CalculateExecutionContext(exe_ctx);
2513 InstructionList instruction_list;
2514 InstructionSP prev_insn;
2515 bool prefer_file_cache = true; // Read from file
2516 uint32_t inst_to_choose = 0;
2518 for (uint32_t i = 1; i <= loop_count; i++) {
2519 // Adjust the address to read from.
2520 resolved_addr.Slide(-2);
2521 AddressRange range(resolved_addr, i * 2);
2522 uint32_t insn_size = 0;
2524 disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
2526 uint32_t num_insns = disasm_sp->GetInstructionList().GetSize();
2528 prev_insn = disasm_sp->GetInstructionList().GetInstructionAtIndex(0);
2529 insn_size = prev_insn->GetOpcode().GetByteSize();
2530 if (i == 1 && insn_size == 2) {
2531 // This looks like a valid 2-byte instruction (but it could be a part
2532 // of upper 4 byte instruction).
2533 instruction_list.Append(prev_insn);
2535 } else if (i == 2) {
2536 // Here we may get one 4-byte instruction or two 2-byte instructions.
2537 if (num_insns == 2) {
2538 // Looks like there are two 2-byte instructions above our
2539 // breakpoint target address. Now the upper 2-byte instruction is
2540 // either a valid 2-byte instruction or could be a part of it's
2541 // upper 4-byte instruction. In both cases we don't care because in
2542 // this case lower 2-byte instruction is definitely a valid
2543 // instruction and whatever i=1 iteration has found out is true.
2546 } else if (insn_size == 4) {
2547 // This instruction claims its a valid 4-byte instruction. But it
2548 // could be a part of it's upper 4-byte instruction. Lets try
2549 // scanning upper 2 bytes to verify this.
2550 instruction_list.Append(prev_insn);
2553 } else if (i == 3) {
2555 // FIXME: We reached here that means instruction at [target - 4] has
2556 // already claimed to be a 4-byte instruction, and now instruction
2557 // at [target - 6] is also claiming that it's a 4-byte instruction.
2558 // This can not be true. In this case we can not decide the valid
2559 // previous instruction so we let lldb set the breakpoint at the
2560 // address given by user.
2563 // This is straight-forward
2568 // Decode failed, bytes do not form a valid instruction. So whatever
2569 // previous iteration has found out is true.
2571 inst_to_choose = i - 1;
2577 // Check if we are able to find any valid instruction.
2578 if (inst_to_choose) {
2579 if (inst_to_choose > instruction_list.GetSize())
2581 prev_insn = instruction_list.GetInstructionAtIndex(inst_to_choose - 1);
2583 if (prev_insn->HasDelaySlot()) {
2584 uint32_t shift_size = prev_insn->GetOpcode().GetByteSize();
2585 // Adjust the breakable address
2586 breakable_addr = addr - shift_size;
2588 log->Printf("Target::%s Breakpoint at 0x%8.8" PRIx64
2589 " is adjusted to 0x%8.8" PRIx64 " due to delay slot\n",
2590 __FUNCTION__, addr, breakable_addr);
2596 return breakable_addr;
2599 SourceManager &Target::GetSourceManager() {
2600 if (!m_source_manager_ap)
2601 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2602 return *m_source_manager_ap;
2605 ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2606 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2611 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2613 if (!m_clang_modules_decl_vendor_ap) {
2614 m_clang_modules_decl_vendor_ap.reset(
2615 ClangModulesDeclVendor::Create(*this));
2619 return m_clang_modules_decl_vendor_ap.get();
2622 Target::StopHookSP Target::CreateStopHook() {
2623 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2624 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2625 m_stop_hooks[new_uid] = stop_hook_sp;
2626 return stop_hook_sp;
2629 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2630 size_t num_removed = m_stop_hooks.erase(user_id);
2631 return (num_removed != 0);
2634 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2636 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2637 StopHookSP found_hook;
2639 StopHookCollection::iterator specified_hook_iter;
2640 specified_hook_iter = m_stop_hooks.find(user_id);
2641 if (specified_hook_iter != m_stop_hooks.end())
2642 found_hook = (*specified_hook_iter).second;
2646 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2647 bool active_state) {
2648 StopHookCollection::iterator specified_hook_iter;
2649 specified_hook_iter = m_stop_hooks.find(user_id);
2650 if (specified_hook_iter == m_stop_hooks.end())
2653 (*specified_hook_iter).second->SetIsActive(active_state);
2657 void Target::SetAllStopHooksActiveState(bool active_state) {
2658 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2659 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2660 (*pos).second->SetIsActive(active_state);
2664 void Target::RunStopHooks() {
2665 if (m_suppress_stop_hooks)
2671 // Somebody might have restarted the process:
2672 if (m_process_sp->GetState() != eStateStopped)
2675 // <rdar://problem/12027563> make sure we check that we are not stopped
2676 // because of us running a user expression since in that case we do not want
2677 // to run the stop-hooks
2678 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2681 if (m_stop_hooks.empty())
2684 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2686 // If there aren't any active stop hooks, don't bother either:
2687 bool any_active_hooks = false;
2688 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2689 if ((*pos).second->IsActive()) {
2690 any_active_hooks = true;
2694 if (!any_active_hooks)
2697 CommandReturnObject result;
2699 std::vector<ExecutionContext> exc_ctx_with_reasons;
2700 std::vector<SymbolContext> sym_ctx_with_reasons;
2702 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2703 size_t num_threads = cur_threadlist.GetSize();
2704 for (size_t i = 0; i < num_threads; i++) {
2705 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2706 if (cur_thread_sp->ThreadStoppedForAReason()) {
2707 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2708 exc_ctx_with_reasons.push_back(ExecutionContext(
2709 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2710 sym_ctx_with_reasons.push_back(
2711 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2715 // If no threads stopped for a reason, don't run the stop-hooks.
2716 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2717 if (num_exe_ctx == 0)
2720 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2721 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2723 bool keep_going = true;
2724 bool hooks_ran = false;
2725 bool print_hook_header = (m_stop_hooks.size() != 1);
2726 bool print_thread_header = (num_exe_ctx != 1);
2728 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2730 StopHookSP cur_hook_sp = (*pos).second;
2731 if (!cur_hook_sp->IsActive())
2734 bool any_thread_matched = false;
2735 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2736 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2737 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2738 sym_ctx_with_reasons[i])) &&
2739 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2740 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2741 exc_ctx_with_reasons[i].GetThreadRef()))) {
2745 if (print_hook_header && !any_thread_matched) {
2747 (cur_hook_sp->GetCommands().GetSize() == 1
2748 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2751 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2752 cur_hook_sp->GetID(), cmd);
2754 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2755 cur_hook_sp->GetID());
2756 any_thread_matched = true;
2759 if (print_thread_header)
2760 result.AppendMessageWithFormat(
2762 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2764 CommandInterpreterRunOptions options;
2765 options.SetStopOnContinue(true);
2766 options.SetStopOnError(true);
2767 options.SetEchoCommands(false);
2768 options.SetPrintResults(true);
2769 options.SetAddToHistory(false);
2771 GetDebugger().GetCommandInterpreter().HandleCommands(
2772 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2775 // If the command started the target going again, we should bag out of
2776 // running the stop hooks.
2777 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2778 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2779 // But only complain if there were more stop hooks to do:
2780 StopHookCollection::iterator tmp = pos;
2782 result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64
2783 " set the program running.\n",
2784 cur_hook_sp->GetID());
2791 result.GetImmediateOutputStream()->Flush();
2792 result.GetImmediateErrorStream()->Flush();
2795 const TargetPropertiesSP &Target::GetGlobalProperties() {
2796 // NOTE: intentional leak so we don't crash if global destructor chain gets
2797 // called as other threads still use the result of this function
2798 static TargetPropertiesSP *g_settings_sp_ptr =
2799 new TargetPropertiesSP(new TargetProperties(nullptr));
2800 return *g_settings_sp_ptr;
2803 Status Target::Install(ProcessLaunchInfo *launch_info) {
2805 PlatformSP platform_sp(GetPlatform());
2807 if (platform_sp->IsRemote()) {
2808 if (platform_sp->IsConnected()) {
2809 // Install all files that have an install path, and always install the
2810 // main executable when connected to a remote platform
2811 const ModuleList &modules = GetImages();
2812 const size_t num_images = modules.GetSize();
2813 for (size_t idx = 0; idx < num_images; ++idx) {
2814 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2816 const bool is_main_executable = module_sp == GetExecutableModule();
2817 FileSpec local_file(module_sp->GetFileSpec());
2819 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2821 if (is_main_executable) // TODO: add setting for always
2822 // installing main executable???
2824 // Always install the main executable
2825 remote_file = platform_sp->GetRemoteWorkingDirectory();
2826 remote_file.AppendPathComponent(
2827 module_sp->GetFileSpec().GetFilename().GetCString());
2831 error = platform_sp->Install(local_file, remote_file);
2832 if (error.Success()) {
2833 module_sp->SetPlatformFileSpec(remote_file);
2834 if (is_main_executable) {
2835 platform_sp->SetFilePermissions(remote_file, 0700);
2837 launch_info->SetExecutableFile(remote_file, false);
2851 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2853 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2856 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2857 Address &resolved_addr) {
2858 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2861 bool Target::SetSectionLoadAddress(const SectionSP §ion_sp,
2862 addr_t new_section_load_addr,
2863 bool warn_multiple) {
2864 const addr_t old_section_load_addr =
2865 m_section_load_history.GetSectionLoadAddress(
2866 SectionLoadHistory::eStopIDNow, section_sp);
2867 if (old_section_load_addr != new_section_load_addr) {
2868 uint32_t stop_id = 0;
2869 ProcessSP process_sp(GetProcessSP());
2871 stop_id = process_sp->GetStopID();
2873 stop_id = m_section_load_history.GetLastStopID();
2874 if (m_section_load_history.SetSectionLoadAddress(
2875 stop_id, section_sp, new_section_load_addr, warn_multiple))
2876 return true; // Return true if the section load address was changed...
2878 return false; // Return false to indicate nothing changed
2881 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2882 size_t section_unload_count = 0;
2883 size_t num_modules = module_list.GetSize();
2884 for (size_t i = 0; i < num_modules; ++i) {
2885 section_unload_count +=
2886 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2888 return section_unload_count;
2891 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2892 uint32_t stop_id = 0;
2893 ProcessSP process_sp(GetProcessSP());
2895 stop_id = process_sp->GetStopID();
2897 stop_id = m_section_load_history.GetLastStopID();
2898 SectionList *sections = module_sp->GetSectionList();
2899 size_t section_unload_count = 0;
2901 const uint32_t num_sections = sections->GetNumSections(0);
2902 for (uint32_t i = 0; i < num_sections; ++i) {
2903 section_unload_count += m_section_load_history.SetSectionUnloaded(
2904 stop_id, sections->GetSectionAtIndex(i));
2907 return section_unload_count;
2910 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp) {
2911 uint32_t stop_id = 0;
2912 ProcessSP process_sp(GetProcessSP());
2914 stop_id = process_sp->GetStopID();
2916 stop_id = m_section_load_history.GetLastStopID();
2917 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2920 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp,
2922 uint32_t stop_id = 0;
2923 ProcessSP process_sp(GetProcessSP());
2925 stop_id = process_sp->GetStopID();
2927 stop_id = m_section_load_history.GetLastStopID();
2928 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2932 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2934 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2936 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2939 log->Printf("Target::%s() called for %s", __FUNCTION__,
2940 launch_info.GetExecutableFile().GetPath().c_str());
2942 StateType state = eStateInvalid;
2944 // Scope to temporarily get the process state in case someone has manually
2945 // remotely connected already to a process and we can skip the platform
2948 ProcessSP process_sp(GetProcessSP());
2951 state = process_sp->GetState();
2954 "Target::%s the process exists, and its current state is %s",
2955 __FUNCTION__, StateAsCString(state));
2958 log->Printf("Target::%s the process instance doesn't currently exist.",
2963 launch_info.GetFlags().Set(eLaunchFlagDebug);
2965 // Get the value of synchronous execution here. If you wait till after you
2966 // have started to run, then you could have hit a breakpoint, whose command
2967 // might switch the value, and then you'll pick up that incorrect value.
2968 Debugger &debugger = GetDebugger();
2969 const bool synchronous_execution =
2970 debugger.GetCommandInterpreter().GetSynchronous();
2972 PlatformSP platform_sp(GetPlatform());
2974 // Finalize the file actions, and if none were given, default to opening up a
2976 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2978 log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2979 "default_to_use_pty=%s",
2980 __FUNCTION__, platform_sp ? "true" : "false",
2981 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2983 default_to_use_pty ? "true" : "false");
2985 launch_info.FinalizeFileActions(this, default_to_use_pty);
2987 if (state == eStateConnected) {
2988 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2989 error.SetErrorString(
2990 "can't launch in tty when launching through a remote connection");
2995 if (!launch_info.GetArchitecture().IsValid())
2996 launch_info.GetArchitecture() = GetArchitecture();
2998 // If we're not already connected to the process, and if we have a platform
2999 // that can launch a process for debugging, go ahead and do that here.
3000 if (state != eStateConnected && platform_sp &&
3001 platform_sp->CanDebugProcess()) {
3003 log->Printf("Target::%s asking the platform to debug the process",
3006 // Get a weak pointer to the previous process if we have one
3007 ProcessWP process_wp;
3009 process_wp = m_process_sp;
3011 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
3013 // Cleanup the old process since someone might still have a strong
3014 // reference to this process and we would like to allow it to cleanup as
3015 // much as it can without the object being destroyed. We try to lock the
3016 // shared pointer and if that works, then someone else still has a strong
3017 // reference to the process.
3019 ProcessSP old_process_sp(process_wp.lock());
3021 old_process_sp->Finalize();
3024 log->Printf("Target::%s the platform doesn't know how to debug a "
3025 "process, getting a process plugin to do this for us.",
3028 if (state == eStateConnected) {
3029 assert(m_process_sp);
3031 // Use a Process plugin to construct the process.
3032 const char *plugin_name = launch_info.GetProcessPluginName();
3033 CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name,
3037 // Since we didn't have a platform launch the process, launch it here.
3039 error = m_process_sp->Launch(launch_info);
3042 if (!m_process_sp) {
3043 if (error.Success())
3044 error.SetErrorString("failed to launch or debug process");
3048 if (error.Success()) {
3049 if (synchronous_execution ||
3050 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
3051 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
3052 if (!hijack_listener_sp) {
3053 hijack_listener_sp =
3054 Listener::MakeListener("lldb.Target.Launch.hijack");
3055 launch_info.SetHijackListener(hijack_listener_sp);
3056 m_process_sp->HijackProcessEvents(hijack_listener_sp);
3059 StateType state = m_process_sp->WaitForProcessToStop(
3060 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
3062 if (state == eStateStopped) {
3063 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
3064 if (synchronous_execution) {
3065 error = m_process_sp->PrivateResume();
3066 if (error.Success()) {
3067 state = m_process_sp->WaitForProcessToStop(
3068 llvm::None, nullptr, true, hijack_listener_sp, stream);
3069 const bool must_be_alive =
3070 false; // eStateExited is ok, so this must be false
3071 if (!StateIsStoppedState(state, must_be_alive)) {
3072 error.SetErrorStringWithFormat("process isn't stopped: %s",
3073 StateAsCString(state));
3077 m_process_sp->RestoreProcessEvents();
3078 error = m_process_sp->PrivateResume();
3080 if (!error.Success()) {
3082 error2.SetErrorStringWithFormat(
3083 "process resume at entry point failed: %s", error.AsCString());
3087 } else if (state == eStateExited) {
3088 bool with_shell = !!launch_info.GetShell();
3089 const int exit_status = m_process_sp->GetExitStatus();
3090 const char *exit_desc = m_process_sp->GetExitDescription();
3091 #define LAUNCH_SHELL_MESSAGE \
3092 "\n'r' and 'run' are aliases that default to launching through a " \
3093 "shell.\nTry launching without going through a shell by using 'process " \
3095 if (exit_desc && exit_desc[0]) {
3097 error.SetErrorStringWithFormat(
3098 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
3099 exit_status, exit_desc);
3101 error.SetErrorStringWithFormat("process exited with status %i (%s)",
3102 exit_status, exit_desc);
3105 error.SetErrorStringWithFormat(
3106 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
3109 error.SetErrorStringWithFormat("process exited with status %i",
3113 error.SetErrorStringWithFormat(
3114 "initial process state wasn't stopped: %s", StateAsCString(state));
3117 m_process_sp->RestoreProcessEvents();
3120 error2.SetErrorStringWithFormat("process launch failed: %s",
3127 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
3128 auto state = eStateInvalid;
3129 auto process_sp = GetProcessSP();
3131 state = process_sp->GetState();
3132 if (process_sp->IsAlive() && state != eStateConnected) {
3133 if (state == eStateAttaching)
3134 return Status("process attach is in progress");
3135 return Status("a process is already being debugged");
3139 const ModuleSP old_exec_module_sp = GetExecutableModule();
3141 // If no process info was specified, then use the target executable name as
3142 // the process to attach to by default
3143 if (!attach_info.ProcessInfoSpecified()) {
3144 if (old_exec_module_sp)
3145 attach_info.GetExecutableFile().GetFilename() =
3146 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3148 if (!attach_info.ProcessInfoSpecified()) {
3149 return Status("no process specified, create a target with a file, or "
3150 "specify the --pid or --name");
3154 const auto platform_sp =
3155 GetDebugger().GetPlatformList().GetSelectedPlatform();
3156 ListenerSP hijack_listener_sp;
3157 const bool async = attach_info.GetAsync();
3159 hijack_listener_sp =
3160 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3161 attach_info.SetHijackListener(hijack_listener_sp);
3165 if (state != eStateConnected && platform_sp != nullptr &&
3166 platform_sp->CanDebugProcess()) {
3167 SetPlatform(platform_sp);
3168 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3170 if (state != eStateConnected) {
3171 const char *plugin_name = attach_info.GetProcessPluginName();
3173 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3174 plugin_name, nullptr);
3175 if (process_sp == nullptr) {
3176 error.SetErrorStringWithFormat(
3177 "failed to create process using plugin %s",
3178 (plugin_name) ? plugin_name : "null");
3182 if (hijack_listener_sp)
3183 process_sp->HijackProcessEvents(hijack_listener_sp);
3184 error = process_sp->Attach(attach_info);
3187 if (error.Success() && process_sp) {
3189 process_sp->RestoreProcessEvents();
3191 state = process_sp->WaitForProcessToStop(
3192 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3193 process_sp->RestoreProcessEvents();
3195 if (state != eStateStopped) {
3196 const char *exit_desc = process_sp->GetExitDescription();
3198 error.SetErrorStringWithFormat("%s", exit_desc);
3200 error.SetErrorString(
3201 "process did not stop (no such process or permission problem?)");
3202 process_sp->Destroy(false);
3209 //--------------------------------------------------------------
3211 //--------------------------------------------------------------
3212 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3213 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3214 m_thread_spec_ap(), m_active(true) {}
3216 Target::StopHook::StopHook(const StopHook &rhs)
3217 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3218 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3219 m_thread_spec_ap(), m_active(rhs.m_active) {
3220 if (rhs.m_thread_spec_ap)
3221 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
3224 Target::StopHook::~StopHook() = default;
3226 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3227 m_specifier_sp.reset(specifier);
3230 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3231 m_thread_spec_ap.reset(specifier);
3234 void Target::StopHook::GetDescription(Stream *s,
3235 lldb::DescriptionLevel level) const {
3236 int indent_level = s->GetIndentLevel();
3238 s->SetIndentLevel(indent_level + 2);
3240 s->Printf("Hook: %" PRIu64 "\n", GetID());
3242 s->Indent("State: enabled\n");
3244 s->Indent("State: disabled\n");
3246 if (m_specifier_sp) {
3248 s->PutCString("Specifier:\n");
3249 s->SetIndentLevel(indent_level + 4);
3250 m_specifier_sp->GetDescription(s, level);
3251 s->SetIndentLevel(indent_level + 2);
3254 if (m_thread_spec_ap) {
3256 s->Indent("Thread:\n");
3257 m_thread_spec_ap->GetDescription(&tmp, level);
3258 s->SetIndentLevel(indent_level + 4);
3259 s->Indent(tmp.GetString());
3260 s->PutCString("\n");
3261 s->SetIndentLevel(indent_level + 2);
3264 s->Indent("Commands: \n");
3265 s->SetIndentLevel(indent_level + 4);
3266 uint32_t num_commands = m_commands.GetSize();
3267 for (uint32_t i = 0; i < num_commands; i++) {
3268 s->Indent(m_commands.GetStringAtIndex(i));
3269 s->PutCString("\n");
3271 s->SetIndentLevel(indent_level);
3274 //--------------------------------------------------------------
3275 // class TargetProperties
3276 //--------------------------------------------------------------
3278 OptionEnumValueElement lldb_private::g_dynamic_value_types[] = {
3279 {eNoDynamicValues, "no-dynamic-values",
3280 "Don't calculate the dynamic type of values"},
3281 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3282 "even if you have to run the target."},
3283 {eDynamicDontRunTarget, "no-run-target",
3284 "Calculate the dynamic type of values, but don't run the target."},
3285 {0, nullptr, nullptr}};
3287 static OptionEnumValueElement g_inline_breakpoint_enums[] = {
3288 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3289 "locations (fastest). This setting "
3290 "should only be used if you know that "
3291 "no inlining occurs in your programs."},
3292 {eInlineBreakpointsHeaders, "headers",
3293 "Only check for inline breakpoint locations when setting breakpoints in "
3294 "header files, but not when setting breakpoint in implementation source "
3295 "files (default)."},
3296 {eInlineBreakpointsAlways, "always",
3297 "Always look for inline breakpoint locations when setting file and line "
3298 "breakpoints (slower but most accurate)."},
3299 {0, nullptr, nullptr}};
3301 typedef enum x86DisassemblyFlavor {
3302 eX86DisFlavorDefault,
3305 } x86DisassemblyFlavor;
3307 static OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3308 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3309 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3310 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
3311 {0, nullptr, nullptr}};
3313 static OptionEnumValueElement g_hex_immediate_style_values[] = {
3314 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3315 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
3316 {0, nullptr, nullptr}};
3318 static OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3319 {eLoadScriptFromSymFileTrue, "true",
3320 "Load debug scripts inside symbol files"},
3321 {eLoadScriptFromSymFileFalse, "false",
3322 "Do not load debug scripts inside symbol files."},
3323 {eLoadScriptFromSymFileWarn, "warn",
3324 "Warn about debug scripts inside symbol files but do not load them."},
3325 {0, nullptr, nullptr}};
3327 static OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3328 {eLoadCWDlldbinitTrue, "true",
3329 "Load .lldbinit files from current directory"},
3330 {eLoadCWDlldbinitFalse, "false",
3331 "Do not load .lldbinit files from current directory"},
3332 {eLoadCWDlldbinitWarn, "warn",
3333 "Warn about loading .lldbinit files from current directory"},
3334 {0, nullptr, nullptr}};
3336 static OptionEnumValueElement g_memory_module_load_level_values[] = {
3337 {eMemoryModuleLoadLevelMinimal, "minimal",
3338 "Load minimal information when loading modules from memory. Currently "
3339 "this setting loads sections only."},
3340 {eMemoryModuleLoadLevelPartial, "partial",
3341 "Load partial information when loading modules from memory. Currently "
3342 "this setting loads sections and function bounds."},
3343 {eMemoryModuleLoadLevelComplete, "complete",
3344 "Load complete information when loading modules from memory. Currently "
3345 "this setting loads sections and all symbols."},
3346 {0, nullptr, nullptr}};
3348 static PropertyDefinition g_properties[] = {
3349 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, nullptr,
3350 "Default architecture to choose, when there's a choice."},
3351 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3352 nullptr, "Move breakpoints to nearest code."},
3353 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3355 "The language to use when interpreting expressions entered in commands."},
3356 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3357 "Path to a file containing expressions to be prepended to all "
3359 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3360 eDynamicDontRunTarget, nullptr, g_dynamic_value_types,
3361 "Should printed values be shown as their dynamic value."},
3362 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3363 nullptr, "Should synthetic values be used by default whenever available."},
3364 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3365 "Skip function prologues when setting breakpoints by name."},
3366 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, nullptr,
3367 "Source path remappings are used to track the change of location between "
3368 "a source file when built, and "
3369 "where it exists on the current system. It consists of an array of "
3370 "duples, the first element of each duple is "
3371 "some part (starting at the root) of the path to the file when it was "
3373 "and the second is where the remainder of the original build hierarchy is "
3374 "rooted on the local system. "
3375 "Each element of the array is checked in order and the first one that "
3376 "results in a match wins."},
3377 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3378 nullptr, "Executable search paths to use when locating executable files "
3379 "whose paths don't match the local file system."},
3380 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3382 "List of directories to be searched when locating debug symbol files."},
3383 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3385 "List of directories to be searched when locating modules for Clang."},
3386 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3388 "Automatically load Clang modules referred to by the program."},
3389 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3390 nullptr, "Automatically apply fix-it hints to expressions."},
3391 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3392 nullptr, "Print the fixed expression text."},
3393 {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
3394 nullptr, "Save intermediate object files generated by the LLVM JIT"},
3395 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3396 nullptr, "Maximum number of children to expand in any level of depth."},
3397 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3399 "Maximum number of characters to show when using %s in summary strings."},
3400 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3401 nullptr, "Maximum number of bytes that 'memory read' will fetch before "
3402 "--force must be specified."},
3403 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3404 true, nullptr, nullptr, "Consult the platform module avoid list when "
3405 "setting non-module specific breakpoints."},
3406 {"arg0", OptionValue::eTypeString, false, 0, nullptr, nullptr,
3407 "The first argument passed to the program in the argument array which can "
3408 "be different from the executable itself."},
3409 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, nullptr,
3410 "A list containing all the arguments to be passed to the executable when "
3411 "it is run. Note that this does NOT include the argv[0] which is in "
3413 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3414 nullptr, nullptr, "A list of all the environment variables to be passed "
3415 "to the executable's environment, and their values."},
3416 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3417 "Inherit the environment from the process that is running LLDB."},
3418 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3419 "The file/path to be used by the executable program for reading its "
3421 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3422 "The file/path to be used by the executable program for writing its "
3423 "standard output."},
3424 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3425 "The file/path to be used by the executable program for writing its "
3427 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3428 nullptr, "debugserver will detach (rather than killing) a process if it "
3429 "loses connection with lldb."},
3430 {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3431 "Enable loading of symbol tables before they are needed."},
3432 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3433 "Disable Address Space Layout Randomization (ASLR)"},
3434 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, nullptr,
3435 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3436 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3437 eInlineBreakpointsAlways, nullptr, g_inline_breakpoint_enums,
3438 "The strategy to use when settings breakpoints by file and line. "
3439 "Breakpoint locations can end up being inlined by the compiler, so that a "
3440 "compile unit 'a.c' might contain an inlined function from another source "
3442 "Usually this is limited to breakpoint locations from inlined functions "
3443 "from header or other include files, or more accurately "
3444 "non-implementation source files. "
3445 "Sometimes code might #include implementation files and cause inlined "
3446 "breakpoint locations in inlined implementation files. "
3447 "Always checking for inlined breakpoint locations can be expensive "
3448 "(memory and time), so if you have a project with many headers "
3449 "and find that setting breakpoints is slow, then you can change this "
3450 "setting to headers. "
3451 "This setting allows you to control exactly which strategy is used when "
3453 "file and line breakpoints."},
3454 // FIXME: This is the wrong way to do per-architecture settings, but we
3455 // don't have a general per architecture settings system in place yet.
3456 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3457 eX86DisFlavorDefault, nullptr, g_x86_dis_flavor_value_types,
3458 "The default disassembly flavor to use for x86 or x86-64 targets."},
3459 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3460 nullptr, "Show immediates in disassembly as hexadecimal."},
3461 {"hex-immediate-style", OptionValue::eTypeEnum, false,
3462 Disassembler::eHexStyleC, nullptr, g_hex_immediate_style_values,
3463 "Which style to use for printing hexadecimal disassembly values."},
3464 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3465 nullptr, "Use a fast stepping algorithm based on running from branch to "
3466 "branch rather than instruction single-stepping."},
3467 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3468 eLoadScriptFromSymFileWarn, nullptr, g_load_script_from_sym_file_values,
3469 "Allow LLDB to load scripting resources embedded in symbol files when "
3471 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3472 nullptr, g_load_current_working_dir_lldbinit_values,
3473 "Allow LLDB to .lldbinit files from the current directory automatically."},
3474 {"memory-module-load-level", OptionValue::eTypeEnum, false,
3475 eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3476 "Loading modules from memory can be slow as reading the symbol tables and "
3477 "other data can take a long time depending on your connection to the "
3479 "This setting helps users control how much information gets loaded when "
3480 "loading modules from memory."
3481 "'complete' is the default value for this setting which will load all "
3482 "sections and symbols by reading them from memory (slowest, most "
3484 "'partial' will load sections and attempt to find function bounds without "
3485 "downloading the symbol table (faster, still accurate, missing symbol "
3487 "'minimal' is the fastest setting and will load section data with no "
3488 "symbols, but should rarely be used as stack frames in these memory "
3489 "regions will be inaccurate and not provide any context (fastest). "},
3490 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3491 nullptr, nullptr, "Expressions that crash will show up in crash logs if "
3492 "the host system supports executable specific crash log "
3493 "strings and this setting is set to true."},
3494 {"trap-handler-names", OptionValue::eTypeArray, true,
3495 OptionValue::eTypeString, nullptr, nullptr,
3496 "A list of trap handler function names, e.g. a common Unix user process "
3497 "one is _sigtramp."},
3498 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3499 nullptr, nullptr, "If true, LLDB will show variables that are meant to "
3500 "support the operation of a language's runtime "
3502 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, nullptr,
3503 "Disable lock-step debugging, instead control threads independently."},
3504 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
3507 ePropertyDefaultArch,
3508 ePropertyMoveToNearestCode,
3510 ePropertyExprPrefix,
3511 ePropertyPreferDynamic,
3512 ePropertyEnableSynthetic,
3513 ePropertySkipPrologue,
3515 ePropertyExecutableSearchPaths,
3516 ePropertyDebugFileSearchPaths,
3517 ePropertyClangModuleSearchPaths,
3518 ePropertyAutoImportClangModules,
3519 ePropertyAutoApplyFixIts,
3520 ePropertyNotifyAboutFixIts,
3521 ePropertySaveObjects,
3522 ePropertyMaxChildrenCount,
3523 ePropertyMaxSummaryLength,
3524 ePropertyMaxMemReadSize,
3525 ePropertyBreakpointUseAvoidList,
3529 ePropertyInheritEnv,
3531 ePropertyOutputPath,
3533 ePropertyDetachOnError,
3534 ePropertyPreloadSymbols,
3535 ePropertyDisableASLR,
3536 ePropertyDisableSTDIO,
3537 ePropertyInlineStrategy,
3538 ePropertyDisassemblyFlavor,
3539 ePropertyUseHexImmediates,
3540 ePropertyHexImmediateStyle,
3541 ePropertyUseFastStepping,
3542 ePropertyLoadScriptFromSymbolFile,
3543 ePropertyLoadCWDlldbinitFile,
3544 ePropertyMemoryModuleLoadLevel,
3545 ePropertyDisplayExpressionsInCrashlogs,
3546 ePropertyTrapHandlerNames,
3547 ePropertyDisplayRuntimeSupportValues,
3548 ePropertyNonStopModeEnabled,
3549 ePropertyExperimental
3552 class TargetOptionValueProperties : public OptionValueProperties {
3554 TargetOptionValueProperties(const ConstString &name)
3555 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
3557 // This constructor is used when creating TargetOptionValueProperties when it
3558 // is part of a new lldb_private::Target instance. It will copy all current
3559 // global property values as needed
3560 TargetOptionValueProperties(Target *target,
3561 const TargetPropertiesSP &target_properties_sp)
3562 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3563 m_target(target), m_got_host_env(false) {}
3565 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3567 uint32_t idx) const override {
3568 // When getting the value for a key from the target options, we will always
3569 // try and grab the setting from the current target if there is one. Else
3570 // we just use the one from this instance.
3571 if (idx == ePropertyEnvVars)
3572 GetHostEnvironmentIfNeeded();
3575 Target *target = exe_ctx->GetTargetPtr();
3577 TargetOptionValueProperties *target_properties =
3578 static_cast<TargetOptionValueProperties *>(
3579 target->GetValueProperties().get());
3580 if (this != target_properties)
3581 return target_properties->ProtectedGetPropertyAtIndex(idx);
3584 return ProtectedGetPropertyAtIndex(idx);
3587 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3590 void GetHostEnvironmentIfNeeded() const {
3591 if (!m_got_host_env) {
3593 m_got_host_env = true;
3594 const uint32_t idx = ePropertyInheritEnv;
3595 if (GetPropertyAtIndexAsBoolean(
3596 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3597 PlatformSP platform_sp(m_target->GetPlatform());
3599 Environment env = platform_sp->GetEnvironment();
3600 OptionValueDictionary *env_dict =
3601 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3604 const bool can_replace = false;
3605 for (const auto &KV : env) {
3606 // Don't allow existing keys to be replaced with ones we get
3607 // from the platform environment
3608 env_dict->SetValueForKey(
3609 ConstString(KV.first()),
3610 OptionValueSP(new OptionValueString(KV.second.c_str())),
3620 mutable bool m_got_host_env;
3623 //----------------------------------------------------------------------
3625 //----------------------------------------------------------------------
3626 static PropertyDefinition g_experimental_properties[]{
3627 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3629 "If true, inject local variables explicitly into the expression text. "
3630 "This will fix symbol resolution when there are name collisions between "
3631 "ivars and local variables. "
3632 "But it can make expressions run much more slowly."},
3633 {"use-modern-type-lookup", OptionValue::eTypeBoolean, true, false, nullptr,
3634 nullptr, "If true, use Clang's modern type lookup infrastructure."},
3635 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
3637 enum { ePropertyInjectLocalVars = 0, ePropertyUseModernTypeLookup };
3639 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3641 TargetExperimentalOptionValueProperties()
3642 : OptionValueProperties(
3643 ConstString(Properties::GetExperimentalSettingsName())) {}
3646 TargetExperimentalProperties::TargetExperimentalProperties()
3647 : Properties(OptionValuePropertiesSP(
3648 new TargetExperimentalOptionValueProperties())) {
3649 m_collection_sp->Initialize(g_experimental_properties);
3652 //----------------------------------------------------------------------
3654 //----------------------------------------------------------------------
3655 TargetProperties::TargetProperties(Target *target)
3656 : Properties(), m_launch_info() {
3658 m_collection_sp.reset(
3659 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
3661 // Set callbacks to update launch_info whenever "settins set" updated any
3662 // of these properties
3663 m_collection_sp->SetValueChangedCallback(
3664 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3665 m_collection_sp->SetValueChangedCallback(
3666 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3667 m_collection_sp->SetValueChangedCallback(
3668 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3669 m_collection_sp->SetValueChangedCallback(
3670 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3672 m_collection_sp->SetValueChangedCallback(
3673 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3675 m_collection_sp->SetValueChangedCallback(
3676 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3678 m_collection_sp->SetValueChangedCallback(
3679 ePropertyDetachOnError,
3680 TargetProperties::DetachOnErrorValueChangedCallback, this);
3681 m_collection_sp->SetValueChangedCallback(
3682 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3684 m_collection_sp->SetValueChangedCallback(
3685 ePropertyDisableSTDIO,
3686 TargetProperties::DisableSTDIOValueChangedCallback, this);
3688 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3689 m_collection_sp->AppendProperty(
3690 ConstString(Properties::GetExperimentalSettingsName()),
3691 ConstString("Experimental settings - setting these won't produce "
3692 "errors if the setting is not present."),
3693 true, m_experimental_properties_up->GetValueProperties());
3695 // Update m_launch_info once it was created
3696 Arg0ValueChangedCallback(this, nullptr);
3697 RunArgsValueChangedCallback(this, nullptr);
3698 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3699 // Target::GetPlatform()
3700 InputPathValueChangedCallback(this, nullptr);
3701 OutputPathValueChangedCallback(this, nullptr);
3702 ErrorPathValueChangedCallback(this, nullptr);
3703 DetachOnErrorValueChangedCallback(this, nullptr);
3704 DisableASLRValueChangedCallback(this, nullptr);
3705 DisableSTDIOValueChangedCallback(this, nullptr);
3707 m_collection_sp.reset(
3708 new TargetOptionValueProperties(ConstString("target")));
3709 m_collection_sp->Initialize(g_properties);
3710 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3711 m_collection_sp->AppendProperty(
3712 ConstString(Properties::GetExperimentalSettingsName()),
3713 ConstString("Experimental settings - setting these won't produce "
3714 "errors if the setting is not present."),
3715 true, m_experimental_properties_up->GetValueProperties());
3716 m_collection_sp->AppendProperty(
3717 ConstString("process"), ConstString("Settings specific to processes."),
3718 true, Process::GetGlobalProperties()->GetValueProperties());
3722 TargetProperties::~TargetProperties() = default;
3724 bool TargetProperties::GetInjectLocalVariables(
3725 ExecutionContext *exe_ctx) const {
3726 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3727 exe_ctx, false, ePropertyExperimental);
3728 OptionValueProperties *exp_values =
3729 exp_property->GetValue()->GetAsProperties();
3731 return exp_values->GetPropertyAtIndexAsBoolean(
3732 exe_ctx, ePropertyInjectLocalVars, true);
3737 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3739 const Property *exp_property =
3740 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3741 OptionValueProperties *exp_values =
3742 exp_property->GetValue()->GetAsProperties();
3744 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3748 bool TargetProperties::GetUseModernTypeLookup() const {
3749 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3750 nullptr, false, ePropertyExperimental);
3751 OptionValueProperties *exp_values =
3752 exp_property->GetValue()->GetAsProperties();
3754 return exp_values->GetPropertyAtIndexAsBoolean(
3755 nullptr, ePropertyUseModernTypeLookup, true);
3760 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3761 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3762 nullptr, ePropertyDefaultArch);
3764 return value->GetCurrentValue();
3768 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3769 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3770 nullptr, ePropertyDefaultArch);
3772 return value->SetCurrentValue(arch, true);
3775 bool TargetProperties::GetMoveToNearestCode() const {
3776 const uint32_t idx = ePropertyMoveToNearestCode;
3777 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3778 nullptr, idx, g_properties[idx].default_uint_value != 0);
3781 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3782 const uint32_t idx = ePropertyPreferDynamic;
3783 return (lldb::DynamicValueType)
3784 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3785 nullptr, idx, g_properties[idx].default_uint_value);
3788 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3789 const uint32_t idx = ePropertyPreferDynamic;
3790 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3793 bool TargetProperties::GetPreloadSymbols() const {
3794 const uint32_t idx = ePropertyPreloadSymbols;
3795 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3796 nullptr, idx, g_properties[idx].default_uint_value != 0);
3799 void TargetProperties::SetPreloadSymbols(bool b) {
3800 const uint32_t idx = ePropertyPreloadSymbols;
3801 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3804 bool TargetProperties::GetDisableASLR() const {
3805 const uint32_t idx = ePropertyDisableASLR;
3806 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3807 nullptr, idx, g_properties[idx].default_uint_value != 0);
3810 void TargetProperties::SetDisableASLR(bool b) {
3811 const uint32_t idx = ePropertyDisableASLR;
3812 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3815 bool TargetProperties::GetDetachOnError() const {
3816 const uint32_t idx = ePropertyDetachOnError;
3817 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3818 nullptr, idx, g_properties[idx].default_uint_value != 0);
3821 void TargetProperties::SetDetachOnError(bool b) {
3822 const uint32_t idx = ePropertyDetachOnError;
3823 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3826 bool TargetProperties::GetDisableSTDIO() const {
3827 const uint32_t idx = ePropertyDisableSTDIO;
3828 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3829 nullptr, idx, g_properties[idx].default_uint_value != 0);
3832 void TargetProperties::SetDisableSTDIO(bool b) {
3833 const uint32_t idx = ePropertyDisableSTDIO;
3834 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3837 const char *TargetProperties::GetDisassemblyFlavor() const {
3838 const uint32_t idx = ePropertyDisassemblyFlavor;
3839 const char *return_value;
3841 x86DisassemblyFlavor flavor_value =
3842 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3843 nullptr, idx, g_properties[idx].default_uint_value);
3844 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3845 return return_value;
3848 InlineStrategy TargetProperties::GetInlineStrategy() const {
3849 const uint32_t idx = ePropertyInlineStrategy;
3850 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3851 nullptr, idx, g_properties[idx].default_uint_value);
3854 llvm::StringRef TargetProperties::GetArg0() const {
3855 const uint32_t idx = ePropertyArg0;
3856 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
3859 void TargetProperties::SetArg0(llvm::StringRef arg) {
3860 const uint32_t idx = ePropertyArg0;
3861 m_collection_sp->SetPropertyAtIndexAsString(
3863 m_launch_info.SetArg0(arg);
3866 bool TargetProperties::GetRunArguments(Args &args) const {
3867 const uint32_t idx = ePropertyRunArgs;
3868 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3871 void TargetProperties::SetRunArguments(const Args &args) {
3872 const uint32_t idx = ePropertyRunArgs;
3873 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3874 m_launch_info.GetArguments() = args;
3877 Environment TargetProperties::GetEnvironment() const {
3878 // TODO: Get rid of the Args intermediate step
3880 const uint32_t idx = ePropertyEnvVars;
3881 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3882 return Environment(env);
3885 void TargetProperties::SetEnvironment(Environment env) {
3886 // TODO: Get rid of the Args intermediate step
3887 const uint32_t idx = ePropertyEnvVars;
3888 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3889 m_launch_info.GetEnvironment() = std::move(env);
3892 bool TargetProperties::GetSkipPrologue() const {
3893 const uint32_t idx = ePropertySkipPrologue;
3894 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3895 nullptr, idx, g_properties[idx].default_uint_value != 0);
3898 PathMappingList &TargetProperties::GetSourcePathMap() const {
3899 const uint32_t idx = ePropertySourceMap;
3900 OptionValuePathMappings *option_value =
3901 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3903 assert(option_value);
3904 return option_value->GetCurrentValue();
3907 FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3908 const uint32_t idx = ePropertyExecutableSearchPaths;
3909 OptionValueFileSpecList *option_value =
3910 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3912 assert(option_value);
3913 return option_value->GetCurrentValue();
3916 FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3917 const uint32_t idx = ePropertyDebugFileSearchPaths;
3918 OptionValueFileSpecList *option_value =
3919 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3921 assert(option_value);
3922 return option_value->GetCurrentValue();
3925 FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3926 const uint32_t idx = ePropertyClangModuleSearchPaths;
3927 OptionValueFileSpecList *option_value =
3928 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3930 assert(option_value);
3931 return option_value->GetCurrentValue();
3934 bool TargetProperties::GetEnableAutoImportClangModules() const {
3935 const uint32_t idx = ePropertyAutoImportClangModules;
3936 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3937 nullptr, idx, g_properties[idx].default_uint_value != 0);
3940 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3941 const uint32_t idx = ePropertyAutoApplyFixIts;
3942 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3943 nullptr, idx, g_properties[idx].default_uint_value != 0);
3946 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3947 const uint32_t idx = ePropertyNotifyAboutFixIts;
3948 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3949 nullptr, idx, g_properties[idx].default_uint_value != 0);
3952 bool TargetProperties::GetEnableSaveObjects() const {
3953 const uint32_t idx = ePropertySaveObjects;
3954 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3955 nullptr, idx, g_properties[idx].default_uint_value != 0);
3958 bool TargetProperties::GetEnableSyntheticValue() const {
3959 const uint32_t idx = ePropertyEnableSynthetic;
3960 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3961 nullptr, idx, g_properties[idx].default_uint_value != 0);
3964 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3965 const uint32_t idx = ePropertyMaxChildrenCount;
3966 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3967 nullptr, idx, g_properties[idx].default_uint_value);
3970 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3971 const uint32_t idx = ePropertyMaxSummaryLength;
3972 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3973 nullptr, idx, g_properties[idx].default_uint_value);
3976 uint32_t TargetProperties::GetMaximumMemReadSize() const {
3977 const uint32_t idx = ePropertyMaxMemReadSize;
3978 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3979 nullptr, idx, g_properties[idx].default_uint_value);
3982 FileSpec TargetProperties::GetStandardInputPath() const {
3983 const uint32_t idx = ePropertyInputPath;
3984 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3987 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
3988 const uint32_t idx = ePropertyInputPath;
3989 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3992 FileSpec TargetProperties::GetStandardOutputPath() const {
3993 const uint32_t idx = ePropertyOutputPath;
3994 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3997 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
3998 const uint32_t idx = ePropertyOutputPath;
3999 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4002 FileSpec TargetProperties::GetStandardErrorPath() const {
4003 const uint32_t idx = ePropertyErrorPath;
4004 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4007 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4008 const uint32_t idx = ePropertyErrorPath;
4009 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4012 LanguageType TargetProperties::GetLanguage() const {
4013 OptionValueLanguage *value =
4014 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
4015 nullptr, ePropertyLanguage);
4017 return value->GetCurrentValue();
4018 return LanguageType();
4021 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
4022 const uint32_t idx = ePropertyExprPrefix;
4023 OptionValueFileSpec *file =
4024 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
4027 DataBufferSP data_sp(file->GetFileContents());
4029 return llvm::StringRef(
4030 reinterpret_cast<const char *>(data_sp->GetBytes()),
4031 data_sp->GetByteSize());
4036 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4037 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4038 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4039 nullptr, idx, g_properties[idx].default_uint_value != 0);
4042 bool TargetProperties::GetUseHexImmediates() const {
4043 const uint32_t idx = ePropertyUseHexImmediates;
4044 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4045 nullptr, idx, g_properties[idx].default_uint_value != 0);
4048 bool TargetProperties::GetUseFastStepping() const {
4049 const uint32_t idx = ePropertyUseFastStepping;
4050 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4051 nullptr, idx, g_properties[idx].default_uint_value != 0);
4054 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4055 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4056 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4057 nullptr, idx, g_properties[idx].default_uint_value != 0);
4060 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4061 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4062 return (LoadScriptFromSymFile)
4063 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4064 nullptr, idx, g_properties[idx].default_uint_value);
4067 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4068 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4069 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4070 nullptr, idx, g_properties[idx].default_uint_value);
4073 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4074 const uint32_t idx = ePropertyHexImmediateStyle;
4075 return (Disassembler::HexImmediateStyle)
4076 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4077 nullptr, idx, g_properties[idx].default_uint_value);
4080 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4081 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4082 return (MemoryModuleLoadLevel)
4083 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4084 nullptr, idx, g_properties[idx].default_uint_value);
4087 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4088 const uint32_t idx = ePropertyTrapHandlerNames;
4089 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4092 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4093 const uint32_t idx = ePropertyTrapHandlerNames;
4094 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4097 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4098 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4099 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4102 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4103 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4104 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4107 bool TargetProperties::GetNonStopModeEnabled() const {
4108 const uint32_t idx = ePropertyNonStopModeEnabled;
4109 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4112 void TargetProperties::SetNonStopModeEnabled(bool b) {
4113 const uint32_t idx = ePropertyNonStopModeEnabled;
4114 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4117 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
4118 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4119 return m_launch_info;
4122 void TargetProperties::SetProcessLaunchInfo(
4123 const ProcessLaunchInfo &launch_info) {
4124 m_launch_info = launch_info;
4125 SetArg0(launch_info.GetArg0());
4126 SetRunArguments(launch_info.GetArguments());
4127 SetEnvironment(launch_info.GetEnvironment());
4128 const FileAction *input_file_action =
4129 launch_info.GetFileActionForFD(STDIN_FILENO);
4130 if (input_file_action) {
4131 SetStandardInputPath(input_file_action->GetPath());
4133 const FileAction *output_file_action =
4134 launch_info.GetFileActionForFD(STDOUT_FILENO);
4135 if (output_file_action) {
4136 SetStandardOutputPath(output_file_action->GetPath());
4138 const FileAction *error_file_action =
4139 launch_info.GetFileActionForFD(STDERR_FILENO);
4140 if (error_file_action) {
4141 SetStandardErrorPath(error_file_action->GetPath());
4143 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4144 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4145 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4148 void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4150 TargetProperties *this_ =
4151 reinterpret_cast<TargetProperties *>(target_property_ptr);
4152 this_->m_launch_info.SetArg0(this_->GetArg0());
4155 void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4157 TargetProperties *this_ =
4158 reinterpret_cast<TargetProperties *>(target_property_ptr);
4160 if (this_->GetRunArguments(args))
4161 this_->m_launch_info.GetArguments() = args;
4164 void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4166 TargetProperties *this_ =
4167 reinterpret_cast<TargetProperties *>(target_property_ptr);
4168 this_->m_launch_info.GetEnvironment() = this_->GetEnvironment();
4171 void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4173 TargetProperties *this_ =
4174 reinterpret_cast<TargetProperties *>(target_property_ptr);
4175 this_->m_launch_info.AppendOpenFileAction(
4176 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
4179 void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4181 TargetProperties *this_ =
4182 reinterpret_cast<TargetProperties *>(target_property_ptr);
4183 this_->m_launch_info.AppendOpenFileAction(
4184 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
4187 void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4189 TargetProperties *this_ =
4190 reinterpret_cast<TargetProperties *>(target_property_ptr);
4191 this_->m_launch_info.AppendOpenFileAction(
4192 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
4195 void TargetProperties::DetachOnErrorValueChangedCallback(
4196 void *target_property_ptr, OptionValue *) {
4197 TargetProperties *this_ =
4198 reinterpret_cast<TargetProperties *>(target_property_ptr);
4199 if (this_->GetDetachOnError())
4200 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4202 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4205 void TargetProperties::DisableASLRValueChangedCallback(
4206 void *target_property_ptr, OptionValue *) {
4207 TargetProperties *this_ =
4208 reinterpret_cast<TargetProperties *>(target_property_ptr);
4209 if (this_->GetDisableASLR())
4210 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4212 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4215 void TargetProperties::DisableSTDIOValueChangedCallback(
4216 void *target_property_ptr, OptionValue *) {
4217 TargetProperties *this_ =
4218 reinterpret_cast<TargetProperties *>(target_property_ptr);
4219 if (this_->GetDisableSTDIO())
4220 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4222 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4225 //----------------------------------------------------------------------
4226 // Target::TargetEventData
4227 //----------------------------------------------------------------------
4229 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4230 : EventData(), m_target_sp(target_sp), m_module_list() {}
4232 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4233 const ModuleList &module_list)
4234 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4236 Target::TargetEventData::~TargetEventData() = default;
4238 const ConstString &Target::TargetEventData::GetFlavorString() {
4239 static ConstString g_flavor("Target::TargetEventData");
4243 void Target::TargetEventData::Dump(Stream *s) const {
4244 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4247 m_module_list.GetModuleAtIndex(i)->GetDescription(
4248 s, lldb::eDescriptionLevelBrief);
4252 const Target::TargetEventData *
4253 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4255 const EventData *event_data = event_ptr->GetData();
4257 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4258 return static_cast<const TargetEventData *>(event_ptr->GetData());
4263 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4265 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4267 target_sp = event_data->m_target_sp;
4272 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4273 ModuleList module_list;
4274 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4276 module_list = event_data->m_module_list;