1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 // Other libraries and framework includes
15 #include "lldb/Target/Target.h"
16 #include "lldb/Breakpoint/BreakpointResolver.h"
17 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
18 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
19 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
20 #include "lldb/Breakpoint/BreakpointResolverName.h"
21 #include "lldb/Breakpoint/Watchpoint.h"
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/Event.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/Module.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/Section.h"
28 #include "lldb/Core/SourceManager.h"
29 #include "lldb/Core/State.h"
30 #include "lldb/Core/StreamFile.h"
31 #include "lldb/Core/StreamString.h"
32 #include "lldb/Core/Timer.h"
33 #include "lldb/Core/ValueObject.h"
34 #include "lldb/Expression/REPL.h"
35 #include "lldb/Expression/UserExpression.h"
36 #include "Plugins/ExpressionParser/Clang/ClangASTSource.h"
37 #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h"
38 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
39 #include "lldb/Host/FileSpec.h"
40 #include "lldb/Host/Host.h"
41 #include "lldb/Interpreter/CommandInterpreter.h"
42 #include "lldb/Interpreter/CommandReturnObject.h"
43 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
44 #include "lldb/Interpreter/OptionValues.h"
45 #include "lldb/Interpreter/Property.h"
46 #include "lldb/Symbol/ClangASTContext.h"
47 #include "lldb/Symbol/ObjectFile.h"
48 #include "lldb/Symbol/Function.h"
49 #include "lldb/Symbol/Symbol.h"
50 #include "lldb/Target/Language.h"
51 #include "lldb/Target/LanguageRuntime.h"
52 #include "lldb/Target/ObjCLanguageRuntime.h"
53 #include "lldb/Target/Process.h"
54 #include "lldb/Target/SectionLoadList.h"
55 #include "lldb/Target/StackFrame.h"
56 #include "lldb/Target/SystemRuntime.h"
57 #include "lldb/Target/Thread.h"
58 #include "lldb/Target/ThreadSpec.h"
59 #include "lldb/Utility/LLDBAssert.h"
62 using namespace lldb_private;
65 Target::GetStaticBroadcasterClass ()
67 static ConstString class_name ("lldb.target");
71 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp,
73 : TargetProperties(this),
74 Broadcaster(debugger.GetBroadcasterManager(), Target::GetStaticBroadcasterClass().AsCString()),
75 ExecutionContextScope(),
77 m_platform_sp(platform_sp),
81 m_section_load_history(),
82 m_breakpoint_list(false),
83 m_internal_breakpoint_list(true),
87 m_image_search_paths(ImageSearchPathsChanged, this),
89 m_source_manager_ap(),
91 m_stop_hook_next_id(0),
93 m_suppress_stop_hooks(false),
94 m_is_dummy_target(is_dummy_target)
97 SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
98 SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
99 SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
100 SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
101 SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
103 CheckInWithManager();
105 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
107 log->Printf("%p Target::Target()", static_cast<void *>(this));
108 if (m_arch.IsValid())
110 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::Target created with architecture %s (%s)",
111 m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
117 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
119 log->Printf ("%p Target::~Target()", static_cast<void*>(this));
120 DeleteCurrentProcess ();
124 Target::PrimeFromDummyTarget(Target *target)
129 m_stop_hooks = target->m_stop_hooks;
131 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints())
133 if (breakpoint_sp->IsInternal())
136 BreakpointSP new_bp (new Breakpoint (*this, *breakpoint_sp.get()));
137 AddBreakpoint (new_bp, false);
142 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
144 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
145 if (description_level != lldb::eDescriptionLevelBrief)
148 s->PutCString("Target\n");
151 m_breakpoint_list.Dump(s);
152 m_internal_breakpoint_list.Dump(s);
157 Module *exe_module = GetExecutableModulePointer();
159 s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
161 s->PutCString ("No executable module.");
166 Target::CleanupProcess ()
168 // Do any cleanup of the target we need to do between process instances.
169 // NB It is better to do this before destroying the process in case the
170 // clean up needs some help from the process.
171 m_breakpoint_list.ClearAllBreakpointSites();
172 m_internal_breakpoint_list.ClearAllBreakpointSites();
173 // Disable watchpoints just on the debugger side.
174 std::unique_lock<std::recursive_mutex> lock;
175 this->GetWatchpointList().GetListMutex(lock);
176 DisableAllWatchpoints(false);
177 ClearAllWatchpointHitCounts();
178 ClearAllWatchpointHistoricValues();
182 Target::DeleteCurrentProcess ()
186 m_section_load_history.Clear();
187 if (m_process_sp->IsAlive())
188 m_process_sp->Destroy(false);
190 m_process_sp->Finalize();
194 m_process_sp.reset();
198 const lldb::ProcessSP &
199 Target::CreateProcess (ListenerSP listener_sp, const char *plugin_name, const FileSpec *crash_file)
201 DeleteCurrentProcess ();
202 m_process_sp = Process::FindPlugin(shared_from_this(), plugin_name, listener_sp, crash_file);
206 const lldb::ProcessSP &
207 Target::GetProcessSP () const
213 Target::GetREPL (Error &err, lldb::LanguageType language, const char *repl_options, bool can_create)
215 if (language == eLanguageTypeUnknown)
217 std::set<LanguageType> repl_languages;
219 Language::GetLanguagesSupportingREPLs(repl_languages);
221 if (repl_languages.size() == 1)
223 language = *repl_languages.begin();
225 else if (repl_languages.size() == 0)
227 err.SetErrorStringWithFormat("LLDB isn't configured with REPL support for any languages.");
232 err.SetErrorStringWithFormat("Multiple possible REPL languages. Please specify a language.");
237 REPLMap::iterator pos = m_repl_map.find(language);
239 if (pos != m_repl_map.end())
246 err.SetErrorStringWithFormat("Couldn't find an existing REPL for %s, and can't create a new one", Language::GetNameForLanguageType(language));
247 return lldb::REPLSP();
250 Debugger *const debugger = nullptr;
251 lldb::REPLSP ret = REPL::Create(err, language, debugger, this, repl_options);
255 m_repl_map[language] = ret;
256 return m_repl_map[language];
261 err.SetErrorStringWithFormat("Couldn't create a REPL for %s", Language::GetNameForLanguageType(language));
264 return lldb::REPLSP();
268 Target::SetREPL (lldb::LanguageType language, lldb::REPLSP repl_sp)
270 lldbassert(!m_repl_map.count(language));
272 m_repl_map[language] = repl_sp;
278 std::lock_guard<std::recursive_mutex> guard(m_mutex);
280 DeleteCurrentProcess ();
281 m_platform_sp.reset();
284 m_section_load_history.Clear();
285 const bool notify = false;
286 m_breakpoint_list.RemoveAll(notify);
287 m_internal_breakpoint_list.RemoveAll(notify);
288 m_last_created_breakpoint.reset();
289 m_last_created_watchpoint.reset();
290 m_search_filter_sp.reset();
291 m_image_search_paths.Clear(notify);
292 m_stop_hooks.clear();
293 m_stop_hook_next_id = 0;
294 m_suppress_stop_hooks = false;
298 Target::GetBreakpointList(bool internal)
301 return m_internal_breakpoint_list;
303 return m_breakpoint_list;
306 const BreakpointList &
307 Target::GetBreakpointList(bool internal) const
310 return m_internal_breakpoint_list;
312 return m_breakpoint_list;
316 Target::GetBreakpointByID (break_id_t break_id)
320 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
321 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
323 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
329 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
330 const FileSpecList *source_file_spec_list,
331 const std::unordered_set<std::string> &function_names,
332 RegularExpression &source_regex,
335 LazyBool move_to_nearest_code)
337 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list));
338 if (move_to_nearest_code == eLazyBoolCalculate)
339 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
340 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex(nullptr,
343 !static_cast<bool>(move_to_nearest_code)));
345 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
349 Target::CreateBreakpoint (const FileSpecList *containingModules,
350 const FileSpec &file,
353 LazyBool check_inlines,
354 LazyBool skip_prologue,
357 LazyBool move_to_nearest_code)
359 FileSpec remapped_file;
360 ConstString remapped_path;
361 if (GetSourcePathMap().ReverseRemapPath(ConstString(file.GetPath().c_str()), remapped_path))
362 remapped_file.SetFile(remapped_path.AsCString(), true);
364 remapped_file = file;
366 if (check_inlines == eLazyBoolCalculate)
368 const InlineStrategy inline_strategy = GetInlineStrategy();
369 switch (inline_strategy)
371 case eInlineBreakpointsNever:
372 check_inlines = eLazyBoolNo;
375 case eInlineBreakpointsHeaders:
376 if (remapped_file.IsSourceImplementationFile())
377 check_inlines = eLazyBoolNo;
379 check_inlines = eLazyBoolYes;
382 case eInlineBreakpointsAlways:
383 check_inlines = eLazyBoolYes;
387 SearchFilterSP filter_sp;
388 if (check_inlines == eLazyBoolNo)
390 // Not checking for inlines, we are looking only for matching compile units
391 FileSpecList compile_unit_list;
392 compile_unit_list.Append (remapped_file);
393 filter_sp = GetSearchFilterForModuleAndCUList (containingModules, &compile_unit_list);
397 filter_sp = GetSearchFilterForModuleList (containingModules);
399 if (skip_prologue == eLazyBoolCalculate)
400 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
401 if (move_to_nearest_code == eLazyBoolCalculate)
402 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
404 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (nullptr,
410 !static_cast<bool>(move_to_nearest_code)));
411 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
415 Target::CreateBreakpoint (lldb::addr_t addr, bool internal, bool hardware)
419 // Check for any reason we want to move this breakpoint to other address.
420 addr = GetBreakableLoadAddress(addr);
422 // Attempt to resolve our load address if possible, though it is ok if
423 // it doesn't resolve to section/offset.
425 // Try and resolve as a load address if possible
426 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
427 if (!so_addr.IsValid())
429 // The address didn't resolve, so just set this as an absolute address
430 so_addr.SetOffset (addr);
432 BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal, hardware));
437 Target::CreateBreakpoint (const Address &addr, bool internal, bool hardware)
439 SearchFilterSP filter_sp(new SearchFilterForUnconstrainedSearches (shared_from_this()));
440 BreakpointResolverSP resolver_sp(new BreakpointResolverAddress(nullptr, addr));
441 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, false);
445 Target::CreateAddressInModuleBreakpoint (lldb::addr_t file_addr,
447 const FileSpec *file_spec,
448 bool request_hardware)
450 SearchFilterSP filter_sp(new SearchFilterForUnconstrainedSearches (shared_from_this()));
451 BreakpointResolverSP resolver_sp(new BreakpointResolverAddress(nullptr, file_addr, file_spec));
452 return CreateBreakpoint (filter_sp, resolver_sp, internal, request_hardware, false);
456 Target::CreateBreakpoint (const FileSpecList *containingModules,
457 const FileSpecList *containingSourceFiles,
458 const char *func_name,
459 uint32_t func_name_type_mask,
460 LanguageType language,
462 LazyBool skip_prologue,
469 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
471 if (skip_prologue == eLazyBoolCalculate)
472 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
473 if (language == lldb::eLanguageTypeUnknown)
474 language = GetLanguage();
476 BreakpointResolverSP resolver_sp (new BreakpointResolverName (nullptr,
483 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
489 Target::CreateBreakpoint (const FileSpecList *containingModules,
490 const FileSpecList *containingSourceFiles,
491 const std::vector<std::string> &func_names,
492 uint32_t func_name_type_mask,
493 LanguageType language,
495 LazyBool skip_prologue,
500 size_t num_names = func_names.size();
503 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
505 if (skip_prologue == eLazyBoolCalculate)
506 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
507 if (language == lldb::eLanguageTypeUnknown)
508 language = GetLanguage();
511 BreakpointResolverSP resolver_sp (new BreakpointResolverName (nullptr,
517 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
523 Target::CreateBreakpoint (const FileSpecList *containingModules,
524 const FileSpecList *containingSourceFiles,
525 const char *func_names[],
527 uint32_t func_name_type_mask,
528 LanguageType language,
530 LazyBool skip_prologue,
537 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
539 if (skip_prologue == eLazyBoolCalculate)
542 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
544 skip_prologue = eLazyBoolNo;
546 if (language == lldb::eLanguageTypeUnknown)
547 language = GetLanguage();
549 BreakpointResolverSP resolver_sp (new BreakpointResolverName (nullptr,
556 resolver_sp->SetOffset(offset);
557 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
563 Target::GetSearchFilterForModule (const FileSpec *containingModule)
565 SearchFilterSP filter_sp;
566 if (containingModule != nullptr)
568 // TODO: We should look into sharing module based search filters
569 // across many breakpoints like we do for the simple target based one
570 filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule));
574 if (!m_search_filter_sp)
575 m_search_filter_sp.reset (new SearchFilterForUnconstrainedSearches (shared_from_this()));
576 filter_sp = m_search_filter_sp;
582 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules)
584 SearchFilterSP filter_sp;
585 if (containingModules && containingModules->GetSize() != 0)
587 // TODO: We should look into sharing module based search filters
588 // across many breakpoints like we do for the simple target based one
589 filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules));
593 if (!m_search_filter_sp)
594 m_search_filter_sp.reset (new SearchFilterForUnconstrainedSearches (shared_from_this()));
595 filter_sp = m_search_filter_sp;
601 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules,
602 const FileSpecList *containingSourceFiles)
604 if (containingSourceFiles == nullptr || containingSourceFiles->GetSize() == 0)
605 return GetSearchFilterForModuleList(containingModules);
607 SearchFilterSP filter_sp;
608 if (containingModules == nullptr)
610 // We could make a special "CU List only SearchFilter". Better yet was if these could be composable,
611 // but that will take a little reworking.
613 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles));
617 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles));
623 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
624 const FileSpecList *containingSourceFiles,
625 RegularExpression &func_regex,
626 lldb::LanguageType requested_language,
627 LazyBool skip_prologue,
631 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
633 (skip_prologue == eLazyBoolCalculate) ? GetSkipPrologue()
634 : static_cast<bool>(skip_prologue);
635 BreakpointResolverSP resolver_sp(new BreakpointResolverName (nullptr,
641 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
645 Target::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal, Args *additional_args, Error *error)
647 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal);
648 if (exc_bkpt_sp && additional_args)
650 Breakpoint::BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
651 if (precondition_sp && additional_args)
654 *error = precondition_sp->ConfigurePrecondition(*additional_args);
656 precondition_sp->ConfigurePrecondition(*additional_args);
663 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal, bool request_hardware, bool resolve_indirect_symbols)
666 if (filter_sp && resolver_sp)
668 bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp, request_hardware, resolve_indirect_symbols));
669 resolver_sp->SetBreakpoint (bp_sp.get());
670 AddBreakpoint (bp_sp, internal);
676 Target::AddBreakpoint (lldb::BreakpointSP bp_sp, bool internal)
681 m_internal_breakpoint_list.Add (bp_sp, false);
683 m_breakpoint_list.Add (bp_sp, true);
685 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
689 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
690 log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
693 bp_sp->ResolveBreakpoint();
697 m_last_created_breakpoint = bp_sp;
702 Target::ProcessIsValid()
704 return (m_process_sp && m_process_sp->IsAlive());
708 CheckIfWatchpointsExhausted(Target *target, Error &error)
710 uint32_t num_supported_hardware_watchpoints;
711 Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints);
712 if (num_supported_hardware_watchpoints == 0)
714 error.SetErrorStringWithFormat ("Target supports (%u) hardware watchpoint slots.\n",
715 num_supported_hardware_watchpoints);
721 // See also Watchpoint::SetWatchpointType(uint32_t type) and
722 // the OptionGroupWatchpoint::WatchType enum type.
724 Target::CreateWatchpoint(lldb::addr_t addr, size_t size, const CompilerType *type, uint32_t kind, Error &error)
726 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
728 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64 " type = %u)\n",
729 __FUNCTION__, addr, (uint64_t)size, kind);
732 if (!ProcessIsValid())
734 error.SetErrorString("process is not alive");
738 if (addr == LLDB_INVALID_ADDRESS || size == 0)
741 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
743 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
747 if (!LLDB_WATCH_TYPE_IS_VALID(kind))
749 error.SetErrorStringWithFormat ("invalid watchpoint type: %d", kind);
752 if (!CheckIfWatchpointsExhausted (this, error))
755 // Currently we only support one watchpoint per address, with total number
756 // of watchpoints limited by the hardware which the inferior is running on.
758 // Grab the list mutex while doing operations.
759 const bool notify = false; // Don't notify about all the state changes we do on creating the watchpoint.
760 std::unique_lock<std::recursive_mutex> lock;
761 this->GetWatchpointList().GetListMutex(lock);
762 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
765 size_t old_size = matched_sp->GetByteSize();
767 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
768 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
769 // Return the existing watchpoint if both size and type match.
770 if (size == old_size && kind == old_type)
773 wp_sp->SetEnabled(false, notify);
777 // Nil the matched watchpoint; we will be creating a new one.
778 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
779 m_watchpoint_list.Remove(matched_sp->GetID(), true);
785 wp_sp.reset(new Watchpoint(*this, addr, size, type));
786 wp_sp->SetWatchpointType(kind, notify);
787 m_watchpoint_list.Add (wp_sp, true);
790 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
792 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
794 error.Success() ? "succeeded" : "failed",
799 // Enabling the watchpoint on the device side failed.
800 // Remove the said watchpoint from the list maintained by the target instance.
801 m_watchpoint_list.Remove (wp_sp->GetID(), true);
802 // See if we could provide more helpful error message.
803 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
804 error.SetErrorStringWithFormat("watch size of %" PRIu64 " is not supported", (uint64_t)size);
809 m_last_created_watchpoint = wp_sp;
814 Target::RemoveAllBreakpoints (bool internal_also)
816 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
818 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
820 m_breakpoint_list.RemoveAll (true);
822 m_internal_breakpoint_list.RemoveAll (false);
824 m_last_created_breakpoint.reset();
828 Target::DisableAllBreakpoints (bool internal_also)
830 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
832 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
834 m_breakpoint_list.SetEnabledAll (false);
836 m_internal_breakpoint_list.SetEnabledAll (false);
840 Target::EnableAllBreakpoints (bool internal_also)
842 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
844 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
846 m_breakpoint_list.SetEnabledAll (true);
848 m_internal_breakpoint_list.SetEnabledAll (true);
852 Target::RemoveBreakpointByID (break_id_t break_id)
854 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
856 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
858 if (DisableBreakpointByID (break_id))
860 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
861 m_internal_breakpoint_list.Remove(break_id, false);
864 if (m_last_created_breakpoint)
866 if (m_last_created_breakpoint->GetID() == break_id)
867 m_last_created_breakpoint.reset();
869 m_breakpoint_list.Remove(break_id, true);
877 Target::DisableBreakpointByID (break_id_t break_id)
879 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
881 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
885 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
886 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
888 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
891 bp_sp->SetEnabled (false);
898 Target::EnableBreakpointByID (break_id_t break_id)
900 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
902 log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
905 LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
909 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
910 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
912 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
916 bp_sp->SetEnabled (true);
922 // The flag 'end_to_end', default to true, signifies that the operation is
923 // performed end to end, for both the debugger and the debuggee.
925 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
926 // to end operations.
928 Target::RemoveAllWatchpoints (bool end_to_end)
930 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
932 log->Printf ("Target::%s\n", __FUNCTION__);
935 m_watchpoint_list.RemoveAll(true);
939 // Otherwise, it's an end to end operation.
941 if (!ProcessIsValid())
944 size_t num_watchpoints = m_watchpoint_list.GetSize();
945 for (size_t i = 0; i < num_watchpoints; ++i)
947 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
951 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
955 m_watchpoint_list.RemoveAll (true);
956 m_last_created_watchpoint.reset();
957 return true; // Success!
960 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
963 Target::DisableAllWatchpoints (bool end_to_end)
965 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
967 log->Printf ("Target::%s\n", __FUNCTION__);
970 m_watchpoint_list.SetEnabledAll(false);
974 // Otherwise, it's an end to end operation.
976 if (!ProcessIsValid())
979 size_t num_watchpoints = m_watchpoint_list.GetSize();
980 for (size_t i = 0; i < num_watchpoints; ++i)
982 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
986 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
990 return true; // Success!
993 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
996 Target::EnableAllWatchpoints (bool end_to_end)
998 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1000 log->Printf ("Target::%s\n", __FUNCTION__);
1003 m_watchpoint_list.SetEnabledAll(true);
1007 // Otherwise, it's an end to end operation.
1009 if (!ProcessIsValid())
1012 size_t num_watchpoints = m_watchpoint_list.GetSize();
1013 for (size_t i = 0; i < num_watchpoints; ++i)
1015 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1019 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1023 return true; // Success!
1026 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1028 Target::ClearAllWatchpointHitCounts ()
1030 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1032 log->Printf ("Target::%s\n", __FUNCTION__);
1034 size_t num_watchpoints = m_watchpoint_list.GetSize();
1035 for (size_t i = 0; i < num_watchpoints; ++i)
1037 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1041 wp_sp->ResetHitCount();
1043 return true; // Success!
1046 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1048 Target::ClearAllWatchpointHistoricValues ()
1050 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1052 log->Printf ("Target::%s\n", __FUNCTION__);
1054 size_t num_watchpoints = m_watchpoint_list.GetSize();
1055 for (size_t i = 0; i < num_watchpoints; ++i)
1057 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1061 wp_sp->ResetHistoricValues();
1063 return true; // Success!
1066 // Assumption: Caller holds the list mutex lock for m_watchpoint_list
1067 // during these operations.
1069 Target::IgnoreAllWatchpoints (uint32_t ignore_count)
1071 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1073 log->Printf ("Target::%s\n", __FUNCTION__);
1075 if (!ProcessIsValid())
1078 size_t num_watchpoints = m_watchpoint_list.GetSize();
1079 for (size_t i = 0; i < num_watchpoints; ++i)
1081 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
1085 wp_sp->SetIgnoreCount(ignore_count);
1087 return true; // Success!
1090 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1092 Target::DisableWatchpointByID (lldb::watch_id_t watch_id)
1094 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1096 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1098 if (!ProcessIsValid())
1101 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
1104 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
1108 // Else, fallthrough.
1113 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1115 Target::EnableWatchpointByID (lldb::watch_id_t watch_id)
1117 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1119 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1121 if (!ProcessIsValid())
1124 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
1127 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1131 // Else, fallthrough.
1136 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1138 Target::RemoveWatchpointByID (lldb::watch_id_t watch_id)
1140 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1142 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1144 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1145 if (watch_to_remove_sp == m_last_created_watchpoint)
1146 m_last_created_watchpoint.reset();
1148 if (DisableWatchpointByID (watch_id))
1150 m_watchpoint_list.Remove(watch_id, true);
1156 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1158 Target::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
1160 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1162 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1164 if (!ProcessIsValid())
1167 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
1170 wp_sp->SetIgnoreCount(ignore_count);
1177 Target::GetExecutableModule ()
1179 // search for the first executable in the module list
1180 for (size_t i = 0; i < m_images.GetSize(); ++i)
1182 ModuleSP module_sp = m_images.GetModuleAtIndex (i);
1183 lldb_private::ObjectFile * obj = module_sp->GetObjectFile();
1186 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1189 // as fall back return the first module loaded
1190 return m_images.GetModuleAtIndex (0);
1194 Target::GetExecutableModulePointer ()
1196 return GetExecutableModule().get();
1200 LoadScriptingResourceForModule (const ModuleSP &module_sp, Target *target)
1203 StreamString feedback_stream;
1204 if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error, &feedback_stream))
1206 if (error.AsCString())
1207 target->GetDebugger().GetErrorFile()->Printf("unable to load scripting data for module %s - error reported was %s\n",
1208 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1211 if (feedback_stream.GetSize())
1212 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1213 feedback_stream.GetData());
1217 Target::ClearModules(bool delete_locations)
1219 ModulesDidUnload (m_images, delete_locations);
1220 m_section_load_history.Clear();
1222 m_scratch_type_system_map.Clear();
1223 m_ast_importer_sp.reset();
1229 // When a process exec's we need to know about it so we can do some cleanup.
1230 m_breakpoint_list.RemoveInvalidLocations(m_arch);
1231 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch);
1235 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
1237 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1238 ClearModules(false);
1242 Timer scoped_timer (__PRETTY_FUNCTION__,
1243 "Target::SetExecutableModule (executable = '%s')",
1244 executable_sp->GetFileSpec().GetPath().c_str());
1246 m_images.Append(executable_sp); // The first image is our executable file
1248 // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
1249 if (!m_arch.IsValid())
1251 m_arch = executable_sp->GetArchitecture();
1253 log->Printf ("Target::SetExecutableModule setting architecture to %s (%s) based on executable file", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
1256 FileSpecList dependent_files;
1257 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1259 if (executable_objfile && get_dependent_files)
1261 executable_objfile->GetDependentModules(dependent_files);
1262 for (uint32_t i=0; i<dependent_files.GetSize(); i++)
1264 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
1265 FileSpec platform_dependent_file_spec;
1267 m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr, platform_dependent_file_spec);
1269 platform_dependent_file_spec = dependent_file_spec;
1271 ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
1272 ModuleSP image_module_sp(GetSharedModule (module_spec));
1273 if (image_module_sp)
1275 ObjectFile *objfile = image_module_sp->GetObjectFile();
1277 objfile->GetDependentModules(dependent_files);
1285 Target::SetArchitecture (const ArchSpec &arch_spec)
1287 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1288 bool missing_local_arch = !m_arch.IsValid();
1289 bool replace_local_arch = true;
1290 bool compatible_local_arch = false;
1291 ArchSpec other(arch_spec);
1293 if (!missing_local_arch)
1295 if (m_arch.IsCompatibleMatch(arch_spec))
1297 other.MergeFrom(m_arch);
1299 if (m_arch.IsCompatibleMatch(other))
1301 compatible_local_arch = true;
1302 bool arch_changed, vendor_changed, os_changed, os_ver_changed, env_changed;
1304 m_arch.PiecewiseTripleCompare(other,
1311 if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1312 replace_local_arch = false;
1317 if (compatible_local_arch || missing_local_arch)
1319 // If we haven't got a valid arch spec, or the architectures are compatible
1320 // update the architecture, unless the one we already have is more specified
1321 if (replace_local_arch)
1324 log->Printf ("Target::SetArchitecture set architecture to %s (%s)", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
1328 // If we have an executable file, try to reset the executable to the desired architecture
1330 log->Printf ("Target::SetArchitecture changing architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1332 ModuleSP executable_sp = GetExecutableModule ();
1335 // Need to do something about unsetting breakpoints.
1340 log->Printf("Target::SetArchitecture Trying to select executable file architecture %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1341 ModuleSpec module_spec (executable_sp->GetFileSpec(), other);
1342 Error error = ModuleList::GetSharedModule(module_spec,
1344 &GetExecutableSearchPaths(),
1348 if (!error.Fail() && executable_sp)
1350 SetExecutableModule (executable_sp, true);
1358 Target::MergeArchitecture (const ArchSpec &arch_spec)
1360 if (arch_spec.IsValid())
1362 if (m_arch.IsCompatibleMatch(arch_spec))
1364 // The current target arch is compatible with "arch_spec", see if we
1365 // can improve our current architecture using bits from "arch_spec"
1367 // Merge bits from arch_spec into "merged_arch" and set our architecture
1368 ArchSpec merged_arch (m_arch);
1369 merged_arch.MergeFrom (arch_spec);
1370 return SetArchitecture(merged_arch);
1374 // The new architecture is different, we just need to replace it
1375 return SetArchitecture(arch_spec);
1382 Target::WillClearList (const ModuleList& module_list)
1387 Target::ModuleAdded (const ModuleList& module_list, const ModuleSP &module_sp)
1389 // A module is being added to this target for the first time
1392 ModuleList my_module_list;
1393 my_module_list.Append(module_sp);
1394 LoadScriptingResourceForModule(module_sp, this);
1395 ModulesDidLoad (my_module_list);
1400 Target::ModuleRemoved (const ModuleList& module_list, const ModuleSP &module_sp)
1402 // A module is being removed from this target.
1405 ModuleList my_module_list;
1406 my_module_list.Append(module_sp);
1407 ModulesDidUnload (my_module_list, false);
1412 Target::ModuleUpdated (const ModuleList& module_list, const ModuleSP &old_module_sp, const ModuleSP &new_module_sp)
1414 // A module is replacing an already added module
1417 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1418 m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1423 Target::ModulesDidLoad (ModuleList &module_list)
1425 if (m_valid && module_list.GetSize())
1427 m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1428 m_internal_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1431 m_process_sp->ModulesDidLoad (module_list);
1433 BroadcastEvent (eBroadcastBitModulesLoaded, new TargetEventData (this->shared_from_this(), module_list));
1438 Target::SymbolsDidLoad (ModuleList &module_list)
1440 if (m_valid && module_list.GetSize())
1444 LanguageRuntime* runtime = m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1447 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime*)runtime;
1448 objc_runtime->SymbolsDidLoad(module_list);
1452 m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1453 m_internal_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1454 BroadcastEvent (eBroadcastBitSymbolsLoaded, new TargetEventData (this->shared_from_this(), module_list));
1459 Target::ModulesDidUnload (ModuleList &module_list, bool delete_locations)
1461 if (m_valid && module_list.GetSize())
1463 UnloadModuleSections (module_list);
1464 m_breakpoint_list.UpdateBreakpoints (module_list, false, delete_locations);
1465 m_internal_breakpoint_list.UpdateBreakpoints (module_list, false, delete_locations);
1466 BroadcastEvent (eBroadcastBitModulesUnloaded, new TargetEventData (this->shared_from_this(), module_list));
1471 Target::ModuleIsExcludedForUnconstrainedSearches (const FileSpec &module_file_spec)
1473 if (GetBreakpointsConsultPlatformAvoidList())
1475 ModuleList matchingModules;
1476 ModuleSpec module_spec (module_file_spec);
1477 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1479 // If there is more than one module for this file spec, only return true if ALL the modules are on the
1481 if (num_modules > 0)
1483 for (size_t i = 0; i < num_modules; i++)
1485 if (!ModuleIsExcludedForUnconstrainedSearches (matchingModules.GetModuleAtIndex(i)))
1495 Target::ModuleIsExcludedForUnconstrainedSearches (const lldb::ModuleSP &module_sp)
1497 if (GetBreakpointsConsultPlatformAvoidList())
1500 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches (*this, module_sp);
1506 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
1508 SectionSP section_sp (addr.GetSection());
1511 // If the contents of this section are encrypted, the on-disk file is unusable. Read only from live memory.
1512 if (section_sp->IsEncrypted())
1514 error.SetErrorString("section is encrypted");
1517 ModuleSP module_sp (section_sp->GetModule());
1520 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1523 size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
1530 error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
1533 error.SetErrorString("address isn't from a object file");
1536 error.SetErrorString("address isn't in a module");
1539 error.SetErrorString("address doesn't contain a section that points to a section in a object file");
1545 Target::ReadMemory (const Address& addr,
1546 bool prefer_file_cache,
1550 lldb::addr_t *load_addr_ptr)
1554 // if we end up reading this from process memory, we will fill this
1555 // with the actual load address
1557 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1559 size_t bytes_read = 0;
1561 addr_t load_addr = LLDB_INVALID_ADDRESS;
1562 addr_t file_addr = LLDB_INVALID_ADDRESS;
1563 Address resolved_addr;
1564 if (!addr.IsSectionOffset())
1566 SectionLoadList §ion_load_list = GetSectionLoadList();
1567 if (section_load_list.IsEmpty())
1569 // No sections are loaded, so we must assume we are not running
1570 // yet and anything we are given is a file address.
1571 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
1572 m_images.ResolveFileAddress (file_addr, resolved_addr);
1576 // We have at least one section loaded. This can be because
1577 // we have manually loaded some sections with "target modules load ..."
1578 // or because we have have a live process that has sections loaded
1579 // through the dynamic loader
1580 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1581 section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1584 if (!resolved_addr.IsValid())
1585 resolved_addr = addr;
1587 if (prefer_file_cache)
1589 bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1594 if (ProcessIsValid())
1596 if (load_addr == LLDB_INVALID_ADDRESS)
1597 load_addr = resolved_addr.GetLoadAddress (this);
1599 if (load_addr == LLDB_INVALID_ADDRESS)
1601 ModuleSP addr_module_sp (resolved_addr.GetModule());
1602 if (addr_module_sp && addr_module_sp->GetFileSpec())
1603 error.SetErrorStringWithFormat("%s[0x%" PRIx64 "] can't be resolved, %s in not currently loaded",
1604 addr_module_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"),
1605 resolved_addr.GetFileAddress(),
1606 addr_module_sp->GetFileSpec().GetFilename().AsCString("<Unknonw>"));
1608 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
1612 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1613 if (bytes_read != dst_len)
1615 if (error.Success())
1617 if (bytes_read == 0)
1618 error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed", load_addr);
1620 error.SetErrorStringWithFormat("only %" PRIu64 " of %" PRIu64 " bytes were read from memory at 0x%" PRIx64, (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1626 *load_addr_ptr = load_addr;
1629 // If the address is not section offset we have an address that
1630 // doesn't resolve to any address in any currently loaded shared
1631 // libraries and we failed to read memory so there isn't anything
1632 // more we can do. If it is section offset, we might be able to
1633 // read cached memory from the object file.
1634 if (!resolved_addr.IsSectionOffset())
1639 if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1641 // If we didn't already try and read from the object file cache, then
1642 // try it after failing to read from the process.
1643 return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1649 Target::ReadCStringFromMemory (const Address& addr, std::string &out_str, Error &error)
1653 addr_t curr_addr = addr.GetLoadAddress(this);
1654 Address address(addr);
1657 size_t length = ReadCStringFromMemory (address, buf, sizeof(buf), error);
1660 out_str.append(buf, length);
1661 // If we got "length - 1" bytes, we didn't get the whole C string, we
1662 // need to read some more characters
1663 if (length == sizeof(buf) - 1)
1664 curr_addr += length;
1667 address = Address(curr_addr);
1669 return out_str.size();
1673 Target::ReadCStringFromMemory (const Address& addr, char *dst, size_t dst_max_len, Error &result_error)
1675 size_t total_cstr_len = 0;
1676 if (dst && dst_max_len)
1678 result_error.Clear();
1679 // NULL out everything just to be safe
1680 memset (dst, 0, dst_max_len);
1682 addr_t curr_addr = addr.GetLoadAddress(this);
1683 Address address(addr);
1685 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't
1686 // think this really needs to be tied to the memory cache subsystem's
1687 // cache line size, so leave this as a fixed constant.
1688 const size_t cache_line_size = 512;
1690 size_t bytes_left = dst_max_len - 1;
1691 char *curr_dst = dst;
1693 while (bytes_left > 0)
1695 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1696 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1697 size_t bytes_read = ReadMemory (address, false, curr_dst, bytes_to_read, error);
1699 if (bytes_read == 0)
1701 result_error = error;
1702 dst[total_cstr_len] = '\0';
1705 const size_t len = strlen(curr_dst);
1707 total_cstr_len += len;
1709 if (len < bytes_to_read)
1712 curr_dst += bytes_read;
1713 curr_addr += bytes_read;
1714 bytes_left -= bytes_read;
1715 address = Address(curr_addr);
1721 result_error.SetErrorString("invalid arguments");
1723 result_error.Clear();
1725 return total_cstr_len;
1729 Target::ReadScalarIntegerFromMemory (const Address& addr,
1730 bool prefer_file_cache,
1738 if (byte_size <= sizeof(uval))
1740 size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1741 if (bytes_read == byte_size)
1743 DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1744 lldb::offset_t offset = 0;
1746 scalar = data.GetMaxU32 (&offset, byte_size);
1748 scalar = data.GetMaxU64 (&offset, byte_size);
1751 scalar.SignExtend(byte_size * 8);
1757 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1763 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1764 bool prefer_file_cache,
1765 size_t integer_byte_size,
1766 uint64_t fail_value,
1770 if (ReadScalarIntegerFromMemory (addr,
1776 return scalar.ULongLong(fail_value);
1781 Target::ReadPointerFromMemory (const Address& addr,
1782 bool prefer_file_cache,
1784 Address &pointer_addr)
1787 if (ReadScalarIntegerFromMemory (addr,
1789 m_arch.GetAddressByteSize(),
1794 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1795 if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1797 SectionLoadList §ion_load_list = GetSectionLoadList();
1798 if (section_load_list.IsEmpty())
1800 // No sections are loaded, so we must assume we are not running
1801 // yet and anything we are given is a file address.
1802 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1806 // We have at least one section loaded. This can be because
1807 // we have manually loaded some sections with "target modules load ..."
1808 // or because we have have a live process that has sections loaded
1809 // through the dynamic loader
1810 section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1812 // We weren't able to resolve the pointer value, so just return
1813 // an address with no section
1814 if (!pointer_addr.IsValid())
1815 pointer_addr.SetOffset (pointer_vm_addr);
1824 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
1830 // First see if we already have this module in our module list. If we do, then we're done, we don't need
1831 // to consult the shared modules list. But only do this if we are passed a UUID.
1833 if (module_spec.GetUUID().IsValid())
1834 module_sp = m_images.FindFirstModule(module_spec);
1838 ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1839 bool did_create_module = false;
1841 // If there are image search path entries, try to use them first to acquire a suitable image.
1842 if (m_image_search_paths.GetSize())
1844 ModuleSpec transformed_spec (module_spec);
1845 if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
1847 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
1848 error = ModuleList::GetSharedModule (transformed_spec,
1850 &GetExecutableSearchPaths(),
1852 &did_create_module);
1858 // If we have a UUID, we can check our global shared module list in case
1859 // we already have it. If we don't have a valid UUID, then we can't since
1860 // the path in "module_spec" will be a platform path, and we will need to
1861 // let the platform find that file. For example, we could be asking for
1862 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1863 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1864 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1866 if (module_spec.GetUUID().IsValid())
1868 // We have a UUID, it is OK to check the global module list...
1869 error = ModuleList::GetSharedModule (module_spec,
1871 &GetExecutableSearchPaths(),
1873 &did_create_module);
1878 // The platform is responsible for finding and caching an appropriate
1879 // module in the shared module cache.
1882 error = m_platform_sp->GetSharedModule (module_spec,
1885 &GetExecutableSearchPaths(),
1887 &did_create_module);
1891 error.SetErrorString("no platform is currently set");
1896 // We found a module that wasn't in our target list. Let's make sure that there wasn't an equivalent
1897 // module in the list already, and if there was, let's remove it.
1900 ObjectFile *objfile = module_sp->GetObjectFile();
1903 switch (objfile->GetType())
1905 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of a program's execution state
1906 case ObjectFile::eTypeExecutable: /// A normal executable
1907 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker executable
1908 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1909 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be used during execution
1911 case ObjectFile::eTypeDebugInfo: /// An object file that contains only debug information
1913 error_ptr->SetErrorString("debug info files aren't valid target modules, please specify an executable");
1915 case ObjectFile::eTypeStubLibrary: /// A library that can be linked against but not used for execution
1917 error_ptr->SetErrorString("stub libraries aren't valid target modules, please specify an executable");
1921 error_ptr->SetErrorString("unsupported file type, please specify an executable");
1924 // GetSharedModule is not guaranteed to find the old shared module, for instance
1925 // in the common case where you pass in the UUID, it is only going to find the one
1926 // module matching the UUID. In fact, it has no good way to know what the "old module"
1927 // relevant to this target is, since there might be many copies of a module with this file spec
1928 // in various running debug sessions, but only one of them will belong to this target.
1929 // So let's remove the UUID from the module list, and look in the target's module list.
1930 // Only do this if there is SOMETHING else in the module spec...
1933 if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
1935 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1936 module_spec_copy.GetUUID().Clear();
1938 ModuleList found_modules;
1939 size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
1942 old_module_sp = found_modules.GetModuleAtIndex(0);
1947 if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1949 m_images.ReplaceModule(old_module_sp, module_sp);
1950 Module *old_module_ptr = old_module_sp.get();
1951 old_module_sp.reset();
1952 ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
1955 m_images.Append(module_sp);
1967 Target::CalculateTarget ()
1969 return shared_from_this();
1973 Target::CalculateProcess ()
1975 return m_process_sp;
1979 Target::CalculateThread ()
1985 Target::CalculateStackFrame ()
1987 return StackFrameSP();
1991 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1994 exe_ctx.SetTargetPtr(this);
1998 Target::GetImageSearchPathList ()
2000 return m_image_search_paths;
2004 Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2007 Target *target = (Target *)baton;
2008 ModuleSP exe_module_sp (target->GetExecutableModule());
2010 target->SetExecutableModule (exe_module_sp, true);
2014 Target::GetScratchTypeSystemForLanguage (Error *error, lldb::LanguageType language, bool create_on_demand)
2024 if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all assembly code
2025 || language == eLanguageTypeUnknown)
2027 std::set<lldb::LanguageType> languages_for_types;
2028 std::set<lldb::LanguageType> languages_for_expressions;
2030 Language::GetLanguagesSupportingTypeSystems(languages_for_types, languages_for_expressions);
2032 if (languages_for_expressions.count(eLanguageTypeC))
2034 language = eLanguageTypeC; // LLDB's default. Override by setting the target language.
2038 if (languages_for_expressions.empty())
2044 language = *languages_for_expressions.begin();
2049 return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this, create_on_demand);
2052 PersistentExpressionState *
2053 Target::GetPersistentExpressionStateForLanguage (lldb::LanguageType language)
2055 TypeSystem *type_system = GetScratchTypeSystemForLanguage(nullptr, language, true);
2059 return type_system->GetPersistentExpressionState();
2068 Target::GetUserExpressionForLanguage(const char *expr,
2069 const char *expr_prefix,
2070 lldb::LanguageType language,
2071 Expression::ResultType desired_type,
2072 const EvaluateExpressionOptions &options,
2075 Error type_system_error;
2077 TypeSystem *type_system = GetScratchTypeSystemForLanguage (&type_system_error, language);
2078 UserExpression *user_expr = nullptr;
2082 error.SetErrorStringWithFormat("Could not find type system for language %s: %s", Language::GetNameForLanguageType(language), type_system_error.AsCString());
2086 user_expr = type_system->GetUserExpression(expr, expr_prefix, language, desired_type, options);
2088 error.SetErrorStringWithFormat("Could not create an expression for language %s", Language::GetNameForLanguageType(language));
2094 Target::GetFunctionCallerForLanguage (lldb::LanguageType language,
2095 const CompilerType &return_type,
2096 const Address& function_address,
2097 const ValueList &arg_value_list,
2101 Error type_system_error;
2102 TypeSystem *type_system = GetScratchTypeSystemForLanguage (&type_system_error, language);
2103 FunctionCaller *persistent_fn = nullptr;
2107 error.SetErrorStringWithFormat("Could not find type system for language %s: %s", Language::GetNameForLanguageType(language), type_system_error.AsCString());
2108 return persistent_fn;
2111 persistent_fn = type_system->GetFunctionCaller (return_type, function_address, arg_value_list, name);
2113 error.SetErrorStringWithFormat("Could not create an expression for language %s", Language::GetNameForLanguageType(language));
2115 return persistent_fn;
2119 Target::GetUtilityFunctionForLanguage (const char *text,
2120 lldb::LanguageType language,
2124 Error type_system_error;
2125 TypeSystem *type_system = GetScratchTypeSystemForLanguage (&type_system_error, language);
2126 UtilityFunction *utility_fn = nullptr;
2130 error.SetErrorStringWithFormat("Could not find type system for language %s: %s", Language::GetNameForLanguageType(language), type_system_error.AsCString());
2134 utility_fn = type_system->GetUtilityFunction (text, name);
2136 error.SetErrorStringWithFormat("Could not create an expression for language %s", Language::GetNameForLanguageType(language));
2142 Target::GetScratchClangASTContext(bool create_on_demand)
2146 if (TypeSystem* type_system = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC, create_on_demand))
2147 return llvm::dyn_cast<ClangASTContext>(type_system);
2153 Target::GetClangASTImporter()
2157 if (!m_ast_importer_sp)
2159 m_ast_importer_sp.reset(new ClangASTImporter());
2161 return m_ast_importer_sp;
2163 return ClangASTImporterSP();
2167 Target::SettingsInitialize ()
2169 Process::SettingsInitialize ();
2173 Target::SettingsTerminate ()
2175 Process::SettingsTerminate ();
2179 Target::GetDefaultExecutableSearchPaths ()
2181 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2183 return properties_sp->GetExecutableSearchPaths();
2184 return FileSpecList();
2188 Target::GetDefaultDebugFileSearchPaths ()
2190 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2192 return properties_sp->GetDebugFileSearchPaths();
2193 return FileSpecList();
2197 Target::GetDefaultClangModuleSearchPaths ()
2199 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2201 return properties_sp->GetClangModuleSearchPaths();
2202 return FileSpecList();
2206 Target::GetDefaultArchitecture ()
2208 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2210 return properties_sp->GetDefaultArchitecture();
2215 Target::SetDefaultArchitecture (const ArchSpec &arch)
2217 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2220 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's default architecture to %s (%s)", arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
2221 return properties_sp->SetDefaultArchitecture(arch);
2226 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
2228 // The target can either exist in the "process" of ExecutionContext, or in
2229 // the "target_sp" member of SymbolContext. This accessor helper function
2230 // will get the target from one of these locations.
2232 Target *target = nullptr;
2233 if (sc_ptr != nullptr)
2234 target = sc_ptr->target_sp.get();
2235 if (target == nullptr && exe_ctx_ptr)
2236 target = exe_ctx_ptr->GetTargetPtr();
2241 Target::EvaluateExpression(const char *expr_cstr,
2242 ExecutionContextScope *exe_scope,
2243 lldb::ValueObjectSP &result_valobj_sp,
2244 const EvaluateExpressionOptions& options,
2245 std::string *fixed_expression)
2247 result_valobj_sp.reset();
2249 ExpressionResults execution_results = eExpressionSetupError;
2251 if (expr_cstr == nullptr || expr_cstr[0] == '\0')
2252 return execution_results;
2254 // We shouldn't run stop hooks in expressions.
2255 // Be sure to reset this if you return anywhere within this function.
2256 bool old_suppress_value = m_suppress_stop_hooks;
2257 m_suppress_stop_hooks = true;
2259 ExecutionContext exe_ctx;
2263 exe_scope->CalculateExecutionContext(exe_ctx);
2265 else if (m_process_sp)
2267 m_process_sp->CalculateExecutionContext(exe_ctx);
2271 CalculateExecutionContext(exe_ctx);
2274 // Make sure we aren't just trying to see the value of a persistent
2275 // variable (something like "$0")
2276 lldb::ExpressionVariableSP persistent_var_sp;
2277 // Only check for persistent variables the expression starts with a '$'
2278 if (expr_cstr[0] == '$')
2279 persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)->GetPersistentExpressionState()->GetVariable (expr_cstr);
2281 if (persistent_var_sp)
2283 result_valobj_sp = persistent_var_sp->GetValueObject ();
2284 execution_results = eExpressionCompleted;
2288 const char *prefix = GetExpressionPrefixContentsAsCString();
2290 execution_results = UserExpression::Evaluate (exe_ctx,
2300 m_suppress_stop_hooks = old_suppress_value;
2302 return execution_results;
2305 lldb::ExpressionVariableSP
2306 Target::GetPersistentVariable(const ConstString &name)
2308 lldb::ExpressionVariableSP variable_sp;
2309 m_scratch_type_system_map.ForEach([this, name, &variable_sp](TypeSystem *type_system) -> bool
2311 if (PersistentExpressionState *persistent_state = type_system->GetPersistentExpressionState())
2313 variable_sp = persistent_state->GetVariable(name);
2316 return false; // Stop iterating the ForEach
2318 return true; // Keep iterating the ForEach
2324 Target::GetPersistentSymbol(const ConstString &name)
2326 lldb::addr_t address = LLDB_INVALID_ADDRESS;
2328 m_scratch_type_system_map.ForEach([this, name, &address](TypeSystem *type_system) -> bool
2330 if (PersistentExpressionState *persistent_state = type_system->GetPersistentExpressionState())
2332 address = persistent_state->LookupSymbol(name);
2333 if (address != LLDB_INVALID_ADDRESS)
2334 return false; // Stop iterating the ForEach
2336 return true; // Keep iterating the ForEach
2342 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
2344 addr_t code_addr = load_addr;
2345 switch (m_arch.GetMachine())
2347 case llvm::Triple::mips:
2348 case llvm::Triple::mipsel:
2349 case llvm::Triple::mips64:
2350 case llvm::Triple::mips64el:
2353 case eAddressClassData:
2354 case eAddressClassDebug:
2355 return LLDB_INVALID_ADDRESS;
2357 case eAddressClassUnknown:
2358 case eAddressClassInvalid:
2359 case eAddressClassCode:
2360 case eAddressClassCodeAlternateISA:
2361 case eAddressClassRuntime:
2362 if ((code_addr & 2ull) || (addr_class == eAddressClassCodeAlternateISA))
2368 case llvm::Triple::arm:
2369 case llvm::Triple::thumb:
2372 case eAddressClassData:
2373 case eAddressClassDebug:
2374 return LLDB_INVALID_ADDRESS;
2376 case eAddressClassUnknown:
2377 case eAddressClassInvalid:
2378 case eAddressClassCode:
2379 case eAddressClassCodeAlternateISA:
2380 case eAddressClassRuntime:
2381 // Check if bit zero it no set?
2382 if ((code_addr & 1ull) == 0)
2384 // Bit zero isn't set, check if the address is a multiple of 2?
2385 if (code_addr & 2ull)
2387 // The address is a multiple of 2 so it must be thumb, set bit zero
2390 else if (addr_class == eAddressClassCodeAlternateISA)
2392 // We checked the address and the address claims to be the alternate ISA
2393 // which means thumb, so set bit zero.
2408 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
2410 addr_t opcode_addr = load_addr;
2411 switch (m_arch.GetMachine())
2413 case llvm::Triple::mips:
2414 case llvm::Triple::mipsel:
2415 case llvm::Triple::mips64:
2416 case llvm::Triple::mips64el:
2417 case llvm::Triple::arm:
2418 case llvm::Triple::thumb:
2421 case eAddressClassData:
2422 case eAddressClassDebug:
2423 return LLDB_INVALID_ADDRESS;
2425 case eAddressClassInvalid:
2426 case eAddressClassUnknown:
2427 case eAddressClassCode:
2428 case eAddressClassCodeAlternateISA:
2429 case eAddressClassRuntime:
2430 opcode_addr &= ~(1ull);
2442 Target::GetBreakableLoadAddress (lldb::addr_t addr)
2444 addr_t breakable_addr = addr;
2445 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2447 switch (m_arch.GetMachine())
2451 case llvm::Triple::mips:
2452 case llvm::Triple::mipsel:
2453 case llvm::Triple::mips64:
2454 case llvm::Triple::mips64el:
2456 addr_t function_start = 0;
2457 addr_t current_offset = 0;
2458 uint32_t loop_count = 0;
2459 Address resolved_addr;
2460 uint32_t arch_flags = m_arch.GetFlags ();
2461 bool IsMips16 = arch_flags & ArchSpec::eMIPSAse_mips16;
2462 bool IsMicromips = arch_flags & ArchSpec::eMIPSAse_micromips;
2463 SectionLoadList §ion_load_list = GetSectionLoadList();
2465 if (section_load_list.IsEmpty())
2466 // No sections are loaded, so we must assume we are not running yet
2467 // and need to operate only on file address.
2468 m_images.ResolveFileAddress (addr, resolved_addr);
2470 section_load_list.ResolveLoadAddress(addr, resolved_addr);
2472 // Get the function boundaries to make sure we don't scan back before the beginning of the current function.
2473 ModuleSP temp_addr_module_sp (resolved_addr.GetModule());
2474 if (temp_addr_module_sp)
2477 uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
2478 temp_addr_module_sp->ResolveSymbolContextForAddress(resolved_addr, resolve_scope, sc);
2481 sym_addr = sc.function->GetAddressRange().GetBaseAddress();
2483 sym_addr = sc.symbol->GetAddress();
2485 function_start = sym_addr.GetLoadAddress(this);
2486 if (function_start == LLDB_INVALID_ADDRESS)
2487 function_start = sym_addr.GetFileAddress();
2490 current_offset = addr - function_start;
2493 // If breakpoint address is start of function then we dont have to do anything.
2494 if (current_offset == 0)
2495 return breakable_addr;
2497 loop_count = current_offset / 2;
2501 // Scan previous 6 bytes
2502 if (IsMips16 | IsMicromips)
2504 // For mips-only, instructions are always 4 bytes, so scan previous 4 bytes only.
2509 // Create Disassembler Instance
2510 lldb::DisassemblerSP disasm_sp(Disassembler::FindPlugin(m_arch, nullptr, nullptr));
2512 ExecutionContext exe_ctx;
2513 CalculateExecutionContext(exe_ctx);
2514 InstructionList instruction_list;
2515 InstructionSP prev_insn;
2516 bool prefer_file_cache = true; // Read from file
2517 uint32_t inst_to_choose = 0;
2519 for (uint32_t i = 1; i <= loop_count; i++)
2521 // Adjust the address to read from.
2522 resolved_addr.Slide (-2);
2523 AddressRange range(resolved_addr, i*2);
2524 uint32_t insn_size = 0;
2526 disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
2528 uint32_t num_insns = disasm_sp->GetInstructionList().GetSize();
2531 prev_insn = disasm_sp->GetInstructionList().GetInstructionAtIndex(0);
2532 insn_size = prev_insn->GetOpcode().GetByteSize();
2533 if (i == 1 && insn_size == 2)
2535 // This looks like a valid 2-byte instruction (but it could be a part of upper 4 byte instruction).
2536 instruction_list.Append(prev_insn);
2541 // Here we may get one 4-byte instruction or two 2-byte instructions.
2544 // Looks like there are two 2-byte instructions above our breakpoint target address.
2545 // Now the upper 2-byte instruction is either a valid 2-byte instruction or could be a part of it's upper 4-byte instruction.
2546 // In both cases we don't care because in this case lower 2-byte instruction is definitely a valid instruction
2547 // and whatever i=1 iteration has found out is true.
2551 else if (insn_size == 4)
2553 // This instruction claims its a valid 4-byte instruction. But it could be a part of it's upper 4-byte instruction.
2554 // Lets try scanning upper 2 bytes to verify this.
2555 instruction_list.Append(prev_insn);
2562 // FIXME: We reached here that means instruction at [target - 4] has already claimed to be a 4-byte instruction,
2563 // and now instruction at [target - 6] is also claiming that it's a 4-byte instruction. This can not be true.
2564 // In this case we can not decide the valid previous instruction so we let lldb set the breakpoint at the address given by user.
2567 // This is straight-forward
2574 // Decode failed, bytes do not form a valid instruction. So whatever previous iteration has found out is true.
2577 inst_to_choose = i - 1;
2583 // Check if we are able to find any valid instruction.
2586 if (inst_to_choose > instruction_list.GetSize())
2588 prev_insn = instruction_list.GetInstructionAtIndex(inst_to_choose - 1);
2590 if (prev_insn->HasDelaySlot())
2592 uint32_t shift_size = prev_insn->GetOpcode().GetByteSize();
2593 // Adjust the breakable address
2594 breakable_addr = addr - shift_size;
2596 log->Printf ("Target::%s Breakpoint at 0x%8.8" PRIx64 " is adjusted to 0x%8.8" PRIx64 " due to delay slot\n", __FUNCTION__, addr, breakable_addr);
2602 return breakable_addr;
2606 Target::GetSourceManager ()
2608 if (!m_source_manager_ap)
2609 m_source_manager_ap.reset (new SourceManager(shared_from_this()));
2610 return *m_source_manager_ap;
2613 ClangModulesDeclVendor *
2614 Target::GetClangModulesDeclVendor ()
2616 static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended we can make it per-target
2619 std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2621 if (!m_clang_modules_decl_vendor_ap)
2623 m_clang_modules_decl_vendor_ap.reset(ClangModulesDeclVendor::Create(*this));
2627 return m_clang_modules_decl_vendor_ap.get();
2631 Target::CreateStopHook ()
2633 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2634 Target::StopHookSP stop_hook_sp (new StopHook(shared_from_this(), new_uid));
2635 m_stop_hooks[new_uid] = stop_hook_sp;
2636 return stop_hook_sp;
2640 Target::RemoveStopHookByID (lldb::user_id_t user_id)
2642 size_t num_removed = m_stop_hooks.erase(user_id);
2643 return (num_removed != 0);
2647 Target::RemoveAllStopHooks ()
2649 m_stop_hooks.clear();
2653 Target::GetStopHookByID (lldb::user_id_t user_id)
2655 StopHookSP found_hook;
2657 StopHookCollection::iterator specified_hook_iter;
2658 specified_hook_iter = m_stop_hooks.find (user_id);
2659 if (specified_hook_iter != m_stop_hooks.end())
2660 found_hook = (*specified_hook_iter).second;
2665 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
2667 StopHookCollection::iterator specified_hook_iter;
2668 specified_hook_iter = m_stop_hooks.find (user_id);
2669 if (specified_hook_iter == m_stop_hooks.end())
2672 (*specified_hook_iter).second->SetIsActive (active_state);
2677 Target::SetAllStopHooksActiveState (bool active_state)
2679 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2680 for (pos = m_stop_hooks.begin(); pos != end; pos++)
2682 (*pos).second->SetIsActive (active_state);
2687 Target::RunStopHooks ()
2689 if (m_suppress_stop_hooks)
2695 // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
2696 // since in that case we do not want to run the stop-hooks
2697 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2700 if (m_stop_hooks.empty())
2703 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2705 // If there aren't any active stop hooks, don't bother either:
2706 bool any_active_hooks = false;
2707 for (pos = m_stop_hooks.begin(); pos != end; pos++)
2709 if ((*pos).second->IsActive())
2711 any_active_hooks = true;
2715 if (!any_active_hooks)
2718 CommandReturnObject result;
2720 std::vector<ExecutionContext> exc_ctx_with_reasons;
2721 std::vector<SymbolContext> sym_ctx_with_reasons;
2723 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2724 size_t num_threads = cur_threadlist.GetSize();
2725 for (size_t i = 0; i < num_threads; i++)
2727 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
2728 if (cur_thread_sp->ThreadStoppedForAReason())
2730 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2731 exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2732 sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2736 // If no threads stopped for a reason, don't run the stop-hooks.
2737 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2738 if (num_exe_ctx == 0)
2741 result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
2742 result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
2744 bool keep_going = true;
2745 bool hooks_ran = false;
2746 bool print_hook_header = (m_stop_hooks.size() != 1);
2747 bool print_thread_header = (num_exe_ctx != 1);
2749 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
2752 StopHookSP cur_hook_sp = (*pos).second;
2753 if (!cur_hook_sp->IsActive())
2756 bool any_thread_matched = false;
2757 for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2759 if ((cur_hook_sp->GetSpecifier() == nullptr
2760 || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2761 && (cur_hook_sp->GetThreadSpecifier() == nullptr
2762 || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2768 if (print_hook_header && !any_thread_matched)
2770 const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2771 cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2774 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(), cmd);
2776 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2777 any_thread_matched = true;
2780 if (print_thread_header)
2781 result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2783 CommandInterpreterRunOptions options;
2784 options.SetStopOnContinue (true);
2785 options.SetStopOnError (true);
2786 options.SetEchoCommands (false);
2787 options.SetPrintResults (true);
2788 options.SetAddToHistory (false);
2790 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2791 &exc_ctx_with_reasons[i],
2795 // If the command started the target going again, we should bag out of
2796 // running the stop hooks.
2797 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2798 (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2800 result.AppendMessageWithFormat ("Aborting stop hooks, hook %" PRIu64 " set the program running.", cur_hook_sp->GetID());
2807 result.GetImmediateOutputStream()->Flush();
2808 result.GetImmediateErrorStream()->Flush();
2811 const TargetPropertiesSP &
2812 Target::GetGlobalProperties()
2814 // NOTE: intentional leak so we don't crash if global destructor chain gets
2815 // called as other threads still use the result of this function
2816 static TargetPropertiesSP *g_settings_sp_ptr = nullptr;
2817 static std::once_flag g_once_flag;
2818 std::call_once(g_once_flag, []() {
2819 g_settings_sp_ptr = new TargetPropertiesSP(new TargetProperties(nullptr));
2821 return *g_settings_sp_ptr;
2825 Target::Install (ProcessLaunchInfo *launch_info)
2828 PlatformSP platform_sp (GetPlatform());
2831 if (platform_sp->IsRemote())
2833 if (platform_sp->IsConnected())
2835 // Install all files that have an install path, and always install the
2836 // main executable when connected to a remote platform
2837 const ModuleList& modules = GetImages();
2838 const size_t num_images = modules.GetSize();
2839 for (size_t idx = 0; idx < num_images; ++idx)
2841 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2844 const bool is_main_executable = module_sp == GetExecutableModule();
2845 FileSpec local_file (module_sp->GetFileSpec());
2848 FileSpec remote_file (module_sp->GetRemoteInstallFileSpec());
2851 if (is_main_executable) // TODO: add setting for always installing main executable???
2853 // Always install the main executable
2854 remote_file = platform_sp->GetRemoteWorkingDirectory();
2855 remote_file.AppendPathComponent(module_sp->GetFileSpec().GetFilename().GetCString());
2860 error = platform_sp->Install(local_file, remote_file);
2861 if (error.Success())
2863 module_sp->SetPlatformFileSpec(remote_file);
2864 if (is_main_executable)
2866 platform_sp->SetFilePermissions(remote_file, 0700);
2868 launch_info->SetExecutableFile(remote_file, false);
2884 Target::ResolveLoadAddress (addr_t load_addr, Address &so_addr, uint32_t stop_id)
2886 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2890 Target::ResolveFileAddress (lldb::addr_t file_addr, Address &resolved_addr)
2892 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2896 Target::SetSectionLoadAddress (const SectionSP §ion_sp, addr_t new_section_load_addr, bool warn_multiple)
2898 const addr_t old_section_load_addr = m_section_load_history.GetSectionLoadAddress (SectionLoadHistory::eStopIDNow, section_sp);
2899 if (old_section_load_addr != new_section_load_addr)
2901 uint32_t stop_id = 0;
2902 ProcessSP process_sp(GetProcessSP());
2904 stop_id = process_sp->GetStopID();
2906 stop_id = m_section_load_history.GetLastStopID();
2907 if (m_section_load_history.SetSectionLoadAddress (stop_id, section_sp, new_section_load_addr, warn_multiple))
2908 return true; // Return true if the section load address was changed...
2910 return false; // Return false to indicate nothing changed
2914 Target::UnloadModuleSections (const ModuleList &module_list)
2916 size_t section_unload_count = 0;
2917 size_t num_modules = module_list.GetSize();
2918 for (size_t i=0; i<num_modules; ++i)
2920 section_unload_count += UnloadModuleSections (module_list.GetModuleAtIndex(i));
2922 return section_unload_count;
2926 Target::UnloadModuleSections (const lldb::ModuleSP &module_sp)
2928 uint32_t stop_id = 0;
2929 ProcessSP process_sp(GetProcessSP());
2931 stop_id = process_sp->GetStopID();
2933 stop_id = m_section_load_history.GetLastStopID();
2934 SectionList *sections = module_sp->GetSectionList();
2935 size_t section_unload_count = 0;
2938 const uint32_t num_sections = sections->GetNumSections(0);
2939 for (uint32_t i = 0; i < num_sections; ++i)
2941 section_unload_count += m_section_load_history.SetSectionUnloaded(stop_id, sections->GetSectionAtIndex(i));
2944 return section_unload_count;
2948 Target::SetSectionUnloaded (const lldb::SectionSP §ion_sp)
2950 uint32_t stop_id = 0;
2951 ProcessSP process_sp(GetProcessSP());
2953 stop_id = process_sp->GetStopID();
2955 stop_id = m_section_load_history.GetLastStopID();
2956 return m_section_load_history.SetSectionUnloaded (stop_id, section_sp);
2960 Target::SetSectionUnloaded (const lldb::SectionSP §ion_sp, addr_t load_addr)
2962 uint32_t stop_id = 0;
2963 ProcessSP process_sp(GetProcessSP());
2965 stop_id = process_sp->GetStopID();
2967 stop_id = m_section_load_history.GetLastStopID();
2968 return m_section_load_history.SetSectionUnloaded (stop_id, section_sp, load_addr);
2972 Target::ClearAllLoadedSections ()
2974 m_section_load_history.Clear();
2978 Target::Launch (ProcessLaunchInfo &launch_info, Stream *stream)
2981 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
2984 log->Printf ("Target::%s() called for %s", __FUNCTION__, launch_info.GetExecutableFile().GetPath().c_str ());
2986 StateType state = eStateInvalid;
2988 // Scope to temporarily get the process state in case someone has manually
2989 // remotely connected already to a process and we can skip the platform
2992 ProcessSP process_sp (GetProcessSP());
2996 state = process_sp->GetState();
2998 log->Printf ("Target::%s the process exists, and its current state is %s", __FUNCTION__, StateAsCString (state));
3003 log->Printf ("Target::%s the process instance doesn't currently exist.", __FUNCTION__);
3007 launch_info.GetFlags().Set (eLaunchFlagDebug);
3009 // Get the value of synchronous execution here. If you wait till after you have started to
3010 // run, then you could have hit a breakpoint, whose command might switch the value, and
3011 // then you'll pick up that incorrect value.
3012 Debugger &debugger = GetDebugger();
3013 const bool synchronous_execution = debugger.GetCommandInterpreter().GetSynchronous ();
3015 PlatformSP platform_sp (GetPlatform());
3017 // Finalize the file actions, and if none were given, default to opening
3018 // up a pseudo terminal
3019 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
3021 log->Printf ("Target::%s have platform=%s, platform_sp->IsHost()=%s, default_to_use_pty=%s",
3023 platform_sp ? "true" : "false",
3024 platform_sp ? (platform_sp->IsHost () ? "true" : "false") : "n/a",
3025 default_to_use_pty ? "true" : "false");
3027 launch_info.FinalizeFileActions (this, default_to_use_pty);
3029 if (state == eStateConnected)
3031 if (launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY))
3033 error.SetErrorString("can't launch in tty when launching through a remote connection");
3038 if (!launch_info.GetArchitecture().IsValid())
3039 launch_info.GetArchitecture() = GetArchitecture();
3041 // If we're not already connected to the process, and if we have a platform that can launch a process for debugging, go ahead and do that here.
3042 if (state != eStateConnected && platform_sp && platform_sp->CanDebugProcess ())
3045 log->Printf ("Target::%s asking the platform to debug the process", __FUNCTION__);
3047 // Get a weak pointer to the previous process if we have one
3048 ProcessWP process_wp;
3050 process_wp = m_process_sp;
3051 m_process_sp = GetPlatform()->DebugProcess (launch_info,
3056 // Cleanup the old process since someone might still have a strong
3057 // reference to this process and we would like to allow it to cleanup
3058 // as much as it can without the object being destroyed. We try to
3059 // lock the shared pointer and if that works, then someone else still
3060 // has a strong reference to the process.
3062 ProcessSP old_process_sp(process_wp.lock());
3064 old_process_sp->Finalize();
3069 log->Printf ("Target::%s the platform doesn't know how to debug a process, getting a process plugin to do this for us.", __FUNCTION__);
3071 if (state == eStateConnected)
3073 assert(m_process_sp);
3077 // Use a Process plugin to construct the process.
3078 const char *plugin_name = launch_info.GetProcessPluginName();
3079 CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name, nullptr);
3082 // Since we didn't have a platform launch the process, launch it here.
3084 error = m_process_sp->Launch (launch_info);
3089 if (error.Success())
3090 error.SetErrorString("failed to launch or debug process");
3094 if (error.Success())
3096 if (synchronous_execution || !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3098 ListenerSP hijack_listener_sp (launch_info.GetHijackListener());
3099 if (!hijack_listener_sp)
3101 hijack_listener_sp = Listener::MakeListener("lldb.Target.Launch.hijack");
3102 launch_info.SetHijackListener(hijack_listener_sp);
3103 m_process_sp->HijackProcessEvents(hijack_listener_sp);
3106 StateType state = m_process_sp->WaitForProcessToStop(nullptr, nullptr, false, hijack_listener_sp, nullptr);
3108 if (state == eStateStopped)
3110 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3112 if (synchronous_execution)
3114 error = m_process_sp->PrivateResume();
3115 if (error.Success())
3117 state = m_process_sp->WaitForProcessToStop(nullptr, nullptr, true, hijack_listener_sp, stream);
3118 const bool must_be_alive = false; // eStateExited is ok, so this must be false
3119 if (!StateIsStoppedState(state, must_be_alive))
3121 error.SetErrorStringWithFormat("process isn't stopped: %s", StateAsCString(state));
3127 m_process_sp->RestoreProcessEvents();
3128 error = m_process_sp->PrivateResume();
3130 if (!error.Success())
3133 error2.SetErrorStringWithFormat("process resume at entry point failed: %s", error.AsCString());
3138 else if (state == eStateExited)
3140 bool with_shell = !!launch_info.GetShell();
3141 const int exit_status = m_process_sp->GetExitStatus();
3142 const char *exit_desc = m_process_sp->GetExitDescription();
3143 #define LAUNCH_SHELL_MESSAGE "\n'r' and 'run' are aliases that default to launching through a shell.\nTry launching without going through a shell by using 'process launch'."
3144 if (exit_desc && exit_desc[0])
3147 error.SetErrorStringWithFormat ("process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE, exit_status, exit_desc);
3149 error.SetErrorStringWithFormat ("process exited with status %i (%s)", exit_status, exit_desc);
3154 error.SetErrorStringWithFormat ("process exited with status %i" LAUNCH_SHELL_MESSAGE, exit_status);
3156 error.SetErrorStringWithFormat ("process exited with status %i", exit_status);
3161 error.SetErrorStringWithFormat ("initial process state wasn't stopped: %s", StateAsCString(state));
3164 m_process_sp->RestoreProcessEvents ();
3169 error2.SetErrorStringWithFormat ("process launch failed: %s", error.AsCString());
3176 Target::Attach (ProcessAttachInfo &attach_info, Stream *stream)
3178 auto state = eStateInvalid;
3179 auto process_sp = GetProcessSP ();
3182 state = process_sp->GetState ();
3183 if (process_sp->IsAlive () && state != eStateConnected)
3185 if (state == eStateAttaching)
3186 return Error ("process attach is in progress");
3187 return Error ("a process is already being debugged");
3191 const ModuleSP old_exec_module_sp = GetExecutableModule ();
3193 // If no process info was specified, then use the target executable
3194 // name as the process to attach to by default
3195 if (!attach_info.ProcessInfoSpecified ())
3197 if (old_exec_module_sp)
3198 attach_info.GetExecutableFile ().GetFilename () = old_exec_module_sp->GetPlatformFileSpec ().GetFilename ();
3200 if (!attach_info.ProcessInfoSpecified ())
3202 return Error ("no process specified, create a target with a file, or specify the --pid or --name");
3206 const auto platform_sp = GetDebugger ().GetPlatformList ().GetSelectedPlatform ();
3207 ListenerSP hijack_listener_sp;
3208 const bool async = attach_info.GetAsync();
3211 hijack_listener_sp = Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3212 attach_info.SetHijackListener (hijack_listener_sp);
3216 if (state != eStateConnected && platform_sp != nullptr && platform_sp->CanDebugProcess ())
3218 SetPlatform (platform_sp);
3219 process_sp = platform_sp->Attach (attach_info, GetDebugger (), this, error);
3223 if (state != eStateConnected)
3225 const char *plugin_name = attach_info.GetProcessPluginName ();
3226 process_sp = CreateProcess (attach_info.GetListenerForProcess (GetDebugger ()), plugin_name, nullptr);
3227 if (process_sp == nullptr)
3229 error.SetErrorStringWithFormat ("failed to create process using plugin %s", (plugin_name) ? plugin_name : "null");
3233 if (hijack_listener_sp)
3234 process_sp->HijackProcessEvents (hijack_listener_sp);
3235 error = process_sp->Attach (attach_info);
3238 if (error.Success () && process_sp)
3242 process_sp->RestoreProcessEvents ();
3246 state = process_sp->WaitForProcessToStop (nullptr, nullptr, false, attach_info.GetHijackListener(), stream);
3247 process_sp->RestoreProcessEvents ();
3249 if (state != eStateStopped)
3251 const char *exit_desc = process_sp->GetExitDescription ();
3253 error.SetErrorStringWithFormat ("%s", exit_desc);
3255 error.SetErrorString ("process did not stop (no such process or permission problem?)");
3256 process_sp->Destroy (false);
3263 //--------------------------------------------------------------
3265 //--------------------------------------------------------------
3266 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
3268 m_target_sp (target_sp),
3276 Target::StopHook::StopHook (const StopHook &rhs) :
3277 UserID (rhs.GetID()),
3278 m_target_sp (rhs.m_target_sp),
3279 m_commands (rhs.m_commands),
3280 m_specifier_sp (rhs.m_specifier_sp),
3281 m_thread_spec_ap (),
3282 m_active (rhs.m_active)
3284 if (rhs.m_thread_spec_ap)
3285 m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
3288 Target::StopHook::~StopHook() = default;
3291 Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier)
3293 m_specifier_sp.reset(specifier);
3297 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
3299 m_thread_spec_ap.reset (specifier);
3303 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
3305 int indent_level = s->GetIndentLevel();
3307 s->SetIndentLevel(indent_level + 2);
3309 s->Printf ("Hook: %" PRIu64 "\n", GetID());
3311 s->Indent ("State: enabled\n");
3313 s->Indent ("State: disabled\n");
3318 s->PutCString ("Specifier:\n");
3319 s->SetIndentLevel (indent_level + 4);
3320 m_specifier_sp->GetDescription (s, level);
3321 s->SetIndentLevel (indent_level + 2);
3324 if (m_thread_spec_ap)
3327 s->Indent("Thread:\n");
3328 m_thread_spec_ap->GetDescription (&tmp, level);
3329 s->SetIndentLevel (indent_level + 4);
3330 s->Indent (tmp.GetData());
3331 s->PutCString ("\n");
3332 s->SetIndentLevel (indent_level + 2);
3335 s->Indent ("Commands: \n");
3336 s->SetIndentLevel (indent_level + 4);
3337 uint32_t num_commands = m_commands.GetSize();
3338 for (uint32_t i = 0; i < num_commands; i++)
3340 s->Indent(m_commands.GetStringAtIndex(i));
3341 s->PutCString ("\n");
3343 s->SetIndentLevel (indent_level);
3346 //--------------------------------------------------------------
3347 // class TargetProperties
3348 //--------------------------------------------------------------
3350 OptionEnumValueElement
3351 lldb_private::g_dynamic_value_types[] =
3353 { eNoDynamicValues, "no-dynamic-values", "Don't calculate the dynamic type of values"},
3354 { eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values even if you have to run the target."},
3355 { eDynamicDontRunTarget, "no-run-target", "Calculate the dynamic type of values, but don't run the target."},
3356 { 0, nullptr, nullptr }
3359 static OptionEnumValueElement
3360 g_inline_breakpoint_enums[] =
3362 { eInlineBreakpointsNever, "never", "Never look for inline breakpoint locations (fastest). This setting should only be used if you know that no inlining occurs in your programs."},
3363 { eInlineBreakpointsHeaders, "headers", "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
3364 { eInlineBreakpointsAlways, "always", "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
3365 { 0, nullptr, nullptr }
3368 typedef enum x86DisassemblyFlavor
3370 eX86DisFlavorDefault,
3373 } x86DisassemblyFlavor;
3375 static OptionEnumValueElement
3376 g_x86_dis_flavor_value_types[] =
3378 { eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3379 { eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3380 { eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
3381 { 0, nullptr, nullptr }
3384 static OptionEnumValueElement
3385 g_hex_immediate_style_values[] =
3387 { Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3388 { Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
3389 { 0, nullptr, nullptr }
3392 static OptionEnumValueElement
3393 g_load_script_from_sym_file_values[] =
3395 { eLoadScriptFromSymFileTrue, "true", "Load debug scripts inside symbol files"},
3396 { eLoadScriptFromSymFileFalse, "false", "Do not load debug scripts inside symbol files."},
3397 { eLoadScriptFromSymFileWarn, "warn", "Warn about debug scripts inside symbol files but do not load them."},
3398 { 0, nullptr, nullptr }
3401 static OptionEnumValueElement
3402 g_load_current_working_dir_lldbinit_values[] =
3404 { eLoadCWDlldbinitTrue, "true", "Load .lldbinit files from current directory"},
3405 { eLoadCWDlldbinitFalse, "false", "Do not load .lldbinit files from current directory"},
3406 { eLoadCWDlldbinitWarn, "warn", "Warn about loading .lldbinit files from current directory"},
3407 { 0, nullptr, nullptr }
3410 static OptionEnumValueElement
3411 g_memory_module_load_level_values[] =
3413 { eMemoryModuleLoadLevelMinimal, "minimal" , "Load minimal information when loading modules from memory. Currently this setting loads sections only."},
3414 { eMemoryModuleLoadLevelPartial, "partial" , "Load partial information when loading modules from memory. Currently this setting loads sections and function bounds."},
3415 { eMemoryModuleLoadLevelComplete, "complete", "Load complete information when loading modules from memory. Currently this setting loads sections and all symbols."},
3416 { 0, nullptr, nullptr }
3419 static PropertyDefinition
3422 { "default-arch" , OptionValue::eTypeArch , true , 0 , nullptr, nullptr, "Default architecture to choose, when there's a choice." },
3423 { "move-to-nearest-code" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Move breakpoints to nearest code." },
3424 { "language" , OptionValue::eTypeLanguage , false, eLanguageTypeUnknown , nullptr, nullptr, "The language to use when interpreting expressions entered in commands." },
3425 { "expr-prefix" , OptionValue::eTypeFileSpec , false, 0 , nullptr, nullptr, "Path to a file containing expressions to be prepended to all expressions." },
3426 { "prefer-dynamic-value" , OptionValue::eTypeEnum , false, eDynamicDontRunTarget , nullptr, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
3427 { "enable-synthetic-value" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Should synthetic values be used by default whenever available." },
3428 { "skip-prologue" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Skip function prologues when setting breakpoints by name." },
3429 { "source-map" , OptionValue::eTypePathMap , false, 0 , nullptr, nullptr, "Source path remappings are used to track the change of location between a source file when built, and "
3430 "where it exists on the current system. It consists of an array of duples, the first element of each duple is "
3431 "some part (starting at the root) of the path to the file when it was built, "
3432 "and the second is where the remainder of the original build hierarchy is rooted on the local system. "
3433 "Each element of the array is checked in order and the first one that results in a match wins." },
3434 { "exec-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , nullptr, nullptr, "Executable search paths to use when locating executable files whose paths don't match the local file system." },
3435 { "debug-file-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , nullptr, nullptr, "List of directories to be searched when locating debug symbol files." },
3436 { "clang-module-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , nullptr, nullptr, "List of directories to be searched when locating modules for Clang." },
3437 { "auto-import-clang-modules" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Automatically load Clang modules referred to by the program." },
3438 { "auto-apply-fixits" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Automatically apply fix-it hints to expressions." },
3439 { "notify-about-fixits" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Print the fixed expression text." },
3440 { "max-children-count" , OptionValue::eTypeSInt64 , false, 256 , nullptr, nullptr, "Maximum number of children to expand in any level of depth." },
3441 { "max-string-summary-length" , OptionValue::eTypeSInt64 , false, 1024 , nullptr, nullptr, "Maximum number of characters to show when using %s in summary strings." },
3442 { "max-memory-read-size" , OptionValue::eTypeSInt64 , false, 1024 , nullptr, nullptr, "Maximum number of bytes that 'memory read' will fetch before --force must be specified." },
3443 { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Consult the platform module avoid list when setting non-module specific breakpoints." },
3444 { "arg0" , OptionValue::eTypeString , false, 0 , nullptr, nullptr, "The first argument passed to the program in the argument array which can be different from the executable itself." },
3445 { "run-args" , OptionValue::eTypeArgs , false, 0 , nullptr, nullptr, "A list containing all the arguments to be passed to the executable when it is run. Note that this does NOT include the argv[0] which is in target.arg0." },
3446 { "env-vars" , OptionValue::eTypeDictionary, false, OptionValue::eTypeString , nullptr, nullptr, "A list of all the environment variables to be passed to the executable's environment, and their values." },
3447 { "inherit-env" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Inherit the environment from the process that is running LLDB." },
3448 { "input-path" , OptionValue::eTypeFileSpec , false, 0 , nullptr, nullptr, "The file/path to be used by the executable program for reading its standard input." },
3449 { "output-path" , OptionValue::eTypeFileSpec , false, 0 , nullptr, nullptr, "The file/path to be used by the executable program for writing its standard output." },
3450 { "error-path" , OptionValue::eTypeFileSpec , false, 0 , nullptr, nullptr, "The file/path to be used by the executable program for writing its standard error." },
3451 { "detach-on-error" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "debugserver will detach (rather than killing) a process if it loses connection with lldb." },
3452 { "disable-aslr" , OptionValue::eTypeBoolean , false, true , nullptr, nullptr, "Disable Address Space Layout Randomization (ASLR)" },
3453 { "disable-stdio" , OptionValue::eTypeBoolean , false, false , nullptr, nullptr, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3454 { "inline-breakpoint-strategy" , OptionValue::eTypeEnum , false, eInlineBreakpointsAlways , nullptr, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
3455 "Breakpoint locations can end up being inlined by the compiler, so that a compile unit 'a.c' might contain an inlined function from another source file. "
3456 "Usually this is limited to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
3457 "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
3458 "Always checking for inlined breakpoint locations can be expensive (memory and time), so if you have a project with many headers "
3459 "and find that setting breakpoints is slow, then you can change this setting to headers. "
3460 "This setting allows you to control exactly which strategy is used when setting "
3461 "file and line breakpoints." },
3462 // FIXME: This is the wrong way to do per-architecture settings, but we don't have a general per architecture settings system in place yet.
3463 { "x86-disassembly-flavor" , OptionValue::eTypeEnum , false, eX86DisFlavorDefault, nullptr, g_x86_dis_flavor_value_types, "The default disassembly flavor to use for x86 or x86-64 targets." },
3464 { "use-hex-immediates" , OptionValue::eTypeBoolean , false, true, nullptr, nullptr, "Show immediates in disassembly as hexadecimal." },
3465 { "hex-immediate-style" , OptionValue::eTypeEnum , false, Disassembler::eHexStyleC, nullptr, g_hex_immediate_style_values, "Which style to use for printing hexadecimal disassembly values." },
3466 { "use-fast-stepping" , OptionValue::eTypeBoolean , false, true, nullptr, nullptr, "Use a fast stepping algorithm based on running from branch to branch rather than instruction single-stepping." },
3467 { "load-script-from-symbol-file" , OptionValue::eTypeEnum , false, eLoadScriptFromSymFileWarn, nullptr, g_load_script_from_sym_file_values, "Allow LLDB to load scripting resources embedded in symbol files when available." },
3468 { "load-cwd-lldbinit" , OptionValue::eTypeEnum , false, eLoadCWDlldbinitWarn, nullptr, g_load_current_working_dir_lldbinit_values, "Allow LLDB to .lldbinit files from the current directory automatically." },
3469 { "memory-module-load-level" , OptionValue::eTypeEnum , false, eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3470 "Loading modules from memory can be slow as reading the symbol tables and other data can take a long time depending on your connection to the debug target. "
3471 "This setting helps users control how much information gets loaded when loading modules from memory."
3472 "'complete' is the default value for this setting which will load all sections and symbols by reading them from memory (slowest, most accurate). "
3473 "'partial' will load sections and attempt to find function bounds without downloading the symbol table (faster, still accurate, missing symbol names). "
3474 "'minimal' is the fastest setting and will load section data with no symbols, but should rarely be used as stack frames in these memory regions will be inaccurate and not provide any context (fastest). " },
3475 { "display-expression-in-crashlogs" , OptionValue::eTypeBoolean , false, false, nullptr, nullptr, "Expressions that crash will show up in crash logs if the host system supports executable specific crash log strings and this setting is set to true." },
3476 { "trap-handler-names" , OptionValue::eTypeArray , true, OptionValue::eTypeString, nullptr, nullptr, "A list of trap handler function names, e.g. a common Unix user process one is _sigtramp." },
3477 { "display-runtime-support-values" , OptionValue::eTypeBoolean , false, false, nullptr, nullptr, "If true, LLDB will show variables that are meant to support the operation of a language's runtime support." },
3478 { "non-stop-mode" , OptionValue::eTypeBoolean , false, 0, nullptr, nullptr, "Disable lock-step debugging, instead control threads independently." },
3479 { nullptr , OptionValue::eTypeInvalid , false, 0 , nullptr, nullptr, nullptr }
3484 ePropertyDefaultArch,
3485 ePropertyMoveToNearestCode,
3487 ePropertyExprPrefix,
3488 ePropertyPreferDynamic,
3489 ePropertyEnableSynthetic,
3490 ePropertySkipPrologue,
3492 ePropertyExecutableSearchPaths,
3493 ePropertyDebugFileSearchPaths,
3494 ePropertyClangModuleSearchPaths,
3495 ePropertyAutoImportClangModules,
3496 ePropertyAutoApplyFixIts,
3497 ePropertyNotifyAboutFixIts,
3498 ePropertyMaxChildrenCount,
3499 ePropertyMaxSummaryLength,
3500 ePropertyMaxMemReadSize,
3501 ePropertyBreakpointUseAvoidList,
3505 ePropertyInheritEnv,
3507 ePropertyOutputPath,
3509 ePropertyDetachOnError,
3510 ePropertyDisableASLR,
3511 ePropertyDisableSTDIO,
3512 ePropertyInlineStrategy,
3513 ePropertyDisassemblyFlavor,
3514 ePropertyUseHexImmediates,
3515 ePropertyHexImmediateStyle,
3516 ePropertyUseFastStepping,
3517 ePropertyLoadScriptFromSymbolFile,
3518 ePropertyLoadCWDlldbinitFile,
3519 ePropertyMemoryModuleLoadLevel,
3520 ePropertyDisplayExpressionsInCrashlogs,
3521 ePropertyTrapHandlerNames,
3522 ePropertyDisplayRuntimeSupportValues,
3523 ePropertyNonStopModeEnabled,
3524 ePropertyExperimental
3527 class TargetOptionValueProperties : public OptionValueProperties
3530 TargetOptionValueProperties (const ConstString &name) :
3531 OptionValueProperties (name),
3533 m_got_host_env (false)
3537 // This constructor is used when creating TargetOptionValueProperties when it
3538 // is part of a new lldb_private::Target instance. It will copy all current
3539 // global property values as needed
3540 TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
3541 OptionValueProperties(*target_properties_sp->GetValueProperties()),
3543 m_got_host_env (false)
3548 GetPropertyAtIndex(const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const override
3550 // When getting the value for a key from the target options, we will always
3551 // try and grab the setting from the current target if there is one. Else we just
3552 // use the one from this instance.
3553 if (idx == ePropertyEnvVars)
3554 GetHostEnvironmentIfNeeded ();
3558 Target *target = exe_ctx->GetTargetPtr();
3561 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
3562 if (this != target_properties)
3563 return target_properties->ProtectedGetPropertyAtIndex (idx);
3566 return ProtectedGetPropertyAtIndex (idx);
3572 return m_target->shared_from_this();
3577 GetHostEnvironmentIfNeeded () const
3579 if (!m_got_host_env)
3583 m_got_host_env = true;
3584 const uint32_t idx = ePropertyInheritEnv;
3585 if (GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0))
3587 PlatformSP platform_sp (m_target->GetPlatform());
3591 if (platform_sp->GetEnvironment(env))
3593 OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary(nullptr, ePropertyEnvVars);
3596 const bool can_replace = false;
3597 const size_t envc = env.GetSize();
3598 for (size_t idx=0; idx<envc; idx++)
3600 const char *env_entry = env.GetStringAtIndex (idx);
3603 const char *equal_pos = ::strchr(env_entry, '=');
3605 // It is ok to have environment variables with no values
3606 const char *value = nullptr;
3609 key.SetCStringWithLength(env_entry, equal_pos - env_entry);
3611 value = equal_pos + 1;
3615 key.SetCString(env_entry);
3617 // Don't allow existing keys to be replaced with ones we get from the platform environment
3618 env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
3629 mutable bool m_got_host_env;
3632 //----------------------------------------------------------------------
3634 //----------------------------------------------------------------------
3635 static PropertyDefinition
3636 g_experimental_properties[]
3638 { "inject-local-vars", OptionValue::eTypeBoolean , true, true, nullptr, nullptr, "If true, inject local variables explicitly into the expression text. "
3639 "This will fix symbol resolution when there are name collisions between ivars and local variables. "
3640 "But it can make expressions run much more slowly." },
3641 { nullptr, OptionValue::eTypeInvalid , true, 0 , nullptr, nullptr, nullptr }
3646 ePropertyInjectLocalVars = 0
3649 class TargetExperimentalOptionValueProperties : public OptionValueProperties
3652 TargetExperimentalOptionValueProperties () :
3653 OptionValueProperties (ConstString(Properties::GetExperimentalSettingsName()))
3658 TargetExperimentalProperties::TargetExperimentalProperties() :
3659 Properties(OptionValuePropertiesSP(new TargetExperimentalOptionValueProperties()))
3661 m_collection_sp->Initialize(g_experimental_properties);
3664 //----------------------------------------------------------------------
3666 //----------------------------------------------------------------------
3667 TargetProperties::TargetProperties (Target *target) :
3673 m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
3675 // Set callbacks to update launch_info whenever "settins set" updated any of these properties
3676 m_collection_sp->SetValueChangedCallback(ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3677 m_collection_sp->SetValueChangedCallback(ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3678 m_collection_sp->SetValueChangedCallback(ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3679 m_collection_sp->SetValueChangedCallback(ePropertyInputPath, TargetProperties::InputPathValueChangedCallback, this);
3680 m_collection_sp->SetValueChangedCallback(ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback, this);
3681 m_collection_sp->SetValueChangedCallback(ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback, this);
3682 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, TargetProperties::DetachOnErrorValueChangedCallback, this);
3683 m_collection_sp->SetValueChangedCallback(ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback, this);
3684 m_collection_sp->SetValueChangedCallback(ePropertyDisableSTDIO, TargetProperties::DisableSTDIOValueChangedCallback, this);
3686 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3687 m_collection_sp->AppendProperty (ConstString(Properties::GetExperimentalSettingsName()),
3688 ConstString("Experimental settings - setting these won't produce errors if the setting is not present."),
3690 m_experimental_properties_up->GetValueProperties());
3692 // Update m_launch_info once it was created
3693 Arg0ValueChangedCallback(this, nullptr);
3694 RunArgsValueChangedCallback(this, nullptr);
3695 //EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in Target::GetPlatform()
3696 InputPathValueChangedCallback(this, nullptr);
3697 OutputPathValueChangedCallback(this, nullptr);
3698 ErrorPathValueChangedCallback(this, nullptr);
3699 DetachOnErrorValueChangedCallback(this, nullptr);
3700 DisableASLRValueChangedCallback(this, nullptr);
3701 DisableSTDIOValueChangedCallback(this, nullptr);
3705 m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
3706 m_collection_sp->Initialize(g_properties);
3707 m_experimental_properties_up.reset(new TargetExperimentalProperties());
3708 m_collection_sp->AppendProperty (ConstString(Properties::GetExperimentalSettingsName()),
3709 ConstString("Experimental settings - setting these won't produce errors if the setting is not present."),
3711 m_experimental_properties_up->GetValueProperties());
3712 m_collection_sp->AppendProperty(ConstString("process"),
3713 ConstString("Settings specific to processes."),
3715 Process::GetGlobalProperties()->GetValueProperties());
3719 TargetProperties::~TargetProperties() = default;
3722 TargetProperties::GetInjectLocalVariables(ExecutionContext *exe_ctx) const
3724 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(exe_ctx, false, ePropertyExperimental);
3725 OptionValueProperties *exp_values = exp_property->GetValue()->GetAsProperties();
3727 return exp_values->GetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars, true);
3733 TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx, bool b)
3735 const Property *exp_property = m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3736 OptionValueProperties *exp_values = exp_property->GetValue()->GetAsProperties();
3738 exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars, true);
3742 TargetProperties::GetDefaultArchitecture () const
3744 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(nullptr, ePropertyDefaultArch);
3746 return value->GetCurrentValue();
3751 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
3753 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(nullptr, ePropertyDefaultArch);
3755 return value->SetCurrentValue(arch, true);
3759 TargetProperties::GetMoveToNearestCode() const
3761 const uint32_t idx = ePropertyMoveToNearestCode;
3762 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3765 lldb::DynamicValueType
3766 TargetProperties::GetPreferDynamicValue() const
3768 const uint32_t idx = ePropertyPreferDynamic;
3769 return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3773 TargetProperties::SetPreferDynamicValue (lldb::DynamicValueType d)
3775 const uint32_t idx = ePropertyPreferDynamic;
3776 return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3780 TargetProperties::GetDisableASLR () const
3782 const uint32_t idx = ePropertyDisableASLR;
3783 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3787 TargetProperties::SetDisableASLR (bool b)
3789 const uint32_t idx = ePropertyDisableASLR;
3790 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3794 TargetProperties::GetDetachOnError () const
3796 const uint32_t idx = ePropertyDetachOnError;
3797 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3801 TargetProperties::SetDetachOnError (bool b)
3803 const uint32_t idx = ePropertyDetachOnError;
3804 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3808 TargetProperties::GetDisableSTDIO () const
3810 const uint32_t idx = ePropertyDisableSTDIO;
3811 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3815 TargetProperties::SetDisableSTDIO (bool b)
3817 const uint32_t idx = ePropertyDisableSTDIO;
3818 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3822 TargetProperties::GetDisassemblyFlavor () const
3824 const uint32_t idx = ePropertyDisassemblyFlavor;
3825 const char *return_value;
3827 x86DisassemblyFlavor flavor_value = (x86DisassemblyFlavor) m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3828 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3829 return return_value;
3833 TargetProperties::GetInlineStrategy () const
3835 const uint32_t idx = ePropertyInlineStrategy;
3836 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3840 TargetProperties::GetArg0 () const
3842 const uint32_t idx = ePropertyArg0;
3843 return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, nullptr);
3847 TargetProperties::SetArg0 (const char *arg)
3849 const uint32_t idx = ePropertyArg0;
3850 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3851 m_launch_info.SetArg0(arg);
3855 TargetProperties::GetRunArguments (Args &args) const
3857 const uint32_t idx = ePropertyRunArgs;
3858 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3862 TargetProperties::SetRunArguments (const Args &args)
3864 const uint32_t idx = ePropertyRunArgs;
3865 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3866 m_launch_info.GetArguments() = args;
3870 TargetProperties::GetEnvironmentAsArgs (Args &env) const
3872 const uint32_t idx = ePropertyEnvVars;
3873 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3877 TargetProperties::SetEnvironmentFromArgs (const Args &env)
3879 const uint32_t idx = ePropertyEnvVars;
3880 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, env);
3881 m_launch_info.GetEnvironmentEntries() = env;
3885 TargetProperties::GetSkipPrologue() const
3887 const uint32_t idx = ePropertySkipPrologue;
3888 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3892 TargetProperties::GetSourcePathMap () const
3894 const uint32_t idx = ePropertySourceMap;
3895 OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr, false, idx);
3896 assert(option_value);
3897 return option_value->GetCurrentValue();
3901 TargetProperties::GetExecutableSearchPaths ()
3903 const uint32_t idx = ePropertyExecutableSearchPaths;
3904 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx);
3905 assert(option_value);
3906 return option_value->GetCurrentValue();
3910 TargetProperties::GetDebugFileSearchPaths ()
3912 const uint32_t idx = ePropertyDebugFileSearchPaths;
3913 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx);
3914 assert(option_value);
3915 return option_value->GetCurrentValue();
3919 TargetProperties::GetClangModuleSearchPaths ()
3921 const uint32_t idx = ePropertyClangModuleSearchPaths;
3922 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx);
3923 assert(option_value);
3924 return option_value->GetCurrentValue();
3928 TargetProperties::GetEnableAutoImportClangModules() const
3930 const uint32_t idx = ePropertyAutoImportClangModules;
3931 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3935 TargetProperties::GetEnableAutoApplyFixIts() const
3937 const uint32_t idx = ePropertyAutoApplyFixIts;
3938 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3942 TargetProperties::GetEnableNotifyAboutFixIts() const
3944 const uint32_t idx = ePropertyNotifyAboutFixIts;
3945 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3949 TargetProperties::GetEnableSyntheticValue () const
3951 const uint32_t idx = ePropertyEnableSynthetic;
3952 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3956 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
3958 const uint32_t idx = ePropertyMaxChildrenCount;
3959 return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value);
3963 TargetProperties::GetMaximumSizeOfStringSummary() const
3965 const uint32_t idx = ePropertyMaxSummaryLength;
3966 return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value);
3970 TargetProperties::GetMaximumMemReadSize () const
3972 const uint32_t idx = ePropertyMaxMemReadSize;
3973 return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value);
3977 TargetProperties::GetStandardInputPath () const
3979 const uint32_t idx = ePropertyInputPath;
3980 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3984 TargetProperties::SetStandardInputPath (const char *p)
3986 const uint32_t idx = ePropertyInputPath;
3987 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
3991 TargetProperties::GetStandardOutputPath () const
3993 const uint32_t idx = ePropertyOutputPath;
3994 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3998 TargetProperties::SetStandardOutputPath (const char *p)
4000 const uint32_t idx = ePropertyOutputPath;
4001 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
4005 TargetProperties::GetStandardErrorPath () const
4007 const uint32_t idx = ePropertyErrorPath;
4008 return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4012 TargetProperties::GetLanguage () const
4014 OptionValueLanguage *value = m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(nullptr, ePropertyLanguage);
4016 return value->GetCurrentValue();
4017 return LanguageType();
4021 TargetProperties::GetExpressionPrefixContentsAsCString ()
4023 const uint32_t idx = ePropertyExprPrefix;
4024 OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false, idx);
4027 const bool null_terminate = true;
4028 DataBufferSP data_sp(file->GetFileContents(null_terminate));
4030 return (const char *) data_sp->GetBytes();
4036 TargetProperties::SetStandardErrorPath (const char *p)
4038 const uint32_t idx = ePropertyErrorPath;
4039 m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
4043 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
4045 const uint32_t idx = ePropertyBreakpointUseAvoidList;
4046 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
4050 TargetProperties::GetUseHexImmediates () const
4052 const uint32_t idx = ePropertyUseHexImmediates;
4053 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
4057 TargetProperties::GetUseFastStepping () const
4059 const uint32_t idx = ePropertyUseFastStepping;
4060 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
4064 TargetProperties::GetDisplayExpressionsInCrashlogs () const
4066 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4067 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
4070 LoadScriptFromSymFile
4071 TargetProperties::GetLoadScriptFromSymbolFile () const
4073 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4074 return (LoadScriptFromSymFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
4078 TargetProperties::GetLoadCWDlldbinitFile () const
4080 const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4081 return (LoadCWDlldbinitFile) m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
4084 Disassembler::HexImmediateStyle
4085 TargetProperties::GetHexImmediateStyle () const
4087 const uint32_t idx = ePropertyHexImmediateStyle;
4088 return (Disassembler::HexImmediateStyle)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
4091 MemoryModuleLoadLevel
4092 TargetProperties::GetMemoryModuleLoadLevel() const
4094 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4095 return (MemoryModuleLoadLevel)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
4099 TargetProperties::GetUserSpecifiedTrapHandlerNames (Args &args) const
4101 const uint32_t idx = ePropertyTrapHandlerNames;
4102 return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4106 TargetProperties::SetUserSpecifiedTrapHandlerNames (const Args &args)
4108 const uint32_t idx = ePropertyTrapHandlerNames;
4109 m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4113 TargetProperties::GetDisplayRuntimeSupportValues () const
4115 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4116 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4120 TargetProperties::SetDisplayRuntimeSupportValues (bool b)
4122 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4123 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4127 TargetProperties::GetNonStopModeEnabled () const
4129 const uint32_t idx = ePropertyNonStopModeEnabled;
4130 return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4134 TargetProperties::SetNonStopModeEnabled (bool b)
4136 const uint32_t idx = ePropertyNonStopModeEnabled;
4137 m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4140 const ProcessLaunchInfo &
4141 TargetProperties::GetProcessLaunchInfo ()
4143 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4144 return m_launch_info;
4148 TargetProperties::SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
4150 m_launch_info = launch_info;
4151 SetArg0(launch_info.GetArg0());
4152 SetRunArguments(launch_info.GetArguments());
4153 SetEnvironmentFromArgs(launch_info.GetEnvironmentEntries());
4154 const FileAction *input_file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
4155 if (input_file_action)
4157 const char *input_path = input_file_action->GetPath();
4159 SetStandardInputPath(input_path);
4161 const FileAction *output_file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
4162 if (output_file_action)
4164 const char *output_path = output_file_action->GetPath();
4166 SetStandardOutputPath(output_path);
4168 const FileAction *error_file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
4169 if (error_file_action)
4171 const char *error_path = error_file_action->GetPath();
4173 SetStandardErrorPath(error_path);
4175 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4176 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4177 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4181 TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr, OptionValue *)
4183 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4184 this_->m_launch_info.SetArg0(this_->GetArg0());
4188 TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr, OptionValue *)
4190 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4192 if (this_->GetRunArguments(args))
4193 this_->m_launch_info.GetArguments() = args;
4197 TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr, OptionValue *)
4199 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4201 if (this_->GetEnvironmentAsArgs(args))
4202 this_->m_launch_info.GetEnvironmentEntries() = args;
4206 TargetProperties::InputPathValueChangedCallback(void *target_property_ptr, OptionValue *)
4208 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4209 this_->m_launch_info.AppendOpenFileAction(STDIN_FILENO, this_->GetStandardInputPath(), true, false);
4213 TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr, OptionValue *)
4215 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4216 this_->m_launch_info.AppendOpenFileAction(STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
4220 TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr, OptionValue *)
4222 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4223 this_->m_launch_info.AppendOpenFileAction(STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
4227 TargetProperties::DetachOnErrorValueChangedCallback(void *target_property_ptr, OptionValue *)
4229 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4230 if (this_->GetDetachOnError())
4231 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4233 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4237 TargetProperties::DisableASLRValueChangedCallback(void *target_property_ptr, OptionValue *)
4239 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4240 if (this_->GetDisableASLR())
4241 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4243 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4247 TargetProperties::DisableSTDIOValueChangedCallback(void *target_property_ptr, OptionValue *)
4249 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4250 if (this_->GetDisableSTDIO())
4251 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4253 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4256 //----------------------------------------------------------------------
4257 // Target::TargetEventData
4258 //----------------------------------------------------------------------
4260 Target::TargetEventData::TargetEventData (const lldb::TargetSP &target_sp) :
4262 m_target_sp (target_sp),
4267 Target::TargetEventData::TargetEventData (const lldb::TargetSP &target_sp, const ModuleList &module_list) :
4269 m_target_sp (target_sp),
4270 m_module_list (module_list)
4274 Target::TargetEventData::~TargetEventData() = default;
4277 Target::TargetEventData::GetFlavorString ()
4279 static ConstString g_flavor ("Target::TargetEventData");
4284 Target::TargetEventData::Dump (Stream *s) const
4286 for (size_t i = 0; i < m_module_list.GetSize(); ++i)
4290 m_module_list.GetModuleAtIndex(i)->GetDescription(s, lldb::eDescriptionLevelBrief);
4294 const Target::TargetEventData *
4295 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
4299 const EventData *event_data = event_ptr->GetData();
4300 if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
4301 return static_cast <const TargetEventData *> (event_ptr->GetData());
4307 Target::TargetEventData::GetTargetFromEvent (const Event *event_ptr)
4310 const TargetEventData *event_data = GetEventDataFromEvent (event_ptr);
4312 target_sp = event_data->m_target_sp;
4317 Target::TargetEventData::GetModuleListFromEvent (const Event *event_ptr)
4319 ModuleList module_list;
4320 const TargetEventData *event_data = GetEventDataFromEvent (event_ptr);
4322 module_list = event_data->m_module_list;