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 //===----------------------------------------------------------------------===//
10 #include "lldb/Target/Target.h"
11 #include "Plugins/ExpressionParser/Clang/ClangASTSource.h"
12 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
13 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
14 #include "lldb/Breakpoint/BreakpointIDList.h"
15 #include "lldb/Breakpoint/BreakpointResolver.h"
16 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
17 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
18 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
19 #include "lldb/Breakpoint/BreakpointResolverName.h"
20 #include "lldb/Breakpoint/BreakpointResolverScripted.h"
21 #include "lldb/Breakpoint/Watchpoint.h"
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/Module.h"
24 #include "lldb/Core/ModuleSpec.h"
25 #include "lldb/Core/PluginManager.h"
26 #include "lldb/Core/SearchFilter.h"
27 #include "lldb/Core/Section.h"
28 #include "lldb/Core/SourceManager.h"
29 #include "lldb/Core/StreamFile.h"
30 #include "lldb/Core/StructuredDataImpl.h"
31 #include "lldb/Core/ValueObject.h"
32 #include "lldb/Expression/REPL.h"
33 #include "lldb/Expression/UserExpression.h"
34 #include "lldb/Host/Host.h"
35 #include "lldb/Host/PosixApi.h"
36 #include "lldb/Interpreter/CommandInterpreter.h"
37 #include "lldb/Interpreter/CommandReturnObject.h"
38 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
39 #include "lldb/Interpreter/OptionValues.h"
40 #include "lldb/Interpreter/Property.h"
41 #include "lldb/Symbol/ClangASTContext.h"
42 #include "lldb/Symbol/Function.h"
43 #include "lldb/Symbol/ObjectFile.h"
44 #include "lldb/Symbol/Symbol.h"
45 #include "lldb/Target/Language.h"
46 #include "lldb/Target/LanguageRuntime.h"
47 #include "lldb/Target/ObjCLanguageRuntime.h"
48 #include "lldb/Target/Process.h"
49 #include "lldb/Target/SectionLoadList.h"
50 #include "lldb/Target/StackFrame.h"
51 #include "lldb/Target/SystemRuntime.h"
52 #include "lldb/Target/Thread.h"
53 #include "lldb/Target/ThreadSpec.h"
54 #include "lldb/Utility/Event.h"
55 #include "lldb/Utility/FileSpec.h"
56 #include "lldb/Utility/LLDBAssert.h"
57 #include "lldb/Utility/Log.h"
58 #include "lldb/Utility/State.h"
59 #include "lldb/Utility/StreamString.h"
60 #include "lldb/Utility/Timer.h"
64 using namespace lldb_private;
66 constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
68 Target::Arch::Arch(const ArchSpec &spec)
70 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
72 const Target::Arch& Target::Arch::operator=(const ArchSpec &spec) {
74 m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
78 ConstString &Target::GetStaticBroadcasterClass() {
79 static ConstString class_name("lldb.target");
83 Target::Target(Debugger &debugger, const ArchSpec &target_arch,
84 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
85 : TargetProperties(this),
86 Broadcaster(debugger.GetBroadcasterManager(),
87 Target::GetStaticBroadcasterClass().AsCString()),
88 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
89 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
90 m_breakpoint_list(false), m_internal_breakpoint_list(true),
91 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
92 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
93 m_source_manager_ap(), m_stop_hooks(), m_stop_hook_next_id(0),
94 m_valid(true), m_suppress_stop_hooks(false),
95 m_is_dummy_target(is_dummy_target),
96 m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
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) {
198 listener_sp = GetDebugger().GetListener();
199 DeleteCurrentProcess();
200 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
201 listener_sp, crash_file);
205 const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
207 lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
208 const char *repl_options, bool can_create) {
209 if (language == eLanguageTypeUnknown) {
210 std::set<LanguageType> repl_languages;
212 Language::GetLanguagesSupportingREPLs(repl_languages);
214 if (repl_languages.size() == 1) {
215 language = *repl_languages.begin();
216 } else if (repl_languages.size() == 0) {
217 err.SetErrorStringWithFormat(
218 "LLDB isn't configured with REPL support for any languages.");
221 err.SetErrorStringWithFormat(
222 "Multiple possible REPL languages. Please specify a language.");
227 REPLMap::iterator pos = m_repl_map.find(language);
229 if (pos != m_repl_map.end()) {
234 err.SetErrorStringWithFormat(
235 "Couldn't find an existing REPL for %s, and can't create a new one",
236 Language::GetNameForLanguageType(language));
237 return lldb::REPLSP();
240 Debugger *const debugger = nullptr;
241 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
244 m_repl_map[language] = ret;
245 return m_repl_map[language];
249 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
250 Language::GetNameForLanguageType(language));
253 return lldb::REPLSP();
256 void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
257 lldbassert(!m_repl_map.count(language));
259 m_repl_map[language] = repl_sp;
262 void Target::Destroy() {
263 std::lock_guard<std::recursive_mutex> guard(m_mutex);
265 DeleteCurrentProcess();
266 m_platform_sp.reset();
269 m_section_load_history.Clear();
270 const bool notify = false;
271 m_breakpoint_list.RemoveAll(notify);
272 m_internal_breakpoint_list.RemoveAll(notify);
273 m_last_created_breakpoint.reset();
274 m_last_created_watchpoint.reset();
275 m_search_filter_sp.reset();
276 m_image_search_paths.Clear(notify);
277 m_stop_hooks.clear();
278 m_stop_hook_next_id = 0;
279 m_suppress_stop_hooks = false;
282 BreakpointList &Target::GetBreakpointList(bool internal) {
284 return m_internal_breakpoint_list;
286 return m_breakpoint_list;
289 const BreakpointList &Target::GetBreakpointList(bool internal) const {
291 return m_internal_breakpoint_list;
293 return m_breakpoint_list;
296 BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
299 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
300 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
302 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
307 BreakpointSP Target::CreateSourceRegexBreakpoint(
308 const FileSpecList *containingModules,
309 const FileSpecList *source_file_spec_list,
310 const std::unordered_set<std::string> &function_names,
311 RegularExpression &source_regex, bool internal, bool hardware,
312 LazyBool move_to_nearest_code) {
313 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
314 containingModules, source_file_spec_list));
315 if (move_to_nearest_code == eLazyBoolCalculate)
316 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
317 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
318 nullptr, source_regex, function_names,
319 !static_cast<bool>(move_to_nearest_code)));
321 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
324 BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
325 const FileSpec &file, uint32_t line_no,
326 uint32_t column, lldb::addr_t offset,
327 LazyBool check_inlines,
328 LazyBool skip_prologue, bool internal,
330 LazyBool move_to_nearest_code) {
331 FileSpec remapped_file;
332 if (!GetSourcePathMap().ReverseRemapPath(file, remapped_file))
333 remapped_file = file;
335 if (check_inlines == eLazyBoolCalculate) {
336 const InlineStrategy inline_strategy = GetInlineStrategy();
337 switch (inline_strategy) {
338 case eInlineBreakpointsNever:
339 check_inlines = eLazyBoolNo;
342 case eInlineBreakpointsHeaders:
343 if (remapped_file.IsSourceImplementationFile())
344 check_inlines = eLazyBoolNo;
346 check_inlines = eLazyBoolYes;
349 case eInlineBreakpointsAlways:
350 check_inlines = eLazyBoolYes;
354 SearchFilterSP filter_sp;
355 if (check_inlines == eLazyBoolNo) {
356 // Not checking for inlines, we are looking only for matching compile units
357 FileSpecList compile_unit_list;
358 compile_unit_list.Append(remapped_file);
359 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
362 filter_sp = GetSearchFilterForModuleList(containingModules);
364 if (skip_prologue == eLazyBoolCalculate)
365 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
366 if (move_to_nearest_code == eLazyBoolCalculate)
367 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
369 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
370 nullptr, remapped_file, line_no, column, offset, check_inlines,
371 skip_prologue, !static_cast<bool>(move_to_nearest_code)));
372 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
375 BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
379 // Check for any reason we want to move this breakpoint to other address.
380 addr = GetBreakableLoadAddress(addr);
382 // Attempt to resolve our load address if possible, though it is ok if it
383 // doesn't resolve to section/offset.
385 // Try and resolve as a load address if possible
386 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
387 if (!so_addr.IsValid()) {
388 // The address didn't resolve, so just set this as an absolute address
389 so_addr.SetOffset(addr);
391 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
395 BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
397 SearchFilterSP filter_sp(
398 new SearchFilterForUnconstrainedSearches(shared_from_this()));
399 BreakpointResolverSP resolver_sp(
400 new BreakpointResolverAddress(nullptr, addr));
401 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
405 Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
406 const FileSpec *file_spec,
407 bool request_hardware) {
408 SearchFilterSP filter_sp(
409 new SearchFilterForUnconstrainedSearches(shared_from_this()));
410 BreakpointResolverSP resolver_sp(
411 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
412 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
416 BreakpointSP Target::CreateBreakpoint(
417 const FileSpecList *containingModules,
418 const FileSpecList *containingSourceFiles, const char *func_name,
419 FunctionNameType func_name_type_mask, LanguageType language,
420 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
423 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
424 containingModules, containingSourceFiles));
426 if (skip_prologue == eLazyBoolCalculate)
427 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
428 if (language == lldb::eLanguageTypeUnknown)
429 language = GetLanguage();
431 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
432 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
433 offset, skip_prologue));
434 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
440 Target::CreateBreakpoint(const FileSpecList *containingModules,
441 const FileSpecList *containingSourceFiles,
442 const std::vector<std::string> &func_names,
443 FunctionNameType func_name_type_mask,
444 LanguageType language, lldb::addr_t offset,
445 LazyBool skip_prologue, bool internal, bool hardware) {
447 size_t num_names = func_names.size();
449 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
450 containingModules, containingSourceFiles));
452 if (skip_prologue == eLazyBoolCalculate)
453 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
454 if (language == lldb::eLanguageTypeUnknown)
455 language = GetLanguage();
457 BreakpointResolverSP resolver_sp(
458 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
459 language, offset, skip_prologue));
460 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
466 Target::CreateBreakpoint(const FileSpecList *containingModules,
467 const FileSpecList *containingSourceFiles,
468 const char *func_names[], size_t num_names,
469 FunctionNameType func_name_type_mask,
470 LanguageType language, lldb::addr_t offset,
471 LazyBool skip_prologue, bool internal, bool hardware) {
474 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
475 containingModules, containingSourceFiles));
477 if (skip_prologue == eLazyBoolCalculate) {
479 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
481 skip_prologue = eLazyBoolNo;
483 if (language == lldb::eLanguageTypeUnknown)
484 language = GetLanguage();
486 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
487 nullptr, func_names, num_names, func_name_type_mask, language, offset,
489 resolver_sp->SetOffset(offset);
490 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
496 Target::GetSearchFilterForModule(const FileSpec *containingModule) {
497 SearchFilterSP filter_sp;
498 if (containingModule != nullptr) {
499 // TODO: We should look into sharing module based search filters
500 // across many breakpoints like we do for the simple target based one
502 new SearchFilterByModule(shared_from_this(), *containingModule));
504 if (!m_search_filter_sp)
505 m_search_filter_sp.reset(
506 new SearchFilterForUnconstrainedSearches(shared_from_this()));
507 filter_sp = m_search_filter_sp;
513 Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
514 SearchFilterSP filter_sp;
515 if (containingModules && containingModules->GetSize() != 0) {
516 // TODO: We should look into sharing module based search filters
517 // across many breakpoints like we do for the simple target based one
519 new SearchFilterByModuleList(shared_from_this(), *containingModules));
521 if (!m_search_filter_sp)
522 m_search_filter_sp.reset(
523 new SearchFilterForUnconstrainedSearches(shared_from_this()));
524 filter_sp = m_search_filter_sp;
529 SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
530 const FileSpecList *containingModules,
531 const FileSpecList *containingSourceFiles) {
532 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
533 return GetSearchFilterForModuleList(containingModules);
535 SearchFilterSP filter_sp;
536 if (containingModules == nullptr) {
537 // We could make a special "CU List only SearchFilter". Better yet was if
538 // these could be composable, but that will take a little reworking.
540 filter_sp.reset(new SearchFilterByModuleListAndCU(
541 shared_from_this(), FileSpecList(), *containingSourceFiles));
543 filter_sp.reset(new SearchFilterByModuleListAndCU(
544 shared_from_this(), *containingModules, *containingSourceFiles));
549 BreakpointSP Target::CreateFuncRegexBreakpoint(
550 const FileSpecList *containingModules,
551 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
552 lldb::LanguageType requested_language, LazyBool skip_prologue,
553 bool internal, bool hardware) {
554 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
555 containingModules, containingSourceFiles));
556 bool skip = (skip_prologue == eLazyBoolCalculate)
558 : static_cast<bool>(skip_prologue);
559 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
560 nullptr, func_regex, requested_language, 0, skip));
562 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
566 Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
567 bool catch_bp, bool throw_bp, bool internal,
568 Args *additional_args, Status *error) {
569 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
570 *this, language, catch_bp, throw_bp, internal);
571 if (exc_bkpt_sp && additional_args) {
572 Breakpoint::BreakpointPreconditionSP precondition_sp =
573 exc_bkpt_sp->GetPrecondition();
574 if (precondition_sp && additional_args) {
576 *error = precondition_sp->ConfigurePrecondition(*additional_args);
578 precondition_sp->ConfigurePrecondition(*additional_args);
585 Target::CreateScriptedBreakpoint(const llvm::StringRef class_name,
586 const FileSpecList *containingModules,
587 const FileSpecList *containingSourceFiles,
589 bool request_hardware,
590 StructuredData::ObjectSP extra_args_sp,
591 Status *creation_error)
593 SearchFilterSP filter_sp;
595 lldb::SearchDepth depth = lldb::eSearchDepthTarget;
596 bool has_files = containingSourceFiles && containingSourceFiles->GetSize() > 0;
597 bool has_modules = containingModules && containingModules->GetSize() > 0;
599 if (has_files && has_modules) {
600 filter_sp = GetSearchFilterForModuleAndCUList(
601 containingModules, containingSourceFiles);
602 } else if (has_files) {
603 filter_sp = GetSearchFilterForModuleAndCUList(
604 nullptr, containingSourceFiles);
605 } else if (has_modules) {
606 filter_sp = GetSearchFilterForModuleList(containingModules);
608 filter_sp.reset(new SearchFilterForUnconstrainedSearches(shared_from_this()));
611 StructuredDataImpl *extra_args_impl = new StructuredDataImpl();
613 extra_args_impl->SetObjectSP(extra_args_sp);
615 BreakpointResolverSP resolver_sp(new
616 BreakpointResolverScripted(nullptr, class_name,
619 *GetDebugger().GetCommandInterpreter()
620 .GetScriptInterpreter()));
621 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
626 BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
627 BreakpointResolverSP &resolver_sp,
628 bool internal, bool request_hardware,
629 bool resolve_indirect_symbols) {
631 if (filter_sp && resolver_sp) {
632 const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
633 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
634 resolve_indirect_symbols));
635 resolver_sp->SetBreakpoint(bp_sp.get());
636 AddBreakpoint(bp_sp, internal);
641 void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
645 m_internal_breakpoint_list.Add(bp_sp, false);
647 m_breakpoint_list.Add(bp_sp, true);
649 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
652 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
653 log->Printf("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__,
654 bp_sp->IsInternal() ? "yes" : "no", s.GetData());
657 bp_sp->ResolveBreakpoint();
660 m_last_created_breakpoint = bp_sp;
664 void Target::AddNameToBreakpoint(BreakpointID &id,
669 = m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
673 id.GetDescription(&s, eDescriptionLevelBrief);
674 error.SetErrorStringWithFormat("Could not find breakpoint %s",
678 AddNameToBreakpoint(bp_sp, name, error);
681 void Target::AddNameToBreakpoint(BreakpointSP &bp_sp,
688 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
692 bp_name->ConfigureBreakpoint(bp_sp);
693 bp_sp->AddName(name);
696 void Target::AddBreakpointName(BreakpointName *bp_name) {
697 m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name));
700 BreakpointName *Target::FindBreakpointName(const ConstString &name,
704 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
705 if (!error.Success())
708 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
709 if (iter == m_breakpoint_names.end()) {
712 error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
713 "can_create is false.", name.AsCString());
717 iter = m_breakpoint_names.insert(std::make_pair(name,
718 new BreakpointName(name)))
721 return (iter->second);
725 Target::DeleteBreakpointName(const ConstString &name)
727 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
729 if (iter != m_breakpoint_names.end()) {
730 const char *name_cstr = name.AsCString();
731 m_breakpoint_names.erase(iter);
732 for (auto bp_sp : m_breakpoint_list.Breakpoints())
733 bp_sp->RemoveName(name_cstr);
737 void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
738 const ConstString &name)
740 bp_sp->RemoveName(name.AsCString());
743 void Target::ConfigureBreakpointName(BreakpointName &bp_name,
744 const BreakpointOptions &new_options,
745 const BreakpointName::Permissions &new_permissions)
747 bp_name.GetOptions().CopyOverSetOptions(new_options);
748 bp_name.GetPermissions().MergeInto(new_permissions);
749 ApplyNameToBreakpoints(bp_name);
752 void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
753 BreakpointList bkpts_with_name(false);
754 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString(),
757 for (auto bp_sp : bkpts_with_name.Breakpoints())
758 bp_name.ConfigureBreakpoint(bp_sp);
761 void Target::GetBreakpointNames(std::vector<std::string> &names)
764 for (auto bp_name : m_breakpoint_names) {
765 names.push_back(bp_name.first.AsCString());
767 llvm::sort(names.begin(), names.end());
770 bool Target::ProcessIsValid() {
771 return (m_process_sp && m_process_sp->IsAlive());
774 static bool CheckIfWatchpointsSupported(Target *target, Status &error) {
775 uint32_t num_supported_hardware_watchpoints;
776 Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
777 num_supported_hardware_watchpoints);
779 // If unable to determine the # of watchpoints available,
780 // assume they are supported.
784 if (num_supported_hardware_watchpoints == 0) {
785 error.SetErrorStringWithFormat(
786 "Target supports (%u) hardware watchpoint slots.\n",
787 num_supported_hardware_watchpoints);
793 // See also Watchpoint::SetWatchpointType(uint32_t type) and the
794 // OptionGroupWatchpoint::WatchType enum type.
795 WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
796 const CompilerType *type, uint32_t kind,
798 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
800 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
802 __FUNCTION__, addr, (uint64_t)size, kind);
805 if (!ProcessIsValid()) {
806 error.SetErrorString("process is not alive");
810 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
812 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
814 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
818 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
819 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
822 if (!CheckIfWatchpointsSupported(this, error))
825 // Currently we only support one watchpoint per address, with total number of
826 // watchpoints limited by the hardware which the inferior is running on.
828 // Grab the list mutex while doing operations.
829 const bool notify = false; // Don't notify about all the state changes we do
830 // on creating the watchpoint.
831 std::unique_lock<std::recursive_mutex> lock;
832 this->GetWatchpointList().GetListMutex(lock);
833 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
835 size_t old_size = matched_sp->GetByteSize();
837 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
838 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
839 // Return the existing watchpoint if both size and type match.
840 if (size == old_size && kind == old_type) {
842 wp_sp->SetEnabled(false, notify);
844 // Nil the matched watchpoint; we will be creating a new one.
845 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
846 m_watchpoint_list.Remove(matched_sp->GetID(), true);
851 wp_sp.reset(new Watchpoint(*this, addr, size, type));
852 wp_sp->SetWatchpointType(kind, notify);
853 m_watchpoint_list.Add(wp_sp, true);
856 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
858 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
859 __FUNCTION__, error.Success() ? "succeeded" : "failed",
863 // Enabling the watchpoint on the device side failed. Remove the said
864 // watchpoint from the list maintained by the target instance.
865 m_watchpoint_list.Remove(wp_sp->GetID(), true);
866 // See if we could provide more helpful error message.
867 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
868 error.SetErrorStringWithFormat(
869 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
873 m_last_created_watchpoint = wp_sp;
877 void Target::RemoveAllowedBreakpoints ()
879 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
881 log->Printf("Target::%s \n", __FUNCTION__);
883 m_breakpoint_list.RemoveAllowed(true);
885 m_last_created_breakpoint.reset();
888 void Target::RemoveAllBreakpoints(bool internal_also) {
889 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
891 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
892 internal_also ? "yes" : "no");
894 m_breakpoint_list.RemoveAll(true);
896 m_internal_breakpoint_list.RemoveAll(false);
898 m_last_created_breakpoint.reset();
901 void Target::DisableAllBreakpoints(bool internal_also) {
902 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
904 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
905 internal_also ? "yes" : "no");
907 m_breakpoint_list.SetEnabledAll(false);
909 m_internal_breakpoint_list.SetEnabledAll(false);
912 void Target::DisableAllowedBreakpoints() {
913 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
915 log->Printf("Target::%s", __FUNCTION__);
917 m_breakpoint_list.SetEnabledAllowed(false);
920 void Target::EnableAllBreakpoints(bool internal_also) {
921 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
923 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
924 internal_also ? "yes" : "no");
926 m_breakpoint_list.SetEnabledAll(true);
928 m_internal_breakpoint_list.SetEnabledAll(true);
931 void Target::EnableAllowedBreakpoints() {
932 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
934 log->Printf("Target::%s", __FUNCTION__);
936 m_breakpoint_list.SetEnabledAllowed(true);
939 bool Target::RemoveBreakpointByID(break_id_t break_id) {
940 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
942 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
943 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
945 if (DisableBreakpointByID(break_id)) {
946 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
947 m_internal_breakpoint_list.Remove(break_id, false);
949 if (m_last_created_breakpoint) {
950 if (m_last_created_breakpoint->GetID() == break_id)
951 m_last_created_breakpoint.reset();
953 m_breakpoint_list.Remove(break_id, true);
960 bool Target::DisableBreakpointByID(break_id_t break_id) {
961 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
963 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
964 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
968 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
969 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
971 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
973 bp_sp->SetEnabled(false);
979 bool Target::EnableBreakpointByID(break_id_t break_id) {
980 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
982 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
983 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
987 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
988 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
990 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
993 bp_sp->SetEnabled(true);
999 Status Target::SerializeBreakpointsToFile(const FileSpec &file,
1000 const BreakpointIDList &bp_ids,
1005 error.SetErrorString("Invalid FileSpec.");
1009 std::string path(file.GetPath());
1010 StructuredData::ObjectSP input_data_sp;
1012 StructuredData::ArraySP break_store_sp;
1013 StructuredData::Array *break_store_ptr = nullptr;
1016 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1017 if (error.Success()) {
1018 break_store_ptr = input_data_sp->GetAsArray();
1019 if (!break_store_ptr) {
1020 error.SetErrorStringWithFormat(
1021 "Tried to append to invalid input file %s", path.c_str());
1027 if (!break_store_ptr) {
1028 break_store_sp.reset(new StructuredData::Array());
1029 break_store_ptr = break_store_sp.get();
1032 StreamFile out_file(path.c_str(),
1033 File::OpenOptions::eOpenOptionTruncate |
1034 File::OpenOptions::eOpenOptionWrite |
1035 File::OpenOptions::eOpenOptionCanCreate |
1036 File::OpenOptions::eOpenOptionCloseOnExec,
1037 lldb::eFilePermissionsFileDefault);
1038 if (!out_file.GetFile().IsValid()) {
1039 error.SetErrorStringWithFormat("Unable to open output file: %s.",
1044 std::unique_lock<std::recursive_mutex> lock;
1045 GetBreakpointList().GetListMutex(lock);
1047 if (bp_ids.GetSize() == 0) {
1048 const BreakpointList &breakpoints = GetBreakpointList();
1050 size_t num_breakpoints = breakpoints.GetSize();
1051 for (size_t i = 0; i < num_breakpoints; i++) {
1052 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1053 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1054 // If a breakpoint can't serialize it, just ignore it for now:
1056 break_store_ptr->AddItem(bkpt_save_sp);
1060 std::unordered_set<lldb::break_id_t> processed_bkpts;
1061 const size_t count = bp_ids.GetSize();
1062 for (size_t i = 0; i < count; ++i) {
1063 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1064 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1066 if (bp_id != LLDB_INVALID_BREAK_ID) {
1067 // Only do each breakpoint once:
1068 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1069 insert_result = processed_bkpts.insert(bp_id);
1070 if (!insert_result.second)
1073 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1074 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1075 // If the user explicitly asked to serialize a breakpoint, and we
1076 // can't, then raise an error:
1077 if (!bkpt_save_sp) {
1078 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1082 break_store_ptr->AddItem(bkpt_save_sp);
1087 break_store_ptr->Dump(out_file, false);
1088 out_file.PutChar('\n');
1092 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1093 BreakpointIDList &new_bps) {
1094 std::vector<std::string> no_names;
1095 return CreateBreakpointsFromFile(file, no_names, new_bps);
1098 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1099 std::vector<std::string> &names,
1100 BreakpointIDList &new_bps) {
1101 std::unique_lock<std::recursive_mutex> lock;
1102 GetBreakpointList().GetListMutex(lock);
1105 StructuredData::ObjectSP input_data_sp =
1106 StructuredData::ParseJSONFromFile(file, error);
1107 if (!error.Success()) {
1109 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1110 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1111 file.GetPath().c_str());
1115 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1117 error.SetErrorStringWithFormat(
1118 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1122 size_t num_bkpts = bkpt_array->GetSize();
1123 size_t num_names = names.size();
1125 for (size_t i = 0; i < num_bkpts; i++) {
1126 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1127 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1128 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1130 error.SetErrorStringWithFormat(
1131 "Invalid breakpoint data for element %zu from input file: %s.", i,
1132 file.GetPath().c_str());
1135 StructuredData::ObjectSP bkpt_data_sp =
1136 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
1138 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1141 BreakpointSP bkpt_sp =
1142 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1143 if (!error.Success()) {
1144 error.SetErrorStringWithFormat(
1145 "Error restoring breakpoint %zu from %s: %s.", i,
1146 file.GetPath().c_str(), error.AsCString());
1149 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1154 // The flag 'end_to_end', default to true, signifies that the operation is
1155 // performed end to end, for both the debugger and the debuggee.
1157 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1158 // to end operations.
1159 bool Target::RemoveAllWatchpoints(bool end_to_end) {
1160 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1162 log->Printf("Target::%s\n", __FUNCTION__);
1165 m_watchpoint_list.RemoveAll(true);
1169 // Otherwise, it's an end to end operation.
1171 if (!ProcessIsValid())
1174 size_t num_watchpoints = m_watchpoint_list.GetSize();
1175 for (size_t i = 0; i < num_watchpoints; ++i) {
1176 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1180 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1184 m_watchpoint_list.RemoveAll(true);
1185 m_last_created_watchpoint.reset();
1186 return true; // Success!
1189 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1190 // to end operations.
1191 bool Target::DisableAllWatchpoints(bool end_to_end) {
1192 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1194 log->Printf("Target::%s\n", __FUNCTION__);
1197 m_watchpoint_list.SetEnabledAll(false);
1201 // Otherwise, it's an end to end operation.
1203 if (!ProcessIsValid())
1206 size_t num_watchpoints = m_watchpoint_list.GetSize();
1207 for (size_t i = 0; i < num_watchpoints; ++i) {
1208 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1212 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1216 return true; // Success!
1219 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1220 // to end operations.
1221 bool Target::EnableAllWatchpoints(bool end_to_end) {
1222 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1224 log->Printf("Target::%s\n", __FUNCTION__);
1227 m_watchpoint_list.SetEnabledAll(true);
1231 // Otherwise, it's an end to end operation.
1233 if (!ProcessIsValid())
1236 size_t num_watchpoints = m_watchpoint_list.GetSize();
1237 for (size_t i = 0; i < num_watchpoints; ++i) {
1238 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1242 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1246 return true; // Success!
1249 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1250 bool Target::ClearAllWatchpointHitCounts() {
1251 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1253 log->Printf("Target::%s\n", __FUNCTION__);
1255 size_t num_watchpoints = m_watchpoint_list.GetSize();
1256 for (size_t i = 0; i < num_watchpoints; ++i) {
1257 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1261 wp_sp->ResetHitCount();
1263 return true; // Success!
1266 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1267 bool Target::ClearAllWatchpointHistoricValues() {
1268 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1270 log->Printf("Target::%s\n", __FUNCTION__);
1272 size_t num_watchpoints = m_watchpoint_list.GetSize();
1273 for (size_t i = 0; i < num_watchpoints; ++i) {
1274 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1278 wp_sp->ResetHistoricValues();
1280 return true; // Success!
1283 // Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1284 // these operations.
1285 bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1286 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1288 log->Printf("Target::%s\n", __FUNCTION__);
1290 if (!ProcessIsValid())
1293 size_t num_watchpoints = m_watchpoint_list.GetSize();
1294 for (size_t i = 0; i < num_watchpoints; ++i) {
1295 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1299 wp_sp->SetIgnoreCount(ignore_count);
1301 return true; // Success!
1304 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1305 bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1306 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1308 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1310 if (!ProcessIsValid())
1313 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1315 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1319 // Else, fallthrough.
1324 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1325 bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1326 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1328 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1330 if (!ProcessIsValid())
1333 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1335 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1339 // Else, fallthrough.
1344 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1345 bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1346 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1348 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1350 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1351 if (watch_to_remove_sp == m_last_created_watchpoint)
1352 m_last_created_watchpoint.reset();
1354 if (DisableWatchpointByID(watch_id)) {
1355 m_watchpoint_list.Remove(watch_id, true);
1361 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1362 bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1363 uint32_t ignore_count) {
1364 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1366 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1368 if (!ProcessIsValid())
1371 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1373 wp_sp->SetIgnoreCount(ignore_count);
1379 ModuleSP Target::GetExecutableModule() {
1380 // search for the first executable in the module list
1381 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1382 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1383 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1386 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1389 // as fall back return the first module loaded
1390 return m_images.GetModuleAtIndex(0);
1393 Module *Target::GetExecutableModulePointer() {
1394 return GetExecutableModule().get();
1397 static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1400 StreamString feedback_stream;
1402 !module_sp->LoadScriptingResourceInTarget(target, error,
1403 &feedback_stream)) {
1404 if (error.AsCString())
1405 target->GetDebugger().GetErrorFile()->Printf(
1406 "unable to load scripting data for module %s - error reported was "
1408 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1411 if (feedback_stream.GetSize())
1412 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1413 feedback_stream.GetData());
1416 void Target::ClearModules(bool delete_locations) {
1417 ModulesDidUnload(m_images, delete_locations);
1418 m_section_load_history.Clear();
1420 m_scratch_type_system_map.Clear();
1421 m_ast_importer_sp.reset();
1424 void Target::DidExec() {
1425 // When a process exec's we need to know about it so we can do some cleanup.
1426 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1427 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1430 void Target::SetExecutableModule(ModuleSP &executable_sp,
1431 LoadDependentFiles load_dependent_files) {
1432 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1433 ClearModules(false);
1435 if (executable_sp) {
1436 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1437 Timer scoped_timer(func_cat,
1438 "Target::SetExecutableModule (executable = '%s')",
1439 executable_sp->GetFileSpec().GetPath().c_str());
1441 m_images.Append(executable_sp); // The first image is our executable file
1443 // If we haven't set an architecture yet, reset our architecture based on
1444 // what we found in the executable module.
1445 if (!m_arch.GetSpec().IsValid()) {
1446 m_arch = executable_sp->GetArchitecture();
1448 "setting architecture to {0} ({1}) based on executable file",
1449 m_arch.GetSpec().GetArchitectureName(),
1450 m_arch.GetSpec().GetTriple().getTriple());
1453 FileSpecList dependent_files;
1454 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1455 bool load_dependents = true;
1456 switch (load_dependent_files) {
1457 case eLoadDependentsDefault:
1458 load_dependents = executable_sp->IsExecutable();
1460 case eLoadDependentsYes:
1461 load_dependents = true;
1463 case eLoadDependentsNo:
1464 load_dependents = false;
1468 if (executable_objfile && load_dependents) {
1469 executable_objfile->GetDependentModules(dependent_files);
1470 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1471 FileSpec dependent_file_spec(
1472 dependent_files.GetFileSpecPointerAtIndex(i));
1473 FileSpec platform_dependent_file_spec;
1475 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1476 platform_dependent_file_spec);
1478 platform_dependent_file_spec = dependent_file_spec;
1480 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1481 ModuleSP image_module_sp(GetSharedModule(module_spec));
1482 if (image_module_sp) {
1483 ObjectFile *objfile = image_module_sp->GetObjectFile();
1485 objfile->GetDependentModules(dependent_files);
1492 bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform) {
1493 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1494 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1495 bool replace_local_arch = true;
1496 bool compatible_local_arch = false;
1497 ArchSpec other(arch_spec);
1499 // Changing the architecture might mean that the currently selected platform
1500 // isn't compatible. Set the platform correctly if we are asked to do so,
1501 // otherwise assume the user will set the platform manually.
1503 if (other.IsValid()) {
1504 auto platform_sp = GetPlatform();
1506 !platform_sp->IsCompatibleArchitecture(other, false, nullptr)) {
1507 ArchSpec platform_arch;
1508 auto arch_platform_sp =
1509 Platform::GetPlatformForArchitecture(other, &platform_arch);
1510 if (arch_platform_sp) {
1511 SetPlatform(arch_platform_sp);
1512 if (platform_arch.IsValid())
1513 other = platform_arch;
1519 if (!missing_local_arch) {
1520 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1521 other.MergeFrom(m_arch.GetSpec());
1523 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1524 compatible_local_arch = true;
1525 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1528 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed, vendor_changed,
1529 os_changed, os_ver_changed, env_changed);
1531 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1532 replace_local_arch = false;
1537 if (compatible_local_arch || missing_local_arch) {
1538 // If we haven't got a valid arch spec, or the architectures are compatible
1539 // update the architecture, unless the one we already have is more
1541 if (replace_local_arch)
1543 LLDB_LOG(log, "set architecture to {0} ({1})",
1544 m_arch.GetSpec().GetArchitectureName(),
1545 m_arch.GetSpec().GetTriple().getTriple());
1549 // If we have an executable file, try to reset the executable to the desired
1552 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1553 arch_spec.GetArchitectureName(),
1554 arch_spec.GetTriple().getTriple().c_str());
1556 ModuleSP executable_sp = GetExecutableModule();
1559 // Need to do something about unsetting breakpoints.
1561 if (executable_sp) {
1563 log->Printf("Target::SetArchitecture Trying to select executable file "
1564 "architecture %s (%s)",
1565 arch_spec.GetArchitectureName(),
1566 arch_spec.GetTriple().getTriple().c_str());
1567 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1568 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1569 &GetExecutableSearchPaths(),
1572 if (!error.Fail() && executable_sp) {
1573 SetExecutableModule(executable_sp, eLoadDependentsYes);
1580 bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1581 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1582 if (arch_spec.IsValid()) {
1583 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1584 // The current target arch is compatible with "arch_spec", see if we can
1585 // improve our current architecture using bits from "arch_spec"
1588 log->Printf("Target::MergeArchitecture target has arch %s, merging with "
1590 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1591 arch_spec.GetTriple().getTriple().c_str());
1593 // Merge bits from arch_spec into "merged_arch" and set our architecture
1594 ArchSpec merged_arch(m_arch.GetSpec());
1595 merged_arch.MergeFrom(arch_spec);
1596 return SetArchitecture(merged_arch);
1598 // The new architecture is different, we just need to replace it
1599 return SetArchitecture(arch_spec);
1605 void Target::WillClearList(const ModuleList &module_list) {}
1607 void Target::ModuleAdded(const ModuleList &module_list,
1608 const ModuleSP &module_sp) {
1609 // A module is being added to this target for the first time
1611 ModuleList my_module_list;
1612 my_module_list.Append(module_sp);
1613 LoadScriptingResourceForModule(module_sp, this);
1614 ModulesDidLoad(my_module_list);
1618 void Target::ModuleRemoved(const ModuleList &module_list,
1619 const ModuleSP &module_sp) {
1620 // A module is being removed from this target.
1622 ModuleList my_module_list;
1623 my_module_list.Append(module_sp);
1624 ModulesDidUnload(my_module_list, false);
1628 void Target::ModuleUpdated(const ModuleList &module_list,
1629 const ModuleSP &old_module_sp,
1630 const ModuleSP &new_module_sp) {
1631 // A module is replacing an already added module
1633 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1635 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1636 old_module_sp, new_module_sp);
1640 void Target::ModulesDidLoad(ModuleList &module_list) {
1641 if (m_valid && module_list.GetSize()) {
1642 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1643 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1645 m_process_sp->ModulesDidLoad(module_list);
1647 BroadcastEvent(eBroadcastBitModulesLoaded,
1648 new TargetEventData(this->shared_from_this(), module_list));
1652 void Target::SymbolsDidLoad(ModuleList &module_list) {
1653 if (m_valid && module_list.GetSize()) {
1655 LanguageRuntime *runtime =
1656 m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1658 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime *)runtime;
1659 objc_runtime->SymbolsDidLoad(module_list);
1663 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1664 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1665 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1666 new TargetEventData(this->shared_from_this(), module_list));
1670 void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1671 if (m_valid && module_list.GetSize()) {
1672 UnloadModuleSections(module_list);
1673 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1674 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1676 BroadcastEvent(eBroadcastBitModulesUnloaded,
1677 new TargetEventData(this->shared_from_this(), module_list));
1681 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1682 const FileSpec &module_file_spec) {
1683 if (GetBreakpointsConsultPlatformAvoidList()) {
1684 ModuleList matchingModules;
1685 ModuleSpec module_spec(module_file_spec);
1686 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1688 // If there is more than one module for this file spec, only return true if
1689 // ALL the modules are on the
1691 if (num_modules > 0) {
1692 for (size_t i = 0; i < num_modules; i++) {
1693 if (!ModuleIsExcludedForUnconstrainedSearches(
1694 matchingModules.GetModuleAtIndex(i)))
1703 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1704 const lldb::ModuleSP &module_sp) {
1705 if (GetBreakpointsConsultPlatformAvoidList()) {
1707 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1713 size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1714 size_t dst_len, Status &error) {
1715 SectionSP section_sp(addr.GetSection());
1717 // If the contents of this section are encrypted, the on-disk file is
1718 // unusable. Read only from live memory.
1719 if (section_sp->IsEncrypted()) {
1720 error.SetErrorString("section is encrypted");
1723 ModuleSP module_sp(section_sp->GetModule());
1725 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1727 size_t bytes_read = objfile->ReadSectionData(
1728 section_sp.get(), addr.GetOffset(), dst, dst_len);
1732 error.SetErrorStringWithFormat("error reading data from section %s",
1733 section_sp->GetName().GetCString());
1735 error.SetErrorString("address isn't from a object file");
1737 error.SetErrorString("address isn't in a module");
1739 error.SetErrorString("address doesn't contain a section that points to a "
1740 "section in a object file");
1745 size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1746 void *dst, size_t dst_len, Status &error,
1747 lldb::addr_t *load_addr_ptr) {
1750 // if we end up reading this from process memory, we will fill this with the
1751 // actual load address
1753 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1755 size_t bytes_read = 0;
1757 addr_t load_addr = LLDB_INVALID_ADDRESS;
1758 addr_t file_addr = LLDB_INVALID_ADDRESS;
1759 Address resolved_addr;
1760 if (!addr.IsSectionOffset()) {
1761 SectionLoadList §ion_load_list = GetSectionLoadList();
1762 if (section_load_list.IsEmpty()) {
1763 // No sections are loaded, so we must assume we are not running yet and
1764 // anything we are given is a file address.
1765 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1766 // offset is the file address
1767 m_images.ResolveFileAddress(file_addr, resolved_addr);
1769 // We have at least one section loaded. This can be because we have
1770 // manually loaded some sections with "target modules load ..." or
1771 // because we have have a live process that has sections loaded through
1772 // the dynamic loader
1773 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1774 // offset is the load address
1775 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1778 if (!resolved_addr.IsValid())
1779 resolved_addr = addr;
1781 if (prefer_file_cache) {
1782 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1787 if (ProcessIsValid()) {
1788 if (load_addr == LLDB_INVALID_ADDRESS)
1789 load_addr = resolved_addr.GetLoadAddress(this);
1791 if (load_addr == LLDB_INVALID_ADDRESS) {
1792 ModuleSP addr_module_sp(resolved_addr.GetModule());
1793 if (addr_module_sp && addr_module_sp->GetFileSpec())
1794 error.SetErrorStringWithFormatv(
1795 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1796 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1798 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1799 resolved_addr.GetFileAddress());
1801 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1802 if (bytes_read != dst_len) {
1803 if (error.Success()) {
1804 if (bytes_read == 0)
1805 error.SetErrorStringWithFormat(
1806 "read memory from 0x%" PRIx64 " failed", load_addr);
1808 error.SetErrorStringWithFormat(
1809 "only %" PRIu64 " of %" PRIu64
1810 " bytes were read from memory at 0x%" PRIx64,
1811 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1816 *load_addr_ptr = load_addr;
1819 // If the address is not section offset we have an address that doesn't
1820 // resolve to any address in any currently loaded shared libraries and we
1821 // failed to read memory so there isn't anything more we can do. If it is
1822 // section offset, we might be able to read cached memory from the object
1824 if (!resolved_addr.IsSectionOffset())
1829 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1830 // If we didn't already try and read from the object file cache, then try
1831 // it after failing to read from the process.
1832 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1837 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1841 addr_t curr_addr = addr.GetLoadAddress(this);
1842 Address address(addr);
1844 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1847 out_str.append(buf, length);
1848 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1849 // to read some more characters
1850 if (length == sizeof(buf) - 1)
1851 curr_addr += length;
1854 address = Address(curr_addr);
1856 return out_str.size();
1859 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1860 size_t dst_max_len, Status &result_error) {
1861 size_t total_cstr_len = 0;
1862 if (dst && dst_max_len) {
1863 result_error.Clear();
1864 // NULL out everything just to be safe
1865 memset(dst, 0, dst_max_len);
1867 addr_t curr_addr = addr.GetLoadAddress(this);
1868 Address address(addr);
1870 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1871 // this really needs to be tied to the memory cache subsystem's cache line
1872 // size, so leave this as a fixed constant.
1873 const size_t cache_line_size = 512;
1875 size_t bytes_left = dst_max_len - 1;
1876 char *curr_dst = dst;
1878 while (bytes_left > 0) {
1879 addr_t cache_line_bytes_left =
1880 cache_line_size - (curr_addr % cache_line_size);
1881 addr_t bytes_to_read =
1882 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1884 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1886 if (bytes_read == 0) {
1887 result_error = error;
1888 dst[total_cstr_len] = '\0';
1891 const size_t len = strlen(curr_dst);
1893 total_cstr_len += len;
1895 if (len < bytes_to_read)
1898 curr_dst += bytes_read;
1899 curr_addr += bytes_read;
1900 bytes_left -= bytes_read;
1901 address = Address(curr_addr);
1905 result_error.SetErrorString("invalid arguments");
1907 result_error.Clear();
1909 return total_cstr_len;
1912 size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1913 bool prefer_file_cache,
1914 uint32_t byte_size, bool is_signed,
1915 Scalar &scalar, Status &error) {
1918 if (byte_size <= sizeof(uval)) {
1920 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1921 if (bytes_read == byte_size) {
1922 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1923 m_arch.GetSpec().GetAddressByteSize());
1924 lldb::offset_t offset = 0;
1926 scalar = data.GetMaxU32(&offset, byte_size);
1928 scalar = data.GetMaxU64(&offset, byte_size);
1931 scalar.SignExtend(byte_size * 8);
1935 error.SetErrorStringWithFormat(
1936 "byte size of %u is too large for integer scalar type", byte_size);
1941 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1942 bool prefer_file_cache,
1943 size_t integer_byte_size,
1944 uint64_t fail_value,
1947 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1948 false, scalar, error))
1949 return scalar.ULongLong(fail_value);
1953 bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1954 Status &error, Address &pointer_addr) {
1956 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1957 m_arch.GetSpec().GetAddressByteSize(), false, scalar,
1959 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1960 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1961 SectionLoadList §ion_load_list = GetSectionLoadList();
1962 if (section_load_list.IsEmpty()) {
1963 // No sections are loaded, so we must assume we are not running yet and
1964 // anything we are given is a file address.
1965 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1967 // We have at least one section loaded. This can be because we have
1968 // manually loaded some sections with "target modules load ..." or
1969 // because we have have a live process that has sections loaded through
1970 // the dynamic loader
1971 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1973 // We weren't able to resolve the pointer value, so just return an
1974 // address with no section
1975 if (!pointer_addr.IsValid())
1976 pointer_addr.SetOffset(pointer_vm_addr);
1983 ModuleSP Target::GetSharedModule(const ModuleSpec &module_spec,
1984 Status *error_ptr) {
1989 // First see if we already have this module in our module list. If we do,
1990 // then we're done, we don't need to consult the shared modules list. But
1991 // only do this if we are passed a UUID.
1993 if (module_spec.GetUUID().IsValid())
1994 module_sp = m_images.FindFirstModule(module_spec);
1997 ModuleSP old_module_sp; // This will get filled in if we have a new version
1999 bool did_create_module = false;
2001 // If there are image search path entries, try to use them first to acquire
2002 // a suitable image.
2003 if (m_image_search_paths.GetSize()) {
2004 ModuleSpec transformed_spec(module_spec);
2005 if (m_image_search_paths.RemapPath(
2006 module_spec.GetFileSpec().GetDirectory(),
2007 transformed_spec.GetFileSpec().GetDirectory())) {
2008 transformed_spec.GetFileSpec().GetFilename() =
2009 module_spec.GetFileSpec().GetFilename();
2010 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2011 &GetExecutableSearchPaths(),
2012 &old_module_sp, &did_create_module);
2017 // If we have a UUID, we can check our global shared module list in case
2018 // we already have it. If we don't have a valid UUID, then we can't since
2019 // the path in "module_spec" will be a platform path, and we will need to
2020 // let the platform find that file. For example, we could be asking for
2021 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2022 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2023 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2025 if (module_spec.GetUUID().IsValid()) {
2026 // We have a UUID, it is OK to check the global module list...
2027 error = ModuleList::GetSharedModule(module_spec, module_sp,
2028 &GetExecutableSearchPaths(),
2029 &old_module_sp, &did_create_module);
2033 // The platform is responsible for finding and caching an appropriate
2034 // module in the shared module cache.
2035 if (m_platform_sp) {
2036 error = m_platform_sp->GetSharedModule(
2037 module_spec, m_process_sp.get(), module_sp,
2038 &GetExecutableSearchPaths(), &old_module_sp, &did_create_module);
2040 error.SetErrorString("no platform is currently set");
2045 // We found a module that wasn't in our target list. Let's make sure that
2046 // there wasn't an equivalent module in the list already, and if there was,
2049 ObjectFile *objfile = module_sp->GetObjectFile();
2051 switch (objfile->GetType()) {
2052 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2053 /// a program's execution state
2054 case ObjectFile::eTypeExecutable: /// A normal executable
2055 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2057 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2058 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2059 /// used during execution
2061 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2062 /// debug information
2064 error_ptr->SetErrorString("debug info files aren't valid target "
2065 "modules, please specify an executable");
2067 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2068 /// against but not used for
2071 error_ptr->SetErrorString("stub libraries aren't valid target "
2072 "modules, please specify an executable");
2076 error_ptr->SetErrorString(
2077 "unsupported file type, please specify an executable");
2080 // GetSharedModule is not guaranteed to find the old shared module, for
2081 // instance in the common case where you pass in the UUID, it is only
2082 // going to find the one module matching the UUID. In fact, it has no
2083 // good way to know what the "old module" relevant to this target is,
2084 // since there might be many copies of a module with this file spec in
2085 // various running debug sessions, but only one of them will belong to
2086 // this target. So let's remove the UUID from the module list, and look
2087 // in the target's module list. Only do this if there is SOMETHING else
2088 // in the module spec...
2089 if (!old_module_sp) {
2090 if (module_spec.GetUUID().IsValid() &&
2091 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2092 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2093 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2094 module_spec_copy.GetUUID().Clear();
2096 ModuleList found_modules;
2098 m_images.FindModules(module_spec_copy, found_modules);
2099 if (num_found == 1) {
2100 old_module_sp = found_modules.GetModuleAtIndex(0);
2105 // Preload symbols outside of any lock, so hopefully we can do this for
2106 // each library in parallel.
2107 if (GetPreloadSymbols())
2108 module_sp->PreloadSymbols();
2110 if (old_module_sp &&
2111 m_images.GetIndexForModule(old_module_sp.get()) !=
2112 LLDB_INVALID_INDEX32) {
2113 m_images.ReplaceModule(old_module_sp, module_sp);
2114 Module *old_module_ptr = old_module_sp.get();
2115 old_module_sp.reset();
2116 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2118 m_images.Append(module_sp);
2128 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2130 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2132 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2134 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2136 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2138 exe_ctx.SetTargetPtr(this);
2141 PathMappingList &Target::GetImageSearchPathList() {
2142 return m_image_search_paths;
2145 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2147 Target *target = (Target *)baton;
2148 ModuleSP exe_module_sp(target->GetExecutableModule());
2150 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2153 TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error,
2154 lldb::LanguageType language,
2155 bool create_on_demand) {
2163 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2165 || language == eLanguageTypeUnknown) {
2166 std::set<lldb::LanguageType> languages_for_types;
2167 std::set<lldb::LanguageType> languages_for_expressions;
2169 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
2170 languages_for_expressions);
2172 if (languages_for_expressions.count(eLanguageTypeC)) {
2173 language = eLanguageTypeC; // LLDB's default. Override by setting the
2176 if (languages_for_expressions.empty()) {
2179 language = *languages_for_expressions.begin();
2184 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2188 PersistentExpressionState *
2189 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2190 TypeSystem *type_system =
2191 GetScratchTypeSystemForLanguage(nullptr, language, true);
2194 return type_system->GetPersistentExpressionState();
2200 UserExpression *Target::GetUserExpressionForLanguage(
2201 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2202 Expression::ResultType desired_type,
2203 const EvaluateExpressionOptions &options, Status &error) {
2204 Status type_system_error;
2206 TypeSystem *type_system =
2207 GetScratchTypeSystemForLanguage(&type_system_error, language);
2208 UserExpression *user_expr = nullptr;
2211 error.SetErrorStringWithFormat(
2212 "Could not find type system for language %s: %s",
2213 Language::GetNameForLanguageType(language),
2214 type_system_error.AsCString());
2218 user_expr = type_system->GetUserExpression(expr, prefix, language,
2219 desired_type, options);
2221 error.SetErrorStringWithFormat(
2222 "Could not create an expression for language %s",
2223 Language::GetNameForLanguageType(language));
2228 FunctionCaller *Target::GetFunctionCallerForLanguage(
2229 lldb::LanguageType language, const CompilerType &return_type,
2230 const Address &function_address, const ValueList &arg_value_list,
2231 const char *name, Status &error) {
2232 Status type_system_error;
2233 TypeSystem *type_system =
2234 GetScratchTypeSystemForLanguage(&type_system_error, language);
2235 FunctionCaller *persistent_fn = nullptr;
2238 error.SetErrorStringWithFormat(
2239 "Could not find type system for language %s: %s",
2240 Language::GetNameForLanguageType(language),
2241 type_system_error.AsCString());
2242 return persistent_fn;
2245 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2246 arg_value_list, name);
2248 error.SetErrorStringWithFormat(
2249 "Could not create an expression for language %s",
2250 Language::GetNameForLanguageType(language));
2252 return persistent_fn;
2256 Target::GetUtilityFunctionForLanguage(const char *text,
2257 lldb::LanguageType language,
2258 const char *name, Status &error) {
2259 Status type_system_error;
2260 TypeSystem *type_system =
2261 GetScratchTypeSystemForLanguage(&type_system_error, language);
2262 UtilityFunction *utility_fn = nullptr;
2265 error.SetErrorStringWithFormat(
2266 "Could not find type system for language %s: %s",
2267 Language::GetNameForLanguageType(language),
2268 type_system_error.AsCString());
2272 utility_fn = type_system->GetUtilityFunction(text, name);
2274 error.SetErrorStringWithFormat(
2275 "Could not create an expression for language %s",
2276 Language::GetNameForLanguageType(language));
2281 ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2283 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2284 nullptr, eLanguageTypeC, create_on_demand))
2285 return llvm::dyn_cast<ClangASTContext>(type_system);
2290 ClangASTImporterSP Target::GetClangASTImporter() {
2292 if (!m_ast_importer_sp) {
2293 m_ast_importer_sp.reset(new ClangASTImporter());
2295 return m_ast_importer_sp;
2297 return ClangASTImporterSP();
2300 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2302 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2304 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2305 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2307 return properties_sp->GetExecutableSearchPaths();
2308 return FileSpecList();
2311 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2312 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2314 return properties_sp->GetDebugFileSearchPaths();
2315 return FileSpecList();
2318 FileSpecList Target::GetDefaultClangModuleSearchPaths() {
2319 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2321 return properties_sp->GetClangModuleSearchPaths();
2322 return FileSpecList();
2325 ArchSpec Target::GetDefaultArchitecture() {
2326 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2328 return properties_sp->GetDefaultArchitecture();
2332 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2333 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2334 if (properties_sp) {
2335 LogIfAnyCategoriesSet(
2336 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2337 "default architecture to %s (%s)",
2338 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2339 return properties_sp->SetDefaultArchitecture(arch);
2343 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2344 const SymbolContext *sc_ptr) {
2345 // The target can either exist in the "process" of ExecutionContext, or in
2346 // the "target_sp" member of SymbolContext. This accessor helper function
2347 // will get the target from one of these locations.
2349 Target *target = nullptr;
2350 if (sc_ptr != nullptr)
2351 target = sc_ptr->target_sp.get();
2352 if (target == nullptr && exe_ctx_ptr)
2353 target = exe_ctx_ptr->GetTargetPtr();
2357 ExpressionResults Target::EvaluateExpression(
2358 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2359 lldb::ValueObjectSP &result_valobj_sp,
2360 const EvaluateExpressionOptions &options, std::string *fixed_expression) {
2361 result_valobj_sp.reset();
2363 ExpressionResults execution_results = eExpressionSetupError;
2366 return execution_results;
2368 // We shouldn't run stop hooks in expressions. Be sure to reset this if you
2369 // return anywhere within this function.
2370 bool old_suppress_value = m_suppress_stop_hooks;
2371 m_suppress_stop_hooks = true;
2373 ExecutionContext exe_ctx;
2376 exe_scope->CalculateExecutionContext(exe_ctx);
2377 } else if (m_process_sp) {
2378 m_process_sp->CalculateExecutionContext(exe_ctx);
2380 CalculateExecutionContext(exe_ctx);
2383 // Make sure we aren't just trying to see the value of a persistent variable
2384 // (something like "$0")
2385 lldb::ExpressionVariableSP persistent_var_sp;
2386 // Only check for persistent variables the expression starts with a '$'
2388 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2389 ->GetPersistentExpressionState()
2390 ->GetVariable(expr);
2392 if (persistent_var_sp) {
2393 result_valobj_sp = persistent_var_sp->GetValueObject();
2394 execution_results = eExpressionCompleted;
2396 llvm::StringRef prefix = GetExpressionPrefixContents();
2398 execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2399 result_valobj_sp, error,
2404 m_suppress_stop_hooks = old_suppress_value;
2406 return execution_results;
2409 lldb::ExpressionVariableSP
2410 Target::GetPersistentVariable(const ConstString &name) {
2411 lldb::ExpressionVariableSP variable_sp;
2412 m_scratch_type_system_map.ForEach(
2413 [name, &variable_sp](TypeSystem *type_system) -> bool {
2414 if (PersistentExpressionState *persistent_state =
2415 type_system->GetPersistentExpressionState()) {
2416 variable_sp = persistent_state->GetVariable(name);
2419 return false; // Stop iterating the ForEach
2421 return true; // Keep iterating the ForEach
2426 lldb::addr_t Target::GetPersistentSymbol(const ConstString &name) {
2427 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2429 m_scratch_type_system_map.ForEach(
2430 [name, &address](TypeSystem *type_system) -> bool {
2431 if (PersistentExpressionState *persistent_state =
2432 type_system->GetPersistentExpressionState()) {
2433 address = persistent_state->LookupSymbol(name);
2434 if (address != LLDB_INVALID_ADDRESS)
2435 return false; // Stop iterating the ForEach
2437 return true; // Keep iterating the ForEach
2442 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2443 AddressClass addr_class) const {
2444 auto arch_plugin = GetArchitecturePlugin();
2445 return arch_plugin ?
2446 arch_plugin->GetCallableLoadAddress(load_addr, addr_class) : load_addr;
2449 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2450 AddressClass addr_class) const {
2451 auto arch_plugin = GetArchitecturePlugin();
2452 return arch_plugin ?
2453 arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class) : load_addr;
2456 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2457 auto arch_plugin = GetArchitecturePlugin();
2458 return arch_plugin ?
2459 arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2462 SourceManager &Target::GetSourceManager() {
2463 if (!m_source_manager_ap)
2464 m_source_manager_ap.reset(new SourceManager(shared_from_this()));
2465 return *m_source_manager_ap;
2468 ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2469 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2474 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2476 if (!m_clang_modules_decl_vendor_ap) {
2477 m_clang_modules_decl_vendor_ap.reset(
2478 ClangModulesDeclVendor::Create(*this));
2482 return m_clang_modules_decl_vendor_ap.get();
2485 Target::StopHookSP Target::CreateStopHook() {
2486 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2487 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2488 m_stop_hooks[new_uid] = stop_hook_sp;
2489 return stop_hook_sp;
2492 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2493 size_t num_removed = m_stop_hooks.erase(user_id);
2494 return (num_removed != 0);
2497 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2499 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2500 StopHookSP found_hook;
2502 StopHookCollection::iterator specified_hook_iter;
2503 specified_hook_iter = m_stop_hooks.find(user_id);
2504 if (specified_hook_iter != m_stop_hooks.end())
2505 found_hook = (*specified_hook_iter).second;
2509 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2510 bool active_state) {
2511 StopHookCollection::iterator specified_hook_iter;
2512 specified_hook_iter = m_stop_hooks.find(user_id);
2513 if (specified_hook_iter == m_stop_hooks.end())
2516 (*specified_hook_iter).second->SetIsActive(active_state);
2520 void Target::SetAllStopHooksActiveState(bool active_state) {
2521 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2522 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2523 (*pos).second->SetIsActive(active_state);
2527 void Target::RunStopHooks() {
2528 if (m_suppress_stop_hooks)
2534 // Somebody might have restarted the process:
2535 if (m_process_sp->GetState() != eStateStopped)
2538 // <rdar://problem/12027563> make sure we check that we are not stopped
2539 // because of us running a user expression since in that case we do not want
2540 // to run the stop-hooks
2541 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2544 if (m_stop_hooks.empty())
2547 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2549 // If there aren't any active stop hooks, don't bother either:
2550 bool any_active_hooks = false;
2551 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2552 if ((*pos).second->IsActive()) {
2553 any_active_hooks = true;
2557 if (!any_active_hooks)
2560 CommandReturnObject result;
2562 std::vector<ExecutionContext> exc_ctx_with_reasons;
2563 std::vector<SymbolContext> sym_ctx_with_reasons;
2565 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2566 size_t num_threads = cur_threadlist.GetSize();
2567 for (size_t i = 0; i < num_threads; i++) {
2568 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2569 if (cur_thread_sp->ThreadStoppedForAReason()) {
2570 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2571 exc_ctx_with_reasons.push_back(ExecutionContext(
2572 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2573 sym_ctx_with_reasons.push_back(
2574 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2578 // If no threads stopped for a reason, don't run the stop-hooks.
2579 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2580 if (num_exe_ctx == 0)
2583 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2584 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2586 bool keep_going = true;
2587 bool hooks_ran = false;
2588 bool print_hook_header = (m_stop_hooks.size() != 1);
2589 bool print_thread_header = (num_exe_ctx != 1);
2591 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2593 StopHookSP cur_hook_sp = (*pos).second;
2594 if (!cur_hook_sp->IsActive())
2597 bool any_thread_matched = false;
2598 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2599 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2600 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2601 sym_ctx_with_reasons[i])) &&
2602 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2603 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2604 exc_ctx_with_reasons[i].GetThreadRef()))) {
2608 if (print_hook_header && !any_thread_matched) {
2610 (cur_hook_sp->GetCommands().GetSize() == 1
2611 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2614 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2615 cur_hook_sp->GetID(), cmd);
2617 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2618 cur_hook_sp->GetID());
2619 any_thread_matched = true;
2622 if (print_thread_header)
2623 result.AppendMessageWithFormat(
2625 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2627 CommandInterpreterRunOptions options;
2628 options.SetStopOnContinue(true);
2629 options.SetStopOnError(true);
2630 options.SetEchoCommands(false);
2631 options.SetPrintResults(true);
2632 options.SetAddToHistory(false);
2634 GetDebugger().GetCommandInterpreter().HandleCommands(
2635 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2638 // If the command started the target going again, we should bag out of
2639 // running the stop hooks.
2640 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2641 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2642 // But only complain if there were more stop hooks to do:
2643 StopHookCollection::iterator tmp = pos;
2645 result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64
2646 " set the program running.\n",
2647 cur_hook_sp->GetID());
2654 result.GetImmediateOutputStream()->Flush();
2655 result.GetImmediateErrorStream()->Flush();
2658 const TargetPropertiesSP &Target::GetGlobalProperties() {
2659 // NOTE: intentional leak so we don't crash if global destructor chain gets
2660 // called as other threads still use the result of this function
2661 static TargetPropertiesSP *g_settings_sp_ptr =
2662 new TargetPropertiesSP(new TargetProperties(nullptr));
2663 return *g_settings_sp_ptr;
2666 Status Target::Install(ProcessLaunchInfo *launch_info) {
2668 PlatformSP platform_sp(GetPlatform());
2670 if (platform_sp->IsRemote()) {
2671 if (platform_sp->IsConnected()) {
2672 // Install all files that have an install path, and always install the
2673 // main executable when connected to a remote platform
2674 const ModuleList &modules = GetImages();
2675 const size_t num_images = modules.GetSize();
2676 for (size_t idx = 0; idx < num_images; ++idx) {
2677 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2679 const bool is_main_executable = module_sp == GetExecutableModule();
2680 FileSpec local_file(module_sp->GetFileSpec());
2682 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2684 if (is_main_executable) // TODO: add setting for always
2685 // installing main executable???
2687 // Always install the main executable
2688 remote_file = platform_sp->GetRemoteWorkingDirectory();
2689 remote_file.AppendPathComponent(
2690 module_sp->GetFileSpec().GetFilename().GetCString());
2694 error = platform_sp->Install(local_file, remote_file);
2695 if (error.Success()) {
2696 module_sp->SetPlatformFileSpec(remote_file);
2697 if (is_main_executable) {
2698 platform_sp->SetFilePermissions(remote_file, 0700);
2700 launch_info->SetExecutableFile(remote_file, false);
2714 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2716 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2719 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2720 Address &resolved_addr) {
2721 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2724 bool Target::SetSectionLoadAddress(const SectionSP §ion_sp,
2725 addr_t new_section_load_addr,
2726 bool warn_multiple) {
2727 const addr_t old_section_load_addr =
2728 m_section_load_history.GetSectionLoadAddress(
2729 SectionLoadHistory::eStopIDNow, section_sp);
2730 if (old_section_load_addr != new_section_load_addr) {
2731 uint32_t stop_id = 0;
2732 ProcessSP process_sp(GetProcessSP());
2734 stop_id = process_sp->GetStopID();
2736 stop_id = m_section_load_history.GetLastStopID();
2737 if (m_section_load_history.SetSectionLoadAddress(
2738 stop_id, section_sp, new_section_load_addr, warn_multiple))
2739 return true; // Return true if the section load address was changed...
2741 return false; // Return false to indicate nothing changed
2744 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2745 size_t section_unload_count = 0;
2746 size_t num_modules = module_list.GetSize();
2747 for (size_t i = 0; i < num_modules; ++i) {
2748 section_unload_count +=
2749 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2751 return section_unload_count;
2754 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2755 uint32_t stop_id = 0;
2756 ProcessSP process_sp(GetProcessSP());
2758 stop_id = process_sp->GetStopID();
2760 stop_id = m_section_load_history.GetLastStopID();
2761 SectionList *sections = module_sp->GetSectionList();
2762 size_t section_unload_count = 0;
2764 const uint32_t num_sections = sections->GetNumSections(0);
2765 for (uint32_t i = 0; i < num_sections; ++i) {
2766 section_unload_count += m_section_load_history.SetSectionUnloaded(
2767 stop_id, sections->GetSectionAtIndex(i));
2770 return section_unload_count;
2773 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp) {
2774 uint32_t stop_id = 0;
2775 ProcessSP process_sp(GetProcessSP());
2777 stop_id = process_sp->GetStopID();
2779 stop_id = m_section_load_history.GetLastStopID();
2780 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2783 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp,
2785 uint32_t stop_id = 0;
2786 ProcessSP process_sp(GetProcessSP());
2788 stop_id = process_sp->GetStopID();
2790 stop_id = m_section_load_history.GetLastStopID();
2791 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2795 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2797 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2799 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2802 log->Printf("Target::%s() called for %s", __FUNCTION__,
2803 launch_info.GetExecutableFile().GetPath().c_str());
2805 StateType state = eStateInvalid;
2807 // Scope to temporarily get the process state in case someone has manually
2808 // remotely connected already to a process and we can skip the platform
2811 ProcessSP process_sp(GetProcessSP());
2814 state = process_sp->GetState();
2817 "Target::%s the process exists, and its current state is %s",
2818 __FUNCTION__, StateAsCString(state));
2821 log->Printf("Target::%s the process instance doesn't currently exist.",
2826 launch_info.GetFlags().Set(eLaunchFlagDebug);
2828 // Get the value of synchronous execution here. If you wait till after you
2829 // have started to run, then you could have hit a breakpoint, whose command
2830 // might switch the value, and then you'll pick up that incorrect value.
2831 Debugger &debugger = GetDebugger();
2832 const bool synchronous_execution =
2833 debugger.GetCommandInterpreter().GetSynchronous();
2835 PlatformSP platform_sp(GetPlatform());
2837 FinalizeFileActions(launch_info);
2839 if (state == eStateConnected) {
2840 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2841 error.SetErrorString(
2842 "can't launch in tty when launching through a remote connection");
2847 if (!launch_info.GetArchitecture().IsValid())
2848 launch_info.GetArchitecture() = GetArchitecture();
2850 // If we're not already connected to the process, and if we have a platform
2851 // that can launch a process for debugging, go ahead and do that here.
2852 if (state != eStateConnected && platform_sp &&
2853 platform_sp->CanDebugProcess()) {
2855 log->Printf("Target::%s asking the platform to debug the process",
2858 // If there was a previous process, delete it before we make the new one.
2859 // One subtle point, we delete the process before we release the reference
2860 // to m_process_sp. That way even if we are the last owner, the process
2861 // will get Finalized before it gets destroyed.
2862 DeleteCurrentProcess();
2865 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2869 log->Printf("Target::%s the platform doesn't know how to debug a "
2870 "process, getting a process plugin to do this for us.",
2873 if (state == eStateConnected) {
2874 assert(m_process_sp);
2876 // Use a Process plugin to construct the process.
2877 const char *plugin_name = launch_info.GetProcessPluginName();
2878 CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
2881 // Since we didn't have a platform launch the process, launch it here.
2883 error = m_process_sp->Launch(launch_info);
2886 if (!m_process_sp) {
2887 if (error.Success())
2888 error.SetErrorString("failed to launch or debug process");
2892 if (error.Success()) {
2893 if (synchronous_execution ||
2894 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2895 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2896 if (!hijack_listener_sp) {
2897 hijack_listener_sp =
2898 Listener::MakeListener("lldb.Target.Launch.hijack");
2899 launch_info.SetHijackListener(hijack_listener_sp);
2900 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2903 StateType state = m_process_sp->WaitForProcessToStop(
2904 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
2906 if (state == eStateStopped) {
2907 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2908 if (synchronous_execution) {
2909 error = m_process_sp->PrivateResume();
2910 if (error.Success()) {
2911 state = m_process_sp->WaitForProcessToStop(
2912 llvm::None, nullptr, true, hijack_listener_sp, stream);
2913 const bool must_be_alive =
2914 false; // eStateExited is ok, so this must be false
2915 if (!StateIsStoppedState(state, must_be_alive)) {
2916 error.SetErrorStringWithFormat("process isn't stopped: %s",
2917 StateAsCString(state));
2921 m_process_sp->RestoreProcessEvents();
2922 error = m_process_sp->PrivateResume();
2924 if (!error.Success()) {
2926 error2.SetErrorStringWithFormat(
2927 "process resume at entry point failed: %s", error.AsCString());
2931 } else if (state == eStateExited) {
2932 bool with_shell = !!launch_info.GetShell();
2933 const int exit_status = m_process_sp->GetExitStatus();
2934 const char *exit_desc = m_process_sp->GetExitDescription();
2935 #define LAUNCH_SHELL_MESSAGE \
2936 "\n'r' and 'run' are aliases that default to launching through a " \
2937 "shell.\nTry launching without going through a shell by using 'process " \
2939 if (exit_desc && exit_desc[0]) {
2941 error.SetErrorStringWithFormat(
2942 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2943 exit_status, exit_desc);
2945 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2946 exit_status, exit_desc);
2949 error.SetErrorStringWithFormat(
2950 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2953 error.SetErrorStringWithFormat("process exited with status %i",
2957 error.SetErrorStringWithFormat(
2958 "initial process state wasn't stopped: %s", StateAsCString(state));
2961 m_process_sp->RestoreProcessEvents();
2964 error2.SetErrorStringWithFormat("process launch failed: %s",
2971 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
2972 auto state = eStateInvalid;
2973 auto process_sp = GetProcessSP();
2975 state = process_sp->GetState();
2976 if (process_sp->IsAlive() && state != eStateConnected) {
2977 if (state == eStateAttaching)
2978 return Status("process attach is in progress");
2979 return Status("a process is already being debugged");
2983 const ModuleSP old_exec_module_sp = GetExecutableModule();
2985 // If no process info was specified, then use the target executable name as
2986 // the process to attach to by default
2987 if (!attach_info.ProcessInfoSpecified()) {
2988 if (old_exec_module_sp)
2989 attach_info.GetExecutableFile().GetFilename() =
2990 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
2992 if (!attach_info.ProcessInfoSpecified()) {
2993 return Status("no process specified, create a target with a file, or "
2994 "specify the --pid or --name");
2998 const auto platform_sp =
2999 GetDebugger().GetPlatformList().GetSelectedPlatform();
3000 ListenerSP hijack_listener_sp;
3001 const bool async = attach_info.GetAsync();
3003 hijack_listener_sp =
3004 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3005 attach_info.SetHijackListener(hijack_listener_sp);
3009 if (state != eStateConnected && platform_sp != nullptr &&
3010 platform_sp->CanDebugProcess()) {
3011 SetPlatform(platform_sp);
3012 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3014 if (state != eStateConnected) {
3015 const char *plugin_name = attach_info.GetProcessPluginName();
3017 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3018 plugin_name, nullptr);
3019 if (process_sp == nullptr) {
3020 error.SetErrorStringWithFormat(
3021 "failed to create process using plugin %s",
3022 (plugin_name) ? plugin_name : "null");
3026 if (hijack_listener_sp)
3027 process_sp->HijackProcessEvents(hijack_listener_sp);
3028 error = process_sp->Attach(attach_info);
3031 if (error.Success() && process_sp) {
3033 process_sp->RestoreProcessEvents();
3035 state = process_sp->WaitForProcessToStop(
3036 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3037 process_sp->RestoreProcessEvents();
3039 if (state != eStateStopped) {
3040 const char *exit_desc = process_sp->GetExitDescription();
3042 error.SetErrorStringWithFormat("%s", exit_desc);
3044 error.SetErrorString(
3045 "process did not stop (no such process or permission problem?)");
3046 process_sp->Destroy(false);
3053 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3054 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3056 // Finalize the file actions, and if none were given, default to opening up a
3058 PlatformSP platform_sp = GetPlatform();
3059 const bool default_to_use_pty =
3060 m_platform_sp ? m_platform_sp->IsHost() : false;
3063 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3065 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3066 default_to_use_pty);
3068 // If nothing for stdin or stdout or stderr was specified, then check the
3069 // process for any default settings that were set with "settings set"
3070 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3071 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3072 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3073 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3074 "default handling");
3076 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3077 // Do nothing, if we are launching in a remote terminal no file actions
3078 // should be done at all.
3082 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3083 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3084 "for stdin, stdout and stderr");
3085 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3086 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3087 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3089 // Check for any values that might have gotten set with any of: (lldb)
3090 // settings set target.input-path (lldb) settings set target.output-path
3091 // (lldb) settings set target.error-path
3092 FileSpec in_file_spec;
3093 FileSpec out_file_spec;
3094 FileSpec err_file_spec;
3095 // Only override with the target settings if we don't already have an
3096 // action for in, out or error
3097 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3098 in_file_spec = GetStandardInputPath();
3099 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3100 out_file_spec = GetStandardOutputPath();
3101 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3102 err_file_spec = GetStandardErrorPath();
3104 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3105 in_file_spec, out_file_spec, err_file_spec);
3108 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3109 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3112 if (out_file_spec) {
3113 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3114 LLDB_LOG(log, "appended stdout open file action for {0}",
3118 if (err_file_spec) {
3119 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3120 LLDB_LOG(log, "appended stderr open file action for {0}",
3124 if (default_to_use_pty &&
3125 (!in_file_spec || !out_file_spec || !err_file_spec)) {
3126 llvm::Error Err = info.SetUpPtyRedirection();
3127 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3133 //--------------------------------------------------------------
3135 //--------------------------------------------------------------
3136 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3137 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3138 m_thread_spec_ap(), m_active(true) {}
3140 Target::StopHook::StopHook(const StopHook &rhs)
3141 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3142 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3143 m_thread_spec_ap(), m_active(rhs.m_active) {
3144 if (rhs.m_thread_spec_ap)
3145 m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
3148 Target::StopHook::~StopHook() = default;
3150 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3151 m_specifier_sp.reset(specifier);
3154 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3155 m_thread_spec_ap.reset(specifier);
3158 void Target::StopHook::GetDescription(Stream *s,
3159 lldb::DescriptionLevel level) const {
3160 int indent_level = s->GetIndentLevel();
3162 s->SetIndentLevel(indent_level + 2);
3164 s->Printf("Hook: %" PRIu64 "\n", GetID());
3166 s->Indent("State: enabled\n");
3168 s->Indent("State: disabled\n");
3170 if (m_specifier_sp) {
3172 s->PutCString("Specifier:\n");
3173 s->SetIndentLevel(indent_level + 4);
3174 m_specifier_sp->GetDescription(s, level);
3175 s->SetIndentLevel(indent_level + 2);
3178 if (m_thread_spec_ap) {
3180 s->Indent("Thread:\n");
3181 m_thread_spec_ap->GetDescription(&tmp, level);
3182 s->SetIndentLevel(indent_level + 4);
3183 s->Indent(tmp.GetString());
3184 s->PutCString("\n");
3185 s->SetIndentLevel(indent_level + 2);
3188 s->Indent("Commands: \n");
3189 s->SetIndentLevel(indent_level + 4);
3190 uint32_t num_commands = m_commands.GetSize();
3191 for (uint32_t i = 0; i < num_commands; i++) {
3192 s->Indent(m_commands.GetStringAtIndex(i));
3193 s->PutCString("\n");
3195 s->SetIndentLevel(indent_level);
3198 //--------------------------------------------------------------
3199 // class TargetProperties
3200 //--------------------------------------------------------------
3203 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3204 {eNoDynamicValues, "no-dynamic-values",
3205 "Don't calculate the dynamic type of values"},
3206 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3207 "even if you have to run the target."},
3208 {eDynamicDontRunTarget, "no-run-target",
3209 "Calculate the dynamic type of values, but don't run the target."} };
3211 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3212 return OptionEnumValues(g_dynamic_value_types);
3215 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3216 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3217 "locations (fastest). This setting "
3218 "should only be used if you know that "
3219 "no inlining occurs in your programs."},
3220 {eInlineBreakpointsHeaders, "headers",
3221 "Only check for inline breakpoint locations when setting breakpoints in "
3222 "header files, but not when setting breakpoint in implementation source "
3223 "files (default)."},
3224 {eInlineBreakpointsAlways, "always",
3225 "Always look for inline breakpoint locations when setting file and line "
3226 "breakpoints (slower but most accurate)."} };
3228 typedef enum x86DisassemblyFlavor {
3229 eX86DisFlavorDefault,
3232 } x86DisassemblyFlavor;
3234 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3235 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3236 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3237 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."} };
3239 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3240 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3241 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."} };
3243 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3244 {eLoadScriptFromSymFileTrue, "true",
3245 "Load debug scripts inside symbol files"},
3246 {eLoadScriptFromSymFileFalse, "false",
3247 "Do not load debug scripts inside symbol files."},
3248 {eLoadScriptFromSymFileWarn, "warn",
3249 "Warn about debug scripts inside symbol files but do not load them."} };
3252 OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3253 {eLoadCWDlldbinitTrue, "true",
3254 "Load .lldbinit files from current directory"},
3255 {eLoadCWDlldbinitFalse, "false",
3256 "Do not load .lldbinit files from current directory"},
3257 {eLoadCWDlldbinitWarn, "warn",
3258 "Warn about loading .lldbinit files from current directory"} };
3260 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3261 {eMemoryModuleLoadLevelMinimal, "minimal",
3262 "Load minimal information when loading modules from memory. Currently "
3263 "this setting loads sections only."},
3264 {eMemoryModuleLoadLevelPartial, "partial",
3265 "Load partial information when loading modules from memory. Currently "
3266 "this setting loads sections and function bounds."},
3267 {eMemoryModuleLoadLevelComplete, "complete",
3268 "Load complete information when loading modules from memory. Currently "
3269 "this setting loads sections and all symbols."} };
3271 static constexpr PropertyDefinition g_properties[] = {
3272 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, {},
3273 "Default architecture to choose, when there's a choice."},
3274 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3275 {}, "Move breakpoints to nearest code."},
3276 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3278 "The language to use when interpreting expressions entered in commands."},
3279 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
3280 "Path to a file containing expressions to be prepended to all "
3282 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3283 eDynamicDontRunTarget, nullptr, OptionEnumValues(g_dynamic_value_types),
3284 "Should printed values be shown as their dynamic value."},
3285 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3286 {}, "Should synthetic values be used by default whenever available."},
3287 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, {},
3288 "Skip function prologues when setting breakpoints by name."},
3289 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, {},
3290 "Source path remappings are used to track the change of location between "
3291 "a source file when built, and "
3292 "where it exists on the current system. It consists of an array of "
3293 "duples, the first element of each duple is "
3294 "some part (starting at the root) of the path to the file when it was "
3296 "and the second is where the remainder of the original build hierarchy is "
3297 "rooted on the local system. "
3298 "Each element of the array is checked in order and the first one that "
3299 "results in a match wins."},
3300 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3301 {}, "Executable search paths to use when locating executable files "
3302 "whose paths don't match the local file system."},
3303 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3305 "List of directories to be searched when locating debug symbol files. "
3306 "See also symbols.enable-external-lookup."},
3307 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3309 "List of directories to be searched when locating modules for Clang."},
3310 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3312 "Automatically load Clang modules referred to by the program."},
3313 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3314 {}, "Automatically apply fix-it hints to expressions."},
3315 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3316 {}, "Print the fixed expression text."},
3317 {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
3318 {}, "Save intermediate object files generated by the LLVM JIT"},
3319 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3320 {}, "Maximum number of children to expand in any level of depth."},
3321 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3323 "Maximum number of characters to show when using %s in summary strings."},
3324 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3325 {}, "Maximum number of bytes that 'memory read' will fetch before "
3326 "--force must be specified."},
3327 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3328 true, nullptr, {}, "Consult the platform module avoid list when "
3329 "setting non-module specific breakpoints."},
3330 {"arg0", OptionValue::eTypeString, false, 0, nullptr, {},
3331 "The first argument passed to the program in the argument array which can "
3332 "be different from the executable itself."},
3333 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, {},
3334 "A list containing all the arguments to be passed to the executable when "
3335 "it is run. Note that this does NOT include the argv[0] which is in "
3337 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3338 nullptr, {}, "A list of all the environment variables to be passed "
3339 "to the executable's environment, and their values."},
3340 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, {},
3341 "Inherit the environment from the process that is running LLDB."},
3342 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
3343 "The file/path to be used by the executable program for reading its "
3345 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
3346 "The file/path to be used by the executable program for writing its "
3347 "standard output."},
3348 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
3349 "The file/path to be used by the executable program for writing its "
3351 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3352 {}, "debugserver will detach (rather than killing) a process if it "
3353 "loses connection with lldb."},
3354 {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, {},
3355 "Enable loading of symbol tables before they are needed."},
3356 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, {},
3357 "Disable Address Space Layout Randomization (ASLR)"},
3358 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, {},
3359 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3360 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3361 eInlineBreakpointsAlways, nullptr,
3362 OptionEnumValues(g_inline_breakpoint_enums),
3363 "The strategy to use when settings breakpoints by file and line. "
3364 "Breakpoint locations can end up being inlined by the compiler, so that a "
3365 "compile unit 'a.c' might contain an inlined function from another source "
3367 "Usually this is limited to breakpoint locations from inlined functions "
3368 "from header or other include files, or more accurately "
3369 "non-implementation source files. "
3370 "Sometimes code might #include implementation files and cause inlined "
3371 "breakpoint locations in inlined implementation files. "
3372 "Always checking for inlined breakpoint locations can be expensive "
3373 "(memory and time), so if you have a project with many headers "
3374 "and find that setting breakpoints is slow, then you can change this "
3375 "setting to headers. "
3376 "This setting allows you to control exactly which strategy is used when "
3378 "file and line breakpoints."},
3379 // FIXME: This is the wrong way to do per-architecture settings, but we
3380 // don't have a general per architecture settings system in place yet.
3381 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3382 eX86DisFlavorDefault, nullptr,
3383 OptionEnumValues(g_x86_dis_flavor_value_types),
3384 "The default disassembly flavor to use for x86 or x86-64 targets."},
3385 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3386 {}, "Show immediates in disassembly as hexadecimal."},
3387 {"hex-immediate-style", OptionValue::eTypeEnum, false,
3388 Disassembler::eHexStyleC, nullptr,
3389 OptionEnumValues(g_hex_immediate_style_values),
3390 "Which style to use for printing hexadecimal disassembly values."},
3391 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3392 {}, "Use a fast stepping algorithm based on running from branch to "
3393 "branch rather than instruction single-stepping."},
3394 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3395 eLoadScriptFromSymFileWarn, nullptr,
3396 OptionEnumValues(g_load_script_from_sym_file_values),
3397 "Allow LLDB to load scripting resources embedded in symbol files when "
3399 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3400 nullptr, OptionEnumValues(g_load_current_working_dir_lldbinit_values),
3401 "Allow LLDB to .lldbinit files from the current directory automatically."},
3402 {"memory-module-load-level", OptionValue::eTypeEnum, false,
3403 eMemoryModuleLoadLevelComplete, nullptr,
3404 OptionEnumValues(g_memory_module_load_level_values),
3405 "Loading modules from memory can be slow as reading the symbol tables and "
3406 "other data can take a long time depending on your connection to the "
3408 "This setting helps users control how much information gets loaded when "
3409 "loading modules from memory."
3410 "'complete' is the default value for this setting which will load all "
3411 "sections and symbols by reading them from memory (slowest, most "
3413 "'partial' will load sections and attempt to find function bounds without "
3414 "downloading the symbol table (faster, still accurate, missing symbol "
3416 "'minimal' is the fastest setting and will load section data with no "
3417 "symbols, but should rarely be used as stack frames in these memory "
3418 "regions will be inaccurate and not provide any context (fastest). "},
3419 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3420 nullptr, {}, "Expressions that crash will show up in crash logs if "
3421 "the host system supports executable specific crash log "
3422 "strings and this setting is set to true."},
3423 {"trap-handler-names", OptionValue::eTypeArray, true,
3424 OptionValue::eTypeString, nullptr, {},
3425 "A list of trap handler function names, e.g. a common Unix user process "
3426 "one is _sigtramp."},
3427 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3428 nullptr, {}, "If true, LLDB will show variables that are meant to "
3429 "support the operation of a language's runtime support."},
3430 {"display-recognized-arguments", OptionValue::eTypeBoolean, false, false,
3431 nullptr, {}, "Show recognized arguments in variable listings by default."},
3432 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, {},
3433 "Disable lock-step debugging, instead control threads independently."},
3434 {"require-hardware-breakpoint", OptionValue::eTypeBoolean, false, 0,
3435 nullptr, {}, "Require all breakpoints to be hardware breakpoints."}};
3439 ePropertyDefaultArch,
3440 ePropertyMoveToNearestCode,
3442 ePropertyExprPrefix,
3443 ePropertyPreferDynamic,
3444 ePropertyEnableSynthetic,
3445 ePropertySkipPrologue,
3447 ePropertyExecutableSearchPaths,
3448 ePropertyDebugFileSearchPaths,
3449 ePropertyClangModuleSearchPaths,
3450 ePropertyAutoImportClangModules,
3451 ePropertyAutoApplyFixIts,
3452 ePropertyNotifyAboutFixIts,
3453 ePropertySaveObjects,
3454 ePropertyMaxChildrenCount,
3455 ePropertyMaxSummaryLength,
3456 ePropertyMaxMemReadSize,
3457 ePropertyBreakpointUseAvoidList,
3461 ePropertyInheritEnv,
3463 ePropertyOutputPath,
3465 ePropertyDetachOnError,
3466 ePropertyPreloadSymbols,
3467 ePropertyDisableASLR,
3468 ePropertyDisableSTDIO,
3469 ePropertyInlineStrategy,
3470 ePropertyDisassemblyFlavor,
3471 ePropertyUseHexImmediates,
3472 ePropertyHexImmediateStyle,
3473 ePropertyUseFastStepping,
3474 ePropertyLoadScriptFromSymbolFile,
3475 ePropertyLoadCWDlldbinitFile,
3476 ePropertyMemoryModuleLoadLevel,
3477 ePropertyDisplayExpressionsInCrashlogs,
3478 ePropertyTrapHandlerNames,
3479 ePropertyDisplayRuntimeSupportValues,
3480 ePropertyDisplayRecognizedArguments,
3481 ePropertyNonStopModeEnabled,
3482 ePropertyRequireHardwareBreakpoints,
3483 ePropertyExperimental,
3486 class TargetOptionValueProperties : public OptionValueProperties {
3488 TargetOptionValueProperties(const ConstString &name)
3489 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
3491 // This constructor is used when creating TargetOptionValueProperties when it
3492 // is part of a new lldb_private::Target instance. It will copy all current
3493 // global property values as needed
3494 TargetOptionValueProperties(Target *target,
3495 const TargetPropertiesSP &target_properties_sp)
3496 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3497 m_target(target), m_got_host_env(false) {}
3499 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3501 uint32_t idx) const override {
3502 // When getting the value for a key from the target options, we will always
3503 // try and grab the setting from the current target if there is one. Else
3504 // we just use the one from this instance.
3505 if (idx == ePropertyEnvVars)
3506 GetHostEnvironmentIfNeeded();
3509 Target *target = exe_ctx->GetTargetPtr();
3511 TargetOptionValueProperties *target_properties =
3512 static_cast<TargetOptionValueProperties *>(
3513 target->GetValueProperties().get());
3514 if (this != target_properties)
3515 return target_properties->ProtectedGetPropertyAtIndex(idx);
3518 return ProtectedGetPropertyAtIndex(idx);
3521 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3524 void GetHostEnvironmentIfNeeded() const {
3525 if (!m_got_host_env) {
3527 m_got_host_env = true;
3528 const uint32_t idx = ePropertyInheritEnv;
3529 if (GetPropertyAtIndexAsBoolean(
3530 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3531 PlatformSP platform_sp(m_target->GetPlatform());
3533 Environment env = platform_sp->GetEnvironment();
3534 OptionValueDictionary *env_dict =
3535 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3538 const bool can_replace = false;
3539 for (const auto &KV : env) {
3540 // Don't allow existing keys to be replaced with ones we get
3541 // from the platform environment
3542 env_dict->SetValueForKey(
3543 ConstString(KV.first()),
3544 OptionValueSP(new OptionValueString(KV.second.c_str())),
3554 mutable bool m_got_host_env;
3557 //----------------------------------------------------------------------
3559 //----------------------------------------------------------------------
3560 static constexpr PropertyDefinition g_experimental_properties[]{
3561 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3563 "If true, inject local variables explicitly into the expression text. "
3564 "This will fix symbol resolution when there are name collisions between "
3565 "ivars and local variables. "
3566 "But it can make expressions run much more slowly."},
3567 {"use-modern-type-lookup", OptionValue::eTypeBoolean, true, false, nullptr,
3568 {}, "If true, use Clang's modern type lookup infrastructure."}};
3570 enum { ePropertyInjectLocalVars = 0, ePropertyUseModernTypeLookup };
3572 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3574 TargetExperimentalOptionValueProperties()
3575 : OptionValueProperties(
3576 ConstString(Properties::GetExperimentalSettingsName())) {}
3579 TargetExperimentalProperties::TargetExperimentalProperties()
3580 : Properties(OptionValuePropertiesSP(
3581 new TargetExperimentalOptionValueProperties())) {
3582 m_collection_sp->Initialize(g_experimental_properties);
3585 //----------------------------------------------------------------------
3587 //----------------------------------------------------------------------
3588 TargetProperties::TargetProperties(Target *target)
3589 : Properties(), m_launch_info() {
3591 m_collection_sp.reset(
3592 new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
3594 // Set callbacks to update launch_info whenever "settins set" updated any
3595 // of these properties
3596 m_collection_sp->SetValueChangedCallback(
3597 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3598 m_collection_sp->SetValueChangedCallback(
3599 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3600 m_collection_sp->SetValueChangedCallback(
3601 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3602 m_collection_sp->SetValueChangedCallback(
3603 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3605 m_collection_sp->SetValueChangedCallback(
3606 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3608 m_collection_sp->SetValueChangedCallback(
3609 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3611 m_collection_sp->SetValueChangedCallback(
3612 ePropertyDetachOnError,
3613 TargetProperties::DetachOnErrorValueChangedCallback, this);
3614 m_collection_sp->SetValueChangedCallback(
3615 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3617 m_collection_sp->SetValueChangedCallback(
3618 ePropertyDisableSTDIO,
3619 TargetProperties::DisableSTDIOValueChangedCallback, this);
3621 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3622 m_collection_sp->AppendProperty(
3623 ConstString(Properties::GetExperimentalSettingsName()),
3624 ConstString("Experimental settings - setting these won't produce "
3625 "errors if the setting is not present."),
3626 true, m_experimental_properties_up->GetValueProperties());
3628 // Update m_launch_info once it was created
3629 Arg0ValueChangedCallback(this, nullptr);
3630 RunArgsValueChangedCallback(this, nullptr);
3631 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3632 // Target::GetPlatform()
3633 InputPathValueChangedCallback(this, nullptr);
3634 OutputPathValueChangedCallback(this, nullptr);
3635 ErrorPathValueChangedCallback(this, nullptr);
3636 DetachOnErrorValueChangedCallback(this, nullptr);
3637 DisableASLRValueChangedCallback(this, nullptr);
3638 DisableSTDIOValueChangedCallback(this, nullptr);
3640 m_collection_sp.reset(
3641 new TargetOptionValueProperties(ConstString("target")));
3642 m_collection_sp->Initialize(g_properties);
3643 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3644 m_collection_sp->AppendProperty(
3645 ConstString(Properties::GetExperimentalSettingsName()),
3646 ConstString("Experimental settings - setting these won't produce "
3647 "errors if the setting is not present."),
3648 true, m_experimental_properties_up->GetValueProperties());
3649 m_collection_sp->AppendProperty(
3650 ConstString("process"), ConstString("Settings specific to processes."),
3651 true, Process::GetGlobalProperties()->GetValueProperties());
3655 TargetProperties::~TargetProperties() = default;
3657 bool TargetProperties::GetInjectLocalVariables(
3658 ExecutionContext *exe_ctx) const {
3659 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3660 exe_ctx, false, ePropertyExperimental);
3661 OptionValueProperties *exp_values =
3662 exp_property->GetValue()->GetAsProperties();
3664 return exp_values->GetPropertyAtIndexAsBoolean(
3665 exe_ctx, ePropertyInjectLocalVars, true);
3670 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3672 const Property *exp_property =
3673 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3674 OptionValueProperties *exp_values =
3675 exp_property->GetValue()->GetAsProperties();
3677 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3681 bool TargetProperties::GetUseModernTypeLookup() const {
3682 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3683 nullptr, false, ePropertyExperimental);
3684 OptionValueProperties *exp_values =
3685 exp_property->GetValue()->GetAsProperties();
3687 return exp_values->GetPropertyAtIndexAsBoolean(
3688 nullptr, ePropertyUseModernTypeLookup, true);
3693 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3694 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3695 nullptr, ePropertyDefaultArch);
3697 return value->GetCurrentValue();
3701 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3702 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3703 nullptr, ePropertyDefaultArch);
3705 return value->SetCurrentValue(arch, true);
3708 bool TargetProperties::GetMoveToNearestCode() const {
3709 const uint32_t idx = ePropertyMoveToNearestCode;
3710 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3711 nullptr, idx, g_properties[idx].default_uint_value != 0);
3714 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3715 const uint32_t idx = ePropertyPreferDynamic;
3716 return (lldb::DynamicValueType)
3717 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3718 nullptr, idx, g_properties[idx].default_uint_value);
3721 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3722 const uint32_t idx = ePropertyPreferDynamic;
3723 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3726 bool TargetProperties::GetPreloadSymbols() const {
3727 const uint32_t idx = ePropertyPreloadSymbols;
3728 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3729 nullptr, idx, g_properties[idx].default_uint_value != 0);
3732 void TargetProperties::SetPreloadSymbols(bool b) {
3733 const uint32_t idx = ePropertyPreloadSymbols;
3734 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3737 bool TargetProperties::GetDisableASLR() const {
3738 const uint32_t idx = ePropertyDisableASLR;
3739 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3740 nullptr, idx, g_properties[idx].default_uint_value != 0);
3743 void TargetProperties::SetDisableASLR(bool b) {
3744 const uint32_t idx = ePropertyDisableASLR;
3745 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3748 bool TargetProperties::GetDetachOnError() const {
3749 const uint32_t idx = ePropertyDetachOnError;
3750 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3751 nullptr, idx, g_properties[idx].default_uint_value != 0);
3754 void TargetProperties::SetDetachOnError(bool b) {
3755 const uint32_t idx = ePropertyDetachOnError;
3756 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3759 bool TargetProperties::GetDisableSTDIO() const {
3760 const uint32_t idx = ePropertyDisableSTDIO;
3761 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3762 nullptr, idx, g_properties[idx].default_uint_value != 0);
3765 void TargetProperties::SetDisableSTDIO(bool b) {
3766 const uint32_t idx = ePropertyDisableSTDIO;
3767 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3770 const char *TargetProperties::GetDisassemblyFlavor() const {
3771 const uint32_t idx = ePropertyDisassemblyFlavor;
3772 const char *return_value;
3774 x86DisassemblyFlavor flavor_value =
3775 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3776 nullptr, idx, g_properties[idx].default_uint_value);
3777 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3778 return return_value;
3781 InlineStrategy TargetProperties::GetInlineStrategy() const {
3782 const uint32_t idx = ePropertyInlineStrategy;
3783 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3784 nullptr, idx, g_properties[idx].default_uint_value);
3787 llvm::StringRef TargetProperties::GetArg0() const {
3788 const uint32_t idx = ePropertyArg0;
3789 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
3792 void TargetProperties::SetArg0(llvm::StringRef arg) {
3793 const uint32_t idx = ePropertyArg0;
3794 m_collection_sp->SetPropertyAtIndexAsString(
3796 m_launch_info.SetArg0(arg);
3799 bool TargetProperties::GetRunArguments(Args &args) const {
3800 const uint32_t idx = ePropertyRunArgs;
3801 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3804 void TargetProperties::SetRunArguments(const Args &args) {
3805 const uint32_t idx = ePropertyRunArgs;
3806 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3807 m_launch_info.GetArguments() = args;
3810 Environment TargetProperties::GetEnvironment() const {
3811 // TODO: Get rid of the Args intermediate step
3813 const uint32_t idx = ePropertyEnvVars;
3814 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3815 return Environment(env);
3818 void TargetProperties::SetEnvironment(Environment env) {
3819 // TODO: Get rid of the Args intermediate step
3820 const uint32_t idx = ePropertyEnvVars;
3821 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3822 m_launch_info.GetEnvironment() = std::move(env);
3825 bool TargetProperties::GetSkipPrologue() const {
3826 const uint32_t idx = ePropertySkipPrologue;
3827 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3828 nullptr, idx, g_properties[idx].default_uint_value != 0);
3831 PathMappingList &TargetProperties::GetSourcePathMap() const {
3832 const uint32_t idx = ePropertySourceMap;
3833 OptionValuePathMappings *option_value =
3834 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3836 assert(option_value);
3837 return option_value->GetCurrentValue();
3840 FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3841 const uint32_t idx = ePropertyExecutableSearchPaths;
3842 OptionValueFileSpecList *option_value =
3843 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3845 assert(option_value);
3846 return option_value->GetCurrentValue();
3849 FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3850 const uint32_t idx = ePropertyDebugFileSearchPaths;
3851 OptionValueFileSpecList *option_value =
3852 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3854 assert(option_value);
3855 return option_value->GetCurrentValue();
3858 FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3859 const uint32_t idx = ePropertyClangModuleSearchPaths;
3860 OptionValueFileSpecList *option_value =
3861 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3863 assert(option_value);
3864 return option_value->GetCurrentValue();
3867 bool TargetProperties::GetEnableAutoImportClangModules() const {
3868 const uint32_t idx = ePropertyAutoImportClangModules;
3869 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3870 nullptr, idx, g_properties[idx].default_uint_value != 0);
3873 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3874 const uint32_t idx = ePropertyAutoApplyFixIts;
3875 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3876 nullptr, idx, g_properties[idx].default_uint_value != 0);
3879 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3880 const uint32_t idx = ePropertyNotifyAboutFixIts;
3881 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3882 nullptr, idx, g_properties[idx].default_uint_value != 0);
3885 bool TargetProperties::GetEnableSaveObjects() const {
3886 const uint32_t idx = ePropertySaveObjects;
3887 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3888 nullptr, idx, g_properties[idx].default_uint_value != 0);
3891 bool TargetProperties::GetEnableSyntheticValue() const {
3892 const uint32_t idx = ePropertyEnableSynthetic;
3893 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3894 nullptr, idx, g_properties[idx].default_uint_value != 0);
3897 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3898 const uint32_t idx = ePropertyMaxChildrenCount;
3899 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3900 nullptr, idx, g_properties[idx].default_uint_value);
3903 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3904 const uint32_t idx = ePropertyMaxSummaryLength;
3905 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3906 nullptr, idx, g_properties[idx].default_uint_value);
3909 uint32_t TargetProperties::GetMaximumMemReadSize() const {
3910 const uint32_t idx = ePropertyMaxMemReadSize;
3911 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3912 nullptr, idx, g_properties[idx].default_uint_value);
3915 FileSpec TargetProperties::GetStandardInputPath() const {
3916 const uint32_t idx = ePropertyInputPath;
3917 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3920 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
3921 const uint32_t idx = ePropertyInputPath;
3922 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3925 FileSpec TargetProperties::GetStandardOutputPath() const {
3926 const uint32_t idx = ePropertyOutputPath;
3927 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3930 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
3931 const uint32_t idx = ePropertyOutputPath;
3932 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3935 FileSpec TargetProperties::GetStandardErrorPath() const {
3936 const uint32_t idx = ePropertyErrorPath;
3937 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3940 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3941 const uint32_t idx = ePropertyErrorPath;
3942 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3945 LanguageType TargetProperties::GetLanguage() const {
3946 OptionValueLanguage *value =
3947 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3948 nullptr, ePropertyLanguage);
3950 return value->GetCurrentValue();
3951 return LanguageType();
3954 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
3955 const uint32_t idx = ePropertyExprPrefix;
3956 OptionValueFileSpec *file =
3957 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3960 DataBufferSP data_sp(file->GetFileContents());
3962 return llvm::StringRef(
3963 reinterpret_cast<const char *>(data_sp->GetBytes()),
3964 data_sp->GetByteSize());
3969 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3970 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3971 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3972 nullptr, idx, g_properties[idx].default_uint_value != 0);
3975 bool TargetProperties::GetUseHexImmediates() const {
3976 const uint32_t idx = ePropertyUseHexImmediates;
3977 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3978 nullptr, idx, g_properties[idx].default_uint_value != 0);
3981 bool TargetProperties::GetUseFastStepping() const {
3982 const uint32_t idx = ePropertyUseFastStepping;
3983 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3984 nullptr, idx, g_properties[idx].default_uint_value != 0);
3987 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3988 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3989 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3990 nullptr, idx, g_properties[idx].default_uint_value != 0);
3993 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3994 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3995 return (LoadScriptFromSymFile)
3996 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3997 nullptr, idx, g_properties[idx].default_uint_value);
4000 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4001 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4002 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4003 nullptr, idx, g_properties[idx].default_uint_value);
4006 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4007 const uint32_t idx = ePropertyHexImmediateStyle;
4008 return (Disassembler::HexImmediateStyle)
4009 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4010 nullptr, idx, g_properties[idx].default_uint_value);
4013 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4014 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4015 return (MemoryModuleLoadLevel)
4016 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4017 nullptr, idx, g_properties[idx].default_uint_value);
4020 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4021 const uint32_t idx = ePropertyTrapHandlerNames;
4022 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4025 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4026 const uint32_t idx = ePropertyTrapHandlerNames;
4027 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4030 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4031 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4032 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4035 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4036 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4037 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4040 bool TargetProperties::GetDisplayRecognizedArguments() const {
4041 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4042 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4045 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
4046 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4047 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4050 bool TargetProperties::GetNonStopModeEnabled() const {
4051 const uint32_t idx = ePropertyNonStopModeEnabled;
4052 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4055 void TargetProperties::SetNonStopModeEnabled(bool b) {
4056 const uint32_t idx = ePropertyNonStopModeEnabled;
4057 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4060 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
4061 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4062 return m_launch_info;
4065 void TargetProperties::SetProcessLaunchInfo(
4066 const ProcessLaunchInfo &launch_info) {
4067 m_launch_info = launch_info;
4068 SetArg0(launch_info.GetArg0());
4069 SetRunArguments(launch_info.GetArguments());
4070 SetEnvironment(launch_info.GetEnvironment());
4071 const FileAction *input_file_action =
4072 launch_info.GetFileActionForFD(STDIN_FILENO);
4073 if (input_file_action) {
4074 SetStandardInputPath(input_file_action->GetPath());
4076 const FileAction *output_file_action =
4077 launch_info.GetFileActionForFD(STDOUT_FILENO);
4078 if (output_file_action) {
4079 SetStandardOutputPath(output_file_action->GetPath());
4081 const FileAction *error_file_action =
4082 launch_info.GetFileActionForFD(STDERR_FILENO);
4083 if (error_file_action) {
4084 SetStandardErrorPath(error_file_action->GetPath());
4086 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4087 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4088 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4091 bool TargetProperties::GetRequireHardwareBreakpoints() const {
4092 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4093 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4094 nullptr, idx, g_properties[idx].default_uint_value != 0);
4097 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
4098 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4099 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4102 void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4104 TargetProperties *this_ =
4105 reinterpret_cast<TargetProperties *>(target_property_ptr);
4106 this_->m_launch_info.SetArg0(this_->GetArg0());
4109 void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4111 TargetProperties *this_ =
4112 reinterpret_cast<TargetProperties *>(target_property_ptr);
4114 if (this_->GetRunArguments(args))
4115 this_->m_launch_info.GetArguments() = args;
4118 void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4120 TargetProperties *this_ =
4121 reinterpret_cast<TargetProperties *>(target_property_ptr);
4122 this_->m_launch_info.GetEnvironment() = this_->GetEnvironment();
4125 void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4127 TargetProperties *this_ =
4128 reinterpret_cast<TargetProperties *>(target_property_ptr);
4129 this_->m_launch_info.AppendOpenFileAction(
4130 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
4133 void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4135 TargetProperties *this_ =
4136 reinterpret_cast<TargetProperties *>(target_property_ptr);
4137 this_->m_launch_info.AppendOpenFileAction(
4138 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
4141 void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4143 TargetProperties *this_ =
4144 reinterpret_cast<TargetProperties *>(target_property_ptr);
4145 this_->m_launch_info.AppendOpenFileAction(
4146 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
4149 void TargetProperties::DetachOnErrorValueChangedCallback(
4150 void *target_property_ptr, OptionValue *) {
4151 TargetProperties *this_ =
4152 reinterpret_cast<TargetProperties *>(target_property_ptr);
4153 if (this_->GetDetachOnError())
4154 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4156 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4159 void TargetProperties::DisableASLRValueChangedCallback(
4160 void *target_property_ptr, OptionValue *) {
4161 TargetProperties *this_ =
4162 reinterpret_cast<TargetProperties *>(target_property_ptr);
4163 if (this_->GetDisableASLR())
4164 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4166 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4169 void TargetProperties::DisableSTDIOValueChangedCallback(
4170 void *target_property_ptr, OptionValue *) {
4171 TargetProperties *this_ =
4172 reinterpret_cast<TargetProperties *>(target_property_ptr);
4173 if (this_->GetDisableSTDIO())
4174 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4176 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4179 //----------------------------------------------------------------------
4180 // Target::TargetEventData
4181 //----------------------------------------------------------------------
4183 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4184 : EventData(), m_target_sp(target_sp), m_module_list() {}
4186 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4187 const ModuleList &module_list)
4188 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4190 Target::TargetEventData::~TargetEventData() = default;
4192 const ConstString &Target::TargetEventData::GetFlavorString() {
4193 static ConstString g_flavor("Target::TargetEventData");
4197 void Target::TargetEventData::Dump(Stream *s) const {
4198 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4201 m_module_list.GetModuleAtIndex(i)->GetDescription(
4202 s, lldb::eDescriptionLevelBrief);
4206 const Target::TargetEventData *
4207 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4209 const EventData *event_data = event_ptr->GetData();
4211 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4212 return static_cast<const TargetEventData *>(event_ptr->GetData());
4217 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4219 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4221 target_sp = event_data->m_target_sp;
4226 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4227 ModuleList module_list;
4228 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4230 module_list = event_data->m_module_list;