1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Target/Target.h"
10 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
11 #include "lldb/Breakpoint/BreakpointIDList.h"
12 #include "lldb/Breakpoint/BreakpointPrecondition.h"
13 #include "lldb/Breakpoint/BreakpointResolver.h"
14 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
15 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
16 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
17 #include "lldb/Breakpoint/BreakpointResolverName.h"
18 #include "lldb/Breakpoint/BreakpointResolverScripted.h"
19 #include "lldb/Breakpoint/Watchpoint.h"
20 #include "lldb/Core/Debugger.h"
21 #include "lldb/Core/Module.h"
22 #include "lldb/Core/ModuleSpec.h"
23 #include "lldb/Core/PluginManager.h"
24 #include "lldb/Core/SearchFilter.h"
25 #include "lldb/Core/Section.h"
26 #include "lldb/Core/SourceManager.h"
27 #include "lldb/Core/StreamFile.h"
28 #include "lldb/Core/StructuredDataImpl.h"
29 #include "lldb/Core/ValueObject.h"
30 #include "lldb/Expression/REPL.h"
31 #include "lldb/Expression/UserExpression.h"
32 #include "lldb/Host/Host.h"
33 #include "lldb/Host/PosixApi.h"
34 #include "lldb/Interpreter/CommandInterpreter.h"
35 #include "lldb/Interpreter/CommandReturnObject.h"
36 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
37 #include "lldb/Interpreter/OptionValues.h"
38 #include "lldb/Interpreter/Property.h"
39 #include "lldb/Symbol/ClangASTContext.h"
40 #include "lldb/Symbol/ClangASTImporter.h"
41 #include "lldb/Symbol/Function.h"
42 #include "lldb/Symbol/ObjectFile.h"
43 #include "lldb/Symbol/Symbol.h"
44 #include "lldb/Target/Language.h"
45 #include "lldb/Target/LanguageRuntime.h"
46 #include "lldb/Target/Process.h"
47 #include "lldb/Target/SectionLoadList.h"
48 #include "lldb/Target/StackFrame.h"
49 #include "lldb/Target/SystemRuntime.h"
50 #include "lldb/Target/Thread.h"
51 #include "lldb/Target/ThreadSpec.h"
52 #include "lldb/Utility/Event.h"
53 #include "lldb/Utility/FileSpec.h"
54 #include "lldb/Utility/LLDBAssert.h"
55 #include "lldb/Utility/Log.h"
56 #include "lldb/Utility/State.h"
57 #include "lldb/Utility/StreamString.h"
58 #include "lldb/Utility/Timer.h"
60 #include "llvm/ADT/ScopeExit.h"
66 using namespace lldb_private;
68 constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
70 Target::Arch::Arch(const ArchSpec &spec)
72 m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
74 const Target::Arch& Target::Arch::operator=(const ArchSpec &spec) {
76 m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
80 ConstString &Target::GetStaticBroadcasterClass() {
81 static ConstString class_name("lldb.target");
85 Target::Target(Debugger &debugger, const ArchSpec &target_arch,
86 const lldb::PlatformSP &platform_sp, bool is_dummy_target)
87 : TargetProperties(this),
88 Broadcaster(debugger.GetBroadcasterManager(),
89 Target::GetStaticBroadcasterClass().AsCString()),
90 ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
91 m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
92 m_breakpoint_list(false), m_internal_breakpoint_list(true),
93 m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
94 m_image_search_paths(ImageSearchPathsChanged, this), m_ast_importer_sp(),
95 m_source_manager_up(), m_stop_hooks(), m_stop_hook_next_id(0),
96 m_valid(true), m_suppress_stop_hooks(false),
97 m_is_dummy_target(is_dummy_target),
98 m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
101 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
102 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
103 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
104 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
105 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
107 CheckInWithManager();
109 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
111 log->Printf("%p Target::Target()", static_cast<void *>(this));
112 if (target_arch.IsValid()) {
113 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET,
114 "Target::Target created with architecture %s (%s)",
115 target_arch.GetArchitectureName(),
116 target_arch.GetTriple().getTriple().c_str());
121 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
123 log->Printf("%p Target::~Target()", static_cast<void *>(this));
124 DeleteCurrentProcess();
127 void Target::PrimeFromDummyTarget(Target *target) {
131 m_stop_hooks = target->m_stop_hooks;
133 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
134 if (breakpoint_sp->IsInternal())
137 BreakpointSP new_bp(new Breakpoint(*this, *breakpoint_sp.get()));
138 AddBreakpoint(new_bp, false);
141 for (auto bp_name_entry : target->m_breakpoint_names)
144 BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
145 AddBreakpointName(new_bp_name);
149 void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
150 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
151 if (description_level != lldb::eDescriptionLevelBrief) {
153 s->PutCString("Target\n");
156 m_breakpoint_list.Dump(s);
157 m_internal_breakpoint_list.Dump(s);
160 Module *exe_module = GetExecutableModulePointer();
162 s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
164 s->PutCString("No executable module.");
168 void Target::CleanupProcess() {
169 // Do any cleanup of the target we need to do between process instances.
170 // NB It is better to do this before destroying the process in case the
171 // clean up needs some help from the process.
172 m_breakpoint_list.ClearAllBreakpointSites();
173 m_internal_breakpoint_list.ClearAllBreakpointSites();
174 // Disable watchpoints just on the debugger side.
175 std::unique_lock<std::recursive_mutex> lock;
176 this->GetWatchpointList().GetListMutex(lock);
177 DisableAllWatchpoints(false);
178 ClearAllWatchpointHitCounts();
179 ClearAllWatchpointHistoricValues();
182 void Target::DeleteCurrentProcess() {
184 m_section_load_history.Clear();
185 if (m_process_sp->IsAlive())
186 m_process_sp->Destroy(false);
188 m_process_sp->Finalize();
192 m_process_sp.reset();
196 const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
197 llvm::StringRef plugin_name,
198 const FileSpec *crash_file) {
200 listener_sp = GetDebugger().GetListener();
201 DeleteCurrentProcess();
202 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name,
203 listener_sp, crash_file);
207 const lldb::ProcessSP &Target::GetProcessSP() const { return m_process_sp; }
209 lldb::REPLSP Target::GetREPL(Status &err, lldb::LanguageType language,
210 const char *repl_options, bool can_create) {
211 if (language == eLanguageTypeUnknown) {
212 std::set<LanguageType> repl_languages;
214 Language::GetLanguagesSupportingREPLs(repl_languages);
216 if (repl_languages.size() == 1) {
217 language = *repl_languages.begin();
218 } else if (repl_languages.size() == 0) {
219 err.SetErrorStringWithFormat(
220 "LLDB isn't configured with REPL support for any languages.");
223 err.SetErrorStringWithFormat(
224 "Multiple possible REPL languages. Please specify a language.");
229 REPLMap::iterator pos = m_repl_map.find(language);
231 if (pos != m_repl_map.end()) {
236 err.SetErrorStringWithFormat(
237 "Couldn't find an existing REPL for %s, and can't create a new one",
238 Language::GetNameForLanguageType(language));
239 return lldb::REPLSP();
242 Debugger *const debugger = nullptr;
243 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
246 m_repl_map[language] = ret;
247 return m_repl_map[language];
251 err.SetErrorStringWithFormat("Couldn't create a REPL for %s",
252 Language::GetNameForLanguageType(language));
255 return lldb::REPLSP();
258 void Target::SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp) {
259 lldbassert(!m_repl_map.count(language));
261 m_repl_map[language] = repl_sp;
264 void Target::Destroy() {
265 std::lock_guard<std::recursive_mutex> guard(m_mutex);
267 DeleteCurrentProcess();
268 m_platform_sp.reset();
271 m_section_load_history.Clear();
272 const bool notify = false;
273 m_breakpoint_list.RemoveAll(notify);
274 m_internal_breakpoint_list.RemoveAll(notify);
275 m_last_created_breakpoint.reset();
276 m_last_created_watchpoint.reset();
277 m_search_filter_sp.reset();
278 m_image_search_paths.Clear(notify);
279 m_stop_hooks.clear();
280 m_stop_hook_next_id = 0;
281 m_suppress_stop_hooks = false;
284 BreakpointList &Target::GetBreakpointList(bool internal) {
286 return m_internal_breakpoint_list;
288 return m_breakpoint_list;
291 const BreakpointList &Target::GetBreakpointList(bool internal) const {
293 return m_internal_breakpoint_list;
295 return m_breakpoint_list;
298 BreakpointSP Target::GetBreakpointByID(break_id_t break_id) {
301 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
302 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
304 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
309 BreakpointSP Target::CreateSourceRegexBreakpoint(
310 const FileSpecList *containingModules,
311 const FileSpecList *source_file_spec_list,
312 const std::unordered_set<std::string> &function_names,
313 RegularExpression &source_regex, bool internal, bool hardware,
314 LazyBool move_to_nearest_code) {
315 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
316 containingModules, source_file_spec_list));
317 if (move_to_nearest_code == eLazyBoolCalculate)
318 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
319 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(
320 nullptr, source_regex, function_names,
321 !static_cast<bool>(move_to_nearest_code)));
323 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
326 BreakpointSP Target::CreateBreakpoint(const FileSpecList *containingModules,
327 const FileSpec &file, uint32_t line_no,
328 uint32_t column, lldb::addr_t offset,
329 LazyBool check_inlines,
330 LazyBool skip_prologue, bool internal,
332 LazyBool move_to_nearest_code) {
333 FileSpec remapped_file;
334 if (!GetSourcePathMap().ReverseRemapPath(file, remapped_file))
335 remapped_file = file;
337 if (check_inlines == eLazyBoolCalculate) {
338 const InlineStrategy inline_strategy = GetInlineStrategy();
339 switch (inline_strategy) {
340 case eInlineBreakpointsNever:
341 check_inlines = eLazyBoolNo;
344 case eInlineBreakpointsHeaders:
345 if (remapped_file.IsSourceImplementationFile())
346 check_inlines = eLazyBoolNo;
348 check_inlines = eLazyBoolYes;
351 case eInlineBreakpointsAlways:
352 check_inlines = eLazyBoolYes;
356 SearchFilterSP filter_sp;
357 if (check_inlines == eLazyBoolNo) {
358 // Not checking for inlines, we are looking only for matching compile units
359 FileSpecList compile_unit_list;
360 compile_unit_list.Append(remapped_file);
361 filter_sp = GetSearchFilterForModuleAndCUList(containingModules,
364 filter_sp = GetSearchFilterForModuleList(containingModules);
366 if (skip_prologue == eLazyBoolCalculate)
367 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
368 if (move_to_nearest_code == eLazyBoolCalculate)
369 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
371 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine(
372 nullptr, remapped_file, line_no, column, offset, check_inlines,
373 skip_prologue, !static_cast<bool>(move_to_nearest_code)));
374 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
377 BreakpointSP Target::CreateBreakpoint(lldb::addr_t addr, bool internal,
381 // Check for any reason we want to move this breakpoint to other address.
382 addr = GetBreakableLoadAddress(addr);
384 // Attempt to resolve our load address if possible, though it is ok if it
385 // doesn't resolve to section/offset.
387 // Try and resolve as a load address if possible
388 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
389 if (!so_addr.IsValid()) {
390 // The address didn't resolve, so just set this as an absolute address
391 so_addr.SetOffset(addr);
393 BreakpointSP bp_sp(CreateBreakpoint(so_addr, internal, hardware));
397 BreakpointSP Target::CreateBreakpoint(const Address &addr, bool internal,
399 SearchFilterSP filter_sp(
400 new SearchFilterForUnconstrainedSearches(shared_from_this()));
401 BreakpointResolverSP resolver_sp(
402 new BreakpointResolverAddress(nullptr, addr));
403 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, false);
407 Target::CreateAddressInModuleBreakpoint(lldb::addr_t file_addr, bool internal,
408 const FileSpec *file_spec,
409 bool request_hardware) {
410 SearchFilterSP filter_sp(
411 new SearchFilterForUnconstrainedSearches(shared_from_this()));
412 BreakpointResolverSP resolver_sp(
413 new BreakpointResolverAddress(nullptr, file_addr, file_spec));
414 return CreateBreakpoint(filter_sp, resolver_sp, internal, request_hardware,
418 BreakpointSP Target::CreateBreakpoint(
419 const FileSpecList *containingModules,
420 const FileSpecList *containingSourceFiles, const char *func_name,
421 FunctionNameType func_name_type_mask, LanguageType language,
422 lldb::addr_t offset, LazyBool skip_prologue, bool internal, bool hardware) {
425 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
426 containingModules, containingSourceFiles));
428 if (skip_prologue == eLazyBoolCalculate)
429 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
430 if (language == lldb::eLanguageTypeUnknown)
431 language = GetLanguage();
433 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
434 nullptr, func_name, func_name_type_mask, language, Breakpoint::Exact,
435 offset, skip_prologue));
436 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
442 Target::CreateBreakpoint(const FileSpecList *containingModules,
443 const FileSpecList *containingSourceFiles,
444 const std::vector<std::string> &func_names,
445 FunctionNameType func_name_type_mask,
446 LanguageType language, lldb::addr_t offset,
447 LazyBool skip_prologue, bool internal, bool hardware) {
449 size_t num_names = func_names.size();
451 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
452 containingModules, containingSourceFiles));
454 if (skip_prologue == eLazyBoolCalculate)
455 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
456 if (language == lldb::eLanguageTypeUnknown)
457 language = GetLanguage();
459 BreakpointResolverSP resolver_sp(
460 new BreakpointResolverName(nullptr, func_names, func_name_type_mask,
461 language, offset, skip_prologue));
462 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
468 Target::CreateBreakpoint(const FileSpecList *containingModules,
469 const FileSpecList *containingSourceFiles,
470 const char *func_names[], size_t num_names,
471 FunctionNameType func_name_type_mask,
472 LanguageType language, lldb::addr_t offset,
473 LazyBool skip_prologue, bool internal, bool hardware) {
476 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
477 containingModules, containingSourceFiles));
479 if (skip_prologue == eLazyBoolCalculate) {
481 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
483 skip_prologue = eLazyBoolNo;
485 if (language == lldb::eLanguageTypeUnknown)
486 language = GetLanguage();
488 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
489 nullptr, func_names, num_names, func_name_type_mask, language, offset,
491 resolver_sp->SetOffset(offset);
492 bp_sp = CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
498 Target::GetSearchFilterForModule(const FileSpec *containingModule) {
499 SearchFilterSP filter_sp;
500 if (containingModule != nullptr) {
501 // TODO: We should look into sharing module based search filters
502 // across many breakpoints like we do for the simple target based one
503 filter_sp = std::make_shared<SearchFilterByModule>(shared_from_this(),
506 if (!m_search_filter_sp)
508 std::make_shared<SearchFilterForUnconstrainedSearches>(
510 filter_sp = m_search_filter_sp;
516 Target::GetSearchFilterForModuleList(const FileSpecList *containingModules) {
517 SearchFilterSP filter_sp;
518 if (containingModules && containingModules->GetSize() != 0) {
519 // TODO: We should look into sharing module based search filters
520 // across many breakpoints like we do for the simple target based one
521 filter_sp = std::make_shared<SearchFilterByModuleList>(shared_from_this(),
524 if (!m_search_filter_sp)
526 std::make_shared<SearchFilterForUnconstrainedSearches>(
528 filter_sp = m_search_filter_sp;
533 SearchFilterSP Target::GetSearchFilterForModuleAndCUList(
534 const FileSpecList *containingModules,
535 const FileSpecList *containingSourceFiles) {
536 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
537 return GetSearchFilterForModuleList(containingModules);
539 SearchFilterSP filter_sp;
540 if (containingModules == nullptr) {
541 // We could make a special "CU List only SearchFilter". Better yet was if
542 // these could be composable, but that will take a little reworking.
544 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
545 shared_from_this(), FileSpecList(), *containingSourceFiles);
547 filter_sp = std::make_shared<SearchFilterByModuleListAndCU>(
548 shared_from_this(), *containingModules, *containingSourceFiles);
553 BreakpointSP Target::CreateFuncRegexBreakpoint(
554 const FileSpecList *containingModules,
555 const FileSpecList *containingSourceFiles, RegularExpression &func_regex,
556 lldb::LanguageType requested_language, LazyBool skip_prologue,
557 bool internal, bool hardware) {
558 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList(
559 containingModules, containingSourceFiles));
560 bool skip = (skip_prologue == eLazyBoolCalculate)
562 : static_cast<bool>(skip_prologue);
563 BreakpointResolverSP resolver_sp(new BreakpointResolverName(
564 nullptr, func_regex, requested_language, 0, skip));
566 return CreateBreakpoint(filter_sp, resolver_sp, internal, hardware, true);
570 Target::CreateExceptionBreakpoint(enum lldb::LanguageType language,
571 bool catch_bp, bool throw_bp, bool internal,
572 Args *additional_args, Status *error) {
573 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint(
574 *this, language, catch_bp, throw_bp, internal);
575 if (exc_bkpt_sp && additional_args) {
576 BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
577 if (precondition_sp && additional_args) {
579 *error = precondition_sp->ConfigurePrecondition(*additional_args);
581 precondition_sp->ConfigurePrecondition(*additional_args);
588 Target::CreateScriptedBreakpoint(const llvm::StringRef class_name,
589 const FileSpecList *containingModules,
590 const FileSpecList *containingSourceFiles,
592 bool request_hardware,
593 StructuredData::ObjectSP extra_args_sp,
594 Status *creation_error)
596 SearchFilterSP filter_sp;
598 lldb::SearchDepth depth = lldb::eSearchDepthTarget;
599 bool has_files = containingSourceFiles && containingSourceFiles->GetSize() > 0;
600 bool has_modules = containingModules && containingModules->GetSize() > 0;
602 if (has_files && has_modules) {
603 filter_sp = GetSearchFilterForModuleAndCUList(
604 containingModules, containingSourceFiles);
605 } else if (has_files) {
606 filter_sp = GetSearchFilterForModuleAndCUList(
607 nullptr, containingSourceFiles);
608 } else if (has_modules) {
609 filter_sp = GetSearchFilterForModuleList(containingModules);
611 filter_sp = std::make_shared<SearchFilterForUnconstrainedSearches>(
615 StructuredDataImpl *extra_args_impl = new StructuredDataImpl();
617 extra_args_impl->SetObjectSP(extra_args_sp);
619 BreakpointResolverSP resolver_sp(new BreakpointResolverScripted(
620 nullptr, class_name, depth, extra_args_impl,
621 *GetDebugger().GetScriptInterpreter()));
622 return CreateBreakpoint(filter_sp, resolver_sp, internal, false, true);
627 BreakpointSP Target::CreateBreakpoint(SearchFilterSP &filter_sp,
628 BreakpointResolverSP &resolver_sp,
629 bool internal, bool request_hardware,
630 bool resolve_indirect_symbols) {
632 if (filter_sp && resolver_sp) {
633 const bool hardware = request_hardware || GetRequireHardwareBreakpoints();
634 bp_sp.reset(new Breakpoint(*this, filter_sp, resolver_sp, hardware,
635 resolve_indirect_symbols));
636 resolver_sp->SetBreakpoint(bp_sp.get());
637 AddBreakpoint(bp_sp, internal);
642 void Target::AddBreakpoint(lldb::BreakpointSP bp_sp, bool internal) {
646 m_internal_breakpoint_list.Add(bp_sp, false);
648 m_breakpoint_list.Add(bp_sp, true);
650 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
653 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
654 log->Printf("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__,
655 bp_sp->IsInternal() ? "yes" : "no", s.GetData());
658 bp_sp->ResolveBreakpoint();
661 m_last_created_breakpoint = bp_sp;
665 void Target::AddNameToBreakpoint(BreakpointID &id,
670 = m_breakpoint_list.FindBreakpointByID(id.GetBreakpointID());
674 id.GetDescription(&s, eDescriptionLevelBrief);
675 error.SetErrorStringWithFormat("Could not find breakpoint %s",
679 AddNameToBreakpoint(bp_sp, name, error);
682 void Target::AddNameToBreakpoint(BreakpointSP &bp_sp,
689 BreakpointName *bp_name = FindBreakpointName(ConstString(name), true, error);
693 bp_name->ConfigureBreakpoint(bp_sp);
694 bp_sp->AddName(name);
697 void Target::AddBreakpointName(BreakpointName *bp_name) {
698 m_breakpoint_names.insert(std::make_pair(bp_name->GetName(), bp_name));
701 BreakpointName *Target::FindBreakpointName(ConstString name,
705 BreakpointID::StringIsBreakpointName(name.GetStringRef(), error);
706 if (!error.Success())
709 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
710 if (iter == m_breakpoint_names.end()) {
713 error.SetErrorStringWithFormat("Breakpoint name \"%s\" doesn't exist and "
714 "can_create is false.", name.AsCString());
718 iter = m_breakpoint_names.insert(std::make_pair(name,
719 new BreakpointName(name)))
722 return (iter->second);
726 Target::DeleteBreakpointName(ConstString name)
728 BreakpointNameList::iterator iter = m_breakpoint_names.find(name);
730 if (iter != m_breakpoint_names.end()) {
731 const char *name_cstr = name.AsCString();
732 m_breakpoint_names.erase(iter);
733 for (auto bp_sp : m_breakpoint_list.Breakpoints())
734 bp_sp->RemoveName(name_cstr);
738 void Target::RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
741 bp_sp->RemoveName(name.AsCString());
744 void Target::ConfigureBreakpointName(BreakpointName &bp_name,
745 const BreakpointOptions &new_options,
746 const BreakpointName::Permissions &new_permissions)
748 bp_name.GetOptions().CopyOverSetOptions(new_options);
749 bp_name.GetPermissions().MergeInto(new_permissions);
750 ApplyNameToBreakpoints(bp_name);
753 void Target::ApplyNameToBreakpoints(BreakpointName &bp_name) {
754 BreakpointList bkpts_with_name(false);
755 m_breakpoint_list.FindBreakpointsByName(bp_name.GetName().AsCString(),
758 for (auto bp_sp : bkpts_with_name.Breakpoints())
759 bp_name.ConfigureBreakpoint(bp_sp);
762 void Target::GetBreakpointNames(std::vector<std::string> &names)
765 for (auto bp_name : m_breakpoint_names) {
766 names.push_back(bp_name.first.AsCString());
768 llvm::sort(names.begin(), names.end());
771 bool Target::ProcessIsValid() {
772 return (m_process_sp && m_process_sp->IsAlive());
775 static bool CheckIfWatchpointsSupported(Target *target, Status &error) {
776 uint32_t num_supported_hardware_watchpoints;
777 Status rc = target->GetProcessSP()->GetWatchpointSupportInfo(
778 num_supported_hardware_watchpoints);
780 // If unable to determine the # of watchpoints available,
781 // assume they are supported.
785 if (num_supported_hardware_watchpoints == 0) {
786 error.SetErrorStringWithFormat(
787 "Target supports (%u) hardware watchpoint slots.\n",
788 num_supported_hardware_watchpoints);
794 // See also Watchpoint::SetWatchpointType(uint32_t type) and the
795 // OptionGroupWatchpoint::WatchType enum type.
796 WatchpointSP Target::CreateWatchpoint(lldb::addr_t addr, size_t size,
797 const CompilerType *type, uint32_t kind,
799 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
801 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64
803 __FUNCTION__, addr, (uint64_t)size, kind);
806 if (!ProcessIsValid()) {
807 error.SetErrorString("process is not alive");
811 if (addr == LLDB_INVALID_ADDRESS || size == 0) {
813 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
815 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
819 if (!LLDB_WATCH_TYPE_IS_VALID(kind)) {
820 error.SetErrorStringWithFormat("invalid watchpoint type: %d", kind);
823 if (!CheckIfWatchpointsSupported(this, error))
826 // Currently we only support one watchpoint per address, with total number of
827 // watchpoints limited by the hardware which the inferior is running on.
829 // Grab the list mutex while doing operations.
830 const bool notify = false; // Don't notify about all the state changes we do
831 // on creating the watchpoint.
832 std::unique_lock<std::recursive_mutex> lock;
833 this->GetWatchpointList().GetListMutex(lock);
834 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
836 size_t old_size = matched_sp->GetByteSize();
838 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
839 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
840 // Return the existing watchpoint if both size and type match.
841 if (size == old_size && kind == old_type) {
843 wp_sp->SetEnabled(false, notify);
845 // Nil the matched watchpoint; we will be creating a new one.
846 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
847 m_watchpoint_list.Remove(matched_sp->GetID(), true);
852 wp_sp = std::make_shared<Watchpoint>(*this, addr, size, type);
853 wp_sp->SetWatchpointType(kind, notify);
854 m_watchpoint_list.Add(wp_sp, true);
857 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
859 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
860 __FUNCTION__, error.Success() ? "succeeded" : "failed",
864 // Enabling the watchpoint on the device side failed. Remove the said
865 // watchpoint from the list maintained by the target instance.
866 m_watchpoint_list.Remove(wp_sp->GetID(), true);
867 // See if we could provide more helpful error message.
868 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
869 error.SetErrorStringWithFormat(
870 "watch size of %" PRIu64 " is not supported", (uint64_t)size);
874 m_last_created_watchpoint = wp_sp;
878 void Target::RemoveAllowedBreakpoints ()
880 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
882 log->Printf("Target::%s \n", __FUNCTION__);
884 m_breakpoint_list.RemoveAllowed(true);
886 m_last_created_breakpoint.reset();
889 void Target::RemoveAllBreakpoints(bool internal_also) {
890 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
892 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
893 internal_also ? "yes" : "no");
895 m_breakpoint_list.RemoveAll(true);
897 m_internal_breakpoint_list.RemoveAll(false);
899 m_last_created_breakpoint.reset();
902 void Target::DisableAllBreakpoints(bool internal_also) {
903 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
905 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
906 internal_also ? "yes" : "no");
908 m_breakpoint_list.SetEnabledAll(false);
910 m_internal_breakpoint_list.SetEnabledAll(false);
913 void Target::DisableAllowedBreakpoints() {
914 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
916 log->Printf("Target::%s", __FUNCTION__);
918 m_breakpoint_list.SetEnabledAllowed(false);
921 void Target::EnableAllBreakpoints(bool internal_also) {
922 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
924 log->Printf("Target::%s (internal_also = %s)\n", __FUNCTION__,
925 internal_also ? "yes" : "no");
927 m_breakpoint_list.SetEnabledAll(true);
929 m_internal_breakpoint_list.SetEnabledAll(true);
932 void Target::EnableAllowedBreakpoints() {
933 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
935 log->Printf("Target::%s", __FUNCTION__);
937 m_breakpoint_list.SetEnabledAllowed(true);
940 bool Target::RemoveBreakpointByID(break_id_t break_id) {
941 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
943 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
944 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
946 if (DisableBreakpointByID(break_id)) {
947 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
948 m_internal_breakpoint_list.Remove(break_id, false);
950 if (m_last_created_breakpoint) {
951 if (m_last_created_breakpoint->GetID() == break_id)
952 m_last_created_breakpoint.reset();
954 m_breakpoint_list.Remove(break_id, true);
961 bool Target::DisableBreakpointByID(break_id_t break_id) {
962 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
964 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
965 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
969 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
970 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
972 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
974 bp_sp->SetEnabled(false);
980 bool Target::EnableBreakpointByID(break_id_t break_id) {
981 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_BREAKPOINTS));
983 log->Printf("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__,
984 break_id, LLDB_BREAK_ID_IS_INTERNAL(break_id) ? "yes" : "no");
988 if (LLDB_BREAK_ID_IS_INTERNAL(break_id))
989 bp_sp = m_internal_breakpoint_list.FindBreakpointByID(break_id);
991 bp_sp = m_breakpoint_list.FindBreakpointByID(break_id);
994 bp_sp->SetEnabled(true);
1000 Status Target::SerializeBreakpointsToFile(const FileSpec &file,
1001 const BreakpointIDList &bp_ids,
1006 error.SetErrorString("Invalid FileSpec.");
1010 std::string path(file.GetPath());
1011 StructuredData::ObjectSP input_data_sp;
1013 StructuredData::ArraySP break_store_sp;
1014 StructuredData::Array *break_store_ptr = nullptr;
1017 input_data_sp = StructuredData::ParseJSONFromFile(file, error);
1018 if (error.Success()) {
1019 break_store_ptr = input_data_sp->GetAsArray();
1020 if (!break_store_ptr) {
1021 error.SetErrorStringWithFormat(
1022 "Tried to append to invalid input file %s", path.c_str());
1028 if (!break_store_ptr) {
1029 break_store_sp = std::make_shared<StructuredData::Array>();
1030 break_store_ptr = break_store_sp.get();
1033 StreamFile out_file(path.c_str(),
1034 File::OpenOptions::eOpenOptionTruncate |
1035 File::OpenOptions::eOpenOptionWrite |
1036 File::OpenOptions::eOpenOptionCanCreate |
1037 File::OpenOptions::eOpenOptionCloseOnExec,
1038 lldb::eFilePermissionsFileDefault);
1039 if (!out_file.GetFile().IsValid()) {
1040 error.SetErrorStringWithFormat("Unable to open output file: %s.",
1045 std::unique_lock<std::recursive_mutex> lock;
1046 GetBreakpointList().GetListMutex(lock);
1048 if (bp_ids.GetSize() == 0) {
1049 const BreakpointList &breakpoints = GetBreakpointList();
1051 size_t num_breakpoints = breakpoints.GetSize();
1052 for (size_t i = 0; i < num_breakpoints; i++) {
1053 Breakpoint *bp = breakpoints.GetBreakpointAtIndex(i).get();
1054 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1055 // If a breakpoint can't serialize it, just ignore it for now:
1057 break_store_ptr->AddItem(bkpt_save_sp);
1061 std::unordered_set<lldb::break_id_t> processed_bkpts;
1062 const size_t count = bp_ids.GetSize();
1063 for (size_t i = 0; i < count; ++i) {
1064 BreakpointID cur_bp_id = bp_ids.GetBreakpointIDAtIndex(i);
1065 lldb::break_id_t bp_id = cur_bp_id.GetBreakpointID();
1067 if (bp_id != LLDB_INVALID_BREAK_ID) {
1068 // Only do each breakpoint once:
1069 std::pair<std::unordered_set<lldb::break_id_t>::iterator, bool>
1070 insert_result = processed_bkpts.insert(bp_id);
1071 if (!insert_result.second)
1074 Breakpoint *bp = GetBreakpointByID(bp_id).get();
1075 StructuredData::ObjectSP bkpt_save_sp = bp->SerializeToStructuredData();
1076 // If the user explicitly asked to serialize a breakpoint, and we
1077 // can't, then raise an error:
1078 if (!bkpt_save_sp) {
1079 error.SetErrorStringWithFormat("Unable to serialize breakpoint %d",
1083 break_store_ptr->AddItem(bkpt_save_sp);
1088 break_store_ptr->Dump(out_file, false);
1089 out_file.PutChar('\n');
1093 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1094 BreakpointIDList &new_bps) {
1095 std::vector<std::string> no_names;
1096 return CreateBreakpointsFromFile(file, no_names, new_bps);
1099 Status Target::CreateBreakpointsFromFile(const FileSpec &file,
1100 std::vector<std::string> &names,
1101 BreakpointIDList &new_bps) {
1102 std::unique_lock<std::recursive_mutex> lock;
1103 GetBreakpointList().GetListMutex(lock);
1106 StructuredData::ObjectSP input_data_sp =
1107 StructuredData::ParseJSONFromFile(file, error);
1108 if (!error.Success()) {
1110 } else if (!input_data_sp || !input_data_sp->IsValid()) {
1111 error.SetErrorStringWithFormat("Invalid JSON from input file: %s.",
1112 file.GetPath().c_str());
1116 StructuredData::Array *bkpt_array = input_data_sp->GetAsArray();
1118 error.SetErrorStringWithFormat(
1119 "Invalid breakpoint data from input file: %s.", file.GetPath().c_str());
1123 size_t num_bkpts = bkpt_array->GetSize();
1124 size_t num_names = names.size();
1126 for (size_t i = 0; i < num_bkpts; i++) {
1127 StructuredData::ObjectSP bkpt_object_sp = bkpt_array->GetItemAtIndex(i);
1128 // Peel off the breakpoint key, and feed the rest to the Breakpoint:
1129 StructuredData::Dictionary *bkpt_dict = bkpt_object_sp->GetAsDictionary();
1131 error.SetErrorStringWithFormat(
1132 "Invalid breakpoint data for element %zu from input file: %s.", i,
1133 file.GetPath().c_str());
1136 StructuredData::ObjectSP bkpt_data_sp =
1137 bkpt_dict->GetValueForKey(Breakpoint::GetSerializationKey());
1139 !Breakpoint::SerializedBreakpointMatchesNames(bkpt_data_sp, names))
1142 BreakpointSP bkpt_sp =
1143 Breakpoint::CreateFromStructuredData(*this, bkpt_data_sp, error);
1144 if (!error.Success()) {
1145 error.SetErrorStringWithFormat(
1146 "Error restoring breakpoint %zu from %s: %s.", i,
1147 file.GetPath().c_str(), error.AsCString());
1150 new_bps.AddBreakpointID(BreakpointID(bkpt_sp->GetID()));
1155 // The flag 'end_to_end', default to true, signifies that the operation is
1156 // performed end to end, for both the debugger and the debuggee.
1158 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1159 // to end operations.
1160 bool Target::RemoveAllWatchpoints(bool end_to_end) {
1161 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1163 log->Printf("Target::%s\n", __FUNCTION__);
1166 m_watchpoint_list.RemoveAll(true);
1170 // Otherwise, it's an end to end operation.
1172 if (!ProcessIsValid())
1175 size_t num_watchpoints = m_watchpoint_list.GetSize();
1176 for (size_t i = 0; i < num_watchpoints; ++i) {
1177 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1181 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1185 m_watchpoint_list.RemoveAll(true);
1186 m_last_created_watchpoint.reset();
1187 return true; // Success!
1190 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1191 // to end operations.
1192 bool Target::DisableAllWatchpoints(bool end_to_end) {
1193 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1195 log->Printf("Target::%s\n", __FUNCTION__);
1198 m_watchpoint_list.SetEnabledAll(false);
1202 // Otherwise, it's an end to end operation.
1204 if (!ProcessIsValid())
1207 size_t num_watchpoints = m_watchpoint_list.GetSize();
1208 for (size_t i = 0; i < num_watchpoints; ++i) {
1209 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1213 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1217 return true; // Success!
1220 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
1221 // to end operations.
1222 bool Target::EnableAllWatchpoints(bool end_to_end) {
1223 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1225 log->Printf("Target::%s\n", __FUNCTION__);
1228 m_watchpoint_list.SetEnabledAll(true);
1232 // Otherwise, it's an end to end operation.
1234 if (!ProcessIsValid())
1237 size_t num_watchpoints = m_watchpoint_list.GetSize();
1238 for (size_t i = 0; i < num_watchpoints; ++i) {
1239 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1243 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1247 return true; // Success!
1250 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1251 bool Target::ClearAllWatchpointHitCounts() {
1252 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1254 log->Printf("Target::%s\n", __FUNCTION__);
1256 size_t num_watchpoints = m_watchpoint_list.GetSize();
1257 for (size_t i = 0; i < num_watchpoints; ++i) {
1258 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1262 wp_sp->ResetHitCount();
1264 return true; // Success!
1267 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1268 bool Target::ClearAllWatchpointHistoricValues() {
1269 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1271 log->Printf("Target::%s\n", __FUNCTION__);
1273 size_t num_watchpoints = m_watchpoint_list.GetSize();
1274 for (size_t i = 0; i < num_watchpoints; ++i) {
1275 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1279 wp_sp->ResetHistoricValues();
1281 return true; // Success!
1284 // Assumption: Caller holds the list mutex lock for m_watchpoint_list during
1285 // these operations.
1286 bool Target::IgnoreAllWatchpoints(uint32_t ignore_count) {
1287 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1289 log->Printf("Target::%s\n", __FUNCTION__);
1291 if (!ProcessIsValid())
1294 size_t num_watchpoints = m_watchpoint_list.GetSize();
1295 for (size_t i = 0; i < num_watchpoints; ++i) {
1296 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1300 wp_sp->SetIgnoreCount(ignore_count);
1302 return true; // Success!
1305 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1306 bool Target::DisableWatchpointByID(lldb::watch_id_t watch_id) {
1307 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1309 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1311 if (!ProcessIsValid())
1314 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1316 Status rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1320 // Else, fallthrough.
1325 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1326 bool Target::EnableWatchpointByID(lldb::watch_id_t watch_id) {
1327 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1329 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1331 if (!ProcessIsValid())
1334 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1336 Status rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1340 // Else, fallthrough.
1345 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1346 bool Target::RemoveWatchpointByID(lldb::watch_id_t watch_id) {
1347 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1349 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1351 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1352 if (watch_to_remove_sp == m_last_created_watchpoint)
1353 m_last_created_watchpoint.reset();
1355 if (DisableWatchpointByID(watch_id)) {
1356 m_watchpoint_list.Remove(watch_id, true);
1362 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1363 bool Target::IgnoreWatchpointByID(lldb::watch_id_t watch_id,
1364 uint32_t ignore_count) {
1365 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_WATCHPOINTS));
1367 log->Printf("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1369 if (!ProcessIsValid())
1372 WatchpointSP wp_sp = m_watchpoint_list.FindByID(watch_id);
1374 wp_sp->SetIgnoreCount(ignore_count);
1380 ModuleSP Target::GetExecutableModule() {
1381 // search for the first executable in the module list
1382 for (size_t i = 0; i < m_images.GetSize(); ++i) {
1383 ModuleSP module_sp = m_images.GetModuleAtIndex(i);
1384 lldb_private::ObjectFile *obj = module_sp->GetObjectFile();
1387 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1390 // as fall back return the first module loaded
1391 return m_images.GetModuleAtIndex(0);
1394 Module *Target::GetExecutableModulePointer() {
1395 return GetExecutableModule().get();
1398 static void LoadScriptingResourceForModule(const ModuleSP &module_sp,
1401 StreamString feedback_stream;
1403 !module_sp->LoadScriptingResourceInTarget(target, error,
1404 &feedback_stream)) {
1405 if (error.AsCString())
1406 target->GetDebugger().GetErrorFile()->Printf(
1407 "unable to load scripting data for module %s - error reported was "
1409 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1412 if (feedback_stream.GetSize())
1413 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1414 feedback_stream.GetData());
1417 void Target::ClearModules(bool delete_locations) {
1418 ModulesDidUnload(m_images, delete_locations);
1419 m_section_load_history.Clear();
1421 m_scratch_type_system_map.Clear();
1422 m_ast_importer_sp.reset();
1425 void Target::DidExec() {
1426 // When a process exec's we need to know about it so we can do some cleanup.
1427 m_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1428 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch.GetSpec());
1431 void Target::SetExecutableModule(ModuleSP &executable_sp,
1432 LoadDependentFiles load_dependent_files) {
1433 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1434 ClearModules(false);
1436 if (executable_sp) {
1437 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1438 Timer scoped_timer(func_cat,
1439 "Target::SetExecutableModule (executable = '%s')",
1440 executable_sp->GetFileSpec().GetPath().c_str());
1442 const bool notify = true;
1443 m_images.Append(executable_sp, notify); // The first image is our executable file
1445 // If we haven't set an architecture yet, reset our architecture based on
1446 // what we found in the executable module.
1447 if (!m_arch.GetSpec().IsValid()) {
1448 m_arch = executable_sp->GetArchitecture();
1450 "setting architecture to {0} ({1}) based on executable file",
1451 m_arch.GetSpec().GetArchitectureName(),
1452 m_arch.GetSpec().GetTriple().getTriple());
1455 FileSpecList dependent_files;
1456 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1457 bool load_dependents = true;
1458 switch (load_dependent_files) {
1459 case eLoadDependentsDefault:
1460 load_dependents = executable_sp->IsExecutable();
1462 case eLoadDependentsYes:
1463 load_dependents = true;
1465 case eLoadDependentsNo:
1466 load_dependents = false;
1470 if (executable_objfile && load_dependents) {
1471 ModuleList added_modules;
1472 executable_objfile->GetDependentModules(dependent_files);
1473 for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1474 FileSpec dependent_file_spec(
1475 dependent_files.GetFileSpecPointerAtIndex(i));
1476 FileSpec platform_dependent_file_spec;
1478 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1479 platform_dependent_file_spec);
1481 platform_dependent_file_spec = dependent_file_spec;
1483 ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1484 ModuleSP image_module_sp(GetOrCreateModule(module_spec,
1485 false /* notify */));
1486 if (image_module_sp) {
1487 added_modules.AppendIfNeeded (image_module_sp, false);
1488 ObjectFile *objfile = image_module_sp->GetObjectFile();
1490 objfile->GetDependentModules(dependent_files);
1493 ModulesDidLoad(added_modules);
1498 bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform) {
1499 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1500 bool missing_local_arch = !m_arch.GetSpec().IsValid();
1501 bool replace_local_arch = true;
1502 bool compatible_local_arch = false;
1503 ArchSpec other(arch_spec);
1505 // Changing the architecture might mean that the currently selected platform
1506 // isn't compatible. Set the platform correctly if we are asked to do so,
1507 // otherwise assume the user will set the platform manually.
1509 if (other.IsValid()) {
1510 auto platform_sp = GetPlatform();
1512 !platform_sp->IsCompatibleArchitecture(other, false, nullptr)) {
1513 ArchSpec platform_arch;
1514 auto arch_platform_sp =
1515 Platform::GetPlatformForArchitecture(other, &platform_arch);
1516 if (arch_platform_sp) {
1517 SetPlatform(arch_platform_sp);
1518 if (platform_arch.IsValid())
1519 other = platform_arch;
1525 if (!missing_local_arch) {
1526 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1527 other.MergeFrom(m_arch.GetSpec());
1529 if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1530 compatible_local_arch = true;
1531 bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1534 m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed, vendor_changed,
1535 os_changed, os_ver_changed, env_changed);
1537 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1538 replace_local_arch = false;
1543 if (compatible_local_arch || missing_local_arch) {
1544 // If we haven't got a valid arch spec, or the architectures are compatible
1545 // update the architecture, unless the one we already have is more
1547 if (replace_local_arch)
1549 LLDB_LOG(log, "set architecture to {0} ({1})",
1550 m_arch.GetSpec().GetArchitectureName(),
1551 m_arch.GetSpec().GetTriple().getTriple());
1555 // If we have an executable file, try to reset the executable to the desired
1558 log->Printf("Target::SetArchitecture changing architecture to %s (%s)",
1559 arch_spec.GetArchitectureName(),
1560 arch_spec.GetTriple().getTriple().c_str());
1562 ModuleSP executable_sp = GetExecutableModule();
1565 // Need to do something about unsetting breakpoints.
1567 if (executable_sp) {
1569 log->Printf("Target::SetArchitecture Trying to select executable file "
1570 "architecture %s (%s)",
1571 arch_spec.GetArchitectureName(),
1572 arch_spec.GetTriple().getTriple().c_str());
1573 ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1574 FileSpecList search_paths = GetExecutableSearchPaths();
1575 Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1579 if (!error.Fail() && executable_sp) {
1580 SetExecutableModule(executable_sp, eLoadDependentsYes);
1587 bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1588 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1589 if (arch_spec.IsValid()) {
1590 if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1591 // The current target arch is compatible with "arch_spec", see if we can
1592 // improve our current architecture using bits from "arch_spec"
1595 log->Printf("Target::MergeArchitecture target has arch %s, merging with "
1597 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1598 arch_spec.GetTriple().getTriple().c_str());
1600 // Merge bits from arch_spec into "merged_arch" and set our architecture
1601 ArchSpec merged_arch(m_arch.GetSpec());
1602 merged_arch.MergeFrom(arch_spec);
1603 return SetArchitecture(merged_arch);
1605 // The new architecture is different, we just need to replace it
1606 return SetArchitecture(arch_spec);
1612 void Target::NotifyWillClearList(const ModuleList &module_list) {}
1614 void Target::NotifyModuleAdded(const ModuleList &module_list,
1615 const ModuleSP &module_sp) {
1616 // A module is being added to this target for the first time
1618 ModuleList my_module_list;
1619 my_module_list.Append(module_sp);
1620 ModulesDidLoad(my_module_list);
1624 void Target::NotifyModuleRemoved(const ModuleList &module_list,
1625 const ModuleSP &module_sp) {
1626 // A module is being removed from this target.
1628 ModuleList my_module_list;
1629 my_module_list.Append(module_sp);
1630 ModulesDidUnload(my_module_list, false);
1634 void Target::NotifyModuleUpdated(const ModuleList &module_list,
1635 const ModuleSP &old_module_sp,
1636 const ModuleSP &new_module_sp) {
1637 // A module is replacing an already added module
1639 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1641 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1642 old_module_sp, new_module_sp);
1646 void Target::NotifyModulesRemoved(lldb_private::ModuleList &module_list) {
1647 ModulesDidUnload (module_list, false);
1651 void Target::ModulesDidLoad(ModuleList &module_list) {
1652 const size_t num_images = module_list.GetSize();
1653 if (m_valid && num_images) {
1654 for (size_t idx = 0; idx < num_images; ++idx) {
1655 ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1656 LoadScriptingResourceForModule(module_sp, this);
1658 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1659 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1661 m_process_sp->ModulesDidLoad(module_list);
1663 BroadcastEvent(eBroadcastBitModulesLoaded,
1664 new TargetEventData(this->shared_from_this(), module_list));
1668 void Target::SymbolsDidLoad(ModuleList &module_list) {
1669 if (m_valid && module_list.GetSize()) {
1671 for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1672 runtime->SymbolsDidLoad(module_list);
1676 m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1677 m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1678 BroadcastEvent(eBroadcastBitSymbolsLoaded,
1679 new TargetEventData(this->shared_from_this(), module_list));
1683 void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1684 if (m_valid && module_list.GetSize()) {
1685 UnloadModuleSections(module_list);
1686 m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1687 m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1689 BroadcastEvent(eBroadcastBitModulesUnloaded,
1690 new TargetEventData(this->shared_from_this(), module_list));
1694 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1695 const FileSpec &module_file_spec) {
1696 if (GetBreakpointsConsultPlatformAvoidList()) {
1697 ModuleList matchingModules;
1698 ModuleSpec module_spec(module_file_spec);
1699 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1701 // If there is more than one module for this file spec, only return true if
1702 // ALL the modules are on the
1704 if (num_modules > 0) {
1705 for (size_t i = 0; i < num_modules; i++) {
1706 if (!ModuleIsExcludedForUnconstrainedSearches(
1707 matchingModules.GetModuleAtIndex(i)))
1716 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1717 const lldb::ModuleSP &module_sp) {
1718 if (GetBreakpointsConsultPlatformAvoidList()) {
1720 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1726 size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1727 size_t dst_len, Status &error) {
1728 SectionSP section_sp(addr.GetSection());
1730 // If the contents of this section are encrypted, the on-disk file is
1731 // unusable. Read only from live memory.
1732 if (section_sp->IsEncrypted()) {
1733 error.SetErrorString("section is encrypted");
1736 ModuleSP module_sp(section_sp->GetModule());
1738 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1740 size_t bytes_read = objfile->ReadSectionData(
1741 section_sp.get(), addr.GetOffset(), dst, dst_len);
1745 error.SetErrorStringWithFormat("error reading data from section %s",
1746 section_sp->GetName().GetCString());
1748 error.SetErrorString("address isn't from a object file");
1750 error.SetErrorString("address isn't in a module");
1752 error.SetErrorString("address doesn't contain a section that points to a "
1753 "section in a object file");
1758 size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1759 void *dst, size_t dst_len, Status &error,
1760 lldb::addr_t *load_addr_ptr) {
1763 // if we end up reading this from process memory, we will fill this with the
1764 // actual load address
1766 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1768 size_t bytes_read = 0;
1770 addr_t load_addr = LLDB_INVALID_ADDRESS;
1771 addr_t file_addr = LLDB_INVALID_ADDRESS;
1772 Address resolved_addr;
1773 if (!addr.IsSectionOffset()) {
1774 SectionLoadList §ion_load_list = GetSectionLoadList();
1775 if (section_load_list.IsEmpty()) {
1776 // No sections are loaded, so we must assume we are not running yet and
1777 // anything we are given is a file address.
1778 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1779 // offset is the file address
1780 m_images.ResolveFileAddress(file_addr, resolved_addr);
1782 // We have at least one section loaded. This can be because we have
1783 // manually loaded some sections with "target modules load ..." or
1784 // because we have have a live process that has sections loaded through
1785 // the dynamic loader
1786 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1787 // offset is the load address
1788 section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1791 if (!resolved_addr.IsValid())
1792 resolved_addr = addr;
1794 if (prefer_file_cache) {
1795 bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1800 if (ProcessIsValid()) {
1801 if (load_addr == LLDB_INVALID_ADDRESS)
1802 load_addr = resolved_addr.GetLoadAddress(this);
1804 if (load_addr == LLDB_INVALID_ADDRESS) {
1805 ModuleSP addr_module_sp(resolved_addr.GetModule());
1806 if (addr_module_sp && addr_module_sp->GetFileSpec())
1807 error.SetErrorStringWithFormatv(
1808 "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1809 addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1811 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1812 resolved_addr.GetFileAddress());
1814 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1815 if (bytes_read != dst_len) {
1816 if (error.Success()) {
1817 if (bytes_read == 0)
1818 error.SetErrorStringWithFormat(
1819 "read memory from 0x%" PRIx64 " failed", load_addr);
1821 error.SetErrorStringWithFormat(
1822 "only %" PRIu64 " of %" PRIu64
1823 " bytes were read from memory at 0x%" PRIx64,
1824 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1829 *load_addr_ptr = load_addr;
1832 // If the address is not section offset we have an address that doesn't
1833 // resolve to any address in any currently loaded shared libraries and we
1834 // failed to read memory so there isn't anything more we can do. If it is
1835 // section offset, we might be able to read cached memory from the object
1837 if (!resolved_addr.IsSectionOffset())
1842 if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1843 // If we didn't already try and read from the object file cache, then try
1844 // it after failing to read from the process.
1845 return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1850 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1854 addr_t curr_addr = addr.GetLoadAddress(this);
1855 Address address(addr);
1857 size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1860 out_str.append(buf, length);
1861 // If we got "length - 1" bytes, we didn't get the whole C string, we need
1862 // to read some more characters
1863 if (length == sizeof(buf) - 1)
1864 curr_addr += length;
1867 address = Address(curr_addr);
1869 return out_str.size();
1872 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1873 size_t dst_max_len, Status &result_error) {
1874 size_t total_cstr_len = 0;
1875 if (dst && dst_max_len) {
1876 result_error.Clear();
1877 // NULL out everything just to be safe
1878 memset(dst, 0, dst_max_len);
1880 addr_t curr_addr = addr.GetLoadAddress(this);
1881 Address address(addr);
1883 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1884 // this really needs to be tied to the memory cache subsystem's cache line
1885 // size, so leave this as a fixed constant.
1886 const size_t cache_line_size = 512;
1888 size_t bytes_left = dst_max_len - 1;
1889 char *curr_dst = dst;
1891 while (bytes_left > 0) {
1892 addr_t cache_line_bytes_left =
1893 cache_line_size - (curr_addr % cache_line_size);
1894 addr_t bytes_to_read =
1895 std::min<addr_t>(bytes_left, cache_line_bytes_left);
1897 ReadMemory(address, false, curr_dst, bytes_to_read, error);
1899 if (bytes_read == 0) {
1900 result_error = error;
1901 dst[total_cstr_len] = '\0';
1904 const size_t len = strlen(curr_dst);
1906 total_cstr_len += len;
1908 if (len < bytes_to_read)
1911 curr_dst += bytes_read;
1912 curr_addr += bytes_read;
1913 bytes_left -= bytes_read;
1914 address = Address(curr_addr);
1918 result_error.SetErrorString("invalid arguments");
1920 result_error.Clear();
1922 return total_cstr_len;
1925 size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1926 bool prefer_file_cache,
1927 uint32_t byte_size, bool is_signed,
1928 Scalar &scalar, Status &error) {
1931 if (byte_size <= sizeof(uval)) {
1933 ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1934 if (bytes_read == byte_size) {
1935 DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1936 m_arch.GetSpec().GetAddressByteSize());
1937 lldb::offset_t offset = 0;
1939 scalar = data.GetMaxU32(&offset, byte_size);
1941 scalar = data.GetMaxU64(&offset, byte_size);
1944 scalar.SignExtend(byte_size * 8);
1948 error.SetErrorStringWithFormat(
1949 "byte size of %u is too large for integer scalar type", byte_size);
1954 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1955 bool prefer_file_cache,
1956 size_t integer_byte_size,
1957 uint64_t fail_value,
1960 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1961 false, scalar, error))
1962 return scalar.ULongLong(fail_value);
1966 bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1967 Status &error, Address &pointer_addr) {
1969 if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1970 m_arch.GetSpec().GetAddressByteSize(), false, scalar,
1972 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1973 if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1974 SectionLoadList §ion_load_list = GetSectionLoadList();
1975 if (section_load_list.IsEmpty()) {
1976 // No sections are loaded, so we must assume we are not running yet and
1977 // anything we are given is a file address.
1978 m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1980 // We have at least one section loaded. This can be because we have
1981 // manually loaded some sections with "target modules load ..." or
1982 // because we have have a live process that has sections loaded through
1983 // the dynamic loader
1984 section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1986 // We weren't able to resolve the pointer value, so just return an
1987 // address with no section
1988 if (!pointer_addr.IsValid())
1989 pointer_addr.SetOffset(pointer_vm_addr);
1996 ModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
1997 Status *error_ptr) {
2002 // First see if we already have this module in our module list. If we do,
2003 // then we're done, we don't need to consult the shared modules list. But
2004 // only do this if we are passed a UUID.
2006 if (module_spec.GetUUID().IsValid())
2007 module_sp = m_images.FindFirstModule(module_spec);
2010 ModuleSP old_module_sp; // This will get filled in if we have a new version
2012 bool did_create_module = false;
2013 FileSpecList search_paths = GetExecutableSearchPaths();
2014 // If there are image search path entries, try to use them first to acquire
2015 // a suitable image.
2016 if (m_image_search_paths.GetSize()) {
2017 ModuleSpec transformed_spec(module_spec);
2018 if (m_image_search_paths.RemapPath(
2019 module_spec.GetFileSpec().GetDirectory(),
2020 transformed_spec.GetFileSpec().GetDirectory())) {
2021 transformed_spec.GetFileSpec().GetFilename() =
2022 module_spec.GetFileSpec().GetFilename();
2023 error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2025 &old_module_sp, &did_create_module);
2030 // If we have a UUID, we can check our global shared module list in case
2031 // we already have it. If we don't have a valid UUID, then we can't since
2032 // the path in "module_spec" will be a platform path, and we will need to
2033 // let the platform find that file. For example, we could be asking for
2034 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2035 // the local copy of "/usr/lib/dyld" since our platform could be a remote
2036 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2038 if (module_spec.GetUUID().IsValid()) {
2039 // We have a UUID, it is OK to check the global module list...
2040 error = ModuleList::GetSharedModule(module_spec, module_sp,
2042 &old_module_sp, &did_create_module);
2046 // The platform is responsible for finding and caching an appropriate
2047 // module in the shared module cache.
2048 if (m_platform_sp) {
2049 error = m_platform_sp->GetSharedModule(
2050 module_spec, m_process_sp.get(), module_sp,
2051 &search_paths, &old_module_sp, &did_create_module);
2053 error.SetErrorString("no platform is currently set");
2058 // We found a module that wasn't in our target list. Let's make sure that
2059 // there wasn't an equivalent module in the list already, and if there was,
2062 ObjectFile *objfile = module_sp->GetObjectFile();
2064 switch (objfile->GetType()) {
2065 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2066 /// a program's execution state
2067 case ObjectFile::eTypeExecutable: /// A normal executable
2068 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2070 case ObjectFile::eTypeObjectFile: /// An intermediate object file
2071 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2072 /// used during execution
2074 case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2075 /// debug information
2077 error_ptr->SetErrorString("debug info files aren't valid target "
2078 "modules, please specify an executable");
2080 case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2081 /// against but not used for
2084 error_ptr->SetErrorString("stub libraries aren't valid target "
2085 "modules, please specify an executable");
2089 error_ptr->SetErrorString(
2090 "unsupported file type, please specify an executable");
2093 // GetSharedModule is not guaranteed to find the old shared module, for
2094 // instance in the common case where you pass in the UUID, it is only
2095 // going to find the one module matching the UUID. In fact, it has no
2096 // good way to know what the "old module" relevant to this target is,
2097 // since there might be many copies of a module with this file spec in
2098 // various running debug sessions, but only one of them will belong to
2099 // this target. So let's remove the UUID from the module list, and look
2100 // in the target's module list. Only do this if there is SOMETHING else
2101 // in the module spec...
2102 if (!old_module_sp) {
2103 if (module_spec.GetUUID().IsValid() &&
2104 !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2105 !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2106 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2107 module_spec_copy.GetUUID().Clear();
2109 ModuleList found_modules;
2111 m_images.FindModules(module_spec_copy, found_modules);
2112 if (num_found == 1) {
2113 old_module_sp = found_modules.GetModuleAtIndex(0);
2118 // Preload symbols outside of any lock, so hopefully we can do this for
2119 // each library in parallel.
2120 if (GetPreloadSymbols())
2121 module_sp->PreloadSymbols();
2123 if (old_module_sp &&
2124 m_images.GetIndexForModule(old_module_sp.get()) !=
2125 LLDB_INVALID_INDEX32) {
2126 m_images.ReplaceModule(old_module_sp, module_sp);
2127 Module *old_module_ptr = old_module_sp.get();
2128 old_module_sp.reset();
2129 ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2131 m_images.Append(module_sp, notify);
2142 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2144 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2146 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2148 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2150 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2152 exe_ctx.SetTargetPtr(this);
2155 PathMappingList &Target::GetImageSearchPathList() {
2156 return m_image_search_paths;
2159 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2161 Target *target = (Target *)baton;
2162 ModuleSP exe_module_sp(target->GetExecutableModule());
2164 target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2167 TypeSystem *Target::GetScratchTypeSystemForLanguage(Status *error,
2168 lldb::LanguageType language,
2169 bool create_on_demand) {
2177 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2179 || language == eLanguageTypeUnknown) {
2180 std::set<lldb::LanguageType> languages_for_types;
2181 std::set<lldb::LanguageType> languages_for_expressions;
2183 Language::GetLanguagesSupportingTypeSystems(languages_for_types,
2184 languages_for_expressions);
2186 if (languages_for_expressions.count(eLanguageTypeC)) {
2187 language = eLanguageTypeC; // LLDB's default. Override by setting the
2190 if (languages_for_expressions.empty()) {
2193 language = *languages_for_expressions.begin();
2198 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2202 PersistentExpressionState *
2203 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2204 TypeSystem *type_system =
2205 GetScratchTypeSystemForLanguage(nullptr, language, true);
2208 return type_system->GetPersistentExpressionState();
2214 UserExpression *Target::GetUserExpressionForLanguage(
2215 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2216 Expression::ResultType desired_type,
2217 const EvaluateExpressionOptions &options,
2218 ValueObject *ctx_obj, Status &error) {
2219 Status type_system_error;
2221 TypeSystem *type_system =
2222 GetScratchTypeSystemForLanguage(&type_system_error, language);
2223 UserExpression *user_expr = nullptr;
2226 error.SetErrorStringWithFormat(
2227 "Could not find type system for language %s: %s",
2228 Language::GetNameForLanguageType(language),
2229 type_system_error.AsCString());
2233 user_expr = type_system->GetUserExpression(expr, prefix, language,
2234 desired_type, options, ctx_obj);
2236 error.SetErrorStringWithFormat(
2237 "Could not create an expression for language %s",
2238 Language::GetNameForLanguageType(language));
2243 FunctionCaller *Target::GetFunctionCallerForLanguage(
2244 lldb::LanguageType language, const CompilerType &return_type,
2245 const Address &function_address, const ValueList &arg_value_list,
2246 const char *name, Status &error) {
2247 Status type_system_error;
2248 TypeSystem *type_system =
2249 GetScratchTypeSystemForLanguage(&type_system_error, language);
2250 FunctionCaller *persistent_fn = nullptr;
2253 error.SetErrorStringWithFormat(
2254 "Could not find type system for language %s: %s",
2255 Language::GetNameForLanguageType(language),
2256 type_system_error.AsCString());
2257 return persistent_fn;
2260 persistent_fn = type_system->GetFunctionCaller(return_type, function_address,
2261 arg_value_list, name);
2263 error.SetErrorStringWithFormat(
2264 "Could not create an expression for language %s",
2265 Language::GetNameForLanguageType(language));
2267 return persistent_fn;
2271 Target::GetUtilityFunctionForLanguage(const char *text,
2272 lldb::LanguageType language,
2273 const char *name, Status &error) {
2274 Status type_system_error;
2275 TypeSystem *type_system =
2276 GetScratchTypeSystemForLanguage(&type_system_error, language);
2277 UtilityFunction *utility_fn = nullptr;
2280 error.SetErrorStringWithFormat(
2281 "Could not find type system for language %s: %s",
2282 Language::GetNameForLanguageType(language),
2283 type_system_error.AsCString());
2287 utility_fn = type_system->GetUtilityFunction(text, name);
2289 error.SetErrorStringWithFormat(
2290 "Could not create an expression for language %s",
2291 Language::GetNameForLanguageType(language));
2296 ClangASTContext *Target::GetScratchClangASTContext(bool create_on_demand) {
2298 if (TypeSystem *type_system = GetScratchTypeSystemForLanguage(
2299 nullptr, eLanguageTypeC, create_on_demand))
2300 return llvm::dyn_cast<ClangASTContext>(type_system);
2305 ClangASTImporterSP Target::GetClangASTImporter() {
2307 if (!m_ast_importer_sp) {
2308 m_ast_importer_sp = std::make_shared<ClangASTImporter>();
2310 return m_ast_importer_sp;
2312 return ClangASTImporterSP();
2315 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2317 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2319 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2320 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2322 return properties_sp->GetExecutableSearchPaths();
2323 return FileSpecList();
2326 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2327 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2329 return properties_sp->GetDebugFileSearchPaths();
2330 return FileSpecList();
2333 ArchSpec Target::GetDefaultArchitecture() {
2334 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2336 return properties_sp->GetDefaultArchitecture();
2340 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2341 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2342 if (properties_sp) {
2343 LogIfAnyCategoriesSet(
2344 LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's "
2345 "default architecture to %s (%s)",
2346 arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2347 return properties_sp->SetDefaultArchitecture(arch);
2351 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2352 const SymbolContext *sc_ptr) {
2353 // The target can either exist in the "process" of ExecutionContext, or in
2354 // the "target_sp" member of SymbolContext. This accessor helper function
2355 // will get the target from one of these locations.
2357 Target *target = nullptr;
2358 if (sc_ptr != nullptr)
2359 target = sc_ptr->target_sp.get();
2360 if (target == nullptr && exe_ctx_ptr)
2361 target = exe_ctx_ptr->GetTargetPtr();
2365 ExpressionResults Target::EvaluateExpression(
2366 llvm::StringRef expr, ExecutionContextScope *exe_scope,
2367 lldb::ValueObjectSP &result_valobj_sp,
2368 const EvaluateExpressionOptions &options, std::string *fixed_expression,
2369 ValueObject *ctx_obj) {
2370 result_valobj_sp.reset();
2372 ExpressionResults execution_results = eExpressionSetupError;
2375 return execution_results;
2377 // We shouldn't run stop hooks in expressions.
2378 bool old_suppress_value = m_suppress_stop_hooks;
2379 m_suppress_stop_hooks = true;
2380 auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2381 m_suppress_stop_hooks = old_suppress_value; });
2383 ExecutionContext exe_ctx;
2386 exe_scope->CalculateExecutionContext(exe_ctx);
2387 } else if (m_process_sp) {
2388 m_process_sp->CalculateExecutionContext(exe_ctx);
2390 CalculateExecutionContext(exe_ctx);
2393 // Make sure we aren't just trying to see the value of a persistent variable
2394 // (something like "$0")
2395 lldb::ExpressionVariableSP persistent_var_sp;
2396 // Only check for persistent variables the expression starts with a '$'
2398 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)
2399 ->GetPersistentExpressionState()
2400 ->GetVariable(expr);
2402 if (persistent_var_sp) {
2403 result_valobj_sp = persistent_var_sp->GetValueObject();
2404 execution_results = eExpressionCompleted;
2406 llvm::StringRef prefix = GetExpressionPrefixContents();
2409 UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2410 result_valobj_sp, error, fixed_expression,
2415 return execution_results;
2418 lldb::ExpressionVariableSP
2419 Target::GetPersistentVariable(ConstString name) {
2420 lldb::ExpressionVariableSP variable_sp;
2421 m_scratch_type_system_map.ForEach(
2422 [name, &variable_sp](TypeSystem *type_system) -> bool {
2423 if (PersistentExpressionState *persistent_state =
2424 type_system->GetPersistentExpressionState()) {
2425 variable_sp = persistent_state->GetVariable(name);
2428 return false; // Stop iterating the ForEach
2430 return true; // Keep iterating the ForEach
2435 lldb::addr_t Target::GetPersistentSymbol(ConstString name) {
2436 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2438 m_scratch_type_system_map.ForEach(
2439 [name, &address](TypeSystem *type_system) -> bool {
2440 if (PersistentExpressionState *persistent_state =
2441 type_system->GetPersistentExpressionState()) {
2442 address = persistent_state->LookupSymbol(name);
2443 if (address != LLDB_INVALID_ADDRESS)
2444 return false; // Stop iterating the ForEach
2446 return true; // Keep iterating the ForEach
2451 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2452 AddressClass addr_class) const {
2453 auto arch_plugin = GetArchitecturePlugin();
2454 return arch_plugin ?
2455 arch_plugin->GetCallableLoadAddress(load_addr, addr_class) : load_addr;
2458 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2459 AddressClass addr_class) const {
2460 auto arch_plugin = GetArchitecturePlugin();
2461 return arch_plugin ?
2462 arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class) : load_addr;
2465 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2466 auto arch_plugin = GetArchitecturePlugin();
2467 return arch_plugin ?
2468 arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2471 SourceManager &Target::GetSourceManager() {
2472 if (!m_source_manager_up)
2473 m_source_manager_up.reset(new SourceManager(shared_from_this()));
2474 return *m_source_manager_up;
2477 ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2478 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2483 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2485 if (!m_clang_modules_decl_vendor_up) {
2486 m_clang_modules_decl_vendor_up.reset(
2487 ClangModulesDeclVendor::Create(*this));
2491 return m_clang_modules_decl_vendor_up.get();
2494 Target::StopHookSP Target::CreateStopHook() {
2495 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2496 Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2497 m_stop_hooks[new_uid] = stop_hook_sp;
2498 return stop_hook_sp;
2501 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2502 size_t num_removed = m_stop_hooks.erase(user_id);
2503 return (num_removed != 0);
2506 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2508 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2509 StopHookSP found_hook;
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())
2514 found_hook = (*specified_hook_iter).second;
2518 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2519 bool active_state) {
2520 StopHookCollection::iterator specified_hook_iter;
2521 specified_hook_iter = m_stop_hooks.find(user_id);
2522 if (specified_hook_iter == m_stop_hooks.end())
2525 (*specified_hook_iter).second->SetIsActive(active_state);
2529 void Target::SetAllStopHooksActiveState(bool active_state) {
2530 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2531 for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2532 (*pos).second->SetIsActive(active_state);
2536 void Target::RunStopHooks() {
2537 if (m_suppress_stop_hooks)
2543 // Somebody might have restarted the process:
2544 if (m_process_sp->GetState() != eStateStopped)
2547 // <rdar://problem/12027563> make sure we check that we are not stopped
2548 // because of us running a user expression since in that case we do not want
2549 // to run the stop-hooks
2550 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2553 if (m_stop_hooks.empty())
2556 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2558 // If there aren't any active stop hooks, don't bother either.
2559 // Also see if any of the active hooks want to auto-continue.
2560 bool any_active_hooks = false;
2561 bool auto_continue = false;
2562 for (auto hook : m_stop_hooks) {
2563 if (hook.second->IsActive()) {
2564 any_active_hooks = true;
2565 auto_continue |= hook.second->GetAutoContinue();
2568 if (!any_active_hooks)
2571 CommandReturnObject result;
2573 std::vector<ExecutionContext> exc_ctx_with_reasons;
2574 std::vector<SymbolContext> sym_ctx_with_reasons;
2576 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2577 size_t num_threads = cur_threadlist.GetSize();
2578 for (size_t i = 0; i < num_threads; i++) {
2579 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2580 if (cur_thread_sp->ThreadStoppedForAReason()) {
2581 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2582 exc_ctx_with_reasons.push_back(ExecutionContext(
2583 m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2584 sym_ctx_with_reasons.push_back(
2585 cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2589 // If no threads stopped for a reason, don't run the stop-hooks.
2590 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2591 if (num_exe_ctx == 0)
2594 result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2595 result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2597 bool keep_going = true;
2598 bool hooks_ran = false;
2599 bool print_hook_header = (m_stop_hooks.size() != 1);
2600 bool print_thread_header = (num_exe_ctx != 1);
2601 bool did_restart = false;
2603 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2605 StopHookSP cur_hook_sp = (*pos).second;
2606 if (!cur_hook_sp->IsActive())
2609 bool any_thread_matched = false;
2610 for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2611 if ((cur_hook_sp->GetSpecifier() == nullptr ||
2612 cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2613 sym_ctx_with_reasons[i])) &&
2614 (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2615 cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2616 exc_ctx_with_reasons[i].GetThreadRef()))) {
2620 if (print_hook_header && !any_thread_matched) {
2622 (cur_hook_sp->GetCommands().GetSize() == 1
2623 ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2626 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2627 cur_hook_sp->GetID(), cmd);
2629 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2630 cur_hook_sp->GetID());
2631 any_thread_matched = true;
2634 if (print_thread_header)
2635 result.AppendMessageWithFormat(
2637 exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2639 CommandInterpreterRunOptions options;
2640 options.SetStopOnContinue(true);
2641 options.SetStopOnError(true);
2642 options.SetEchoCommands(false);
2643 options.SetPrintResults(true);
2644 options.SetPrintErrors(true);
2645 options.SetAddToHistory(false);
2648 bool old_async = GetDebugger().GetAsyncExecution();
2649 GetDebugger().SetAsyncExecution(true);
2650 GetDebugger().GetCommandInterpreter().HandleCommands(
2651 cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2653 GetDebugger().SetAsyncExecution(old_async);
2654 // If the command started the target going again, we should bag out of
2655 // running the stop hooks.
2656 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2657 (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2658 // But only complain if there were more stop hooks to do:
2659 StopHookCollection::iterator tmp = pos;
2661 result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64
2662 " set the program running.\n"
2663 " Consider using '-G true' to make "
2664 "stop hooks auto-continue.\n",
2665 cur_hook_sp->GetID());
2672 // Finally, if auto-continue was requested, do it now:
2673 if (!did_restart && auto_continue)
2674 m_process_sp->PrivateResume();
2676 result.GetImmediateOutputStream()->Flush();
2677 result.GetImmediateErrorStream()->Flush();
2680 const TargetPropertiesSP &Target::GetGlobalProperties() {
2681 // NOTE: intentional leak so we don't crash if global destructor chain gets
2682 // called as other threads still use the result of this function
2683 static TargetPropertiesSP *g_settings_sp_ptr =
2684 new TargetPropertiesSP(new TargetProperties(nullptr));
2685 return *g_settings_sp_ptr;
2688 Status Target::Install(ProcessLaunchInfo *launch_info) {
2690 PlatformSP platform_sp(GetPlatform());
2692 if (platform_sp->IsRemote()) {
2693 if (platform_sp->IsConnected()) {
2694 // Install all files that have an install path, and always install the
2695 // main executable when connected to a remote platform
2696 const ModuleList &modules = GetImages();
2697 const size_t num_images = modules.GetSize();
2698 for (size_t idx = 0; idx < num_images; ++idx) {
2699 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2701 const bool is_main_executable = module_sp == GetExecutableModule();
2702 FileSpec local_file(module_sp->GetFileSpec());
2704 FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2706 if (is_main_executable) // TODO: add setting for always
2707 // installing main executable???
2709 // Always install the main executable
2710 remote_file = platform_sp->GetRemoteWorkingDirectory();
2711 remote_file.AppendPathComponent(
2712 module_sp->GetFileSpec().GetFilename().GetCString());
2716 error = platform_sp->Install(local_file, remote_file);
2717 if (error.Success()) {
2718 module_sp->SetPlatformFileSpec(remote_file);
2719 if (is_main_executable) {
2720 platform_sp->SetFilePermissions(remote_file, 0700);
2722 launch_info->SetExecutableFile(remote_file, false);
2736 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2738 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2741 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2742 Address &resolved_addr) {
2743 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2746 bool Target::SetSectionLoadAddress(const SectionSP §ion_sp,
2747 addr_t new_section_load_addr,
2748 bool warn_multiple) {
2749 const addr_t old_section_load_addr =
2750 m_section_load_history.GetSectionLoadAddress(
2751 SectionLoadHistory::eStopIDNow, section_sp);
2752 if (old_section_load_addr != new_section_load_addr) {
2753 uint32_t stop_id = 0;
2754 ProcessSP process_sp(GetProcessSP());
2756 stop_id = process_sp->GetStopID();
2758 stop_id = m_section_load_history.GetLastStopID();
2759 if (m_section_load_history.SetSectionLoadAddress(
2760 stop_id, section_sp, new_section_load_addr, warn_multiple))
2761 return true; // Return true if the section load address was changed...
2763 return false; // Return false to indicate nothing changed
2766 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2767 size_t section_unload_count = 0;
2768 size_t num_modules = module_list.GetSize();
2769 for (size_t i = 0; i < num_modules; ++i) {
2770 section_unload_count +=
2771 UnloadModuleSections(module_list.GetModuleAtIndex(i));
2773 return section_unload_count;
2776 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2777 uint32_t stop_id = 0;
2778 ProcessSP process_sp(GetProcessSP());
2780 stop_id = process_sp->GetStopID();
2782 stop_id = m_section_load_history.GetLastStopID();
2783 SectionList *sections = module_sp->GetSectionList();
2784 size_t section_unload_count = 0;
2786 const uint32_t num_sections = sections->GetNumSections(0);
2787 for (uint32_t i = 0; i < num_sections; ++i) {
2788 section_unload_count += m_section_load_history.SetSectionUnloaded(
2789 stop_id, sections->GetSectionAtIndex(i));
2792 return section_unload_count;
2795 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp) {
2796 uint32_t stop_id = 0;
2797 ProcessSP process_sp(GetProcessSP());
2799 stop_id = process_sp->GetStopID();
2801 stop_id = m_section_load_history.GetLastStopID();
2802 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2805 bool Target::SetSectionUnloaded(const lldb::SectionSP §ion_sp,
2807 uint32_t stop_id = 0;
2808 ProcessSP process_sp(GetProcessSP());
2810 stop_id = process_sp->GetStopID();
2812 stop_id = m_section_load_history.GetLastStopID();
2813 return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2817 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2819 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2821 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2824 log->Printf("Target::%s() called for %s", __FUNCTION__,
2825 launch_info.GetExecutableFile().GetPath().c_str());
2827 StateType state = eStateInvalid;
2829 // Scope to temporarily get the process state in case someone has manually
2830 // remotely connected already to a process and we can skip the platform
2833 ProcessSP process_sp(GetProcessSP());
2836 state = process_sp->GetState();
2839 "Target::%s the process exists, and its current state is %s",
2840 __FUNCTION__, StateAsCString(state));
2843 log->Printf("Target::%s the process instance doesn't currently exist.",
2848 launch_info.GetFlags().Set(eLaunchFlagDebug);
2850 // Get the value of synchronous execution here. If you wait till after you
2851 // have started to run, then you could have hit a breakpoint, whose command
2852 // might switch the value, and then you'll pick up that incorrect value.
2853 Debugger &debugger = GetDebugger();
2854 const bool synchronous_execution =
2855 debugger.GetCommandInterpreter().GetSynchronous();
2857 PlatformSP platform_sp(GetPlatform());
2859 FinalizeFileActions(launch_info);
2861 if (state == eStateConnected) {
2862 if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2863 error.SetErrorString(
2864 "can't launch in tty when launching through a remote connection");
2869 if (!launch_info.GetArchitecture().IsValid())
2870 launch_info.GetArchitecture() = GetArchitecture();
2872 // If we're not already connected to the process, and if we have a platform
2873 // that can launch a process for debugging, go ahead and do that here.
2874 if (state != eStateConnected && platform_sp &&
2875 platform_sp->CanDebugProcess()) {
2877 log->Printf("Target::%s asking the platform to debug the process",
2880 // If there was a previous process, delete it before we make the new one.
2881 // One subtle point, we delete the process before we release the reference
2882 // to m_process_sp. That way even if we are the last owner, the process
2883 // will get Finalized before it gets destroyed.
2884 DeleteCurrentProcess();
2887 GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2891 log->Printf("Target::%s the platform doesn't know how to debug a "
2892 "process, getting a process plugin to do this for us.",
2895 if (state == eStateConnected) {
2896 assert(m_process_sp);
2898 // Use a Process plugin to construct the process.
2899 const char *plugin_name = launch_info.GetProcessPluginName();
2900 CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
2903 // Since we didn't have a platform launch the process, launch it here.
2905 error = m_process_sp->Launch(launch_info);
2908 if (!m_process_sp) {
2909 if (error.Success())
2910 error.SetErrorString("failed to launch or debug process");
2914 if (error.Success()) {
2915 if (synchronous_execution ||
2916 !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2917 ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2918 if (!hijack_listener_sp) {
2919 hijack_listener_sp =
2920 Listener::MakeListener("lldb.Target.Launch.hijack");
2921 launch_info.SetHijackListener(hijack_listener_sp);
2922 m_process_sp->HijackProcessEvents(hijack_listener_sp);
2925 StateType state = m_process_sp->WaitForProcessToStop(
2926 llvm::None, nullptr, false, hijack_listener_sp, nullptr);
2928 if (state == eStateStopped) {
2929 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
2930 if (synchronous_execution) {
2931 // Now we have handled the stop-from-attach, and we are just switching
2932 // to a synchronous resume. So we should switch to the SyncResume
2934 m_process_sp->RestoreProcessEvents();
2935 m_process_sp->ResumeSynchronous(stream);
2937 m_process_sp->RestoreProcessEvents();
2938 error = m_process_sp->PrivateResume();
2940 if (!error.Success()) {
2942 error2.SetErrorStringWithFormat(
2943 "process resume at entry point failed: %s", error.AsCString());
2947 } else if (state == eStateExited) {
2948 bool with_shell = !!launch_info.GetShell();
2949 const int exit_status = m_process_sp->GetExitStatus();
2950 const char *exit_desc = m_process_sp->GetExitDescription();
2951 #define LAUNCH_SHELL_MESSAGE \
2952 "\n'r' and 'run' are aliases that default to launching through a " \
2953 "shell.\nTry launching without going through a shell by using 'process " \
2955 if (exit_desc && exit_desc[0]) {
2957 error.SetErrorStringWithFormat(
2958 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
2959 exit_status, exit_desc);
2961 error.SetErrorStringWithFormat("process exited with status %i (%s)",
2962 exit_status, exit_desc);
2965 error.SetErrorStringWithFormat(
2966 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
2969 error.SetErrorStringWithFormat("process exited with status %i",
2973 error.SetErrorStringWithFormat(
2974 "initial process state wasn't stopped: %s", StateAsCString(state));
2977 m_process_sp->RestoreProcessEvents();
2980 error2.SetErrorStringWithFormat("process launch failed: %s",
2987 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
2988 auto state = eStateInvalid;
2989 auto process_sp = GetProcessSP();
2991 state = process_sp->GetState();
2992 if (process_sp->IsAlive() && state != eStateConnected) {
2993 if (state == eStateAttaching)
2994 return Status("process attach is in progress");
2995 return Status("a process is already being debugged");
2999 const ModuleSP old_exec_module_sp = GetExecutableModule();
3001 // If no process info was specified, then use the target executable name as
3002 // the process to attach to by default
3003 if (!attach_info.ProcessInfoSpecified()) {
3004 if (old_exec_module_sp)
3005 attach_info.GetExecutableFile().GetFilename() =
3006 old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3008 if (!attach_info.ProcessInfoSpecified()) {
3009 return Status("no process specified, create a target with a file, or "
3010 "specify the --pid or --name");
3014 const auto platform_sp =
3015 GetDebugger().GetPlatformList().GetSelectedPlatform();
3016 ListenerSP hijack_listener_sp;
3017 const bool async = attach_info.GetAsync();
3019 hijack_listener_sp =
3020 Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3021 attach_info.SetHijackListener(hijack_listener_sp);
3025 if (state != eStateConnected && platform_sp != nullptr &&
3026 platform_sp->CanDebugProcess()) {
3027 SetPlatform(platform_sp);
3028 process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3030 if (state != eStateConnected) {
3031 const char *plugin_name = attach_info.GetProcessPluginName();
3033 CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3034 plugin_name, nullptr);
3035 if (process_sp == nullptr) {
3036 error.SetErrorStringWithFormat(
3037 "failed to create process using plugin %s",
3038 (plugin_name) ? plugin_name : "null");
3042 if (hijack_listener_sp)
3043 process_sp->HijackProcessEvents(hijack_listener_sp);
3044 error = process_sp->Attach(attach_info);
3047 if (error.Success() && process_sp) {
3049 process_sp->RestoreProcessEvents();
3051 state = process_sp->WaitForProcessToStop(
3052 llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3053 process_sp->RestoreProcessEvents();
3055 if (state != eStateStopped) {
3056 const char *exit_desc = process_sp->GetExitDescription();
3058 error.SetErrorStringWithFormat("%s", exit_desc);
3060 error.SetErrorString(
3061 "process did not stop (no such process or permission problem?)");
3062 process_sp->Destroy(false);
3069 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3070 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3072 // Finalize the file actions, and if none were given, default to opening up a
3074 PlatformSP platform_sp = GetPlatform();
3075 const bool default_to_use_pty =
3076 m_platform_sp ? m_platform_sp->IsHost() : false;
3079 "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3081 platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3082 default_to_use_pty);
3084 // If nothing for stdin or stdout or stderr was specified, then check the
3085 // process for any default settings that were set with "settings set"
3086 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3087 info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3088 info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3089 LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3090 "default handling");
3092 if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3093 // Do nothing, if we are launching in a remote terminal no file actions
3094 // should be done at all.
3098 if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3099 LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3100 "for stdin, stdout and stderr");
3101 info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3102 info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3103 info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3105 // Check for any values that might have gotten set with any of: (lldb)
3106 // settings set target.input-path (lldb) settings set target.output-path
3107 // (lldb) settings set target.error-path
3108 FileSpec in_file_spec;
3109 FileSpec out_file_spec;
3110 FileSpec err_file_spec;
3111 // Only override with the target settings if we don't already have an
3112 // action for in, out or error
3113 if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3114 in_file_spec = GetStandardInputPath();
3115 if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3116 out_file_spec = GetStandardOutputPath();
3117 if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3118 err_file_spec = GetStandardErrorPath();
3120 LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3121 in_file_spec, out_file_spec, err_file_spec);
3124 info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3125 LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3128 if (out_file_spec) {
3129 info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3130 LLDB_LOG(log, "appended stdout open file action for {0}",
3134 if (err_file_spec) {
3135 info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3136 LLDB_LOG(log, "appended stderr open file action for {0}",
3140 if (default_to_use_pty &&
3141 (!in_file_spec || !out_file_spec || !err_file_spec)) {
3142 llvm::Error Err = info.SetUpPtyRedirection();
3143 LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3150 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3151 : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3152 m_thread_spec_up() {}
3154 Target::StopHook::StopHook(const StopHook &rhs)
3155 : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3156 m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3157 m_thread_spec_up(), m_active(rhs.m_active),
3158 m_auto_continue(rhs.m_auto_continue) {
3159 if (rhs.m_thread_spec_up)
3160 m_thread_spec_up.reset(new ThreadSpec(*rhs.m_thread_spec_up));
3163 Target::StopHook::~StopHook() = default;
3165 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3166 m_specifier_sp.reset(specifier);
3169 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3170 m_thread_spec_up.reset(specifier);
3173 void Target::StopHook::GetDescription(Stream *s,
3174 lldb::DescriptionLevel level) const {
3175 int indent_level = s->GetIndentLevel();
3177 s->SetIndentLevel(indent_level + 2);
3179 s->Printf("Hook: %" PRIu64 "\n", GetID());
3181 s->Indent("State: enabled\n");
3183 s->Indent("State: disabled\n");
3185 if (m_auto_continue)
3186 s->Indent("AutoContinue on\n");
3188 if (m_specifier_sp) {
3190 s->PutCString("Specifier:\n");
3191 s->SetIndentLevel(indent_level + 4);
3192 m_specifier_sp->GetDescription(s, level);
3193 s->SetIndentLevel(indent_level + 2);
3196 if (m_thread_spec_up) {
3198 s->Indent("Thread:\n");
3199 m_thread_spec_up->GetDescription(&tmp, level);
3200 s->SetIndentLevel(indent_level + 4);
3201 s->Indent(tmp.GetString());
3202 s->PutCString("\n");
3203 s->SetIndentLevel(indent_level + 2);
3206 s->Indent("Commands: \n");
3207 s->SetIndentLevel(indent_level + 4);
3208 uint32_t num_commands = m_commands.GetSize();
3209 for (uint32_t i = 0; i < num_commands; i++) {
3210 s->Indent(m_commands.GetStringAtIndex(i));
3211 s->PutCString("\n");
3213 s->SetIndentLevel(indent_level);
3216 // class TargetProperties
3219 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3220 {eNoDynamicValues, "no-dynamic-values",
3221 "Don't calculate the dynamic type of values"},
3222 {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3223 "even if you have to run the target."},
3224 {eDynamicDontRunTarget, "no-run-target",
3225 "Calculate the dynamic type of values, but don't run the target."} };
3227 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3228 return OptionEnumValues(g_dynamic_value_types);
3231 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3232 {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3233 "locations (fastest). This setting "
3234 "should only be used if you know that "
3235 "no inlining occurs in your programs."},
3236 {eInlineBreakpointsHeaders, "headers",
3237 "Only check for inline breakpoint locations when setting breakpoints in "
3238 "header files, but not when setting breakpoint in implementation source "
3239 "files (default)."},
3240 {eInlineBreakpointsAlways, "always",
3241 "Always look for inline breakpoint locations when setting file and line "
3242 "breakpoints (slower but most accurate)."} };
3244 enum x86DisassemblyFlavor {
3245 eX86DisFlavorDefault,
3250 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3251 {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3252 {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3253 {eX86DisFlavorATT, "att", "AT&T disassembler flavor."} };
3255 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3256 {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3257 {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."} };
3259 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3260 {eLoadScriptFromSymFileTrue, "true",
3261 "Load debug scripts inside symbol files"},
3262 {eLoadScriptFromSymFileFalse, "false",
3263 "Do not load debug scripts inside symbol files."},
3264 {eLoadScriptFromSymFileWarn, "warn",
3265 "Warn about debug scripts inside symbol files but do not load them."} };
3268 OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3269 {eLoadCWDlldbinitTrue, "true",
3270 "Load .lldbinit files from current directory"},
3271 {eLoadCWDlldbinitFalse, "false",
3272 "Do not load .lldbinit files from current directory"},
3273 {eLoadCWDlldbinitWarn, "warn",
3274 "Warn about loading .lldbinit files from current directory"} };
3276 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3277 {eMemoryModuleLoadLevelMinimal, "minimal",
3278 "Load minimal information when loading modules from memory. Currently "
3279 "this setting loads sections only."},
3280 {eMemoryModuleLoadLevelPartial, "partial",
3281 "Load partial information when loading modules from memory. Currently "
3282 "this setting loads sections and function bounds."},
3283 {eMemoryModuleLoadLevelComplete, "complete",
3284 "Load complete information when loading modules from memory. Currently "
3285 "this setting loads sections and all symbols."} };
3287 static constexpr PropertyDefinition g_properties[] = {
3288 {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, {},
3289 "Default architecture to choose, when there's a choice."},
3290 {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3291 {}, "Move breakpoints to nearest code."},
3292 {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3294 "The language to use when interpreting expressions entered in commands."},
3295 {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
3296 "Path to a file containing expressions to be prepended to all "
3298 {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3299 eDynamicDontRunTarget, nullptr, OptionEnumValues(g_dynamic_value_types),
3300 "Should printed values be shown as their dynamic value."},
3301 {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3302 {}, "Should synthetic values be used by default whenever available."},
3303 {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, {},
3304 "Skip function prologues when setting breakpoints by name."},
3305 {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, {},
3306 "Source path remappings are used to track the change of location between "
3307 "a source file when built, and "
3308 "where it exists on the current system. It consists of an array of "
3309 "duples, the first element of each duple is "
3310 "some part (starting at the root) of the path to the file when it was "
3312 "and the second is where the remainder of the original build hierarchy is "
3313 "rooted on the local system. "
3314 "Each element of the array is checked in order and the first one that "
3315 "results in a match wins."},
3316 {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3317 {}, "Executable search paths to use when locating executable files "
3318 "whose paths don't match the local file system."},
3319 {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3321 "List of directories to be searched when locating debug symbol files. "
3322 "See also symbols.enable-external-lookup."},
3323 {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3325 "List of directories to be searched when locating modules for Clang."},
3326 {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3328 "Automatically load Clang modules referred to by the program."},
3329 {"import-std-module", OptionValue::eTypeBoolean, false, false,
3331 "Import the C++ std module to improve debugging STL containers."},
3332 {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3333 {}, "Automatically apply fix-it hints to expressions."},
3334 {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3335 {}, "Print the fixed expression text."},
3336 {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
3337 {}, "Save intermediate object files generated by the LLVM JIT"},
3338 {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3339 {}, "Maximum number of children to expand in any level of depth."},
3340 {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3342 "Maximum number of characters to show when using %s in summary strings."},
3343 {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3344 {}, "Maximum number of bytes that 'memory read' will fetch before "
3345 "--force must be specified."},
3346 {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3347 true, nullptr, {}, "Consult the platform module avoid list when "
3348 "setting non-module specific breakpoints."},
3349 {"arg0", OptionValue::eTypeString, false, 0, nullptr, {},
3350 "The first argument passed to the program in the argument array which can "
3351 "be different from the executable itself."},
3352 {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, {},
3353 "A list containing all the arguments to be passed to the executable when "
3354 "it is run. Note that this does NOT include the argv[0] which is in "
3356 {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3357 nullptr, {}, "A list of all the environment variables to be passed "
3358 "to the executable's environment, and their values."},
3359 {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, {},
3360 "Inherit the environment from the process that is running LLDB."},
3361 {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
3362 "The file/path to be used by the executable program for reading its "
3364 {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
3365 "The file/path to be used by the executable program for writing its "
3366 "standard output."},
3367 {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, {},
3368 "The file/path to be used by the executable program for writing its "
3370 {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3371 {}, "debugserver will detach (rather than killing) a process if it "
3372 "loses connection with lldb."},
3373 {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, {},
3374 "Enable loading of symbol tables before they are needed."},
3375 {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, {},
3376 "Disable Address Space Layout Randomization (ASLR)"},
3377 {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, {},
3378 "Disable stdin/stdout for process (e.g. for a GUI application)"},
3379 {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3380 eInlineBreakpointsAlways, nullptr,
3381 OptionEnumValues(g_inline_breakpoint_enums),
3382 "The strategy to use when settings breakpoints by file and line. "
3383 "Breakpoint locations can end up being inlined by the compiler, so that a "
3384 "compile unit 'a.c' might contain an inlined function from another source "
3386 "Usually this is limited to breakpoint locations from inlined functions "
3387 "from header or other include files, or more accurately "
3388 "non-implementation source files. "
3389 "Sometimes code might #include implementation files and cause inlined "
3390 "breakpoint locations in inlined implementation files. "
3391 "Always checking for inlined breakpoint locations can be expensive "
3392 "(memory and time), so if you have a project with many headers "
3393 "and find that setting breakpoints is slow, then you can change this "
3394 "setting to headers. "
3395 "This setting allows you to control exactly which strategy is used when "
3397 "file and line breakpoints."},
3398 // FIXME: This is the wrong way to do per-architecture settings, but we
3399 // don't have a general per architecture settings system in place yet.
3400 {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3401 eX86DisFlavorDefault, nullptr,
3402 OptionEnumValues(g_x86_dis_flavor_value_types),
3403 "The default disassembly flavor to use for x86 or x86-64 targets."},
3404 {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3405 {}, "Show immediates in disassembly as hexadecimal."},
3406 {"hex-immediate-style", OptionValue::eTypeEnum, false,
3407 Disassembler::eHexStyleC, nullptr,
3408 OptionEnumValues(g_hex_immediate_style_values),
3409 "Which style to use for printing hexadecimal disassembly values."},
3410 {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3411 {}, "Use a fast stepping algorithm based on running from branch to "
3412 "branch rather than instruction single-stepping."},
3413 {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3414 eLoadScriptFromSymFileWarn, nullptr,
3415 OptionEnumValues(g_load_script_from_sym_file_values),
3416 "Allow LLDB to load scripting resources embedded in symbol files when "
3418 {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3419 nullptr, OptionEnumValues(g_load_current_working_dir_lldbinit_values),
3420 "Allow LLDB to .lldbinit files from the current directory automatically."},
3421 {"memory-module-load-level", OptionValue::eTypeEnum, false,
3422 eMemoryModuleLoadLevelComplete, nullptr,
3423 OptionEnumValues(g_memory_module_load_level_values),
3424 "Loading modules from memory can be slow as reading the symbol tables and "
3425 "other data can take a long time depending on your connection to the "
3427 "This setting helps users control how much information gets loaded when "
3428 "loading modules from memory."
3429 "'complete' is the default value for this setting which will load all "
3430 "sections and symbols by reading them from memory (slowest, most "
3432 "'partial' will load sections and attempt to find function bounds without "
3433 "downloading the symbol table (faster, still accurate, missing symbol "
3435 "'minimal' is the fastest setting and will load section data with no "
3436 "symbols, but should rarely be used as stack frames in these memory "
3437 "regions will be inaccurate and not provide any context (fastest). "},
3438 {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3439 nullptr, {}, "Expressions that crash will show up in crash logs if "
3440 "the host system supports executable specific crash log "
3441 "strings and this setting is set to true."},
3442 {"trap-handler-names", OptionValue::eTypeArray, true,
3443 OptionValue::eTypeString, nullptr, {},
3444 "A list of trap handler function names, e.g. a common Unix user process "
3445 "one is _sigtramp."},
3446 {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3447 nullptr, {}, "If true, LLDB will show variables that are meant to "
3448 "support the operation of a language's runtime support."},
3449 {"display-recognized-arguments", OptionValue::eTypeBoolean, false, false,
3450 nullptr, {}, "Show recognized arguments in variable listings by default."},
3451 {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, {},
3452 "Disable lock-step debugging, instead control threads independently."},
3453 {"require-hardware-breakpoint", OptionValue::eTypeBoolean, false, 0,
3454 nullptr, {}, "Require all breakpoints to be hardware breakpoints."}};
3458 ePropertyDefaultArch,
3459 ePropertyMoveToNearestCode,
3461 ePropertyExprPrefix,
3462 ePropertyPreferDynamic,
3463 ePropertyEnableSynthetic,
3464 ePropertySkipPrologue,
3466 ePropertyExecutableSearchPaths,
3467 ePropertyDebugFileSearchPaths,
3468 ePropertyClangModuleSearchPaths,
3469 ePropertyAutoImportClangModules,
3470 ePropertyImportStdModule,
3471 ePropertyAutoApplyFixIts,
3472 ePropertyNotifyAboutFixIts,
3473 ePropertySaveObjects,
3474 ePropertyMaxChildrenCount,
3475 ePropertyMaxSummaryLength,
3476 ePropertyMaxMemReadSize,
3477 ePropertyBreakpointUseAvoidList,
3481 ePropertyInheritEnv,
3483 ePropertyOutputPath,
3485 ePropertyDetachOnError,
3486 ePropertyPreloadSymbols,
3487 ePropertyDisableASLR,
3488 ePropertyDisableSTDIO,
3489 ePropertyInlineStrategy,
3490 ePropertyDisassemblyFlavor,
3491 ePropertyUseHexImmediates,
3492 ePropertyHexImmediateStyle,
3493 ePropertyUseFastStepping,
3494 ePropertyLoadScriptFromSymbolFile,
3495 ePropertyLoadCWDlldbinitFile,
3496 ePropertyMemoryModuleLoadLevel,
3497 ePropertyDisplayExpressionsInCrashlogs,
3498 ePropertyTrapHandlerNames,
3499 ePropertyDisplayRuntimeSupportValues,
3500 ePropertyDisplayRecognizedArguments,
3501 ePropertyNonStopModeEnabled,
3502 ePropertyRequireHardwareBreakpoints,
3503 ePropertyExperimental,
3506 class TargetOptionValueProperties : public OptionValueProperties {
3508 TargetOptionValueProperties(ConstString name)
3509 : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
3511 // This constructor is used when creating TargetOptionValueProperties when it
3512 // is part of a new lldb_private::Target instance. It will copy all current
3513 // global property values as needed
3514 TargetOptionValueProperties(Target *target,
3515 const TargetPropertiesSP &target_properties_sp)
3516 : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3517 m_target(target), m_got_host_env(false) {}
3519 const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3521 uint32_t idx) const override {
3522 // When getting the value for a key from the target options, we will always
3523 // try and grab the setting from the current target if there is one. Else
3524 // we just use the one from this instance.
3525 if (idx == ePropertyEnvVars)
3526 GetHostEnvironmentIfNeeded();
3529 Target *target = exe_ctx->GetTargetPtr();
3531 TargetOptionValueProperties *target_properties =
3532 static_cast<TargetOptionValueProperties *>(
3533 target->GetValueProperties().get());
3534 if (this != target_properties)
3535 return target_properties->ProtectedGetPropertyAtIndex(idx);
3538 return ProtectedGetPropertyAtIndex(idx);
3541 lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3544 void GetHostEnvironmentIfNeeded() const {
3545 if (!m_got_host_env) {
3547 m_got_host_env = true;
3548 const uint32_t idx = ePropertyInheritEnv;
3549 if (GetPropertyAtIndexAsBoolean(
3550 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3551 PlatformSP platform_sp(m_target->GetPlatform());
3553 Environment env = platform_sp->GetEnvironment();
3554 OptionValueDictionary *env_dict =
3555 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3558 const bool can_replace = false;
3559 for (const auto &KV : env) {
3560 // Don't allow existing keys to be replaced with ones we get
3561 // from the platform environment
3562 env_dict->SetValueForKey(
3563 ConstString(KV.first()),
3564 OptionValueSP(new OptionValueString(KV.second.c_str())),
3574 mutable bool m_got_host_env;
3578 static constexpr PropertyDefinition g_experimental_properties[]{
3579 {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3581 "If true, inject local variables explicitly into the expression text. "
3582 "This will fix symbol resolution when there are name collisions between "
3583 "ivars and local variables. "
3584 "But it can make expressions run much more slowly."},
3585 {"use-modern-type-lookup", OptionValue::eTypeBoolean, true, false, nullptr,
3586 {}, "If true, use Clang's modern type lookup infrastructure."}};
3588 enum { ePropertyInjectLocalVars = 0, ePropertyUseModernTypeLookup };
3590 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3592 TargetExperimentalOptionValueProperties()
3593 : OptionValueProperties(
3594 ConstString(Properties::GetExperimentalSettingsName())) {}
3597 TargetExperimentalProperties::TargetExperimentalProperties()
3598 : Properties(OptionValuePropertiesSP(
3599 new TargetExperimentalOptionValueProperties())) {
3600 m_collection_sp->Initialize(g_experimental_properties);
3604 TargetProperties::TargetProperties(Target *target)
3605 : Properties(), m_launch_info() {
3607 m_collection_sp = std::make_shared<TargetOptionValueProperties>(
3608 target, Target::GetGlobalProperties());
3610 // Set callbacks to update launch_info whenever "settins set" updated any
3611 // of these properties
3612 m_collection_sp->SetValueChangedCallback(
3613 ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3614 m_collection_sp->SetValueChangedCallback(
3615 ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3616 m_collection_sp->SetValueChangedCallback(
3617 ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3618 m_collection_sp->SetValueChangedCallback(
3619 ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3621 m_collection_sp->SetValueChangedCallback(
3622 ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3624 m_collection_sp->SetValueChangedCallback(
3625 ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3627 m_collection_sp->SetValueChangedCallback(
3628 ePropertyDetachOnError,
3629 TargetProperties::DetachOnErrorValueChangedCallback, this);
3630 m_collection_sp->SetValueChangedCallback(
3631 ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3633 m_collection_sp->SetValueChangedCallback(
3634 ePropertyDisableSTDIO,
3635 TargetProperties::DisableSTDIOValueChangedCallback, this);
3637 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3638 m_collection_sp->AppendProperty(
3639 ConstString(Properties::GetExperimentalSettingsName()),
3640 ConstString("Experimental settings - setting these won't produce "
3641 "errors if the setting is not present."),
3642 true, m_experimental_properties_up->GetValueProperties());
3644 // Update m_launch_info once it was created
3645 Arg0ValueChangedCallback(this, nullptr);
3646 RunArgsValueChangedCallback(this, nullptr);
3647 // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3648 // Target::GetPlatform()
3649 InputPathValueChangedCallback(this, nullptr);
3650 OutputPathValueChangedCallback(this, nullptr);
3651 ErrorPathValueChangedCallback(this, nullptr);
3652 DetachOnErrorValueChangedCallback(this, nullptr);
3653 DisableASLRValueChangedCallback(this, nullptr);
3654 DisableSTDIOValueChangedCallback(this, nullptr);
3657 std::make_shared<TargetOptionValueProperties>(ConstString("target"));
3658 m_collection_sp->Initialize(g_properties);
3659 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3660 m_collection_sp->AppendProperty(
3661 ConstString(Properties::GetExperimentalSettingsName()),
3662 ConstString("Experimental settings - setting these won't produce "
3663 "errors if the setting is not present."),
3664 true, m_experimental_properties_up->GetValueProperties());
3665 m_collection_sp->AppendProperty(
3666 ConstString("process"), ConstString("Settings specific to processes."),
3667 true, Process::GetGlobalProperties()->GetValueProperties());
3671 TargetProperties::~TargetProperties() = default;
3673 bool TargetProperties::GetInjectLocalVariables(
3674 ExecutionContext *exe_ctx) const {
3675 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3676 exe_ctx, false, ePropertyExperimental);
3677 OptionValueProperties *exp_values =
3678 exp_property->GetValue()->GetAsProperties();
3680 return exp_values->GetPropertyAtIndexAsBoolean(
3681 exe_ctx, ePropertyInjectLocalVars, true);
3686 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3688 const Property *exp_property =
3689 m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3690 OptionValueProperties *exp_values =
3691 exp_property->GetValue()->GetAsProperties();
3693 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3697 bool TargetProperties::GetUseModernTypeLookup() const {
3698 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3699 nullptr, false, ePropertyExperimental);
3700 OptionValueProperties *exp_values =
3701 exp_property->GetValue()->GetAsProperties();
3703 return exp_values->GetPropertyAtIndexAsBoolean(
3704 nullptr, ePropertyUseModernTypeLookup, true);
3709 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3710 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3711 nullptr, ePropertyDefaultArch);
3713 return value->GetCurrentValue();
3717 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3718 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3719 nullptr, ePropertyDefaultArch);
3721 return value->SetCurrentValue(arch, true);
3724 bool TargetProperties::GetMoveToNearestCode() const {
3725 const uint32_t idx = ePropertyMoveToNearestCode;
3726 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3727 nullptr, idx, g_properties[idx].default_uint_value != 0);
3730 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3731 const uint32_t idx = ePropertyPreferDynamic;
3732 return (lldb::DynamicValueType)
3733 m_collection_sp->GetPropertyAtIndexAsEnumeration(
3734 nullptr, idx, g_properties[idx].default_uint_value);
3737 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3738 const uint32_t idx = ePropertyPreferDynamic;
3739 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3742 bool TargetProperties::GetPreloadSymbols() const {
3743 const uint32_t idx = ePropertyPreloadSymbols;
3744 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3745 nullptr, idx, g_properties[idx].default_uint_value != 0);
3748 void TargetProperties::SetPreloadSymbols(bool b) {
3749 const uint32_t idx = ePropertyPreloadSymbols;
3750 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3753 bool TargetProperties::GetDisableASLR() const {
3754 const uint32_t idx = ePropertyDisableASLR;
3755 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3756 nullptr, idx, g_properties[idx].default_uint_value != 0);
3759 void TargetProperties::SetDisableASLR(bool b) {
3760 const uint32_t idx = ePropertyDisableASLR;
3761 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3764 bool TargetProperties::GetDetachOnError() const {
3765 const uint32_t idx = ePropertyDetachOnError;
3766 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3767 nullptr, idx, g_properties[idx].default_uint_value != 0);
3770 void TargetProperties::SetDetachOnError(bool b) {
3771 const uint32_t idx = ePropertyDetachOnError;
3772 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3775 bool TargetProperties::GetDisableSTDIO() const {
3776 const uint32_t idx = ePropertyDisableSTDIO;
3777 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3778 nullptr, idx, g_properties[idx].default_uint_value != 0);
3781 void TargetProperties::SetDisableSTDIO(bool b) {
3782 const uint32_t idx = ePropertyDisableSTDIO;
3783 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3786 const char *TargetProperties::GetDisassemblyFlavor() const {
3787 const uint32_t idx = ePropertyDisassemblyFlavor;
3788 const char *return_value;
3790 x86DisassemblyFlavor flavor_value =
3791 (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3792 nullptr, idx, g_properties[idx].default_uint_value);
3793 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3794 return return_value;
3797 InlineStrategy TargetProperties::GetInlineStrategy() const {
3798 const uint32_t idx = ePropertyInlineStrategy;
3799 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3800 nullptr, idx, g_properties[idx].default_uint_value);
3803 llvm::StringRef TargetProperties::GetArg0() const {
3804 const uint32_t idx = ePropertyArg0;
3805 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
3808 void TargetProperties::SetArg0(llvm::StringRef arg) {
3809 const uint32_t idx = ePropertyArg0;
3810 m_collection_sp->SetPropertyAtIndexAsString(
3812 m_launch_info.SetArg0(arg);
3815 bool TargetProperties::GetRunArguments(Args &args) const {
3816 const uint32_t idx = ePropertyRunArgs;
3817 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3820 void TargetProperties::SetRunArguments(const Args &args) {
3821 const uint32_t idx = ePropertyRunArgs;
3822 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3823 m_launch_info.GetArguments() = args;
3826 Environment TargetProperties::GetEnvironment() const {
3827 // TODO: Get rid of the Args intermediate step
3829 const uint32_t idx = ePropertyEnvVars;
3830 m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3831 return Environment(env);
3834 void TargetProperties::SetEnvironment(Environment env) {
3835 // TODO: Get rid of the Args intermediate step
3836 const uint32_t idx = ePropertyEnvVars;
3837 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3838 m_launch_info.GetEnvironment() = std::move(env);
3841 bool TargetProperties::GetSkipPrologue() const {
3842 const uint32_t idx = ePropertySkipPrologue;
3843 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3844 nullptr, idx, g_properties[idx].default_uint_value != 0);
3847 PathMappingList &TargetProperties::GetSourcePathMap() const {
3848 const uint32_t idx = ePropertySourceMap;
3849 OptionValuePathMappings *option_value =
3850 m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3852 assert(option_value);
3853 return option_value->GetCurrentValue();
3856 void TargetProperties::AppendExecutableSearchPaths(const FileSpec& dir) {
3857 const uint32_t idx = ePropertyExecutableSearchPaths;
3858 OptionValueFileSpecList *option_value =
3859 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3861 assert(option_value);
3862 option_value->AppendCurrentValue(dir);
3865 FileSpecList TargetProperties::GetExecutableSearchPaths() {
3866 const uint32_t idx = ePropertyExecutableSearchPaths;
3867 const OptionValueFileSpecList *option_value =
3868 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3870 assert(option_value);
3871 return option_value->GetCurrentValue();
3874 FileSpecList TargetProperties::GetDebugFileSearchPaths() {
3875 const uint32_t idx = ePropertyDebugFileSearchPaths;
3876 const OptionValueFileSpecList *option_value =
3877 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3879 assert(option_value);
3880 return option_value->GetCurrentValue();
3883 FileSpecList TargetProperties::GetClangModuleSearchPaths() {
3884 const uint32_t idx = ePropertyClangModuleSearchPaths;
3885 const OptionValueFileSpecList *option_value =
3886 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3888 assert(option_value);
3889 return option_value->GetCurrentValue();
3892 bool TargetProperties::GetEnableAutoImportClangModules() const {
3893 const uint32_t idx = ePropertyAutoImportClangModules;
3894 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3895 nullptr, idx, g_properties[idx].default_uint_value != 0);
3898 bool TargetProperties::GetEnableImportStdModule() const {
3899 const uint32_t idx = ePropertyImportStdModule;
3900 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3901 nullptr, idx, g_properties[idx].default_uint_value != 0);
3904 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3905 const uint32_t idx = ePropertyAutoApplyFixIts;
3906 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3907 nullptr, idx, g_properties[idx].default_uint_value != 0);
3910 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3911 const uint32_t idx = ePropertyNotifyAboutFixIts;
3912 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3913 nullptr, idx, g_properties[idx].default_uint_value != 0);
3916 bool TargetProperties::GetEnableSaveObjects() const {
3917 const uint32_t idx = ePropertySaveObjects;
3918 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3919 nullptr, idx, g_properties[idx].default_uint_value != 0);
3922 bool TargetProperties::GetEnableSyntheticValue() const {
3923 const uint32_t idx = ePropertyEnableSynthetic;
3924 return m_collection_sp->GetPropertyAtIndexAsBoolean(
3925 nullptr, idx, g_properties[idx].default_uint_value != 0);
3928 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3929 const uint32_t idx = ePropertyMaxChildrenCount;
3930 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3931 nullptr, idx, g_properties[idx].default_uint_value);
3934 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3935 const uint32_t idx = ePropertyMaxSummaryLength;
3936 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3937 nullptr, idx, g_properties[idx].default_uint_value);
3940 uint32_t TargetProperties::GetMaximumMemReadSize() const {
3941 const uint32_t idx = ePropertyMaxMemReadSize;
3942 return m_collection_sp->GetPropertyAtIndexAsSInt64(
3943 nullptr, idx, g_properties[idx].default_uint_value);
3946 FileSpec TargetProperties::GetStandardInputPath() const {
3947 const uint32_t idx = ePropertyInputPath;
3948 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3951 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
3952 const uint32_t idx = ePropertyInputPath;
3953 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3956 FileSpec TargetProperties::GetStandardOutputPath() const {
3957 const uint32_t idx = ePropertyOutputPath;
3958 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3961 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
3962 const uint32_t idx = ePropertyOutputPath;
3963 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3966 FileSpec TargetProperties::GetStandardErrorPath() const {
3967 const uint32_t idx = ePropertyErrorPath;
3968 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3971 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3972 const uint32_t idx = ePropertyErrorPath;
3973 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3976 LanguageType TargetProperties::GetLanguage() const {
3977 OptionValueLanguage *value =
3978 m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3979 nullptr, ePropertyLanguage);
3981 return value->GetCurrentValue();
3982 return LanguageType();
3985 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
3986 const uint32_t idx = ePropertyExprPrefix;
3987 OptionValueFileSpec *file =
3988 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3991 DataBufferSP data_sp(file->GetFileContents());
3993 return llvm::StringRef(
3994 reinterpret_cast<const char *>(data_sp->GetBytes()),
3995 data_sp->GetByteSize());
4000 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4001 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4002 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4003 nullptr, idx, g_properties[idx].default_uint_value != 0);
4006 bool TargetProperties::GetUseHexImmediates() const {
4007 const uint32_t idx = ePropertyUseHexImmediates;
4008 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4009 nullptr, idx, g_properties[idx].default_uint_value != 0);
4012 bool TargetProperties::GetUseFastStepping() const {
4013 const uint32_t idx = ePropertyUseFastStepping;
4014 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4015 nullptr, idx, g_properties[idx].default_uint_value != 0);
4018 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4019 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4020 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4021 nullptr, idx, g_properties[idx].default_uint_value != 0);
4024 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4025 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4026 return (LoadScriptFromSymFile)
4027 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4028 nullptr, idx, g_properties[idx].default_uint_value);
4031 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4032 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4033 return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4034 nullptr, idx, g_properties[idx].default_uint_value);
4037 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4038 const uint32_t idx = ePropertyHexImmediateStyle;
4039 return (Disassembler::HexImmediateStyle)
4040 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4041 nullptr, idx, g_properties[idx].default_uint_value);
4044 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4045 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4046 return (MemoryModuleLoadLevel)
4047 m_collection_sp->GetPropertyAtIndexAsEnumeration(
4048 nullptr, idx, g_properties[idx].default_uint_value);
4051 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4052 const uint32_t idx = ePropertyTrapHandlerNames;
4053 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4056 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4057 const uint32_t idx = ePropertyTrapHandlerNames;
4058 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4061 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4062 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4063 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4066 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4067 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4068 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4071 bool TargetProperties::GetDisplayRecognizedArguments() const {
4072 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4073 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4076 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
4077 const uint32_t idx = ePropertyDisplayRecognizedArguments;
4078 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4081 bool TargetProperties::GetNonStopModeEnabled() const {
4082 const uint32_t idx = ePropertyNonStopModeEnabled;
4083 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4086 void TargetProperties::SetNonStopModeEnabled(bool b) {
4087 const uint32_t idx = ePropertyNonStopModeEnabled;
4088 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4091 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
4092 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4093 return m_launch_info;
4096 void TargetProperties::SetProcessLaunchInfo(
4097 const ProcessLaunchInfo &launch_info) {
4098 m_launch_info = launch_info;
4099 SetArg0(launch_info.GetArg0());
4100 SetRunArguments(launch_info.GetArguments());
4101 SetEnvironment(launch_info.GetEnvironment());
4102 const FileAction *input_file_action =
4103 launch_info.GetFileActionForFD(STDIN_FILENO);
4104 if (input_file_action) {
4105 SetStandardInputPath(input_file_action->GetPath());
4107 const FileAction *output_file_action =
4108 launch_info.GetFileActionForFD(STDOUT_FILENO);
4109 if (output_file_action) {
4110 SetStandardOutputPath(output_file_action->GetPath());
4112 const FileAction *error_file_action =
4113 launch_info.GetFileActionForFD(STDERR_FILENO);
4114 if (error_file_action) {
4115 SetStandardErrorPath(error_file_action->GetPath());
4117 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4118 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4119 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4122 bool TargetProperties::GetRequireHardwareBreakpoints() const {
4123 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4124 return m_collection_sp->GetPropertyAtIndexAsBoolean(
4125 nullptr, idx, g_properties[idx].default_uint_value != 0);
4128 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
4129 const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4130 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4133 void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4135 TargetProperties *this_ =
4136 reinterpret_cast<TargetProperties *>(target_property_ptr);
4137 this_->m_launch_info.SetArg0(this_->GetArg0());
4140 void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4142 TargetProperties *this_ =
4143 reinterpret_cast<TargetProperties *>(target_property_ptr);
4145 if (this_->GetRunArguments(args))
4146 this_->m_launch_info.GetArguments() = args;
4149 void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4151 TargetProperties *this_ =
4152 reinterpret_cast<TargetProperties *>(target_property_ptr);
4153 this_->m_launch_info.GetEnvironment() = this_->GetEnvironment();
4156 void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4158 TargetProperties *this_ =
4159 reinterpret_cast<TargetProperties *>(target_property_ptr);
4160 this_->m_launch_info.AppendOpenFileAction(
4161 STDIN_FILENO, this_->GetStandardInputPath(), true, false);
4164 void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4166 TargetProperties *this_ =
4167 reinterpret_cast<TargetProperties *>(target_property_ptr);
4168 this_->m_launch_info.AppendOpenFileAction(
4169 STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
4172 void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4174 TargetProperties *this_ =
4175 reinterpret_cast<TargetProperties *>(target_property_ptr);
4176 this_->m_launch_info.AppendOpenFileAction(
4177 STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
4180 void TargetProperties::DetachOnErrorValueChangedCallback(
4181 void *target_property_ptr, OptionValue *) {
4182 TargetProperties *this_ =
4183 reinterpret_cast<TargetProperties *>(target_property_ptr);
4184 if (this_->GetDetachOnError())
4185 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4187 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4190 void TargetProperties::DisableASLRValueChangedCallback(
4191 void *target_property_ptr, OptionValue *) {
4192 TargetProperties *this_ =
4193 reinterpret_cast<TargetProperties *>(target_property_ptr);
4194 if (this_->GetDisableASLR())
4195 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4197 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4200 void TargetProperties::DisableSTDIOValueChangedCallback(
4201 void *target_property_ptr, OptionValue *) {
4202 TargetProperties *this_ =
4203 reinterpret_cast<TargetProperties *>(target_property_ptr);
4204 if (this_->GetDisableSTDIO())
4205 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4207 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4210 // Target::TargetEventData
4212 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4213 : EventData(), m_target_sp(target_sp), m_module_list() {}
4215 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4216 const ModuleList &module_list)
4217 : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4219 Target::TargetEventData::~TargetEventData() = default;
4221 ConstString Target::TargetEventData::GetFlavorString() {
4222 static ConstString g_flavor("Target::TargetEventData");
4226 void Target::TargetEventData::Dump(Stream *s) const {
4227 for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4230 m_module_list.GetModuleAtIndex(i)->GetDescription(
4231 s, lldb::eDescriptionLevelBrief);
4235 const Target::TargetEventData *
4236 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4238 const EventData *event_data = event_ptr->GetData();
4240 event_data->GetFlavor() == TargetEventData::GetFlavorString())
4241 return static_cast<const TargetEventData *>(event_ptr->GetData());
4246 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4248 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4250 target_sp = event_data->m_target_sp;
4255 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4256 ModuleList module_list;
4257 const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4259 module_list = event_data->m_module_list;