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),
91 m_images(this), m_section_load_history(), m_breakpoint_list(false),
92 m_internal_breakpoint_list(true), m_watchpoint_list(), m_process_sp(),
93 m_search_filter_sp(), m_image_search_paths(ImageSearchPathsChanged, this),
94 m_ast_importer_sp(), m_source_manager_ap(), m_stop_hooks(),
95 m_stop_hook_next_id(0), m_valid(true), m_suppress_stop_hooks(false),
96 m_is_dummy_target(is_dummy_target)
99 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
100 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
101 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
102 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
103 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
105 CheckInWithManager();
107 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
109 log->Printf("%p Target::Target()", static_cast<void *>(this));
110 if (target_arch.IsValid()) {
111 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET,
112 "Target::Target created with architecture %s (%s)",
113 target_arch.GetArchitectureName(),
114 target_arch.GetTriple().getTriple().c_str());
119 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
121 log->Printf("%p Target::~Target()", static_cast<void *>(this));
122 DeleteCurrentProcess();
125 void Target::PrimeFromDummyTarget(Target *target) {
129 m_stop_hooks = target->m_stop_hooks;
131 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
132 if (breakpoint_sp->IsInternal())
135 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
136 AddBreakpoint(new_bp, false);
139 for (auto bp_name_entry : target->m_breakpoint_names)
142 BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
143 AddBreakpointName(new_bp_name);
147 void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
148 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
149 if (description_level != lldb::eDescriptionLevelBrief) {
151 s->PutCString("Target\n");
154 m_breakpoint_list.Dump(s);
155 m_internal_breakpoint_list.Dump(s);
158 Module *exe_module = GetExecutableModulePointer();
160 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
162 s->PutCString("No executable module.");
166 void Target::CleanupProcess() {
167 // Do any cleanup of the target we need to do between process instances.
168 // NB It is better to do this before destroying the process in case the
169 // clean up needs some help from the process.
170 m_breakpoint_list.ClearAllBreakpointSites();
171 m_internal_breakpoint_list.ClearAllBreakpointSites();
172 // Disable watchpoints just on the debugger side.
173 std::unique_lock<std::recursive_mutex> lock;
174 this->GetWatchpointList().GetListMutex(lock);
175 DisableAllWatchpoints(false);
176 ClearAllWatchpointHitCounts();
177 ClearAllWatchpointHistoricValues();
180 void Target::DeleteCurrentProcess() {
182 m_section_load_history.Clear();
183 if (m_process_sp->IsAlive())
184 m_process_sp->Destroy(false);
186 m_process_sp->Finalize();
190 m_process_sp.reset();
194 const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
195 llvm::StringRef plugin_name,
196 const FileSpec *crash_file) {
197 DeleteCurrentProcess();
198 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
199 listener_sp, crash_file);
203 const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
205 lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
206 const char *repl_options, bool can_create) {
207 if (language == eLanguageTypeUnknown) {
208 std::set<LanguageType> repl_languages;
210 Language::GetLanguagesSupportingREPLs(repl_languages);
212 if (repl_languages.size() == 1) {
213 language = *repl_languages.begin();
214 } else if (repl_languages.size() == 0) {
215 err.SetErrorStringWithFormat(
216 "LLDB isn't configured with REPL support for any languages.");
219 err.SetErrorStringWithFormat(
220 "Multiple possible REPL languages. Please specify a language.");
225 REPLMap::iterator pos = m_repl_map.find(language);
227 if (pos != m_repl_map.end()) {
232 err.SetErrorStringWithFormat(
233 "Couldn't find an existing REPL for %s, and can't create a new one",
234 Language::GetNameForLanguageType(language));
235 return lldb::REPLSP();
238 Debugger *const debugger = nullptr;
239 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
242 m_repl_map[language] = ret;
243 return m_repl_map[language];
247 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
248 Language::GetNameForLanguageType(language));
251 return lldb::REPLSP();
254 void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
255 lldbassert(!m_repl_map.count(language));
257 m_repl_map[language] = repl_sp;
260 void Target::Destroy() {
261 std::lock_guard<std::recursive_mutex> guard(m_mutex);
263 DeleteCurrentProcess();
264 m_platform_sp.reset();
267 m_section_load_history.Clear();
268 const bool notify = false;
269 m_breakpoint_list.RemoveAll(notify);
270 m_internal_breakpoint_list.RemoveAll(notify);
271 m_last_created_breakpoint.reset();
272 m_last_created_watchpoint.reset();
273 m_search_filter_sp.reset();
274 m_image_search_paths.Clear(notify);
275 m_stop_hooks.clear();
276 m_stop_hook_next_id = 0;
277 m_suppress_stop_hooks = false;
280 BreakpointList &Target::GetBreakpointList(bool internal) {
282 return m_internal_breakpoint_list;
284 return m_breakpoint_list;
287 const BreakpointList &Target::GetBreakpointList(bool internal) const {
289 return m_internal_breakpoint_list;
291 return m_breakpoint_list;
294 BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
297 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
298 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
300 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
305 BreakpointSP Target::CreateSourceRegexBreakpoint(
306 const FileSpecList *containingModules,
307 const FileSpecList *source_file_spec_list,
308 const std::unordered_set<std::string> &function_names,
309 RegularExpression &source_regex, bool internal, bool hardware,
310 LazyBool move_to_nearest_code) {
311 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
312 containingModules, source_file_spec_list));
313 if (move_to_nearest_code == eLazyBoolCalculate)
314 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
315 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
316 nullptr, source_regex, function_names,
317 !static_cast<bool>(move_to_nearest_code)));
319 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
322 BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
323 const FileSpec &file, uint32_t line_no,
325 LazyBool check_inlines,
326 LazyBool skip_prologue, bool internal,
328 LazyBool move_to_nearest_code) {
329 FileSpec remapped_file;
330 ConstString remapped_path;
331 if (GetSourcePathMap().ReverseRemapPath(ConstString(file.GetPath().c_str()),
333 remapped_file.SetFile(remapped_path.AsCString(), true);
335 remapped_file = file;
337 if (check_inlines == eLazyBoolCalculate) {
338 const InlineStrategy inline_strategy = GetInlineStrategy();
339 switch (inline_strategy) {
340 case eInlineBreakpointsNever:
341 check_inlines = eLazyBoolNo;
344 case eInlineBreakpointsHeaders:
345 if (remapped_file.IsSourceImplementationFile())
346 check_inlines = eLazyBoolNo;
348 check_inlines = eLazyBoolYes;
351 case eInlineBreakpointsAlways:
352 check_inlines = eLazyBoolYes;
356 SearchFilterSP filter_sp;
357 if (check_inlines == eLazyBoolNo) {
358 // Not checking for inlines, we are looking only for matching compile units
359 FileSpecList compile_unit_list;
360 compile_unit_list.Append(remapped_file);
361 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
364 filter_sp = GetSearchFilterForModuleList(containingModules);
366 if (skip_prologue == eLazyBoolCalculate)
367 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
368 if (move_to_nearest_code == eLazyBoolCalculate)
369 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
371 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
372 nullptr, remapped_file, line_no, offset, check_inlines, skip_prologue,
373 !static_cast<bool>(move_to_nearest_code)));
374 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
377 BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
381 // Check for any reason we want to move this breakpoint to other address.
382 addr = GetBreakableLoadAddress(addr);
384 // Attempt to resolve our load address if possible, though it is ok if
385 // it doesn't resolve to section/offset.
387 // Try and resolve as a load address if possible
388 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
389 if (!so_addr.IsValid()) {
390 // The address didn't resolve, so just set this as an absolute address
391 so_addr.SetOffset(addr);
393 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
397 BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
399 SearchFilterSP filter_sp(
400 new SearchFilterForUnconstrainedSearches(shared_from_this()));
401 BreakpointResolverSP resolver_sp(
402 new BreakpointResolverAddress(nullptr, addr));
403 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
407 Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
408 const FileSpec *file_spec,
409 bool request_hardware) {
410 SearchFilterSP filter_sp(
411 new SearchFilterForUnconstrainedSearches(shared_from_this()));
412 BreakpointResolverSP resolver_sp(
413 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
414 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
419 Target::CreateBreakpoint(const FileSpecList *containingModules,
420 const FileSpecList *containingSourceFiles,
421 const char *func_name, uint32_t func_name_type_mask,
422 LanguageType language, lldb::addr_t offset,
423 LazyBool skip_prologue, bool internal, bool hardware) {
426 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
427 containingModules, containingSourceFiles));
429 if (skip_prologue == eLazyBoolCalculate)
430 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
431 if (language == lldb::eLanguageTypeUnknown)
432 language = GetLanguage();
434 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
435 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
436 offset, skip_prologue));
437 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
443 Target::CreateBreakpoint(const FileSpecList *containingModules,
444 const FileSpecList *containingSourceFiles,
445 const std::vector<std::string> &func_names,
446 uint32_t func_name_type_mask, LanguageType language,
447 lldb::addr_t offset, LazyBool skip_prologue,
448 bool internal, bool hardware) {
450 size_t num_names = func_names.size();
452 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
453 containingModules, containingSourceFiles));
455 if (skip_prologue == eLazyBoolCalculate)
456 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
457 if (language == lldb::eLanguageTypeUnknown)
458 language = GetLanguage();
460 BreakpointResolverSP resolver_sp(
461 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
462 language, offset, skip_prologue));
463 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
468 BreakpointSP Target::CreateBreakpoint(
469 const FileSpecList *containingModules,
470 const FileSpecList *containingSourceFiles, const char *func_names[],
471 size_t num_names, uint32_t func_name_type_mask, LanguageType language,
472 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
475 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
476 containingModules, containingSourceFiles));
478 if (skip_prologue == eLazyBoolCalculate) {
480 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
482 skip_prologue = eLazyBoolNo;
484 if (language == lldb::eLanguageTypeUnknown)
485 language = GetLanguage();
487 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
488 nullptr, func_names, num_names, func_name_type_mask, language, offset,
490 resolver_sp->SetOffset(offset);
491 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
497 Target::GetSearchFilterForModule(const FileSpec *containingModule) {
498 SearchFilterSP filter_sp;
499 if (containingModule != nullptr) {
500 // TODO: We should look into sharing module based search filters
501 // across many breakpoints like we do for the simple target based one
503 new SearchFilterByModule(shared_from_this(), *containingModule));
505 if (!m_search_filter_sp)
506 m_search_filter_sp.reset(
507 new SearchFilterForUnconstrainedSearches(shared_from_this()));
508 filter_sp = m_search_filter_sp;
514 Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
515 SearchFilterSP filter_sp;
516 if (containingModules && containingModules->GetSize() != 0) {
517 // TODO: We should look into sharing module based search filters
518 // across many breakpoints like we do for the simple target based one
520 new SearchFilterByModuleList(shared_from_this(), *containingModules));
522 if (!m_search_filter_sp)
523 m_search_filter_sp.reset(
524 new SearchFilterForUnconstrainedSearches(shared_from_this()));
525 filter_sp = m_search_filter_sp;
530 SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
531 const FileSpecList *containingModules,
532 const FileSpecList *containingSourceFiles) {
533 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
534 return GetSearchFilterForModuleList(containingModules);
536 SearchFilterSP filter_sp;
537 if (containingModules == nullptr) {
538 // We could make a special "CU List only SearchFilter". Better yet was if
539 // these could be composable,
540 // but that will take a little reworking.
542 filter_sp.reset(new SearchFilterByModuleListAndCU(
543 shared_from_this(), FileSpecList(), *containingSourceFiles));
545 filter_sp.reset(new SearchFilterByModuleListAndCU(
546 shared_from_this(), *containingModules, *containingSourceFiles));
551 BreakpointSP Target::CreateFuncRegexBreakpoint(
552 const FileSpecList *containingModules,
553 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
554 lldb::LanguageType requested_language, LazyBool skip_prologue,
555 bool internal, bool hardware) {
556 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
557 containingModules, containingSourceFiles));
558 bool skip = (skip_prologue == eLazyBoolCalculate)
560 : static_cast<bool>(skip_prologue);
561 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
562 nullptr, func_regex, requested_language, 0, skip));
564 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
568 Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
569 bool catch_bp, bool throw_bp, bool internal,
570 Args *additional_args, Status *error) {
571 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
572 *this, language, catch_bp, throw_bp, internal);
573 if (exc_bkpt_sp && additional_args) {
574 Breakpoint::BreakpointPreconditionSP precondition_sp =
575 exc_bkpt_sp->GetPrecondition();
576 if (precondition_sp && additional_args) {
578 *error = precondition_sp->ConfigurePrecondition(*additional_args);
580 precondition_sp->ConfigurePrecondition(*additional_args);
586 BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
587 BreakpointResolverSP &resolver_sp,
588 bool internal, bool request_hardware,
589 bool resolve_indirect_symbols) {
591 if (filter_sp && resolver_sp) {
592 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, request_hardware,
593 resolve_indirect_symbols));
594 resolver_sp->SetBreakpoint(bp_sp.get());
595 AddBreakpoint(bp_sp, internal);
600 void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
604 m_internal_breakpoint_list.Add(bp_sp, false);
606 m_breakpoint_list.Add(bp_sp, true);
608 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
611 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
612 log->Printf("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__,
613 bp_sp->IsInternal() ? "yes" : "no", s.GetData());
616 bp_sp->ResolveBreakpoint();
619 m_last_created_breakpoint = bp_sp;
623 void Target::AddNameToBreakpoint(BreakpointID &id,
628 = m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
632 id.GetDescription(&s, eDescriptionLevelBrief);
633 error.SetErrorStringWithFormat("Could not find breakpoint %s",
637 AddNameToBreakpoint(bp_sp, name, error);
640 void Target::AddNameToBreakpoint(BreakpointSP &bp_sp,
647 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
651 bp_name->ConfigureBreakpoint(bp_sp);
652 bp_sp->AddName(name);
655 void Target::AddBreakpointName(BreakpointName *bp_name) {
656 m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name));
659 BreakpointName *Target::FindBreakpointName(const ConstString &name,
663 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
664 if (!error.Success())
667 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
668 if (iter == m_breakpoint_names.end()) {
671 error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
672 "can_create is false.", name.AsCString());
676 iter = m_breakpoint_names.insert(std::make_pair(name,
677 new BreakpointName(name)))
680 return (iter->second);
684 Target::DeleteBreakpointName(const ConstString &name)
686 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
688 if (iter != m_breakpoint_names.end()) {
689 const char *name_cstr = name.AsCString();
690 m_breakpoint_names.erase(iter);
691 for (auto bp_sp : m_breakpoint_list.Breakpoints())
692 bp_sp->RemoveName(name_cstr);
696 void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
697 const ConstString &name)
699 bp_sp->RemoveName(name.AsCString());
702 void Target::ConfigureBreakpointName(BreakpointName &bp_name,
703 const BreakpointOptions &new_options,
704 const BreakpointName::Permissions &new_permissions)
706 bp_name.GetOptions().CopyOverSetOptions(new_options);
707 bp_name.GetPermissions().MergeInto(new_permissions);
708 ApplyNameToBreakpoints(bp_name);
711 void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
712 BreakpointList bkpts_with_name(false);
713 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString(),
716 for (auto bp_sp : bkpts_with_name.Breakpoints())
717 bp_name.ConfigureBreakpoint(bp_sp);
720 void Target::GetBreakpointNames(std::vector<std::string> &names)
723 for (auto bp_name : m_breakpoint_names) {
724 names.push_back(bp_name.first.AsCString());
726 std::sort(names.begin(), names.end());
729 bool Target::ProcessIsValid() {
730 return (m_process_sp && m_process_sp->IsAlive());
733 static bool CheckIfWatchpointsExhausted(Target *target, Status &error) {
734 uint32_t num_supported_hardware_watchpoints;
735 Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
736 num_supported_hardware_watchpoints);
737 if (num_supported_hardware_watchpoints == 0) {
738 error.SetErrorStringWithFormat(
739 "Target supports (%u) hardware watchpoint slots.\n",
740 num_supported_hardware_watchpoints);
746 // See also Watchpoint::SetWatchpointType(uint32_t type) and
747 // the OptionGroupWatchpoint::WatchType enum type.
748 WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
749 const CompilerType *type, uint32_t kind,
751 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
753 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
755 __FUNCTION__, addr, (uint64_t)size, kind);
758 if (!ProcessIsValid()) {
759 error.SetErrorString("process is not alive");
763 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
765 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
767 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
771 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
772 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
775 if (!CheckIfWatchpointsExhausted(this, error))
778 // Currently we only support one watchpoint per address, with total number
779 // of watchpoints limited by the hardware which the inferior is running on.
781 // Grab the list mutex while doing operations.
782 const bool notify = false; // Don't notify about all the state changes we do
783 // on creating the watchpoint.
784 std::unique_lock<std::recursive_mutex> lock;
785 this->GetWatchpointList().GetListMutex(lock);
786 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
788 size_t old_size = matched_sp->GetByteSize();
790 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
791 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
792 // Return the existing watchpoint if both size and type match.
793 if (size == old_size && kind == old_type) {
795 wp_sp->SetEnabled(false, notify);
797 // Nil the matched watchpoint; we will be creating a new one.
798 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
799 m_watchpoint_list.Remove(matched_sp->GetID(), true);
804 wp_sp.reset(new Watchpoint(*this, addr, size, type));
805 wp_sp->SetWatchpointType(kind, notify);
806 m_watchpoint_list.Add(wp_sp, true);
809 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
811 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
812 __FUNCTION__, error.Success() ? "succeeded" : "failed",
816 // Enabling the watchpoint on the device side failed.
817 // Remove the said watchpoint from the list maintained by the target
819 m_watchpoint_list.Remove(wp_sp->GetID(), true);
820 // See if we could provide more helpful error message.
821 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
822 error.SetErrorStringWithFormat(
823 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
827 m_last_created_watchpoint = wp_sp;
831 void Target::RemoveAllowedBreakpoints ()
833 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
835 log->Printf("Target::%s \n", __FUNCTION__);
837 m_breakpoint_list.RemoveAllowed(true);
839 m_last_created_breakpoint.reset();
842 void Target::RemoveAllBreakpoints(bool internal_also) {
843 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
845 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
846 internal_also ? "yes" : "no");
848 m_breakpoint_list.RemoveAll(true);
850 m_internal_breakpoint_list.RemoveAll(false);
852 m_last_created_breakpoint.reset();
855 void Target::DisableAllBreakpoints(bool internal_also) {
856 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
858 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
859 internal_also ? "yes" : "no");
861 m_breakpoint_list.SetEnabledAll(false);
863 m_internal_breakpoint_list.SetEnabledAll(false);
866 void Target::DisableAllowedBreakpoints() {
867 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
869 log->Printf("Target::%s", __FUNCTION__);
871 m_breakpoint_list.SetEnabledAllowed(false);
874 void Target::EnableAllBreakpoints(bool internal_also) {
875 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
877 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
878 internal_also ? "yes" : "no");
880 m_breakpoint_list.SetEnabledAll(true);
882 m_internal_breakpoint_list.SetEnabledAll(true);
885 void Target::EnableAllowedBreakpoints() {
886 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
888 log->Printf("Target::%s", __FUNCTION__);
890 m_breakpoint_list.SetEnabledAllowed(true);
893 bool Target::RemoveBreakpointByID(break_id_t break_id) {
894 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
896 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
897 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
899 if (DisableBreakpointByID(break_id)) {
900 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
901 m_internal_breakpoint_list.Remove(break_id, false);
903 if (m_last_created_breakpoint) {
904 if (m_last_created_breakpoint->GetID() == break_id)
905 m_last_created_breakpoint.reset();
907 m_breakpoint_list.Remove(break_id, true);
914 bool Target::DisableBreakpointByID(break_id_t break_id) {
915 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
917 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
918 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
922 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
923 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
925 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
927 bp_sp->SetEnabled(false);
933 bool Target::EnableBreakpointByID(break_id_t break_id) {
934 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
936 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
937 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
941 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
942 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
944 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
947 bp_sp->SetEnabled(true);
953 Status Target::SerializeBreakpointsToFile(const FileSpec &file,
954 const BreakpointIDList &bp_ids,
959 error.SetErrorString("Invalid FileSpec.");
963 std::string path(file.GetPath());
964 StructuredData::ObjectSP input_data_sp;
966 StructuredData::ArraySP break_store_sp;
967 StructuredData::Array *break_store_ptr = nullptr;
970 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
971 if (error.Success()) {
972 break_store_ptr = input_data_sp->GetAsArray();
973 if (!break_store_ptr) {
974 error.SetErrorStringWithFormat(
975 "Tried to append to invalid input file %s", path.c_str());
981 if (!break_store_ptr) {
982 break_store_sp.reset(new StructuredData::Array());
983 break_store_ptr = break_store_sp.get();
986 StreamFile out_file(path.c_str(),
987 File::OpenOptions::eOpenOptionTruncate |
988 File::OpenOptions::eOpenOptionWrite |
989 File::OpenOptions::eOpenOptionCanCreate |
990 File::OpenOptions::eOpenOptionCloseOnExec,
991 lldb::eFilePermissionsFileDefault);
992 if (!out_file.GetFile().IsValid()) {
993 error.SetErrorStringWithFormat("Unable to open output file: %s.",
998 std::unique_lock<std::recursive_mutex> lock;
999 GetBreakpointList().GetListMutex(lock);
1001 if (bp_ids.GetSize() == 0) {
1002 const BreakpointList &breakpoints = GetBreakpointList();
1004 size_t num_breakpoints = breakpoints.GetSize();
1005 for (size_t i = 0; i < num_breakpoints; i++) {
1006 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1007 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1008 // If a breakpoint can't serialize it, just ignore it for now:
1010 break_store_ptr->AddItem(bkpt_save_sp);
1014 std::unordered_set<lldb::break_id_t> processed_bkpts;
1015 const size_t count = bp_ids.GetSize();
1016 for (size_t i = 0; i < count; ++i) {
1017 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1018 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1020 if (bp_id != LLDB_INVALID_BREAK_ID) {
1021 // Only do each breakpoint once:
1022 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1023 insert_result = processed_bkpts.insert(bp_id);
1024 if (!insert_result.second)
1027 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1028 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1029 // If the user explicitly asked to serialize a breakpoint, and we
1032 if (!bkpt_save_sp) {
1033 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1037 break_store_ptr->AddItem(bkpt_save_sp);
1042 break_store_ptr->Dump(out_file, false);
1043 out_file.PutChar('\n');
1047 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1048 BreakpointIDList &new_bps) {
1049 std::vector<std::string> no_names;
1050 return CreateBreakpointsFromFile(file, no_names, new_bps);
1053 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1054 std::vector<std::string> &names,
1055 BreakpointIDList &new_bps) {
1056 std::unique_lock<std::recursive_mutex> lock;
1057 GetBreakpointList().GetListMutex(lock);
1060 StructuredData::ObjectSP input_data_sp =
1061 StructuredData::ParseJSONFromFile(file, error);
1062 if (!error.Success()) {
1064 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1065 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1066 file.GetPath().c_str());
1070 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1072 error.SetErrorStringWithFormat(
1073 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1077 size_t num_bkpts = bkpt_array->GetSize();
1078 size_t num_names = names.size();
1080 for (size_t i = 0; i < num_bkpts; i++) {
1081 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1082 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1083 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1085 error.SetErrorStringWithFormat(
1086 "Invalid breakpoint data for element %zu from input file: %s.", i,
1087 file.GetPath().c_str());
1090 StructuredData::ObjectSP bkpt_data_sp =
1091 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
1093 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1096 BreakpointSP bkpt_sp =
1097 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1098 if (!error.Success()) {
1099 error.SetErrorStringWithFormat(
1100 "Error restoring breakpoint %zu from %s: %s.", i,
1101 file.GetPath().c_str(), error.AsCString());
1104 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1109 // The flag 'end_to_end', default to true, signifies that the operation is
1110 // performed end to end, for both the debugger and the debuggee.
1112 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1113 // to end operations.
1114 bool Target::RemoveAllWatchpoints(bool end_to_end) {
1115 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1117 log->Printf("Target::%s\n", __FUNCTION__);
1120 m_watchpoint_list.RemoveAll(true);
1124 // Otherwise, it's an end to end operation.
1126 if (!ProcessIsValid())
1129 size_t num_watchpoints = m_watchpoint_list.GetSize();
1130 for (size_t i = 0; i < num_watchpoints; ++i) {
1131 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1135 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1139 m_watchpoint_list.RemoveAll(true);
1140 m_last_created_watchpoint.reset();
1141 return true; // Success!
1144 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
1146 bool Target::DisableAllWatchpoints(bool end_to_end) {
1147 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1149 log->Printf("Target::%s\n", __FUNCTION__);
1152 m_watchpoint_list.SetEnabledAll(false);
1156 // Otherwise, it's an end to end operation.
1158 if (!ProcessIsValid())
1161 size_t num_watchpoints = m_watchpoint_list.GetSize();
1162 for (size_t i = 0; i < num_watchpoints; ++i) {
1163 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1167 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1171 return true; // Success!
1174 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
1176 bool Target::EnableAllWatchpoints(bool end_to_end) {
1177 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1179 log->Printf("Target::%s\n", __FUNCTION__);
1182 m_watchpoint_list.SetEnabledAll(true);
1186 // Otherwise, it's an end to end operation.
1188 if (!ProcessIsValid())
1191 size_t num_watchpoints = m_watchpoint_list.GetSize();
1192 for (size_t i = 0; i < num_watchpoints; ++i) {
1193 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1197 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1201 return true; // Success!
1204 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1205 bool Target::ClearAllWatchpointHitCounts() {
1206 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1208 log->Printf("Target::%s\n", __FUNCTION__);
1210 size_t num_watchpoints = m_watchpoint_list.GetSize();
1211 for (size_t i = 0; i < num_watchpoints; ++i) {
1212 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1216 wp_sp->ResetHitCount();
1218 return true; // Success!
1221 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1222 bool Target::ClearAllWatchpointHistoricValues() {
1223 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1225 log->Printf("Target::%s\n", __FUNCTION__);
1227 size_t num_watchpoints = m_watchpoint_list.GetSize();
1228 for (size_t i = 0; i < num_watchpoints; ++i) {
1229 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1233 wp_sp->ResetHistoricValues();
1235 return true; // Success!
1238 // Assumption: Caller holds the list mutex lock for m_watchpoint_list
1239 // during these operations.
1240 bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1241 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1243 log->Printf("Target::%s\n", __FUNCTION__);
1245 if (!ProcessIsValid())
1248 size_t num_watchpoints = m_watchpoint_list.GetSize();
1249 for (size_t i = 0; i < num_watchpoints; ++i) {
1250 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1254 wp_sp->SetIgnoreCount(ignore_count);
1256 return true; // Success!
1259 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1260 bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1261 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1263 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1265 if (!ProcessIsValid())
1268 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1270 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1274 // Else, fallthrough.
1279 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1280 bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1281 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1283 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1285 if (!ProcessIsValid())
1288 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1290 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1294 // Else, fallthrough.
1299 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1300 bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1301 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1303 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1305 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1306 if (watch_to_remove_sp == m_last_created_watchpoint)
1307 m_last_created_watchpoint.reset();
1309 if (DisableWatchpointByID(watch_id)) {
1310 m_watchpoint_list.Remove(watch_id, true);
1316 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1317 bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1318 uint32_t ignore_count) {
1319 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1321 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1323 if (!ProcessIsValid())
1326 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1328 wp_sp->SetIgnoreCount(ignore_count);
1334 ModuleSP Target::GetExecutableModule() {
1335 // search for the first executable in the module list
1336 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1337 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1338 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1341 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1344 // as fall back return the first module loaded
1345 return m_images.GetModuleAtIndex(0);
1348 Module *Target::GetExecutableModulePointer() {
1349 return GetExecutableModule().get();
1352 static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1355 StreamString feedback_stream;
1357 !module_sp->LoadScriptingResourceInTarget(target, error,
1358 &feedback_stream)) {
1359 if (error.AsCString())
1360 target->GetDebugger().GetErrorFile()->Printf(
1361 "unable to load scripting data for module %s - error reported was "
1363 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1366 if (feedback_stream.GetSize())
1367 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1368 feedback_stream.GetData());
1371 void Target::ClearModules(bool delete_locations) {
1372 ModulesDidUnload(m_images, delete_locations);
1373 m_section_load_history.Clear();
1375 m_scratch_type_system_map.Clear();
1376 m_ast_importer_sp.reset();
1379 void Target::DidExec() {
1380 // When a process exec's we need to know about it so we can do some cleanup.
1381 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1382 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1385 void Target::SetExecutableModule(ModuleSP &executable_sp,
1386 bool get_dependent_files) {
1387 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1388 ClearModules(false);
1390 if (executable_sp) {
1391 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1392 Timer scoped_timer(func_cat,
1393 "Target::SetExecutableModule (executable = '%s')",
1394 executable_sp->GetFileSpec().GetPath().c_str());
1396 m_images.Append(executable_sp); // The first image is our executable file
1398 // If we haven't set an architecture yet, reset our architecture based on
1399 // what we found in the executable module.
1400 if (!m_arch.GetSpec().IsValid()) {
1401 m_arch = executable_sp->GetArchitecture();
1403 "setting architecture to {0} ({1}) based on executable file",
1404 m_arch.GetSpec().GetArchitectureName(),
1405 m_arch.GetSpec().GetTriple().getTriple());
1408 FileSpecList dependent_files;
1409 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1411 if (executable_objfile && get_dependent_files) {
1412 executable_objfile->GetDependentModules(dependent_files);
1413 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1414 FileSpec dependent_file_spec(
1415 dependent_files.GetFileSpecPointerAtIndex(i));
1416 FileSpec platform_dependent_file_spec;
1418 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1419 platform_dependent_file_spec);
1421 platform_dependent_file_spec = dependent_file_spec;
1423 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1424 ModuleSP image_module_sp(GetSharedModule(module_spec));
1425 if (image_module_sp) {
1426 ObjectFile *objfile = image_module_sp->GetObjectFile();
1428 objfile->GetDependentModules(dependent_files);
1435 bool Target::SetArchitecture(const ArchSpec &arch_spec) {
1436 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1437 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1438 bool replace_local_arch = true;
1439 bool compatible_local_arch = false;
1440 ArchSpec other(arch_spec);
1442 if (!missing_local_arch) {
1443 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1444 other.MergeFrom(m_arch.GetSpec());
1446 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1447 compatible_local_arch = true;
1448 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1451 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed, vendor_changed,
1452 os_changed, os_ver_changed, env_changed);
1454 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1455 replace_local_arch = false;
1460 if (compatible_local_arch || missing_local_arch) {
1461 // If we haven't got a valid arch spec, or the architectures are compatible
1462 // update the architecture, unless the one we already have is more specified
1463 if (replace_local_arch)
1465 LLDB_LOG(log, "set architecture to {0} ({1})",
1466 m_arch.GetSpec().GetArchitectureName(),
1467 m_arch.GetSpec().GetTriple().getTriple());
1471 // If we have an executable file, try to reset the executable to the desired
1474 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1475 arch_spec.GetArchitectureName(),
1476 arch_spec.GetTriple().getTriple().c_str());
1478 ModuleSP executable_sp = GetExecutableModule();
1481 // Need to do something about unsetting breakpoints.
1483 if (executable_sp) {
1485 log->Printf("Target::SetArchitecture Trying to select executable file "
1486 "architecture %s (%s)",
1487 arch_spec.GetArchitectureName(),
1488 arch_spec.GetTriple().getTriple().c_str());
1489 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1490 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1491 &GetExecutableSearchPaths(),
1494 if (!error.Fail() && executable_sp) {
1495 SetExecutableModule(executable_sp, true);
1502 bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1503 if (arch_spec.IsValid()) {
1504 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1505 // The current target arch is compatible with "arch_spec", see if we
1506 // can improve our current architecture using bits from "arch_spec"
1508 // Merge bits from arch_spec into "merged_arch" and set our architecture
1509 ArchSpec merged_arch(m_arch.GetSpec());
1510 merged_arch.MergeFrom(arch_spec);
1511 return SetArchitecture(merged_arch);
1513 // The new architecture is different, we just need to replace it
1514 return SetArchitecture(arch_spec);
1520 void Target::WillClearList(const ModuleList &module_list) {}
1522 void Target::ModuleAdded(const ModuleList &module_list,
1523 const ModuleSP &module_sp) {
1524 // A module is being added to this target for the first time
1526 ModuleList my_module_list;
1527 my_module_list.Append(module_sp);
1528 LoadScriptingResourceForModule(module_sp, this);
1529 ModulesDidLoad(my_module_list);
1533 void Target::ModuleRemoved(const ModuleList &module_list,
1534 const ModuleSP &module_sp) {
1535 // A module is being removed from this target.
1537 ModuleList my_module_list;
1538 my_module_list.Append(module_sp);
1539 ModulesDidUnload(my_module_list, false);
1543 void Target::ModuleUpdated(const ModuleList &module_list,
1544 const ModuleSP &old_module_sp,
1545 const ModuleSP &new_module_sp) {
1546 // A module is replacing an already added module
1548 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1550 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1551 old_module_sp, new_module_sp);
1555 void Target::ModulesDidLoad(ModuleList &module_list) {
1556 if (m_valid && module_list.GetSize()) {
1557 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1558 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1560 m_process_sp->ModulesDidLoad(module_list);
1562 BroadcastEvent(eBroadcastBitModulesLoaded,
1563 new TargetEventData(this->shared_from_this(), module_list));
1567 void Target::SymbolsDidLoad(ModuleList &module_list) {
1568 if (m_valid && module_list.GetSize()) {
1570 LanguageRuntime *runtime =
1571 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1573 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1574 objc_runtime->SymbolsDidLoad(module_list);
1578 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1579 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1580 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1581 new TargetEventData(this->shared_from_this(), module_list));
1585 void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1586 if (m_valid && module_list.GetSize()) {
1587 UnloadModuleSections(module_list);
1588 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1589 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1591 BroadcastEvent(eBroadcastBitModulesUnloaded,
1592 new TargetEventData(this->shared_from_this(), module_list));
1596 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1597 const FileSpec &module_file_spec) {
1598 if (GetBreakpointsConsultPlatformAvoidList()) {
1599 ModuleList matchingModules;
1600 ModuleSpec module_spec(module_file_spec);
1601 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1603 // If there is more than one module for this file spec, only return true if
1604 // ALL the modules are on the
1606 if (num_modules > 0) {
1607 for (size_t i = 0; i < num_modules; i++) {
1608 if (!ModuleIsExcludedForUnconstrainedSearches(
1609 matchingModules.GetModuleAtIndex(i)))
1618 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1619 const lldb::ModuleSP &module_sp) {
1620 if (GetBreakpointsConsultPlatformAvoidList()) {
1622 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1628 size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1629 size_t dst_len, Status &error) {
1630 SectionSP section_sp(addr.GetSection());
1632 // If the contents of this section are encrypted, the on-disk file is
1633 // unusable. Read only from live memory.
1634 if (section_sp->IsEncrypted()) {
1635 error.SetErrorString("section is encrypted");
1638 ModuleSP module_sp(section_sp->GetModule());
1640 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1642 size_t bytes_read = objfile->ReadSectionData(
1643 section_sp.get(), addr.GetOffset(), dst, dst_len);
1647 error.SetErrorStringWithFormat("error reading data from section %s",
1648 section_sp->GetName().GetCString());
1650 error.SetErrorString("address isn't from a object file");
1652 error.SetErrorString("address isn't in a module");
1654 error.SetErrorString("address doesn't contain a section that points to a "
1655 "section in a object file");
1660 size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1661 void *dst, size_t dst_len, Status &error,
1662 lldb::addr_t *load_addr_ptr) {
1665 // if we end up reading this from process memory, we will fill this
1666 // with the actual load address
1668 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1670 size_t bytes_read = 0;
1672 addr_t load_addr = LLDB_INVALID_ADDRESS;
1673 addr_t file_addr = LLDB_INVALID_ADDRESS;
1674 Address resolved_addr;
1675 if (!addr.IsSectionOffset()) {
1676 SectionLoadList §ion_load_list = GetSectionLoadList();
1677 if (section_load_list.IsEmpty()) {
1678 // No sections are loaded, so we must assume we are not running
1679 // yet and anything we are given is a file address.
1680 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1681 // offset is the file address
1682 m_images.ResolveFileAddress(file_addr, resolved_addr);
1684 // We have at least one section loaded. This can be because
1685 // we have manually loaded some sections with "target modules load ..."
1686 // or because we have have a live process that has sections loaded
1687 // through the dynamic loader
1688 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1689 // offset is the load address
1690 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1693 if (!resolved_addr.IsValid())
1694 resolved_addr = addr;
1696 if (prefer_file_cache) {
1697 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1702 if (ProcessIsValid()) {
1703 if (load_addr == LLDB_INVALID_ADDRESS)
1704 load_addr = resolved_addr.GetLoadAddress(this);
1706 if (load_addr == LLDB_INVALID_ADDRESS) {
1707 ModuleSP addr_module_sp(resolved_addr.GetModule());
1708 if (addr_module_sp && addr_module_sp->GetFileSpec())
1709 error.SetErrorStringWithFormatv(
1710 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1711 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1713 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1714 resolved_addr.GetFileAddress());
1716 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1717 if (bytes_read != dst_len) {
1718 if (error.Success()) {
1719 if (bytes_read == 0)
1720 error.SetErrorStringWithFormat(
1721 "read memory from 0x%" PRIx64 " failed", load_addr);
1723 error.SetErrorStringWithFormat(
1724 "only %" PRIu64 " of %" PRIu64
1725 " bytes were read from memory at 0x%" PRIx64,
1726 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1731 *load_addr_ptr = load_addr;
1734 // If the address is not section offset we have an address that
1735 // doesn't resolve to any address in any currently loaded shared
1736 // libraries and we failed to read memory so there isn't anything
1737 // more we can do. If it is section offset, we might be able to
1738 // read cached memory from the object file.
1739 if (!resolved_addr.IsSectionOffset())
1744 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1745 // If we didn't already try and read from the object file cache, then
1746 // try it after failing to read from the process.
1747 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1752 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1756 addr_t curr_addr = addr.GetLoadAddress(this);
1757 Address address(addr);
1759 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1762 out_str.append(buf, length);
1763 // If we got "length - 1" bytes, we didn't get the whole C string, we
1764 // need to read some more characters
1765 if (length == sizeof(buf) - 1)
1766 curr_addr += length;
1769 address = Address(curr_addr);
1771 return out_str.size();
1774 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1775 size_t dst_max_len, Status &result_error) {
1776 size_t total_cstr_len = 0;
1777 if (dst && dst_max_len) {
1778 result_error.Clear();
1779 // NULL out everything just to be safe
1780 memset(dst, 0, dst_max_len);
1782 addr_t curr_addr = addr.GetLoadAddress(this);
1783 Address address(addr);
1785 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't
1786 // think this really needs to be tied to the memory cache subsystem's
1787 // cache line size, so leave this as a fixed constant.
1788 const size_t cache_line_size = 512;
1790 size_t bytes_left = dst_max_len - 1;
1791 char *curr_dst = dst;
1793 while (bytes_left > 0) {
1794 addr_t cache_line_bytes_left =
1795 cache_line_size - (curr_addr % cache_line_size);
1796 addr_t bytes_to_read =
1797 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1799 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1801 if (bytes_read == 0) {
1802 result_error = error;
1803 dst[total_cstr_len] = '\0';
1806 const size_t len = strlen(curr_dst);
1808 total_cstr_len += len;
1810 if (len < bytes_to_read)
1813 curr_dst += bytes_read;
1814 curr_addr += bytes_read;
1815 bytes_left -= bytes_read;
1816 address = Address(curr_addr);
1820 result_error.SetErrorString("invalid arguments");
1822 result_error.Clear();
1824 return total_cstr_len;
1827 size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1828 bool prefer_file_cache,
1829 uint32_t byte_size, bool is_signed,
1830 Scalar &scalar, Status &error) {
1833 if (byte_size <= sizeof(uval)) {
1835 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1836 if (bytes_read == byte_size) {
1837 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1838 m_arch.GetSpec().GetAddressByteSize());
1839 lldb::offset_t offset = 0;
1841 scalar = data.GetMaxU32(&offset, byte_size);
1843 scalar = data.GetMaxU64(&offset, byte_size);
1846 scalar.SignExtend(byte_size * 8);
1850 error.SetErrorStringWithFormat(
1851 "byte size of %u is too large for integer scalar type", byte_size);
1856 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1857 bool prefer_file_cache,
1858 size_t integer_byte_size,
1859 uint64_t fail_value,
1862 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1863 false, scalar, error))
1864 return scalar.ULongLong(fail_value);
1868 bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1869 Status &error, Address &pointer_addr) {
1871 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1872 m_arch.GetSpec().GetAddressByteSize(), false, scalar,
1874 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1875 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1876 SectionLoadList §ion_load_list = GetSectionLoadList();
1877 if (section_load_list.IsEmpty()) {
1878 // No sections are loaded, so we must assume we are not running
1879 // yet and anything we are given is a file address.
1880 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1882 // We have at least one section loaded. This can be because
1883 // we have manually loaded some sections with "target modules load ..."
1884 // or because we have have a live process that has sections loaded
1885 // through the dynamic loader
1886 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1888 // We weren't able to resolve the pointer value, so just return
1889 // an address with no section
1890 if (!pointer_addr.IsValid())
1891 pointer_addr.SetOffset(pointer_vm_addr);
1898 ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
1899 Status *error_ptr) {
1904 // First see if we already have this module in our module list. If we do,
1905 // then we're done, we don't need
1906 // to consult the shared modules list. But only do this if we are passed a
1909 if (module_spec.GetUUID().IsValid())
1910 module_sp = m_images.FindFirstModule(module_spec);
1913 ModuleSP old_module_sp; // This will get filled in if we have a new version
1915 bool did_create_module = false;
1917 // If there are image search path entries, try to use them first to acquire
1918 // a suitable image.
1919 if (m_image_search_paths.GetSize()) {
1920 ModuleSpec transformed_spec(module_spec);
1921 if (m_image_search_paths.RemapPath(
1922 module_spec.GetFileSpec().GetDirectory(),
1923 transformed_spec.GetFileSpec().GetDirectory())) {
1924 transformed_spec.GetFileSpec().GetFilename() =
1925 module_spec.GetFileSpec().GetFilename();
1926 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1927 &GetExecutableSearchPaths(),
1928 &old_module_sp, &did_create_module);
1933 // If we have a UUID, we can check our global shared module list in case
1934 // we already have it. If we don't have a valid UUID, then we can't since
1935 // the path in "module_spec" will be a platform path, and we will need to
1936 // let the platform find that file. For example, we could be asking for
1937 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1938 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1939 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1941 if (module_spec.GetUUID().IsValid()) {
1942 // We have a UUID, it is OK to check the global module list...
1943 error = ModuleList::GetSharedModule(module_spec, module_sp,
1944 &GetExecutableSearchPaths(),
1945 &old_module_sp, &did_create_module);
1949 // The platform is responsible for finding and caching an appropriate
1950 // module in the shared module cache.
1951 if (m_platform_sp) {
1952 error = m_platform_sp->GetSharedModule(
1953 module_spec, m_process_sp.get(), module_sp,
1954 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
1956 error.SetErrorString("no platform is currently set");
1961 // We found a module that wasn't in our target list. Let's make sure that
1962 // there wasn't an equivalent
1963 // module in the list already, and if there was, let's remove it.
1965 ObjectFile *objfile = module_sp->GetObjectFile();
1967 switch (objfile->GetType()) {
1968 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
1969 /// a program's execution state
1970 case ObjectFile::eTypeExecutable: /// A normal executable
1971 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
1973 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1974 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
1975 /// used during execution
1977 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
1978 /// debug information
1980 error_ptr->SetErrorString("debug info files aren't valid target "
1981 "modules, please specify an executable");
1983 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
1984 /// against but not used for
1987 error_ptr->SetErrorString("stub libraries aren't valid target "
1988 "modules, please specify an executable");
1992 error_ptr->SetErrorString(
1993 "unsupported file type, please specify an executable");
1996 // GetSharedModule is not guaranteed to find the old shared module, for
1998 // in the common case where you pass in the UUID, it is only going to
2000 // module matching the UUID. In fact, it has no good way to know what
2002 // relevant to this target is, since there might be many copies of a
2003 // module with this file spec
2004 // in various running debug sessions, but only one of them will belong
2006 // So let's remove the UUID from the module list, and look in the
2007 // target's module list.
2008 // Only do this if there is SOMETHING else in the module spec...
2009 if (!old_module_sp) {
2010 if (module_spec.GetUUID().IsValid() &&
2011 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2012 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2013 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2014 module_spec_copy.GetUUID().Clear();
2016 ModuleList found_modules;
2018 m_images.FindModules(module_spec_copy, found_modules);
2019 if (num_found == 1) {
2020 old_module_sp = found_modules.GetModuleAtIndex(0);
2025 // Preload symbols outside of any lock, so hopefully we can do this for
2026 // each library in parallel.
2027 if (GetPreloadSymbols())
2028 module_sp->PreloadSymbols();
2030 if (old_module_sp &&
2031 m_images.GetIndexForModule(old_module_sp.get()) !=
2032 LLDB_INVALID_INDEX32) {
2033 m_images.ReplaceModule(old_module_sp, module_sp);
2034 Module *old_module_ptr = old_module_sp.get();
2035 old_module_sp.reset();
2036 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2038 m_images.Append(module_sp);
2048 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2050 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2052 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2054 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2056 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2058 exe_ctx.SetTargetPtr(this);
2061 PathMappingList &Target::GetImageSearchPathList() {
2062 return m_image_search_paths;
2065 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2067 Target *target = (Target *)baton;
2068 ModuleSP exe_module_sp(target->GetExecutableModule());
2070 target->SetExecutableModule(exe_module_sp, true);
2073 TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error,
2074 lldb::LanguageType language,
2075 bool create_on_demand) {
2083 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2085 || language == eLanguageTypeUnknown) {
2086 std::set<lldb::LanguageType> languages_for_types;
2087 std::set<lldb::LanguageType> languages_for_expressions;
2089 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
2090 languages_for_expressions);
2092 if (languages_for_expressions.count(eLanguageTypeC)) {
2093 language = eLanguageTypeC; // LLDB's default. Override by setting the
2096 if (languages_for_expressions.empty()) {
2099 language = *languages_for_expressions.begin();
2104 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2108 PersistentExpressionState *
2109 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2110 TypeSystem *type_system =
2111 GetScratchTypeSystemForLanguage(nullptr, language, true);
2114 return type_system->GetPersistentExpressionState();
2120 UserExpression *Target::GetUserExpressionForLanguage(
2121 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2122 Expression::ResultType desired_type,
2123 const EvaluateExpressionOptions &options, Status &error) {
2124 Status type_system_error;
2126 TypeSystem *type_system =
2127 GetScratchTypeSystemForLanguage(&type_system_error, language);
2128 UserExpression *user_expr = nullptr;
2131 error.SetErrorStringWithFormat(
2132 "Could not find type system for language %s: %s",
2133 Language::GetNameForLanguageType(language),
2134 type_system_error.AsCString());
2138 user_expr = type_system->GetUserExpression(expr, prefix, language,
2139 desired_type, options);
2141 error.SetErrorStringWithFormat(
2142 "Could not create an expression for language %s",
2143 Language::GetNameForLanguageType(language));
2148 FunctionCaller *Target::GetFunctionCallerForLanguage(
2149 lldb::LanguageType language, const CompilerType &return_type,
2150 const Address &function_address, const ValueList &arg_value_list,
2151 const char *name, Status &error) {
2152 Status type_system_error;
2153 TypeSystem *type_system =
2154 GetScratchTypeSystemForLanguage(&type_system_error, language);
2155 FunctionCaller *persistent_fn = nullptr;
2158 error.SetErrorStringWithFormat(
2159 "Could not find type system for language %s: %s",
2160 Language::GetNameForLanguageType(language),
2161 type_system_error.AsCString());
2162 return persistent_fn;
2165 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2166 arg_value_list, name);
2168 error.SetErrorStringWithFormat(
2169 "Could not create an expression for language %s",
2170 Language::GetNameForLanguageType(language));
2172 return persistent_fn;
2176 Target::GetUtilityFunctionForLanguage(const char *text,
2177 lldb::LanguageType language,
2178 const char *name, Status &error) {
2179 Status type_system_error;
2180 TypeSystem *type_system =
2181 GetScratchTypeSystemForLanguage(&type_system_error, language);
2182 UtilityFunction *utility_fn = nullptr;
2185 error.SetErrorStringWithFormat(
2186 "Could not find type system for language %s: %s",
2187 Language::GetNameForLanguageType(language),
2188 type_system_error.AsCString());
2192 utility_fn = type_system->GetUtilityFunction(text, name);
2194 error.SetErrorStringWithFormat(
2195 "Could not create an expression for language %s",
2196 Language::GetNameForLanguageType(language));
2201 ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2203 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2204 nullptr, eLanguageTypeC, create_on_demand))
2205 return llvm::dyn_cast<ClangASTContext>(type_system);
2210 ClangASTImporterSP Target::GetClangASTImporter() {
2212 if (!m_ast_importer_sp) {
2213 m_ast_importer_sp.reset(new ClangASTImporter());
2215 return m_ast_importer_sp;
2217 return ClangASTImporterSP();
2220 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2222 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2224 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2225 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2227 return properties_sp->GetExecutableSearchPaths();
2228 return FileSpecList();
2231 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2232 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2234 return properties_sp->GetDebugFileSearchPaths();
2235 return FileSpecList();
2238 FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2239 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2241 return properties_sp->GetClangModuleSearchPaths();
2242 return FileSpecList();
2245 ArchSpec Target::GetDefaultArchitecture() {
2246 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2248 return properties_sp->GetDefaultArchitecture();
2252 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2253 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2254 if (properties_sp) {
2255 LogIfAnyCategoriesSet(
2256 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2257 "default architecture to %s (%s)",
2258 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2259 return properties_sp->SetDefaultArchitecture(arch);
2263 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2264 const SymbolContext *sc_ptr) {
2265 // The target can either exist in the "process" of ExecutionContext, or in
2266 // the "target_sp" member of SymbolContext. This accessor helper function
2267 // will get the target from one of these locations.
2269 Target *target = nullptr;
2270 if (sc_ptr != nullptr)
2271 target = sc_ptr->target_sp.get();
2272 if (target == nullptr && exe_ctx_ptr)
2273 target = exe_ctx_ptr->GetTargetPtr();
2277 ExpressionResults Target::EvaluateExpression(
2278 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2279 lldb::ValueObjectSP &result_valobj_sp,
2280 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2281 result_valobj_sp.reset();
2283 ExpressionResults execution_results = eExpressionSetupError;
2286 return execution_results;
2288 // We shouldn't run stop hooks in expressions.
2289 // Be sure to reset this if you return anywhere within this function.
2290 bool old_suppress_value = m_suppress_stop_hooks;
2291 m_suppress_stop_hooks = true;
2293 ExecutionContext exe_ctx;
2296 exe_scope->CalculateExecutionContext(exe_ctx);
2297 } else if (m_process_sp) {
2298 m_process_sp->CalculateExecutionContext(exe_ctx);
2300 CalculateExecutionContext(exe_ctx);
2303 // Make sure we aren't just trying to see the value of a persistent
2304 // variable (something like "$0")
2305 lldb::ExpressionVariableSP persistent_var_sp;
2306 // Only check for persistent variables the expression starts with a '$'
2308 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2309 ->GetPersistentExpressionState()
2310 ->GetVariable(expr);
2312 if (persistent_var_sp) {
2313 result_valobj_sp = persistent_var_sp->GetValueObject();
2314 execution_results = eExpressionCompleted;
2316 llvm::StringRef prefix = GetExpressionPrefixContents();
2318 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2319 result_valobj_sp, error,
2324 m_suppress_stop_hooks = old_suppress_value;
2326 return execution_results;
2329 lldb::ExpressionVariableSP
2330 Target::GetPersistentVariable(const ConstString &name) {
2331 lldb::ExpressionVariableSP variable_sp;
2332 m_scratch_type_system_map.ForEach(
2333 [name, &variable_sp](TypeSystem *type_system) -> bool {
2334 if (PersistentExpressionState *persistent_state =
2335 type_system->GetPersistentExpressionState()) {
2336 variable_sp = persistent_state->GetVariable(name);
2339 return false; // Stop iterating the ForEach
2341 return true; // Keep iterating the ForEach
2346 lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2347 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2349 m_scratch_type_system_map.ForEach(
2350 [name, &address](TypeSystem *type_system) -> bool {
2351 if (PersistentExpressionState *persistent_state =
2352 type_system->GetPersistentExpressionState()) {
2353 address = persistent_state->LookupSymbol(name);
2354 if (address != LLDB_INVALID_ADDRESS)
2355 return false; // Stop iterating the ForEach
2357 return true; // Keep iterating the ForEach
2362 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2363 AddressClass addr_class) const {
2364 addr_t code_addr = load_addr;
2365 switch (m_arch.GetSpec().GetMachine()) {
2366 case llvm::Triple::mips:
2367 case llvm::Triple::mipsel:
2368 case llvm::Triple::mips64:
2369 case llvm::Triple::mips64el:
2370 switch (addr_class) {
2371 case eAddressClassData:
2372 case eAddressClassDebug:
2373 return LLDB_INVALID_ADDRESS;
2375 case eAddressClassUnknown:
2376 case eAddressClassInvalid:
2377 case eAddressClassCode:
2378 case eAddressClassCodeAlternateISA:
2379 case eAddressClassRuntime:
2380 if ((code_addr & 2ull) || (addr_class == eAddressClassCodeAlternateISA))
2386 case llvm::Triple::arm:
2387 case llvm::Triple::thumb:
2388 switch (addr_class) {
2389 case eAddressClassData:
2390 case eAddressClassDebug:
2391 return LLDB_INVALID_ADDRESS;
2393 case eAddressClassUnknown:
2394 case eAddressClassInvalid:
2395 case eAddressClassCode:
2396 case eAddressClassCodeAlternateISA:
2397 case eAddressClassRuntime:
2398 // Check if bit zero it no set?
2399 if ((code_addr & 1ull) == 0) {
2400 // Bit zero isn't set, check if the address is a multiple of 2?
2401 if (code_addr & 2ull) {
2402 // The address is a multiple of 2 so it must be thumb, set bit zero
2404 } else if (addr_class == eAddressClassCodeAlternateISA) {
2405 // We checked the address and the address claims to be the alternate
2407 // which means thumb, so set bit zero.
2421 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2422 AddressClass addr_class) const {
2423 addr_t opcode_addr = load_addr;
2424 switch (m_arch.GetSpec().GetMachine()) {
2425 case llvm::Triple::mips:
2426 case llvm::Triple::mipsel:
2427 case llvm::Triple::mips64:
2428 case llvm::Triple::mips64el:
2429 case llvm::Triple::arm:
2430 case llvm::Triple::thumb:
2431 switch (addr_class) {
2432 case eAddressClassData:
2433 case eAddressClassDebug:
2434 return LLDB_INVALID_ADDRESS;
2436 case eAddressClassInvalid:
2437 case eAddressClassUnknown:
2438 case eAddressClassCode:
2439 case eAddressClassCodeAlternateISA:
2440 case eAddressClassRuntime:
2441 opcode_addr &= ~(1ull);
2452 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2453 addr_t breakable_addr = addr;
2454 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
2456 switch (m_arch.GetSpec().GetMachine()) {
2459 case llvm::Triple::mips:
2460 case llvm::Triple::mipsel:
2461 case llvm::Triple::mips64:
2462 case llvm::Triple::mips64el: {
2463 addr_t function_start = 0;
2464 addr_t current_offset = 0;
2465 uint32_t loop_count = 0;
2466 Address resolved_addr;
2467 uint32_t arch_flags = m_arch.GetSpec().GetFlags();
2468 bool IsMips16 = arch_flags & ArchSpec::eMIPSAse_mips16;
2469 bool IsMicromips = arch_flags & ArchSpec::eMIPSAse_micromips;
2470 SectionLoadList §ion_load_list = GetSectionLoadList();
2472 if (section_load_list.IsEmpty())
2473 // No sections are loaded, so we must assume we are not running yet
2474 // and need to operate only on file address.
2475 m_images.ResolveFileAddress(addr, resolved_addr);
2477 section_load_list.ResolveLoadAddress(addr, resolved_addr);
2479 // Get the function boundaries to make sure we don't scan back before the
2480 // beginning of the current function.
2481 ModuleSP temp_addr_module_sp(resolved_addr.GetModule());
2482 if (temp_addr_module_sp) {
2484 uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
2485 temp_addr_module_sp->ResolveSymbolContextForAddress(resolved_addr,
2489 sym_addr = sc.function->GetAddressRange().GetBaseAddress();
2491 sym_addr = sc.symbol->GetAddress();
2493 function_start = sym_addr.GetLoadAddress(this);
2494 if (function_start == LLDB_INVALID_ADDRESS)
2495 function_start = sym_addr.GetFileAddress();
2498 current_offset = addr - function_start;
2501 // If breakpoint address is start of function then we dont have to do
2503 if (current_offset == 0)
2504 return breakable_addr;
2506 loop_count = current_offset / 2;
2508 if (loop_count > 3) {
2509 // Scan previous 6 bytes
2510 if (IsMips16 | IsMicromips)
2512 // For mips-only, instructions are always 4 bytes, so scan previous 4
2518 // Create Disassembler Instance
2519 lldb::DisassemblerSP disasm_sp(
2520 Disassembler::FindPlugin(m_arch.GetSpec(), nullptr, nullptr));
2522 ExecutionContext exe_ctx;
2523 CalculateExecutionContext(exe_ctx);
2524 InstructionList instruction_list;
2525 InstructionSP prev_insn;
2526 bool prefer_file_cache = true; // Read from file
2527 uint32_t inst_to_choose = 0;
2529 for (uint32_t i = 1; i <= loop_count; i++) {
2530 // Adjust the address to read from.
2531 resolved_addr.Slide(-2);
2532 AddressRange range(resolved_addr, i * 2);
2533 uint32_t insn_size = 0;
2535 disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
2537 uint32_t num_insns = disasm_sp->GetInstructionList().GetSize();
2539 prev_insn = disasm_sp->GetInstructionList().GetInstructionAtIndex(0);
2540 insn_size = prev_insn->GetOpcode().GetByteSize();
2541 if (i == 1 && insn_size == 2) {
2542 // This looks like a valid 2-byte instruction (but it could be a part
2543 // of upper 4 byte instruction).
2544 instruction_list.Append(prev_insn);
2546 } else if (i == 2) {
2547 // Here we may get one 4-byte instruction or two 2-byte instructions.
2548 if (num_insns == 2) {
2549 // Looks like there are two 2-byte instructions above our breakpoint
2551 // Now the upper 2-byte instruction is either a valid 2-byte
2552 // instruction or could be a part of it's upper 4-byte instruction.
2553 // In both cases we don't care because in this case lower 2-byte
2554 // instruction is definitely a valid instruction
2555 // and whatever i=1 iteration has found out is true.
2558 } else if (insn_size == 4) {
2559 // This instruction claims its a valid 4-byte instruction. But it
2560 // could be a part of it's upper 4-byte instruction.
2561 // Lets try scanning upper 2 bytes to verify this.
2562 instruction_list.Append(prev_insn);
2565 } else if (i == 3) {
2567 // FIXME: We reached here that means instruction at [target - 4] has
2568 // already claimed to be a 4-byte instruction,
2569 // and now instruction at [target - 6] is also claiming that it's a
2570 // 4-byte instruction. This can not be true.
2571 // In this case we can not decide the valid previous instruction so
2572 // we let lldb set the breakpoint at the address given by user.
2575 // This is straight-forward
2580 // Decode failed, bytes do not form a valid instruction. So whatever
2581 // previous iteration has found out is true.
2583 inst_to_choose = i - 1;
2589 // Check if we are able to find any valid instruction.
2590 if (inst_to_choose) {
2591 if (inst_to_choose > instruction_list.GetSize())
2593 prev_insn = instruction_list.GetInstructionAtIndex(inst_to_choose - 1);
2595 if (prev_insn->HasDelaySlot()) {
2596 uint32_t shift_size = prev_insn->GetOpcode().GetByteSize();
2597 // Adjust the breakable address
2598 breakable_addr = addr - shift_size;
2600 log->Printf("Target::%s Breakpoint at 0x%8.8" PRIx64
2601 " is adjusted to 0x%8.8" PRIx64 " due to delay slot\n",
2602 __FUNCTION__, addr, breakable_addr);
2608 return breakable_addr;
2611 SourceManager &Target::GetSourceManager() {
2612 if (!m_source_manager_ap)
2613 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2614 return *m_source_manager_ap;
2617 ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2618 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2623 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2625 if (!m_clang_modules_decl_vendor_ap) {
2626 m_clang_modules_decl_vendor_ap.reset(
2627 ClangModulesDeclVendor::Create(*this));
2631 return m_clang_modules_decl_vendor_ap.get();
2634 Target::StopHookSP Target::CreateStopHook() {
2635 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2636 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2637 m_stop_hooks[new_uid] = stop_hook_sp;
2638 return stop_hook_sp;
2641 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2642 size_t num_removed = m_stop_hooks.erase(user_id);
2643 return (num_removed != 0);
2646 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2648 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2649 StopHookSP found_hook;
2651 StopHookCollection::iterator specified_hook_iter;
2652 specified_hook_iter = m_stop_hooks.find(user_id);
2653 if (specified_hook_iter != m_stop_hooks.end())
2654 found_hook = (*specified_hook_iter).second;
2658 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2659 bool active_state) {
2660 StopHookCollection::iterator specified_hook_iter;
2661 specified_hook_iter = m_stop_hooks.find(user_id);
2662 if (specified_hook_iter == m_stop_hooks.end())
2665 (*specified_hook_iter).second->SetIsActive(active_state);
2669 void Target::SetAllStopHooksActiveState(bool active_state) {
2670 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2671 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2672 (*pos).second->SetIsActive(active_state);
2676 void Target::RunStopHooks() {
2677 if (m_suppress_stop_hooks)
2683 // Somebody might have restarted the process:
2684 if (m_process_sp->GetState() != eStateStopped)
2687 // <rdar://problem/12027563> make sure we check that we are not stopped
2688 // because of us running a user expression
2689 // since in that case we do not want to run the stop-hooks
2690 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2693 if (m_stop_hooks.empty())
2696 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2698 // If there aren't any active stop hooks, don't bother either:
2699 bool any_active_hooks = false;
2700 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2701 if ((*pos).second->IsActive()) {
2702 any_active_hooks = true;
2706 if (!any_active_hooks)
2709 CommandReturnObject result;
2711 std::vector<ExecutionContext> exc_ctx_with_reasons;
2712 std::vector<SymbolContext> sym_ctx_with_reasons;
2714 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2715 size_t num_threads = cur_threadlist.GetSize();
2716 for (size_t i = 0; i < num_threads; i++) {
2717 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2718 if (cur_thread_sp->ThreadStoppedForAReason()) {
2719 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2720 exc_ctx_with_reasons.push_back(ExecutionContext(
2721 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2722 sym_ctx_with_reasons.push_back(
2723 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2727 // If no threads stopped for a reason, don't run the stop-hooks.
2728 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2729 if (num_exe_ctx == 0)
2732 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2733 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2735 bool keep_going = true;
2736 bool hooks_ran = false;
2737 bool print_hook_header = (m_stop_hooks.size() != 1);
2738 bool print_thread_header = (num_exe_ctx != 1);
2740 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2742 StopHookSP cur_hook_sp = (*pos).second;
2743 if (!cur_hook_sp->IsActive())
2746 bool any_thread_matched = false;
2747 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2748 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2749 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2750 sym_ctx_with_reasons[i])) &&
2751 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2752 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2753 exc_ctx_with_reasons[i].GetThreadRef()))) {
2757 if (print_hook_header && !any_thread_matched) {
2759 (cur_hook_sp->GetCommands().GetSize() == 1
2760 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2763 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2764 cur_hook_sp->GetID(), cmd);
2766 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2767 cur_hook_sp->GetID());
2768 any_thread_matched = true;
2771 if (print_thread_header)
2772 result.AppendMessageWithFormat(
2774 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2776 CommandInterpreterRunOptions options;
2777 options.SetStopOnContinue(true);
2778 options.SetStopOnError(true);
2779 options.SetEchoCommands(false);
2780 options.SetPrintResults(true);
2781 options.SetAddToHistory(false);
2783 GetDebugger().GetCommandInterpreter().HandleCommands(
2784 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2787 // If the command started the target going again, we should bag out of
2788 // running the stop hooks.
2789 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2790 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2791 // But only complain if there were more stop hooks to do:
2792 StopHookCollection::iterator tmp = pos;
2794 result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64
2795 " set the program running.\n",
2796 cur_hook_sp->GetID());
2803 result.GetImmediateOutputStream()->Flush();
2804 result.GetImmediateErrorStream()->Flush();
2807 const TargetPropertiesSP &Target::GetGlobalProperties() {
2808 // NOTE: intentional leak so we don't crash if global destructor chain gets
2809 // called as other threads still use the result of this function
2810 static TargetPropertiesSP *g_settings_sp_ptr =
2811 new TargetPropertiesSP(new TargetProperties(nullptr));
2812 return *g_settings_sp_ptr;
2815 Status Target::Install(ProcessLaunchInfo *launch_info) {
2817 PlatformSP platform_sp(GetPlatform());
2819 if (platform_sp->IsRemote()) {
2820 if (platform_sp->IsConnected()) {
2821 // Install all files that have an install path, and always install the
2822 // main executable when connected to a remote platform
2823 const ModuleList &modules = GetImages();
2824 const size_t num_images = modules.GetSize();
2825 for (size_t idx = 0; idx < num_images; ++idx) {
2826 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2828 const bool is_main_executable = module_sp == GetExecutableModule();
2829 FileSpec local_file(module_sp->GetFileSpec());
2831 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2833 if (is_main_executable) // TODO: add setting for always
2834 // installing main executable???
2836 // Always install the main executable
2837 remote_file = platform_sp->GetRemoteWorkingDirectory();
2838 remote_file.AppendPathComponent(
2839 module_sp->GetFileSpec().GetFilename().GetCString());
2843 error = platform_sp->Install(local_file, remote_file);
2844 if (error.Success()) {
2845 module_sp->SetPlatformFileSpec(remote_file);
2846 if (is_main_executable) {
2847 platform_sp->SetFilePermissions(remote_file, 0700);
2849 launch_info->SetExecutableFile(remote_file, false);
2863 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2865 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2868 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2869 Address &resolved_addr) {
2870 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2873 bool Target::SetSectionLoadAddress(const SectionSP §ion_sp,
2874 addr_t new_section_load_addr,
2875 bool warn_multiple) {
2876 const addr_t old_section_load_addr =
2877 m_section_load_history.GetSectionLoadAddress(
2878 SectionLoadHistory::eStopIDNow, section_sp);
2879 if (old_section_load_addr != new_section_load_addr) {
2880 uint32_t stop_id = 0;
2881 ProcessSP process_sp(GetProcessSP());
2883 stop_id = process_sp->GetStopID();
2885 stop_id = m_section_load_history.GetLastStopID();
2886 if (m_section_load_history.SetSectionLoadAddress(
2887 stop_id, section_sp, new_section_load_addr, warn_multiple))
2888 return true; // Return true if the section load address was changed...
2890 return false; // Return false to indicate nothing changed
2893 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2894 size_t section_unload_count = 0;
2895 size_t num_modules = module_list.GetSize();
2896 for (size_t i = 0; i < num_modules; ++i) {
2897 section_unload_count +=
2898 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2900 return section_unload_count;
2903 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2904 uint32_t stop_id = 0;
2905 ProcessSP process_sp(GetProcessSP());
2907 stop_id = process_sp->GetStopID();
2909 stop_id = m_section_load_history.GetLastStopID();
2910 SectionList *sections = module_sp->GetSectionList();
2911 size_t section_unload_count = 0;
2913 const uint32_t num_sections = sections->GetNumSections(0);
2914 for (uint32_t i = 0; i < num_sections; ++i) {
2915 section_unload_count += m_section_load_history.SetSectionUnloaded(
2916 stop_id, sections->GetSectionAtIndex(i));
2919 return section_unload_count;
2922 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp) {
2923 uint32_t stop_id = 0;
2924 ProcessSP process_sp(GetProcessSP());
2926 stop_id = process_sp->GetStopID();
2928 stop_id = m_section_load_history.GetLastStopID();
2929 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2932 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp,
2934 uint32_t stop_id = 0;
2935 ProcessSP process_sp(GetProcessSP());
2937 stop_id = process_sp->GetStopID();
2939 stop_id = m_section_load_history.GetLastStopID();
2940 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2944 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2946 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2948 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2951 log->Printf("Target::%s() called for %s", __FUNCTION__,
2952 launch_info.GetExecutableFile().GetPath().c_str());
2954 StateType state = eStateInvalid;
2956 // Scope to temporarily get the process state in case someone has manually
2957 // remotely connected already to a process and we can skip the platform
2960 ProcessSP process_sp(GetProcessSP());
2963 state = process_sp->GetState();
2966 "Target::%s the process exists, and its current state is %s",
2967 __FUNCTION__, StateAsCString(state));
2970 log->Printf("Target::%s the process instance doesn't currently exist.",
2975 launch_info.GetFlags().Set(eLaunchFlagDebug);
2977 // Get the value of synchronous execution here. If you wait till after you
2979 // run, then you could have hit a breakpoint, whose command might switch the
2981 // then you'll pick up that incorrect value.
2982 Debugger &debugger = GetDebugger();
2983 const bool synchronous_execution =
2984 debugger.GetCommandInterpreter().GetSynchronous();
2986 PlatformSP platform_sp(GetPlatform());
2988 // Finalize the file actions, and if none were given, default to opening
2989 // up a pseudo terminal
2990 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2992 log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2993 "default_to_use_pty=%s",
2994 __FUNCTION__, platform_sp ? "true" : "false",
2995 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2997 default_to_use_pty ? "true" : "false");
2999 launch_info.FinalizeFileActions(this, default_to_use_pty);
3001 if (state == eStateConnected) {
3002 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3003 error.SetErrorString(
3004 "can't launch in tty when launching through a remote connection");
3009 if (!launch_info.GetArchitecture().IsValid())
3010 launch_info.GetArchitecture() = GetArchitecture();
3012 // If we're not already connected to the process, and if we have a platform
3013 // that can launch a process for debugging, go ahead and do that here.
3014 if (state != eStateConnected && platform_sp &&
3015 platform_sp->CanDebugProcess()) {
3017 log->Printf("Target::%s asking the platform to debug the process",
3020 // Get a weak pointer to the previous process if we have one
3021 ProcessWP process_wp;
3023 process_wp = m_process_sp;
3025 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
3027 // Cleanup the old process since someone might still have a strong
3028 // reference to this process and we would like to allow it to cleanup
3029 // as much as it can without the object being destroyed. We try to
3030 // lock the shared pointer and if that works, then someone else still
3031 // has a strong reference to the process.
3033 ProcessSP old_process_sp(process_wp.lock());
3035 old_process_sp->Finalize();
3038 log->Printf("Target::%s the platform doesn't know how to debug a "
3039 "process, getting a process plugin to do this for us.",
3042 if (state == eStateConnected) {
3043 assert(m_process_sp);
3045 // Use a Process plugin to construct the process.
3046 const char *plugin_name = launch_info.GetProcessPluginName();
3047 CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name,
3051 // Since we didn't have a platform launch the process, launch it here.
3053 error = m_process_sp->Launch(launch_info);
3056 if (!m_process_sp) {
3057 if (error.Success())
3058 error.SetErrorString("failed to launch or debug process");
3062 if (error.Success()) {
3063 if (synchronous_execution ||
3064 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
3065 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
3066 if (!hijack_listener_sp) {
3067 hijack_listener_sp =
3068 Listener::MakeListener("lldb.Target.Launch.hijack");
3069 launch_info.SetHijackListener(hijack_listener_sp);
3070 m_process_sp->HijackProcessEvents(hijack_listener_sp);
3073 StateType state = m_process_sp->WaitForProcessToStop(
3074 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
3076 if (state == eStateStopped) {
3077 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
3078 if (synchronous_execution) {
3079 error = m_process_sp->PrivateResume();
3080 if (error.Success()) {
3081 state = m_process_sp->WaitForProcessToStop(
3082 llvm::None, nullptr, true, hijack_listener_sp, stream);
3083 const bool must_be_alive =
3084 false; // eStateExited is ok, so this must be false
3085 if (!StateIsStoppedState(state, must_be_alive)) {
3086 error.SetErrorStringWithFormat("process isn't stopped: %s",
3087 StateAsCString(state));
3091 m_process_sp->RestoreProcessEvents();
3092 error = m_process_sp->PrivateResume();
3094 if (!error.Success()) {
3096 error2.SetErrorStringWithFormat(
3097 "process resume at entry point failed: %s", error.AsCString());
3101 } else if (state == eStateExited) {
3102 bool with_shell = !!launch_info.GetShell();
3103 const int exit_status = m_process_sp->GetExitStatus();
3104 const char *exit_desc = m_process_sp->GetExitDescription();
3105 #define LAUNCH_SHELL_MESSAGE \
3106 "\n'r' and 'run' are aliases that default to launching through a " \
3107 "shell.\nTry launching without going through a shell by using 'process " \
3109 if (exit_desc && exit_desc[0]) {
3111 error.SetErrorStringWithFormat(
3112 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
3113 exit_status, exit_desc);
3115 error.SetErrorStringWithFormat("process exited with status %i (%s)",
3116 exit_status, exit_desc);
3119 error.SetErrorStringWithFormat(
3120 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
3123 error.SetErrorStringWithFormat("process exited with status %i",
3127 error.SetErrorStringWithFormat(
3128 "initial process state wasn't stopped: %s", StateAsCString(state));
3131 m_process_sp->RestoreProcessEvents();
3134 error2.SetErrorStringWithFormat("process launch failed: %s",
3141 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
3142 auto state = eStateInvalid;
3143 auto process_sp = GetProcessSP();
3145 state = process_sp->GetState();
3146 if (process_sp->IsAlive() && state != eStateConnected) {
3147 if (state == eStateAttaching)
3148 return Status("process attach is in progress");
3149 return Status("a process is already being debugged");
3153 const ModuleSP old_exec_module_sp = GetExecutableModule();
3155 // If no process info was specified, then use the target executable
3156 // name as the process to attach to by default
3157 if (!attach_info.ProcessInfoSpecified()) {
3158 if (old_exec_module_sp)
3159 attach_info.GetExecutableFile().GetFilename() =
3160 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3162 if (!attach_info.ProcessInfoSpecified()) {
3163 return Status("no process specified, create a target with a file, or "
3164 "specify the --pid or --name");
3168 const auto platform_sp =
3169 GetDebugger().GetPlatformList().GetSelectedPlatform();
3170 ListenerSP hijack_listener_sp;
3171 const bool async = attach_info.GetAsync();
3173 hijack_listener_sp =
3174 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3175 attach_info.SetHijackListener(hijack_listener_sp);
3179 if (state != eStateConnected && platform_sp != nullptr &&
3180 platform_sp->CanDebugProcess()) {
3181 SetPlatform(platform_sp);
3182 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3184 if (state != eStateConnected) {
3185 const char *plugin_name = attach_info.GetProcessPluginName();
3187 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3188 plugin_name, nullptr);
3189 if (process_sp == nullptr) {
3190 error.SetErrorStringWithFormat(
3191 "failed to create process using plugin %s",
3192 (plugin_name) ? plugin_name : "null");
3196 if (hijack_listener_sp)
3197 process_sp->HijackProcessEvents(hijack_listener_sp);
3198 error = process_sp->Attach(attach_info);
3201 if (error.Success() && process_sp) {
3203 process_sp->RestoreProcessEvents();
3205 state = process_sp->WaitForProcessToStop(
3206 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3207 process_sp->RestoreProcessEvents();
3209 if (state != eStateStopped) {
3210 const char *exit_desc = process_sp->GetExitDescription();
3212 error.SetErrorStringWithFormat("%s", exit_desc);
3214 error.SetErrorString(
3215 "process did not stop (no such process or permission problem?)");
3216 process_sp->Destroy(false);
3223 //--------------------------------------------------------------
3225 //--------------------------------------------------------------
3226 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3227 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3228 m_thread_spec_ap(), m_active(true) {}
3230 Target::StopHook::StopHook(const StopHook &rhs)
3231 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3232 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3233 m_thread_spec_ap(), m_active(rhs.m_active) {
3234 if (rhs.m_thread_spec_ap)
3235 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
3238 Target::StopHook::~StopHook() = default;
3240 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3241 m_specifier_sp.reset(specifier);
3244 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3245 m_thread_spec_ap.reset(specifier);
3248 void Target::StopHook::GetDescription(Stream *s,
3249 lldb::DescriptionLevel level) const {
3250 int indent_level = s->GetIndentLevel();
3252 s->SetIndentLevel(indent_level + 2);
3254 s->Printf("Hook: %" PRIu64 "\n", GetID());
3256 s->Indent("State: enabled\n");
3258 s->Indent("State: disabled\n");
3260 if (m_specifier_sp) {
3262 s->PutCString("Specifier:\n");
3263 s->SetIndentLevel(indent_level + 4);
3264 m_specifier_sp->GetDescription(s, level);
3265 s->SetIndentLevel(indent_level + 2);
3268 if (m_thread_spec_ap) {
3270 s->Indent("Thread:\n");
3271 m_thread_spec_ap->GetDescription(&tmp, level);
3272 s->SetIndentLevel(indent_level + 4);
3273 s->Indent(tmp.GetString());
3274 s->PutCString("\n");
3275 s->SetIndentLevel(indent_level + 2);
3278 s->Indent("Commands: \n");
3279 s->SetIndentLevel(indent_level + 4);
3280 uint32_t num_commands = m_commands.GetSize();
3281 for (uint32_t i = 0; i < num_commands; i++) {
3282 s->Indent(m_commands.GetStringAtIndex(i));
3283 s->PutCString("\n");
3285 s->SetIndentLevel(indent_level);
3288 //--------------------------------------------------------------
3289 // class TargetProperties
3290 //--------------------------------------------------------------
3292 OptionEnumValueElement lldb_private::g_dynamic_value_types[] = {
3293 {eNoDynamicValues, "no-dynamic-values",
3294 "Don't calculate the dynamic type of values"},
3295 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3296 "even if you have to run the target."},
3297 {eDynamicDontRunTarget, "no-run-target",
3298 "Calculate the dynamic type of values, but don't run the target."},
3299 {0, nullptr, nullptr}};
3301 static OptionEnumValueElement g_inline_breakpoint_enums[] = {
3302 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3303 "locations (fastest). This setting "
3304 "should only be used if you know that "
3305 "no inlining occurs in your programs."},
3306 {eInlineBreakpointsHeaders, "headers",
3307 "Only check for inline breakpoint locations when setting breakpoints in "
3308 "header files, but not when setting breakpoint in implementation source "
3309 "files (default)."},
3310 {eInlineBreakpointsAlways, "always",
3311 "Always look for inline breakpoint locations when setting file and line "
3312 "breakpoints (slower but most accurate)."},
3313 {0, nullptr, nullptr}};
3315 typedef enum x86DisassemblyFlavor {
3316 eX86DisFlavorDefault,
3319 } x86DisassemblyFlavor;
3321 static OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3322 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3323 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3324 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
3325 {0, nullptr, nullptr}};
3327 static OptionEnumValueElement g_hex_immediate_style_values[] = {
3328 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3329 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
3330 {0, nullptr, nullptr}};
3332 static OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3333 {eLoadScriptFromSymFileTrue, "true",
3334 "Load debug scripts inside symbol files"},
3335 {eLoadScriptFromSymFileFalse, "false",
3336 "Do not load debug scripts inside symbol files."},
3337 {eLoadScriptFromSymFileWarn, "warn",
3338 "Warn about debug scripts inside symbol files but do not load them."},
3339 {0, nullptr, nullptr}};
3341 static OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3342 {eLoadCWDlldbinitTrue, "true",
3343 "Load .lldbinit files from current directory"},
3344 {eLoadCWDlldbinitFalse, "false",
3345 "Do not load .lldbinit files from current directory"},
3346 {eLoadCWDlldbinitWarn, "warn",
3347 "Warn about loading .lldbinit files from current directory"},
3348 {0, nullptr, nullptr}};
3350 static OptionEnumValueElement g_memory_module_load_level_values[] = {
3351 {eMemoryModuleLoadLevelMinimal, "minimal",
3352 "Load minimal information when loading modules from memory. Currently "
3353 "this setting loads sections only."},
3354 {eMemoryModuleLoadLevelPartial, "partial",
3355 "Load partial information when loading modules from memory. Currently "
3356 "this setting loads sections and function bounds."},
3357 {eMemoryModuleLoadLevelComplete, "complete",
3358 "Load complete information when loading modules from memory. Currently "
3359 "this setting loads sections and all symbols."},
3360 {0, nullptr, nullptr}};
3362 static PropertyDefinition g_properties[] = {
3363 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, nullptr,
3364 "Default architecture to choose, when there's a choice."},
3365 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3366 nullptr, "Move breakpoints to nearest code."},
3367 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3369 "The language to use when interpreting expressions entered in commands."},
3370 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3371 "Path to a file containing expressions to be prepended to all "
3373 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3374 eDynamicDontRunTarget, nullptr, g_dynamic_value_types,
3375 "Should printed values be shown as their dynamic value."},
3376 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3377 nullptr, "Should synthetic values be used by default whenever available."},
3378 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3379 "Skip function prologues when setting breakpoints by name."},
3380 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, nullptr,
3381 "Source path remappings are used to track the change of location between "
3382 "a source file when built, and "
3383 "where it exists on the current system. It consists of an array of "
3384 "duples, the first element of each duple is "
3385 "some part (starting at the root) of the path to the file when it was "
3387 "and the second is where the remainder of the original build hierarchy is "
3388 "rooted on the local system. "
3389 "Each element of the array is checked in order and the first one that "
3390 "results in a match wins."},
3391 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3392 nullptr, "Executable search paths to use when locating executable files "
3393 "whose paths don't match the local file system."},
3394 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3396 "List of directories to be searched when locating debug symbol files."},
3397 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3399 "List of directories to be searched when locating modules for Clang."},
3400 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3402 "Automatically load Clang modules referred to by the program."},
3403 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3404 nullptr, "Automatically apply fix-it hints to expressions."},
3405 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3406 nullptr, "Print the fixed expression text."},
3407 {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
3408 nullptr, "Save intermediate object files generated by the LLVM JIT"},
3409 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3410 nullptr, "Maximum number of children to expand in any level of depth."},
3411 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3413 "Maximum number of characters to show when using %s in summary strings."},
3414 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3415 nullptr, "Maximum number of bytes that 'memory read' will fetch before "
3416 "--force must be specified."},
3417 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3418 true, nullptr, nullptr, "Consult the platform module avoid list when "
3419 "setting non-module specific breakpoints."},
3420 {"arg0", OptionValue::eTypeString, false, 0, nullptr, nullptr,
3421 "The first argument passed to the program in the argument array which can "
3422 "be different from the executable itself."},
3423 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, nullptr,
3424 "A list containing all the arguments to be passed to the executable when "
3425 "it is run. Note that this does NOT include the argv[0] which is in "
3427 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3428 nullptr, nullptr, "A list of all the environment variables to be passed "
3429 "to the executable's environment, and their values."},
3430 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3431 "Inherit the environment from the process that is running LLDB."},
3432 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3433 "The file/path to be used by the executable program for reading its "
3435 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3436 "The file/path to be used by the executable program for writing its "
3437 "standard output."},
3438 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3439 "The file/path to be used by the executable program for writing its "
3441 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3442 nullptr, "debugserver will detach (rather than killing) a process if it "
3443 "loses connection with lldb."},
3444 {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3445 "Enable loading of symbol tables before they are needed."},
3446 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3447 "Disable Address Space Layout Randomization (ASLR)"},
3448 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, nullptr,
3449 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3450 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3451 eInlineBreakpointsAlways, nullptr, g_inline_breakpoint_enums,
3452 "The strategy to use when settings breakpoints by file and line. "
3453 "Breakpoint locations can end up being inlined by the compiler, so that a "
3454 "compile unit 'a.c' might contain an inlined function from another source "
3456 "Usually this is limited to breakpoint locations from inlined functions "
3457 "from header or other include files, or more accurately "
3458 "non-implementation source files. "
3459 "Sometimes code might #include implementation files and cause inlined "
3460 "breakpoint locations in inlined implementation files. "
3461 "Always checking for inlined breakpoint locations can be expensive "
3462 "(memory and time), so if you have a project with many headers "
3463 "and find that setting breakpoints is slow, then you can change this "
3464 "setting to headers. "
3465 "This setting allows you to control exactly which strategy is used when "
3467 "file and line breakpoints."},
3468 // FIXME: This is the wrong way to do per-architecture settings, but we
3469 // don't have a general per architecture settings system in place yet.
3470 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3471 eX86DisFlavorDefault, nullptr, g_x86_dis_flavor_value_types,
3472 "The default disassembly flavor to use for x86 or x86-64 targets."},
3473 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3474 nullptr, "Show immediates in disassembly as hexadecimal."},
3475 {"hex-immediate-style", OptionValue::eTypeEnum, false,
3476 Disassembler::eHexStyleC, nullptr, g_hex_immediate_style_values,
3477 "Which style to use for printing hexadecimal disassembly values."},
3478 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3479 nullptr, "Use a fast stepping algorithm based on running from branch to "
3480 "branch rather than instruction single-stepping."},
3481 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3482 eLoadScriptFromSymFileWarn, nullptr, g_load_script_from_sym_file_values,
3483 "Allow LLDB to load scripting resources embedded in symbol files when "
3485 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3486 nullptr, g_load_current_working_dir_lldbinit_values,
3487 "Allow LLDB to .lldbinit files from the current directory automatically."},
3488 {"memory-module-load-level", OptionValue::eTypeEnum, false,
3489 eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3490 "Loading modules from memory can be slow as reading the symbol tables and "
3491 "other data can take a long time depending on your connection to the "
3493 "This setting helps users control how much information gets loaded when "
3494 "loading modules from memory."
3495 "'complete' is the default value for this setting which will load all "
3496 "sections and symbols by reading them from memory (slowest, most "
3498 "'partial' will load sections and attempt to find function bounds without "
3499 "downloading the symbol table (faster, still accurate, missing symbol "
3501 "'minimal' is the fastest setting and will load section data with no "
3502 "symbols, but should rarely be used as stack frames in these memory "
3503 "regions will be inaccurate and not provide any context (fastest). "},
3504 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3505 nullptr, nullptr, "Expressions that crash will show up in crash logs if "
3506 "the host system supports executable specific crash log "
3507 "strings and this setting is set to true."},
3508 {"trap-handler-names", OptionValue::eTypeArray, true,
3509 OptionValue::eTypeString, nullptr, nullptr,
3510 "A list of trap handler function names, e.g. a common Unix user process "
3511 "one is _sigtramp."},
3512 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3513 nullptr, nullptr, "If true, LLDB will show variables that are meant to "
3514 "support the operation of a language's runtime "
3516 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, nullptr,
3517 "Disable lock-step debugging, instead control threads independently."},
3518 {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
3521 ePropertyDefaultArch,
3522 ePropertyMoveToNearestCode,
3524 ePropertyExprPrefix,
3525 ePropertyPreferDynamic,
3526 ePropertyEnableSynthetic,
3527 ePropertySkipPrologue,
3529 ePropertyExecutableSearchPaths,
3530 ePropertyDebugFileSearchPaths,
3531 ePropertyClangModuleSearchPaths,
3532 ePropertyAutoImportClangModules,
3533 ePropertyAutoApplyFixIts,
3534 ePropertyNotifyAboutFixIts,
3535 ePropertySaveObjects,
3536 ePropertyMaxChildrenCount,
3537 ePropertyMaxSummaryLength,
3538 ePropertyMaxMemReadSize,
3539 ePropertyBreakpointUseAvoidList,
3543 ePropertyInheritEnv,
3545 ePropertyOutputPath,
3547 ePropertyDetachOnError,
3548 ePropertyPreloadSymbols,
3549 ePropertyDisableASLR,
3550 ePropertyDisableSTDIO,
3551 ePropertyInlineStrategy,
3552 ePropertyDisassemblyFlavor,
3553 ePropertyUseHexImmediates,
3554 ePropertyHexImmediateStyle,
3555 ePropertyUseFastStepping,
3556 ePropertyLoadScriptFromSymbolFile,
3557 ePropertyLoadCWDlldbinitFile,
3558 ePropertyMemoryModuleLoadLevel,
3559 ePropertyDisplayExpressionsInCrashlogs,
3560 ePropertyTrapHandlerNames,
3561 ePropertyDisplayRuntimeSupportValues,
3562 ePropertyNonStopModeEnabled,
3563 ePropertyExperimental
3566 class TargetOptionValueProperties : public OptionValueProperties {
3568 TargetOptionValueProperties(const ConstString &name)
3569 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
3571 // This constructor is used when creating TargetOptionValueProperties when it
3572 // is part of a new lldb_private::Target instance. It will copy all current
3573 // global property values as needed
3574 TargetOptionValueProperties(Target *target,
3575 const TargetPropertiesSP &target_properties_sp)
3576 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3577 m_target(target), m_got_host_env(false) {}
3579 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3581 uint32_t idx) const override {
3582 // When getting the value for a key from the target options, we will always
3583 // try and grab the setting from the current target if there is one. Else we
3585 // use the one from this instance.
3586 if (idx == ePropertyEnvVars)
3587 GetHostEnvironmentIfNeeded();
3590 Target *target = exe_ctx->GetTargetPtr();
3592 TargetOptionValueProperties *target_properties =
3593 static_cast<TargetOptionValueProperties *>(
3594 target->GetValueProperties().get());
3595 if (this != target_properties)
3596 return target_properties->ProtectedGetPropertyAtIndex(idx);
3599 return ProtectedGetPropertyAtIndex(idx);
3602 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3605 void GetHostEnvironmentIfNeeded() const {
3606 if (!m_got_host_env) {
3608 m_got_host_env = true;
3609 const uint32_t idx = ePropertyInheritEnv;
3610 if (GetPropertyAtIndexAsBoolean(
3611 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3612 PlatformSP platform_sp(m_target->GetPlatform());
3615 if (platform_sp->GetEnvironment(env)) {
3616 OptionValueDictionary *env_dict =
3617 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3620 const bool can_replace = false;
3621 const size_t envc = env.GetSize();
3622 for (size_t idx = 0; idx < envc; idx++) {
3623 const char *env_entry = env.GetStringAtIndex(idx);
3625 const char *equal_pos = ::strchr(env_entry, '=');
3627 // It is ok to have environment variables with no values
3628 const char *value = nullptr;
3630 key.SetCStringWithLength(env_entry,
3631 equal_pos - env_entry);
3633 value = equal_pos + 1;
3635 key.SetCString(env_entry);
3637 // Don't allow existing keys to be replaced with ones we get
3638 // from the platform environment
3639 env_dict->SetValueForKey(
3640 key, OptionValueSP(new OptionValueString(value)),
3652 mutable bool m_got_host_env;
3655 //----------------------------------------------------------------------
3657 //----------------------------------------------------------------------
3658 static PropertyDefinition g_experimental_properties[]{
3659 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3661 "If true, inject local variables explicitly into the expression text. "
3662 "This will fix symbol resolution when there are name collisions between "
3663 "ivars and local variables. "
3664 "But it can make expressions run much more slowly."},
3665 {"use-modern-type-lookup", OptionValue::eTypeBoolean, true, false, nullptr,
3666 nullptr, "If true, use Clang's modern type lookup infrastructure."},
3667 {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
3669 enum { ePropertyInjectLocalVars = 0, ePropertyUseModernTypeLookup };
3671 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3673 TargetExperimentalOptionValueProperties()
3674 : OptionValueProperties(
3675 ConstString(Properties::GetExperimentalSettingsName())) {}
3678 TargetExperimentalProperties::TargetExperimentalProperties()
3679 : Properties(OptionValuePropertiesSP(
3680 new TargetExperimentalOptionValueProperties())) {
3681 m_collection_sp->Initialize(g_experimental_properties);
3684 //----------------------------------------------------------------------
3686 //----------------------------------------------------------------------
3687 TargetProperties::TargetProperties(Target *target)
3688 : Properties(), m_launch_info() {
3690 m_collection_sp.reset(
3691 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
3693 // Set callbacks to update launch_info whenever "settins set" updated any of
3695 m_collection_sp->SetValueChangedCallback(
3696 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3697 m_collection_sp->SetValueChangedCallback(
3698 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3699 m_collection_sp->SetValueChangedCallback(
3700 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3701 m_collection_sp->SetValueChangedCallback(
3702 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3704 m_collection_sp->SetValueChangedCallback(
3705 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3707 m_collection_sp->SetValueChangedCallback(
3708 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3710 m_collection_sp->SetValueChangedCallback(
3711 ePropertyDetachOnError,
3712 TargetProperties::DetachOnErrorValueChangedCallback, this);
3713 m_collection_sp->SetValueChangedCallback(
3714 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3716 m_collection_sp->SetValueChangedCallback(
3717 ePropertyDisableSTDIO,
3718 TargetProperties::DisableSTDIOValueChangedCallback, this);
3720 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3721 m_collection_sp->AppendProperty(
3722 ConstString(Properties::GetExperimentalSettingsName()),
3723 ConstString("Experimental settings - setting these won't produce "
3724 "errors if the setting is not present."),
3725 true, m_experimental_properties_up->GetValueProperties());
3727 // Update m_launch_info once it was created
3728 Arg0ValueChangedCallback(this, nullptr);
3729 RunArgsValueChangedCallback(this, nullptr);
3730 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3731 // Target::GetPlatform()
3732 InputPathValueChangedCallback(this, nullptr);
3733 OutputPathValueChangedCallback(this, nullptr);
3734 ErrorPathValueChangedCallback(this, nullptr);
3735 DetachOnErrorValueChangedCallback(this, nullptr);
3736 DisableASLRValueChangedCallback(this, nullptr);
3737 DisableSTDIOValueChangedCallback(this, nullptr);
3739 m_collection_sp.reset(
3740 new TargetOptionValueProperties(ConstString("target")));
3741 m_collection_sp->Initialize(g_properties);
3742 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3743 m_collection_sp->AppendProperty(
3744 ConstString(Properties::GetExperimentalSettingsName()),
3745 ConstString("Experimental settings - setting these won't produce "
3746 "errors if the setting is not present."),
3747 true, m_experimental_properties_up->GetValueProperties());
3748 m_collection_sp->AppendProperty(
3749 ConstString("process"), ConstString("Settings specific to processes."),
3750 true, Process::GetGlobalProperties()->GetValueProperties());
3754 TargetProperties::~TargetProperties() = default;
3756 bool TargetProperties::GetInjectLocalVariables(
3757 ExecutionContext *exe_ctx) const {
3758 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3759 exe_ctx, false, ePropertyExperimental);
3760 OptionValueProperties *exp_values =
3761 exp_property->GetValue()->GetAsProperties();
3763 return exp_values->GetPropertyAtIndexAsBoolean(
3764 exe_ctx, ePropertyInjectLocalVars, true);
3769 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3771 const Property *exp_property =
3772 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3773 OptionValueProperties *exp_values =
3774 exp_property->GetValue()->GetAsProperties();
3776 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3780 bool TargetProperties::GetUseModernTypeLookup() const {
3781 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3782 nullptr, false, ePropertyExperimental);
3783 OptionValueProperties *exp_values =
3784 exp_property->GetValue()->GetAsProperties();
3786 return exp_values->GetPropertyAtIndexAsBoolean(
3787 nullptr, ePropertyUseModernTypeLookup, true);
3792 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3793 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3794 nullptr, ePropertyDefaultArch);
3796 return value->GetCurrentValue();
3800 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3801 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3802 nullptr, ePropertyDefaultArch);
3804 return value->SetCurrentValue(arch, true);
3807 bool TargetProperties::GetMoveToNearestCode() const {
3808 const uint32_t idx = ePropertyMoveToNearestCode;
3809 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3810 nullptr, idx, g_properties[idx].default_uint_value != 0);
3813 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3814 const uint32_t idx = ePropertyPreferDynamic;
3815 return (lldb::DynamicValueType)
3816 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3817 nullptr, idx, g_properties[idx].default_uint_value);
3820 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3821 const uint32_t idx = ePropertyPreferDynamic;
3822 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3825 bool TargetProperties::GetPreloadSymbols() const {
3826 const uint32_t idx = ePropertyPreloadSymbols;
3827 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3828 nullptr, idx, g_properties[idx].default_uint_value != 0);
3831 void TargetProperties::SetPreloadSymbols(bool b) {
3832 const uint32_t idx = ePropertyPreloadSymbols;
3833 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3836 bool TargetProperties::GetDisableASLR() const {
3837 const uint32_t idx = ePropertyDisableASLR;
3838 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3839 nullptr, idx, g_properties[idx].default_uint_value != 0);
3842 void TargetProperties::SetDisableASLR(bool b) {
3843 const uint32_t idx = ePropertyDisableASLR;
3844 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3847 bool TargetProperties::GetDetachOnError() const {
3848 const uint32_t idx = ePropertyDetachOnError;
3849 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3850 nullptr, idx, g_properties[idx].default_uint_value != 0);
3853 void TargetProperties::SetDetachOnError(bool b) {
3854 const uint32_t idx = ePropertyDetachOnError;
3855 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3858 bool TargetProperties::GetDisableSTDIO() const {
3859 const uint32_t idx = ePropertyDisableSTDIO;
3860 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3861 nullptr, idx, g_properties[idx].default_uint_value != 0);
3864 void TargetProperties::SetDisableSTDIO(bool b) {
3865 const uint32_t idx = ePropertyDisableSTDIO;
3866 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3869 const char *TargetProperties::GetDisassemblyFlavor() const {
3870 const uint32_t idx = ePropertyDisassemblyFlavor;
3871 const char *return_value;
3873 x86DisassemblyFlavor flavor_value =
3874 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3875 nullptr, idx, g_properties[idx].default_uint_value);
3876 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3877 return return_value;
3880 InlineStrategy TargetProperties::GetInlineStrategy() const {
3881 const uint32_t idx = ePropertyInlineStrategy;
3882 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3883 nullptr, idx, g_properties[idx].default_uint_value);
3886 llvm::StringRef TargetProperties::GetArg0() const {
3887 const uint32_t idx = ePropertyArg0;
3888 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
3891 void TargetProperties::SetArg0(llvm::StringRef arg) {
3892 const uint32_t idx = ePropertyArg0;
3893 m_collection_sp->SetPropertyAtIndexAsString(
3895 m_launch_info.SetArg0(arg);
3898 bool TargetProperties::GetRunArguments(Args &args) const {
3899 const uint32_t idx = ePropertyRunArgs;
3900 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3903 void TargetProperties::SetRunArguments(const Args &args) {
3904 const uint32_t idx = ePropertyRunArgs;
3905 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3906 m_launch_info.GetArguments() = args;
3909 size_t TargetProperties::GetEnvironmentAsArgs(Args &env) const {
3910 const uint32_t idx = ePropertyEnvVars;
3911 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3914 void TargetProperties::SetEnvironmentFromArgs(const Args &env) {
3915 const uint32_t idx = ePropertyEnvVars;
3916 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, env);
3917 m_launch_info.GetEnvironmentEntries() = env;
3920 bool TargetProperties::GetSkipPrologue() const {
3921 const uint32_t idx = ePropertySkipPrologue;
3922 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3923 nullptr, idx, g_properties[idx].default_uint_value != 0);
3926 PathMappingList &TargetProperties::GetSourcePathMap() const {
3927 const uint32_t idx = ePropertySourceMap;
3928 OptionValuePathMappings *option_value =
3929 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3931 assert(option_value);
3932 return option_value->GetCurrentValue();
3935 FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3936 const uint32_t idx = ePropertyExecutableSearchPaths;
3937 OptionValueFileSpecList *option_value =
3938 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3940 assert(option_value);
3941 return option_value->GetCurrentValue();
3944 FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3945 const uint32_t idx = ePropertyDebugFileSearchPaths;
3946 OptionValueFileSpecList *option_value =
3947 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3949 assert(option_value);
3950 return option_value->GetCurrentValue();
3953 FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3954 const uint32_t idx = ePropertyClangModuleSearchPaths;
3955 OptionValueFileSpecList *option_value =
3956 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3958 assert(option_value);
3959 return option_value->GetCurrentValue();
3962 bool TargetProperties::GetEnableAutoImportClangModules() const {
3963 const uint32_t idx = ePropertyAutoImportClangModules;
3964 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3965 nullptr, idx, g_properties[idx].default_uint_value != 0);
3968 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3969 const uint32_t idx = ePropertyAutoApplyFixIts;
3970 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3971 nullptr, idx, g_properties[idx].default_uint_value != 0);
3974 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3975 const uint32_t idx = ePropertyNotifyAboutFixIts;
3976 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3977 nullptr, idx, g_properties[idx].default_uint_value != 0);
3980 bool TargetProperties::GetEnableSaveObjects() const {
3981 const uint32_t idx = ePropertySaveObjects;
3982 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3983 nullptr, idx, g_properties[idx].default_uint_value != 0);
3986 bool TargetProperties::GetEnableSyntheticValue() const {
3987 const uint32_t idx = ePropertyEnableSynthetic;
3988 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3989 nullptr, idx, g_properties[idx].default_uint_value != 0);
3992 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3993 const uint32_t idx = ePropertyMaxChildrenCount;
3994 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3995 nullptr, idx, g_properties[idx].default_uint_value);
3998 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3999 const uint32_t idx = ePropertyMaxSummaryLength;
4000 return m_collection_sp->GetPropertyAtIndexAsSInt64(
4001 nullptr, idx, g_properties[idx].default_uint_value);
4004 uint32_t TargetProperties::GetMaximumMemReadSize() const {
4005 const uint32_t idx = ePropertyMaxMemReadSize;
4006 return m_collection_sp->GetPropertyAtIndexAsSInt64(
4007 nullptr, idx, g_properties[idx].default_uint_value);
4010 FileSpec TargetProperties::GetStandardInputPath() const {
4011 const uint32_t idx = ePropertyInputPath;
4012 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4015 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4016 const uint32_t idx = ePropertyInputPath;
4017 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4020 FileSpec TargetProperties::GetStandardOutputPath() const {
4021 const uint32_t idx = ePropertyOutputPath;
4022 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4025 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
4026 const uint32_t idx = ePropertyOutputPath;
4027 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4030 FileSpec TargetProperties::GetStandardErrorPath() const {
4031 const uint32_t idx = ePropertyErrorPath;
4032 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4035 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4036 const uint32_t idx = ePropertyErrorPath;
4037 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4040 LanguageType TargetProperties::GetLanguage() const {
4041 OptionValueLanguage *value =
4042 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
4043 nullptr, ePropertyLanguage);
4045 return value->GetCurrentValue();
4046 return LanguageType();
4049 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
4050 const uint32_t idx = ePropertyExprPrefix;
4051 OptionValueFileSpec *file =
4052 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
4055 DataBufferSP data_sp(file->GetFileContents());
4057 return llvm::StringRef(
4058 reinterpret_cast<const char *>(data_sp->GetBytes()),
4059 data_sp->GetByteSize());
4064 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4065 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4066 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4067 nullptr, idx, g_properties[idx].default_uint_value != 0);
4070 bool TargetProperties::GetUseHexImmediates() const {
4071 const uint32_t idx = ePropertyUseHexImmediates;
4072 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4073 nullptr, idx, g_properties[idx].default_uint_value != 0);
4076 bool TargetProperties::GetUseFastStepping() const {
4077 const uint32_t idx = ePropertyUseFastStepping;
4078 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4079 nullptr, idx, g_properties[idx].default_uint_value != 0);
4082 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4083 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4084 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4085 nullptr, idx, g_properties[idx].default_uint_value != 0);
4088 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4089 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4090 return (LoadScriptFromSymFile)
4091 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4092 nullptr, idx, g_properties[idx].default_uint_value);
4095 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4096 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4097 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4098 nullptr, idx, g_properties[idx].default_uint_value);
4101 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4102 const uint32_t idx = ePropertyHexImmediateStyle;
4103 return (Disassembler::HexImmediateStyle)
4104 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4105 nullptr, idx, g_properties[idx].default_uint_value);
4108 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4109 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4110 return (MemoryModuleLoadLevel)
4111 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4112 nullptr, idx, g_properties[idx].default_uint_value);
4115 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4116 const uint32_t idx = ePropertyTrapHandlerNames;
4117 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4120 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4121 const uint32_t idx = ePropertyTrapHandlerNames;
4122 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4125 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4126 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4127 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4130 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4131 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4132 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4135 bool TargetProperties::GetNonStopModeEnabled() const {
4136 const uint32_t idx = ePropertyNonStopModeEnabled;
4137 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4140 void TargetProperties::SetNonStopModeEnabled(bool b) {
4141 const uint32_t idx = ePropertyNonStopModeEnabled;
4142 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4145 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
4146 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4147 return m_launch_info;
4150 void TargetProperties::SetProcessLaunchInfo(
4151 const ProcessLaunchInfo &launch_info) {
4152 m_launch_info = launch_info;
4153 SetArg0(launch_info.GetArg0());
4154 SetRunArguments(launch_info.GetArguments());
4155 SetEnvironmentFromArgs(launch_info.GetEnvironmentEntries());
4156 const FileAction *input_file_action =
4157 launch_info.GetFileActionForFD(STDIN_FILENO);
4158 if (input_file_action) {
4159 SetStandardInputPath(input_file_action->GetPath());
4161 const FileAction *output_file_action =
4162 launch_info.GetFileActionForFD(STDOUT_FILENO);
4163 if (output_file_action) {
4164 SetStandardOutputPath(output_file_action->GetPath());
4166 const FileAction *error_file_action =
4167 launch_info.GetFileActionForFD(STDERR_FILENO);
4168 if (error_file_action) {
4169 SetStandardErrorPath(error_file_action->GetPath());
4171 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4172 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4173 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4176 void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4178 TargetProperties *this_ =
4179 reinterpret_cast<TargetProperties *>(target_property_ptr);
4180 this_->m_launch_info.SetArg0(this_->GetArg0());
4183 void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4185 TargetProperties *this_ =
4186 reinterpret_cast<TargetProperties *>(target_property_ptr);
4188 if (this_->GetRunArguments(args))
4189 this_->m_launch_info.GetArguments() = args;
4192 void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4194 TargetProperties *this_ =
4195 reinterpret_cast<TargetProperties *>(target_property_ptr);
4197 if (this_->GetEnvironmentAsArgs(args))
4198 this_->m_launch_info.GetEnvironmentEntries() = args;
4201 void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4203 TargetProperties *this_ =
4204 reinterpret_cast<TargetProperties *>(target_property_ptr);
4205 this_->m_launch_info.AppendOpenFileAction(
4206 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
4209 void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4211 TargetProperties *this_ =
4212 reinterpret_cast<TargetProperties *>(target_property_ptr);
4213 this_->m_launch_info.AppendOpenFileAction(
4214 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
4217 void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4219 TargetProperties *this_ =
4220 reinterpret_cast<TargetProperties *>(target_property_ptr);
4221 this_->m_launch_info.AppendOpenFileAction(
4222 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
4225 void TargetProperties::DetachOnErrorValueChangedCallback(
4226 void *target_property_ptr, OptionValue *) {
4227 TargetProperties *this_ =
4228 reinterpret_cast<TargetProperties *>(target_property_ptr);
4229 if (this_->GetDetachOnError())
4230 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4232 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4235 void TargetProperties::DisableASLRValueChangedCallback(
4236 void *target_property_ptr, OptionValue *) {
4237 TargetProperties *this_ =
4238 reinterpret_cast<TargetProperties *>(target_property_ptr);
4239 if (this_->GetDisableASLR())
4240 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4242 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4245 void TargetProperties::DisableSTDIOValueChangedCallback(
4246 void *target_property_ptr, OptionValue *) {
4247 TargetProperties *this_ =
4248 reinterpret_cast<TargetProperties *>(target_property_ptr);
4249 if (this_->GetDisableSTDIO())
4250 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4252 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4255 //----------------------------------------------------------------------
4256 // Target::TargetEventData
4257 //----------------------------------------------------------------------
4259 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4260 : EventData(), m_target_sp(target_sp), m_module_list() {}
4262 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4263 const ModuleList &module_list)
4264 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4266 Target::TargetEventData::~TargetEventData() = default;
4268 const ConstString &Target::TargetEventData::GetFlavorString() {
4269 static ConstString g_flavor("Target::TargetEventData");
4273 void Target::TargetEventData::Dump(Stream *s) const {
4274 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4277 m_module_list.GetModuleAtIndex(i)->GetDescription(
4278 s, lldb::eDescriptionLevelBrief);
4282 const Target::TargetEventData *
4283 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4285 const EventData *event_data = event_ptr->GetData();
4287 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4288 return static_cast<const TargetEventData *>(event_ptr->GetData());
4293 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4295 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4297 target_sp = event_data->m_target_sp;
4302 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4303 ModuleList module_list;
4304 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4306 module_list = event_data->m_module_list;