1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/lldb-python.h"
12 #include "lldb/Target/Target.h"
16 // Other libraries and framework includes
18 #include "lldb/Breakpoint/BreakpointResolver.h"
19 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
20 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
21 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
22 #include "lldb/Breakpoint/BreakpointResolverName.h"
23 #include "lldb/Breakpoint/Watchpoint.h"
24 #include "lldb/Core/Debugger.h"
25 #include "lldb/Core/Event.h"
26 #include "lldb/Core/Log.h"
27 #include "lldb/Core/Module.h"
28 #include "lldb/Core/ModuleSpec.h"
29 #include "lldb/Core/Section.h"
30 #include "lldb/Core/SourceManager.h"
31 #include "lldb/Core/State.h"
32 #include "lldb/Core/StreamFile.h"
33 #include "lldb/Core/StreamString.h"
34 #include "lldb/Core/Timer.h"
35 #include "lldb/Core/ValueObject.h"
36 #include "lldb/Expression/ClangASTSource.h"
37 #include "lldb/Expression/ClangUserExpression.h"
38 #include "lldb/Host/Host.h"
39 #include "lldb/Interpreter/CommandInterpreter.h"
40 #include "lldb/Interpreter/CommandReturnObject.h"
41 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
42 #include "lldb/Interpreter/OptionValues.h"
43 #include "lldb/Interpreter/Property.h"
44 #include "lldb/lldb-private-log.h"
45 #include "lldb/Symbol/ObjectFile.h"
46 #include "lldb/Target/Process.h"
47 #include "lldb/Target/SectionLoadList.h"
48 #include "lldb/Target/StackFrame.h"
49 #include "lldb/Target/SystemRuntime.h"
50 #include "lldb/Target/Thread.h"
51 #include "lldb/Target/ThreadSpec.h"
54 using namespace lldb_private;
57 Target::GetStaticBroadcasterClass ()
59 static ConstString class_name ("lldb.target");
63 //----------------------------------------------------------------------
65 //----------------------------------------------------------------------
66 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
67 TargetProperties (this),
68 Broadcaster (&debugger, Target::GetStaticBroadcasterClass().AsCString()),
69 ExecutionContextScope (),
70 m_debugger (debugger),
71 m_platform_sp (platform_sp),
72 m_mutex (Mutex::eMutexTypeRecursive),
75 m_section_load_history (),
76 m_breakpoint_list (false),
77 m_internal_breakpoint_list (true),
80 m_search_filter_sp (),
81 m_image_search_paths (ImageSearchPathsChanged, this),
82 m_scratch_ast_context_ap (),
83 m_scratch_ast_source_ap (),
85 m_persistent_variables (),
86 m_source_manager_ap(),
88 m_stop_hook_next_id (0),
90 m_suppress_stop_hooks (false)
92 SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
93 SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
94 SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
95 SetEventName (eBroadcastBitWatchpointChanged, "watchpoint-changed");
96 SetEventName (eBroadcastBitSymbolsLoaded, "symbols-loaded");
100 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
102 log->Printf ("%p Target::Target()", this);
103 if (m_arch.IsValid())
105 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::Target created with architecture %s (%s)", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
109 //----------------------------------------------------------------------
111 //----------------------------------------------------------------------
114 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
116 log->Printf ("%p Target::~Target()", this);
117 DeleteCurrentProcess ();
121 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
123 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
124 if (description_level != lldb::eDescriptionLevelBrief)
127 s->PutCString("Target\n");
130 m_breakpoint_list.Dump(s);
131 m_internal_breakpoint_list.Dump(s);
136 Module *exe_module = GetExecutableModulePointer();
138 s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
140 s->PutCString ("No executable module.");
145 Target::CleanupProcess ()
147 // Do any cleanup of the target we need to do between process instances.
148 // NB It is better to do this before destroying the process in case the
149 // clean up needs some help from the process.
150 m_breakpoint_list.ClearAllBreakpointSites();
151 m_internal_breakpoint_list.ClearAllBreakpointSites();
152 // Disable watchpoints just on the debugger side.
153 Mutex::Locker locker;
154 this->GetWatchpointList().GetListMutex(locker);
155 DisableAllWatchpoints(false);
156 ClearAllWatchpointHitCounts();
160 Target::DeleteCurrentProcess ()
162 if (m_process_sp.get())
164 m_section_load_history.Clear();
165 if (m_process_sp->IsAlive())
166 m_process_sp->Destroy();
168 m_process_sp->Finalize();
172 m_process_sp.reset();
176 const lldb::ProcessSP &
177 Target::CreateProcess (Listener &listener, const char *plugin_name, const FileSpec *crash_file)
179 DeleteCurrentProcess ();
180 m_process_sp = Process::FindPlugin(*this, plugin_name, listener, crash_file);
184 const lldb::ProcessSP &
185 Target::GetProcessSP () const
193 Mutex::Locker locker (m_mutex);
195 DeleteCurrentProcess ();
196 m_platform_sp.reset();
199 m_section_load_history.Clear();
200 const bool notify = false;
201 m_breakpoint_list.RemoveAll(notify);
202 m_internal_breakpoint_list.RemoveAll(notify);
203 m_last_created_breakpoint.reset();
204 m_last_created_watchpoint.reset();
205 m_search_filter_sp.reset();
206 m_image_search_paths.Clear(notify);
207 m_persistent_variables.Clear();
208 m_stop_hooks.clear();
209 m_stop_hook_next_id = 0;
210 m_suppress_stop_hooks = false;
215 Target::GetBreakpointList(bool internal)
218 return m_internal_breakpoint_list;
220 return m_breakpoint_list;
223 const BreakpointList &
224 Target::GetBreakpointList(bool internal) const
227 return m_internal_breakpoint_list;
229 return m_breakpoint_list;
233 Target::GetBreakpointByID (break_id_t break_id)
237 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
238 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
240 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
246 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
247 const FileSpecList *source_file_spec_list,
248 RegularExpression &source_regex,
252 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list));
253 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex (NULL, source_regex));
254 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
259 Target::CreateBreakpoint (const FileSpecList *containingModules,
260 const FileSpec &file,
262 LazyBool check_inlines,
263 LazyBool skip_prologue,
267 if (check_inlines == eLazyBoolCalculate)
269 const InlineStrategy inline_strategy = GetInlineStrategy();
270 switch (inline_strategy)
272 case eInlineBreakpointsNever:
273 check_inlines = eLazyBoolNo;
276 case eInlineBreakpointsHeaders:
277 if (file.IsSourceImplementationFile())
278 check_inlines = eLazyBoolNo;
280 check_inlines = eLazyBoolYes;
283 case eInlineBreakpointsAlways:
284 check_inlines = eLazyBoolYes;
288 SearchFilterSP filter_sp;
289 if (check_inlines == eLazyBoolNo)
291 // Not checking for inlines, we are looking only for matching compile units
292 FileSpecList compile_unit_list;
293 compile_unit_list.Append (file);
294 filter_sp = GetSearchFilterForModuleAndCUList (containingModules, &compile_unit_list);
298 filter_sp = GetSearchFilterForModuleList (containingModules);
300 if (skip_prologue == eLazyBoolCalculate)
301 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
303 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL,
308 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
313 Target::CreateBreakpoint (lldb::addr_t addr, bool internal, bool hardware)
316 // Attempt to resolve our load address if possible, though it is ok if
317 // it doesn't resolve to section/offset.
319 // Try and resolve as a load address if possible
320 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
321 if (!so_addr.IsValid())
323 // The address didn't resolve, so just set this as an absolute address
324 so_addr.SetOffset (addr);
326 BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal, hardware));
331 Target::CreateBreakpoint (Address &addr, bool internal, bool hardware)
333 SearchFilterSP filter_sp(new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
334 BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
335 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, false);
339 Target::CreateBreakpoint (const FileSpecList *containingModules,
340 const FileSpecList *containingSourceFiles,
341 const char *func_name,
342 uint32_t func_name_type_mask,
343 LazyBool skip_prologue,
350 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
352 if (skip_prologue == eLazyBoolCalculate)
353 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
355 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
360 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
366 Target::CreateBreakpoint (const FileSpecList *containingModules,
367 const FileSpecList *containingSourceFiles,
368 const std::vector<std::string> &func_names,
369 uint32_t func_name_type_mask,
370 LazyBool skip_prologue,
375 size_t num_names = func_names.size();
378 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
380 if (skip_prologue == eLazyBoolCalculate)
381 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
383 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
387 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
393 Target::CreateBreakpoint (const FileSpecList *containingModules,
394 const FileSpecList *containingSourceFiles,
395 const char *func_names[],
397 uint32_t func_name_type_mask,
398 LazyBool skip_prologue,
405 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
407 if (skip_prologue == eLazyBoolCalculate)
408 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
410 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
415 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
421 Target::GetSearchFilterForModule (const FileSpec *containingModule)
423 SearchFilterSP filter_sp;
424 if (containingModule != NULL)
426 // TODO: We should look into sharing module based search filters
427 // across many breakpoints like we do for the simple target based one
428 filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule));
432 if (m_search_filter_sp.get() == NULL)
433 m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
434 filter_sp = m_search_filter_sp;
440 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules)
442 SearchFilterSP filter_sp;
443 if (containingModules && containingModules->GetSize() != 0)
445 // TODO: We should look into sharing module based search filters
446 // across many breakpoints like we do for the simple target based one
447 filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules));
451 if (m_search_filter_sp.get() == NULL)
452 m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
453 filter_sp = m_search_filter_sp;
459 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules,
460 const FileSpecList *containingSourceFiles)
462 if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0)
463 return GetSearchFilterForModuleList(containingModules);
465 SearchFilterSP filter_sp;
466 if (containingModules == NULL)
468 // We could make a special "CU List only SearchFilter". Better yet was if these could be composable,
469 // but that will take a little reworking.
471 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles));
475 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles));
481 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
482 const FileSpecList *containingSourceFiles,
483 RegularExpression &func_regex,
484 LazyBool skip_prologue,
488 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
489 BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
491 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
493 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
497 Target::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal)
499 return LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal);
503 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal, bool request_hardware, bool resolve_indirect_symbols)
506 if (filter_sp && resolver_sp)
508 bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp, request_hardware, resolve_indirect_symbols));
509 resolver_sp->SetBreakpoint (bp_sp.get());
512 m_internal_breakpoint_list.Add (bp_sp, false);
514 m_breakpoint_list.Add (bp_sp, true);
516 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
520 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
521 log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
524 bp_sp->ResolveBreakpoint();
527 if (!internal && bp_sp)
529 m_last_created_breakpoint = bp_sp;
536 Target::ProcessIsValid()
538 return (m_process_sp && m_process_sp->IsAlive());
542 CheckIfWatchpointsExhausted(Target *target, Error &error)
544 uint32_t num_supported_hardware_watchpoints;
545 Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints);
548 uint32_t num_current_watchpoints = target->GetWatchpointList().GetSize();
549 if (num_current_watchpoints >= num_supported_hardware_watchpoints)
550 error.SetErrorStringWithFormat("number of supported hardware watchpoints (%u) has been reached",
551 num_supported_hardware_watchpoints);
556 // See also Watchpoint::SetWatchpointType(uint32_t type) and
557 // the OptionGroupWatchpoint::WatchType enum type.
559 Target::CreateWatchpoint(lldb::addr_t addr, size_t size, const ClangASTType *type, uint32_t kind, Error &error)
561 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
563 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64 " type = %u)\n",
564 __FUNCTION__, addr, (uint64_t)size, kind);
567 if (!ProcessIsValid())
569 error.SetErrorString("process is not alive");
573 if (addr == LLDB_INVALID_ADDRESS || size == 0)
576 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
578 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
582 if (!LLDB_WATCH_TYPE_IS_VALID(kind))
584 error.SetErrorStringWithFormat ("invalid watchpoint type: %d", kind);
587 // Currently we only support one watchpoint per address, with total number
588 // of watchpoints limited by the hardware which the inferior is running on.
590 // Grab the list mutex while doing operations.
591 const bool notify = false; // Don't notify about all the state changes we do on creating the watchpoint.
592 Mutex::Locker locker;
593 this->GetWatchpointList().GetListMutex(locker);
594 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
597 size_t old_size = matched_sp->GetByteSize();
599 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
600 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
601 // Return the existing watchpoint if both size and type match.
602 if (size == old_size && kind == old_type)
605 wp_sp->SetEnabled(false, notify);
609 // Nil the matched watchpoint; we will be creating a new one.
610 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
611 m_watchpoint_list.Remove(matched_sp->GetID(), true);
617 wp_sp.reset(new Watchpoint(*this, addr, size, type));
618 wp_sp->SetWatchpointType(kind, notify);
619 m_watchpoint_list.Add (wp_sp, true);
622 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
624 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
626 error.Success() ? "succeeded" : "failed",
631 // Enabling the watchpoint on the device side failed.
632 // Remove the said watchpoint from the list maintained by the target instance.
633 m_watchpoint_list.Remove (wp_sp->GetID(), true);
634 // See if we could provide more helpful error message.
635 if (!CheckIfWatchpointsExhausted(this, error))
637 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
638 error.SetErrorStringWithFormat("watch size of %zu is not supported", size);
643 m_last_created_watchpoint = wp_sp;
648 Target::RemoveAllBreakpoints (bool internal_also)
650 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
652 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
654 m_breakpoint_list.RemoveAll (true);
656 m_internal_breakpoint_list.RemoveAll (false);
658 m_last_created_breakpoint.reset();
662 Target::DisableAllBreakpoints (bool internal_also)
664 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
666 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
668 m_breakpoint_list.SetEnabledAll (false);
670 m_internal_breakpoint_list.SetEnabledAll (false);
674 Target::EnableAllBreakpoints (bool internal_also)
676 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
678 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
680 m_breakpoint_list.SetEnabledAll (true);
682 m_internal_breakpoint_list.SetEnabledAll (true);
686 Target::RemoveBreakpointByID (break_id_t break_id)
688 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
690 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
692 if (DisableBreakpointByID (break_id))
694 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
695 m_internal_breakpoint_list.Remove(break_id, false);
698 if (m_last_created_breakpoint)
700 if (m_last_created_breakpoint->GetID() == break_id)
701 m_last_created_breakpoint.reset();
703 m_breakpoint_list.Remove(break_id, true);
711 Target::DisableBreakpointByID (break_id_t break_id)
713 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
715 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
719 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
720 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
722 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
725 bp_sp->SetEnabled (false);
732 Target::EnableBreakpointByID (break_id_t break_id)
734 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
736 log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
739 LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
743 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
744 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
746 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
750 bp_sp->SetEnabled (true);
756 // The flag 'end_to_end', default to true, signifies that the operation is
757 // performed end to end, for both the debugger and the debuggee.
759 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
760 // to end operations.
762 Target::RemoveAllWatchpoints (bool end_to_end)
764 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
766 log->Printf ("Target::%s\n", __FUNCTION__);
769 m_watchpoint_list.RemoveAll(true);
773 // Otherwise, it's an end to end operation.
775 if (!ProcessIsValid())
778 size_t num_watchpoints = m_watchpoint_list.GetSize();
779 for (size_t i = 0; i < num_watchpoints; ++i)
781 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
785 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
789 m_watchpoint_list.RemoveAll (true);
790 m_last_created_watchpoint.reset();
791 return true; // Success!
794 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
797 Target::DisableAllWatchpoints (bool end_to_end)
799 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
801 log->Printf ("Target::%s\n", __FUNCTION__);
804 m_watchpoint_list.SetEnabledAll(false);
808 // Otherwise, it's an end to end operation.
810 if (!ProcessIsValid())
813 size_t num_watchpoints = m_watchpoint_list.GetSize();
814 for (size_t i = 0; i < num_watchpoints; ++i)
816 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
820 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
824 return true; // Success!
827 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
830 Target::EnableAllWatchpoints (bool end_to_end)
832 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
834 log->Printf ("Target::%s\n", __FUNCTION__);
837 m_watchpoint_list.SetEnabledAll(true);
841 // Otherwise, it's an end to end operation.
843 if (!ProcessIsValid())
846 size_t num_watchpoints = m_watchpoint_list.GetSize();
847 for (size_t i = 0; i < num_watchpoints; ++i)
849 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
853 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
857 return true; // Success!
860 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
862 Target::ClearAllWatchpointHitCounts ()
864 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
866 log->Printf ("Target::%s\n", __FUNCTION__);
868 size_t num_watchpoints = m_watchpoint_list.GetSize();
869 for (size_t i = 0; i < num_watchpoints; ++i)
871 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
875 wp_sp->ResetHitCount();
877 return true; // Success!
880 // Assumption: Caller holds the list mutex lock for m_watchpoint_list
881 // during these operations.
883 Target::IgnoreAllWatchpoints (uint32_t ignore_count)
885 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
887 log->Printf ("Target::%s\n", __FUNCTION__);
889 if (!ProcessIsValid())
892 size_t num_watchpoints = m_watchpoint_list.GetSize();
893 for (size_t i = 0; i < num_watchpoints; ++i)
895 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
899 wp_sp->SetIgnoreCount(ignore_count);
901 return true; // Success!
904 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
906 Target::DisableWatchpointByID (lldb::watch_id_t watch_id)
908 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
910 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
912 if (!ProcessIsValid())
915 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
918 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
922 // Else, fallthrough.
927 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
929 Target::EnableWatchpointByID (lldb::watch_id_t watch_id)
931 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
933 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
935 if (!ProcessIsValid())
938 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
941 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
945 // Else, fallthrough.
950 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
952 Target::RemoveWatchpointByID (lldb::watch_id_t watch_id)
954 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
956 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
958 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
959 if (watch_to_remove_sp == m_last_created_watchpoint)
960 m_last_created_watchpoint.reset();
962 if (DisableWatchpointByID (watch_id))
964 m_watchpoint_list.Remove(watch_id, true);
970 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
972 Target::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
974 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
976 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
978 if (!ProcessIsValid())
981 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
984 wp_sp->SetIgnoreCount(ignore_count);
991 Target::GetExecutableModule ()
993 return m_images.GetModuleAtIndex(0);
997 Target::GetExecutableModulePointer ()
999 return m_images.GetModulePointerAtIndex(0);
1003 LoadScriptingResourceForModule (const ModuleSP &module_sp, Target *target)
1006 StreamString feedback_stream;
1007 if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error, &feedback_stream))
1009 if (error.AsCString())
1010 target->GetDebugger().GetErrorFile()->Printf("unable to load scripting data for module %s - error reported was %s\n",
1011 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1013 if (feedback_stream.GetSize())
1014 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1015 feedback_stream.GetData());
1020 Target::ClearModules(bool delete_locations)
1022 ModulesDidUnload (m_images, delete_locations);
1023 m_section_load_history.Clear();
1025 m_scratch_ast_context_ap.reset();
1026 m_scratch_ast_source_ap.reset();
1027 m_ast_importer_ap.reset();
1033 // When a process exec's we need to know about it so we can do some cleanup.
1034 m_breakpoint_list.RemoveInvalidLocations(m_arch);
1035 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch);
1039 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
1041 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1042 ClearModules(false);
1044 if (executable_sp.get())
1046 Timer scoped_timer (__PRETTY_FUNCTION__,
1047 "Target::SetExecutableModule (executable = '%s')",
1048 executable_sp->GetFileSpec().GetPath().c_str());
1050 m_images.Append(executable_sp); // The first image is our exectuable file
1052 // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
1053 if (!m_arch.IsValid())
1055 m_arch = executable_sp->GetArchitecture();
1057 log->Printf ("Target::SetExecutableModule setting architecture to %s (%s) based on executable file", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
1060 FileSpecList dependent_files;
1061 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1063 if (executable_objfile && get_dependent_files)
1065 executable_objfile->GetDependentModules(dependent_files);
1066 for (uint32_t i=0; i<dependent_files.GetSize(); i++)
1068 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
1069 FileSpec platform_dependent_file_spec;
1071 m_platform_sp->GetFileWithUUID (dependent_file_spec, NULL, platform_dependent_file_spec);
1073 platform_dependent_file_spec = dependent_file_spec;
1075 ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
1076 ModuleSP image_module_sp(GetSharedModule (module_spec));
1077 if (image_module_sp.get())
1079 ObjectFile *objfile = image_module_sp->GetObjectFile();
1081 objfile->GetDependentModules(dependent_files);
1090 Target::SetArchitecture (const ArchSpec &arch_spec)
1092 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1093 if (m_arch.IsCompatibleMatch(arch_spec) || !m_arch.IsValid())
1095 // If we haven't got a valid arch spec, or the architectures are
1096 // compatible, so just update the architecture. Architectures can be
1097 // equal, yet the triple OS and vendor might change, so we need to do
1098 // the assignment here just in case.
1101 log->Printf ("Target::SetArchitecture setting architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1106 // If we have an executable file, try to reset the executable to the desired architecture
1108 log->Printf ("Target::SetArchitecture changing architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1110 ModuleSP executable_sp = GetExecutableModule ();
1113 // Need to do something about unsetting breakpoints.
1118 log->Printf("Target::SetArchitecture Trying to select executable file architecture %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1119 ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec);
1120 Error error = ModuleList::GetSharedModule (module_spec,
1122 &GetExecutableSearchPaths(),
1126 if (!error.Fail() && executable_sp)
1128 SetExecutableModule (executable_sp, true);
1137 Target::WillClearList (const ModuleList& module_list)
1142 Target::ModuleAdded (const ModuleList& module_list, const ModuleSP &module_sp)
1144 // A module is being added to this target for the first time
1145 ModuleList my_module_list;
1146 my_module_list.Append(module_sp);
1147 LoadScriptingResourceForModule(module_sp, this);
1148 ModulesDidLoad (my_module_list);
1152 Target::ModuleRemoved (const ModuleList& module_list, const ModuleSP &module_sp)
1154 // A module is being added to this target for the first time
1155 ModuleList my_module_list;
1156 my_module_list.Append(module_sp);
1157 ModulesDidUnload (my_module_list, false);
1161 Target::ModuleUpdated (const ModuleList& module_list, const ModuleSP &old_module_sp, const ModuleSP &new_module_sp)
1163 // A module is replacing an already added module
1164 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1168 Target::ModulesDidLoad (ModuleList &module_list)
1170 if (module_list.GetSize())
1172 m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1175 SystemRuntime *sys_runtime = m_process_sp->GetSystemRuntime();
1178 sys_runtime->ModulesDidLoad (module_list);
1181 // TODO: make event data that packages up the module_list
1182 BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
1187 Target::SymbolsDidLoad (ModuleList &module_list)
1189 if (module_list.GetSize())
1193 LanguageRuntime* runtime = m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1196 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime*)runtime;
1197 objc_runtime->SymbolsDidLoad(module_list);
1201 m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1202 BroadcastEvent(eBroadcastBitSymbolsLoaded, NULL);
1207 Target::ModulesDidUnload (ModuleList &module_list, bool delete_locations)
1209 if (module_list.GetSize())
1211 m_breakpoint_list.UpdateBreakpoints (module_list, false, delete_locations);
1212 // TODO: make event data that packages up the module_list
1213 BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
1218 Target::ModuleIsExcludedForNonModuleSpecificSearches (const FileSpec &module_file_spec)
1220 if (GetBreakpointsConsultPlatformAvoidList())
1222 ModuleList matchingModules;
1223 ModuleSpec module_spec (module_file_spec);
1224 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1226 // If there is more than one module for this file spec, only return true if ALL the modules are on the
1228 if (num_modules > 0)
1230 for (size_t i = 0; i < num_modules; i++)
1232 if (!ModuleIsExcludedForNonModuleSpecificSearches (matchingModules.GetModuleAtIndex(i)))
1242 Target::ModuleIsExcludedForNonModuleSpecificSearches (const lldb::ModuleSP &module_sp)
1244 if (GetBreakpointsConsultPlatformAvoidList())
1247 return m_platform_sp->ModuleIsExcludedForNonModuleSpecificSearches (*this, module_sp);
1253 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
1255 SectionSP section_sp (addr.GetSection());
1258 // If the contents of this section are encrypted, the on-disk file is unusuable. Read only from live memory.
1259 if (section_sp->IsEncrypted())
1261 error.SetErrorString("section is encrypted");
1264 ModuleSP module_sp (section_sp->GetModule());
1267 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1270 size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
1277 error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
1280 error.SetErrorString("address isn't from a object file");
1283 error.SetErrorString("address isn't in a module");
1286 error.SetErrorString("address doesn't contain a section that points to a section in a object file");
1292 Target::ReadMemory (const Address& addr,
1293 bool prefer_file_cache,
1297 lldb::addr_t *load_addr_ptr)
1301 // if we end up reading this from process memory, we will fill this
1302 // with the actual load address
1304 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1306 size_t bytes_read = 0;
1308 addr_t load_addr = LLDB_INVALID_ADDRESS;
1309 addr_t file_addr = LLDB_INVALID_ADDRESS;
1310 Address resolved_addr;
1311 if (!addr.IsSectionOffset())
1313 SectionLoadList §ion_load_list = GetSectionLoadList();
1314 if (section_load_list.IsEmpty())
1316 // No sections are loaded, so we must assume we are not running
1317 // yet and anything we are given is a file address.
1318 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
1319 m_images.ResolveFileAddress (file_addr, resolved_addr);
1323 // We have at least one section loaded. This can be becuase
1324 // we have manually loaded some sections with "target modules load ..."
1325 // or because we have have a live process that has sections loaded
1326 // through the dynamic loader
1327 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1328 section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1331 if (!resolved_addr.IsValid())
1332 resolved_addr = addr;
1335 if (prefer_file_cache)
1337 bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1342 if (ProcessIsValid())
1344 if (load_addr == LLDB_INVALID_ADDRESS)
1345 load_addr = resolved_addr.GetLoadAddress (this);
1347 if (load_addr == LLDB_INVALID_ADDRESS)
1349 ModuleSP addr_module_sp (resolved_addr.GetModule());
1350 if (addr_module_sp && addr_module_sp->GetFileSpec())
1351 error.SetErrorStringWithFormat("%s[0x%" PRIx64 "] can't be resolved, %s in not currently loaded",
1352 addr_module_sp->GetFileSpec().GetFilename().AsCString(),
1353 resolved_addr.GetFileAddress(),
1354 addr_module_sp->GetFileSpec().GetFilename().AsCString());
1356 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
1360 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1361 if (bytes_read != dst_len)
1363 if (error.Success())
1365 if (bytes_read == 0)
1366 error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed", load_addr);
1368 error.SetErrorStringWithFormat("only %" PRIu64 " of %" PRIu64 " bytes were read from memory at 0x%" PRIx64, (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1374 *load_addr_ptr = load_addr;
1377 // If the address is not section offset we have an address that
1378 // doesn't resolve to any address in any currently loaded shared
1379 // libaries and we failed to read memory so there isn't anything
1380 // more we can do. If it is section offset, we might be able to
1381 // read cached memory from the object file.
1382 if (!resolved_addr.IsSectionOffset())
1387 if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1389 // If we didn't already try and read from the object file cache, then
1390 // try it after failing to read from the process.
1391 return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1397 Target::ReadCStringFromMemory (const Address& addr, std::string &out_str, Error &error)
1401 addr_t curr_addr = addr.GetLoadAddress(this);
1402 Address address(addr);
1405 size_t length = ReadCStringFromMemory (address, buf, sizeof(buf), error);
1408 out_str.append(buf, length);
1409 // If we got "length - 1" bytes, we didn't get the whole C string, we
1410 // need to read some more characters
1411 if (length == sizeof(buf) - 1)
1412 curr_addr += length;
1415 address = Address(curr_addr);
1417 return out_str.size();
1422 Target::ReadCStringFromMemory (const Address& addr, char *dst, size_t dst_max_len, Error &result_error)
1424 size_t total_cstr_len = 0;
1425 if (dst && dst_max_len)
1427 result_error.Clear();
1428 // NULL out everything just to be safe
1429 memset (dst, 0, dst_max_len);
1431 addr_t curr_addr = addr.GetLoadAddress(this);
1432 Address address(addr);
1433 const size_t cache_line_size = 512;
1434 size_t bytes_left = dst_max_len - 1;
1435 char *curr_dst = dst;
1437 while (bytes_left > 0)
1439 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1440 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1441 size_t bytes_read = ReadMemory (address, false, curr_dst, bytes_to_read, error);
1443 if (bytes_read == 0)
1445 result_error = error;
1446 dst[total_cstr_len] = '\0';
1449 const size_t len = strlen(curr_dst);
1451 total_cstr_len += len;
1453 if (len < bytes_to_read)
1456 curr_dst += bytes_read;
1457 curr_addr += bytes_read;
1458 bytes_left -= bytes_read;
1459 address = Address(curr_addr);
1465 result_error.SetErrorString("invalid arguments");
1467 result_error.Clear();
1469 return total_cstr_len;
1473 Target::ReadScalarIntegerFromMemory (const Address& addr,
1474 bool prefer_file_cache,
1482 if (byte_size <= sizeof(uval))
1484 size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1485 if (bytes_read == byte_size)
1487 DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1488 lldb::offset_t offset = 0;
1490 scalar = data.GetMaxU32 (&offset, byte_size);
1492 scalar = data.GetMaxU64 (&offset, byte_size);
1495 scalar.SignExtend(byte_size * 8);
1501 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1507 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1508 bool prefer_file_cache,
1509 size_t integer_byte_size,
1510 uint64_t fail_value,
1514 if (ReadScalarIntegerFromMemory (addr,
1520 return scalar.ULongLong(fail_value);
1525 Target::ReadPointerFromMemory (const Address& addr,
1526 bool prefer_file_cache,
1528 Address &pointer_addr)
1531 if (ReadScalarIntegerFromMemory (addr,
1533 m_arch.GetAddressByteSize(),
1538 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1539 if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1541 SectionLoadList §ion_load_list = GetSectionLoadList();
1542 if (section_load_list.IsEmpty())
1544 // No sections are loaded, so we must assume we are not running
1545 // yet and anything we are given is a file address.
1546 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1550 // We have at least one section loaded. This can be becuase
1551 // we have manually loaded some sections with "target modules load ..."
1552 // or because we have have a live process that has sections loaded
1553 // through the dynamic loader
1554 section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1556 // We weren't able to resolve the pointer value, so just return
1557 // an address with no section
1558 if (!pointer_addr.IsValid())
1559 pointer_addr.SetOffset (pointer_vm_addr);
1568 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
1574 // First see if we already have this module in our module list. If we do, then we're done, we don't need
1575 // to consult the shared modules list. But only do this if we are passed a UUID.
1577 if (module_spec.GetUUID().IsValid())
1578 module_sp = m_images.FindFirstModule(module_spec);
1582 ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1583 bool did_create_module = false;
1585 // If there are image search path entries, try to use them first to acquire a suitable image.
1586 if (m_image_search_paths.GetSize())
1588 ModuleSpec transformed_spec (module_spec);
1589 if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
1591 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
1592 error = ModuleList::GetSharedModule (transformed_spec,
1594 &GetExecutableSearchPaths(),
1596 &did_create_module);
1602 // If we have a UUID, we can check our global shared module list in case
1603 // we already have it. If we don't have a valid UUID, then we can't since
1604 // the path in "module_spec" will be a platform path, and we will need to
1605 // let the platform find that file. For example, we could be asking for
1606 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1607 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1608 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1610 if (module_spec.GetUUID().IsValid())
1612 // We have a UUID, it is OK to check the global module list...
1613 error = ModuleList::GetSharedModule (module_spec,
1615 &GetExecutableSearchPaths(),
1617 &did_create_module);
1622 // The platform is responsible for finding and caching an appropriate
1623 // module in the shared module cache.
1626 FileSpec platform_file_spec;
1627 error = m_platform_sp->GetSharedModule (module_spec,
1629 &GetExecutableSearchPaths(),
1631 &did_create_module);
1635 error.SetErrorString("no platform is currently set");
1640 // We found a module that wasn't in our target list. Let's make sure that there wasn't an equivalent
1641 // module in the list already, and if there was, let's remove it.
1644 ObjectFile *objfile = module_sp->GetObjectFile();
1647 switch (objfile->GetType())
1649 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of a program's execution state
1650 case ObjectFile::eTypeExecutable: /// A normal executable
1651 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker executable
1652 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1653 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be used during execution
1655 case ObjectFile::eTypeDebugInfo: /// An object file that contains only debug information
1657 error_ptr->SetErrorString("debug info files aren't valid target modules, please specify an executable");
1659 case ObjectFile::eTypeStubLibrary: /// A library that can be linked against but not used for execution
1661 error_ptr->SetErrorString("stub libraries aren't valid target modules, please specify an executable");
1665 error_ptr->SetErrorString("unsupported file type, please specify an executable");
1668 // GetSharedModule is not guaranteed to find the old shared module, for instance
1669 // in the common case where you pass in the UUID, it is only going to find the one
1670 // module matching the UUID. In fact, it has no good way to know what the "old module"
1671 // relevant to this target is, since there might be many copies of a module with this file spec
1672 // in various running debug sessions, but only one of them will belong to this target.
1673 // So let's remove the UUID from the module list, and look in the target's module list.
1674 // Only do this if there is SOMETHING else in the module spec...
1677 if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
1679 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1680 module_spec_copy.GetUUID().Clear();
1682 ModuleList found_modules;
1683 size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
1686 old_module_sp = found_modules.GetModuleAtIndex(0);
1691 if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1693 m_images.ReplaceModule(old_module_sp, module_sp);
1694 Module *old_module_ptr = old_module_sp.get();
1695 old_module_sp.reset();
1696 ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
1699 m_images.Append(module_sp);
1710 Target::CalculateTarget ()
1712 return shared_from_this();
1716 Target::CalculateProcess ()
1722 Target::CalculateThread ()
1728 Target::CalculateStackFrame ()
1730 return StackFrameSP();
1734 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1737 exe_ctx.SetTargetPtr(this);
1741 Target::GetImageSearchPathList ()
1743 return m_image_search_paths;
1747 Target::ImageSearchPathsChanged
1749 const PathMappingList &path_list,
1753 Target *target = (Target *)baton;
1754 ModuleSP exe_module_sp (target->GetExecutableModule());
1756 target->SetExecutableModule (exe_module_sp, true);
1760 Target::GetScratchClangASTContext(bool create_on_demand)
1762 // Now see if we know the target triple, and if so, create our scratch AST context:
1763 if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand)
1765 m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1766 m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this()));
1767 m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext());
1768 llvm::OwningPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy());
1769 m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source);
1771 return m_scratch_ast_context_ap.get();
1775 Target::GetClangASTImporter()
1777 ClangASTImporter *ast_importer = m_ast_importer_ap.get();
1781 ast_importer = new ClangASTImporter();
1782 m_ast_importer_ap.reset(ast_importer);
1785 return ast_importer;
1789 Target::SettingsInitialize ()
1791 Process::SettingsInitialize ();
1795 Target::SettingsTerminate ()
1797 Process::SettingsTerminate ();
1801 Target::GetDefaultExecutableSearchPaths ()
1803 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1805 return properties_sp->GetExecutableSearchPaths();
1806 return FileSpecList();
1810 Target::GetDefaultDebugFileSearchPaths ()
1812 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1814 return properties_sp->GetDebugFileSearchPaths();
1815 return FileSpecList();
1819 Target::GetDefaultArchitecture ()
1821 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1823 return properties_sp->GetDefaultArchitecture();
1828 Target::SetDefaultArchitecture (const ArchSpec &arch)
1830 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1833 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's default architecture to %s (%s)", arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
1834 return properties_sp->SetDefaultArchitecture(arch);
1839 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1841 // The target can either exist in the "process" of ExecutionContext, or in
1842 // the "target_sp" member of SymbolContext. This accessor helper function
1843 // will get the target from one of these locations.
1845 Target *target = NULL;
1847 target = sc_ptr->target_sp.get();
1848 if (target == NULL && exe_ctx_ptr)
1849 target = exe_ctx_ptr->GetTargetPtr();
1854 Target::EvaluateExpression
1856 const char *expr_cstr,
1858 lldb::ValueObjectSP &result_valobj_sp,
1859 const EvaluateExpressionOptions& options
1862 result_valobj_sp.reset();
1864 ExecutionResults execution_results = eExecutionSetupError;
1866 if (expr_cstr == NULL || expr_cstr[0] == '\0')
1867 return execution_results;
1869 // We shouldn't run stop hooks in expressions.
1870 // Be sure to reset this if you return anywhere within this function.
1871 bool old_suppress_value = m_suppress_stop_hooks;
1872 m_suppress_stop_hooks = true;
1874 ExecutionContext exe_ctx;
1878 frame->CalculateExecutionContext(exe_ctx);
1880 else if (m_process_sp)
1882 m_process_sp->CalculateExecutionContext(exe_ctx);
1886 CalculateExecutionContext(exe_ctx);
1889 // Make sure we aren't just trying to see the value of a persistent
1890 // variable (something like "$0")
1891 lldb::ClangExpressionVariableSP persistent_var_sp;
1892 // Only check for persistent variables the expression starts with a '$'
1893 if (expr_cstr[0] == '$')
1894 persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1896 if (persistent_var_sp)
1898 result_valobj_sp = persistent_var_sp->GetValueObject ();
1899 execution_results = eExecutionCompleted;
1903 const char *prefix = GetExpressionPrefixContentsAsCString();
1905 execution_results = ClangUserExpression::Evaluate (exe_ctx,
1913 m_suppress_stop_hooks = old_suppress_value;
1915 return execution_results;
1919 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1921 addr_t code_addr = load_addr;
1922 switch (m_arch.GetMachine())
1924 case llvm::Triple::arm:
1925 case llvm::Triple::thumb:
1928 case eAddressClassData:
1929 case eAddressClassDebug:
1930 return LLDB_INVALID_ADDRESS;
1932 case eAddressClassUnknown:
1933 case eAddressClassInvalid:
1934 case eAddressClassCode:
1935 case eAddressClassCodeAlternateISA:
1936 case eAddressClassRuntime:
1937 // Check if bit zero it no set?
1938 if ((code_addr & 1ull) == 0)
1940 // Bit zero isn't set, check if the address is a multiple of 2?
1941 if (code_addr & 2ull)
1943 // The address is a multiple of 2 so it must be thumb, set bit zero
1946 else if (addr_class == eAddressClassCodeAlternateISA)
1948 // We checked the address and the address claims to be the alternate ISA
1949 // which means thumb, so set bit zero.
1964 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1966 addr_t opcode_addr = load_addr;
1967 switch (m_arch.GetMachine())
1969 case llvm::Triple::arm:
1970 case llvm::Triple::thumb:
1973 case eAddressClassData:
1974 case eAddressClassDebug:
1975 return LLDB_INVALID_ADDRESS;
1977 case eAddressClassInvalid:
1978 case eAddressClassUnknown:
1979 case eAddressClassCode:
1980 case eAddressClassCodeAlternateISA:
1981 case eAddressClassRuntime:
1982 opcode_addr &= ~(1ull);
1994 Target::GetSourceManager ()
1996 if (m_source_manager_ap.get() == NULL)
1997 m_source_manager_ap.reset (new SourceManager(shared_from_this()));
1998 return *m_source_manager_ap;
2003 Target::CreateStopHook ()
2005 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2006 Target::StopHookSP stop_hook_sp (new StopHook(shared_from_this(), new_uid));
2007 m_stop_hooks[new_uid] = stop_hook_sp;
2008 return stop_hook_sp;
2012 Target::RemoveStopHookByID (lldb::user_id_t user_id)
2015 num_removed = m_stop_hooks.erase (user_id);
2016 if (num_removed == 0)
2023 Target::RemoveAllStopHooks ()
2025 m_stop_hooks.clear();
2029 Target::GetStopHookByID (lldb::user_id_t user_id)
2031 StopHookSP found_hook;
2033 StopHookCollection::iterator specified_hook_iter;
2034 specified_hook_iter = m_stop_hooks.find (user_id);
2035 if (specified_hook_iter != m_stop_hooks.end())
2036 found_hook = (*specified_hook_iter).second;
2041 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
2043 StopHookCollection::iterator specified_hook_iter;
2044 specified_hook_iter = m_stop_hooks.find (user_id);
2045 if (specified_hook_iter == m_stop_hooks.end())
2048 (*specified_hook_iter).second->SetIsActive (active_state);
2053 Target::SetAllStopHooksActiveState (bool active_state)
2055 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2056 for (pos = m_stop_hooks.begin(); pos != end; pos++)
2058 (*pos).second->SetIsActive (active_state);
2063 Target::RunStopHooks ()
2065 if (m_suppress_stop_hooks)
2071 // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
2072 // since in that case we do not want to run the stop-hooks
2073 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2076 if (m_stop_hooks.empty())
2079 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2081 // If there aren't any active stop hooks, don't bother either:
2082 bool any_active_hooks = false;
2083 for (pos = m_stop_hooks.begin(); pos != end; pos++)
2085 if ((*pos).second->IsActive())
2087 any_active_hooks = true;
2091 if (!any_active_hooks)
2094 CommandReturnObject result;
2096 std::vector<ExecutionContext> exc_ctx_with_reasons;
2097 std::vector<SymbolContext> sym_ctx_with_reasons;
2099 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2100 size_t num_threads = cur_threadlist.GetSize();
2101 for (size_t i = 0; i < num_threads; i++)
2103 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
2104 if (cur_thread_sp->ThreadStoppedForAReason())
2106 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2107 exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2108 sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2112 // If no threads stopped for a reason, don't run the stop-hooks.
2113 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2114 if (num_exe_ctx == 0)
2117 result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
2118 result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
2120 bool keep_going = true;
2121 bool hooks_ran = false;
2122 bool print_hook_header;
2123 bool print_thread_header;
2125 if (num_exe_ctx == 1)
2126 print_thread_header = false;
2128 print_thread_header = true;
2130 if (m_stop_hooks.size() == 1)
2131 print_hook_header = false;
2133 print_hook_header = true;
2135 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
2138 StopHookSP cur_hook_sp = (*pos).second;
2139 if (!cur_hook_sp->IsActive())
2142 bool any_thread_matched = false;
2143 for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2145 if ((cur_hook_sp->GetSpecifier () == NULL
2146 || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2147 && (cur_hook_sp->GetThreadSpecifier() == NULL
2148 || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2154 if (print_hook_header && !any_thread_matched)
2156 const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2157 cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2160 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(), cmd);
2162 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2163 any_thread_matched = true;
2166 if (print_thread_header)
2167 result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2169 bool stop_on_continue = true;
2170 bool stop_on_error = true;
2171 bool echo_commands = false;
2172 bool print_results = true;
2173 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2174 &exc_ctx_with_reasons[i],
2182 // If the command started the target going again, we should bag out of
2183 // running the stop hooks.
2184 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2185 (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2187 result.AppendMessageWithFormat ("Aborting stop hooks, hook %" PRIu64 " set the program running.", cur_hook_sp->GetID());
2194 result.GetImmediateOutputStream()->Flush();
2195 result.GetImmediateErrorStream()->Flush();
2198 const TargetPropertiesSP &
2199 Target::GetGlobalProperties()
2201 static TargetPropertiesSP g_settings_sp;
2204 g_settings_sp.reset (new TargetProperties (NULL));
2206 return g_settings_sp;
2210 Target::Install (ProcessLaunchInfo *launch_info)
2213 PlatformSP platform_sp (GetPlatform());
2216 if (platform_sp->IsRemote())
2218 if (platform_sp->IsConnected())
2220 // Install all files that have an install path, and always install the
2221 // main executable when connected to a remote platform
2222 const ModuleList& modules = GetImages();
2223 const size_t num_images = modules.GetSize();
2224 for (size_t idx = 0; idx < num_images; ++idx)
2226 const bool is_main_executable = idx == 0;
2227 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2230 FileSpec local_file (module_sp->GetFileSpec());
2233 FileSpec remote_file (module_sp->GetRemoteInstallFileSpec());
2236 if (is_main_executable) // TODO: add setting for always installing main executable???
2238 // Always install the main executable
2239 remote_file.GetDirectory() = platform_sp->GetWorkingDirectory();
2240 remote_file.GetFilename() = module_sp->GetFileSpec().GetFilename();
2245 error = platform_sp->Install(local_file, remote_file);
2246 if (error.Success())
2248 module_sp->SetPlatformFileSpec(remote_file);
2249 if (is_main_executable)
2252 launch_info->SetExecutableFile(remote_file, false);
2268 Target::ResolveLoadAddress (addr_t load_addr, Address &so_addr, uint32_t stop_id)
2270 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2274 Target::SetSectionLoadAddress (const SectionSP §ion_sp, addr_t new_section_load_addr, bool warn_multiple)
2276 const addr_t old_section_load_addr = m_section_load_history.GetSectionLoadAddress (SectionLoadHistory::eStopIDNow, section_sp);
2277 if (old_section_load_addr != new_section_load_addr)
2279 uint32_t stop_id = 0;
2280 ProcessSP process_sp(GetProcessSP());
2282 stop_id = process_sp->GetStopID();
2284 stop_id = m_section_load_history.GetLastStopID();
2285 if (m_section_load_history.SetSectionLoadAddress (stop_id, section_sp, new_section_load_addr, warn_multiple))
2286 return true; // Return true if the section load address was changed...
2288 return false; // Return false to indicate nothing changed
2293 Target::SetSectionUnloaded (const lldb::SectionSP §ion_sp)
2295 uint32_t stop_id = 0;
2296 ProcessSP process_sp(GetProcessSP());
2298 stop_id = process_sp->GetStopID();
2300 stop_id = m_section_load_history.GetLastStopID();
2301 return m_section_load_history.SetSectionUnloaded (stop_id, section_sp);
2305 Target::SetSectionUnloaded (const lldb::SectionSP §ion_sp, addr_t load_addr)
2307 uint32_t stop_id = 0;
2308 ProcessSP process_sp(GetProcessSP());
2310 stop_id = process_sp->GetStopID();
2312 stop_id = m_section_load_history.GetLastStopID();
2313 return m_section_load_history.SetSectionUnloaded (stop_id, section_sp, load_addr);
2317 Target::ClearAllLoadedSections ()
2319 m_section_load_history.Clear();
2324 Target::Launch (Listener &listener, ProcessLaunchInfo &launch_info)
2328 StateType state = eStateInvalid;
2330 // Scope to temporarily get the process state in case someone has manually
2331 // remotely connected already to a process and we can skip the platform
2334 ProcessSP process_sp (GetProcessSP());
2337 state = process_sp->GetState();
2340 launch_info.GetFlags().Set (eLaunchFlagDebug);
2342 // Get the value of synchronous execution here. If you wait till after you have started to
2343 // run, then you could have hit a breakpoint, whose command might switch the value, and
2344 // then you'll pick up that incorrect value.
2345 Debugger &debugger = GetDebugger();
2346 const bool synchronous_execution = debugger.GetCommandInterpreter().GetSynchronous ();
2348 PlatformSP platform_sp (GetPlatform());
2350 // Finalize the file actions, and if none were given, default to opening
2351 // up a pseudo terminal
2352 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2353 launch_info.FinalizeFileActions (this, default_to_use_pty);
2355 if (state == eStateConnected)
2357 if (launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY))
2359 error.SetErrorString("can't launch in tty when launching through a remote connection");
2364 if (!launch_info.GetArchitecture().IsValid())
2365 launch_info.GetArchitecture() = GetArchitecture();
2367 if (state != eStateConnected && platform_sp && platform_sp->CanDebugProcess ())
2369 m_process_sp = GetPlatform()->DebugProcess (launch_info,
2377 if (state == eStateConnected)
2379 assert(m_process_sp);
2383 const char *plugin_name = launch_info.GetProcessPluginName();
2384 CreateProcess (listener, plugin_name, NULL);
2388 error = m_process_sp->Launch (launch_info);
2393 if (error.Success())
2394 error.SetErrorString("failed to launch or debug process");
2398 if (error.Success())
2400 if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry) == false)
2402 ListenerSP hijack_listener_sp (launch_info.GetHijackListener());
2404 StateType state = m_process_sp->WaitForProcessToStop (NULL, NULL, false, hijack_listener_sp.get());
2406 if (state == eStateStopped)
2408 if (!synchronous_execution)
2409 m_process_sp->RestoreProcessEvents ();
2411 error = m_process_sp->PrivateResume();
2413 if (error.Success())
2415 if (synchronous_execution)
2417 state = m_process_sp->WaitForProcessToStop (NULL, NULL, true, hijack_listener_sp.get());
2418 const bool must_be_alive = false; // eStateExited is ok, so this must be false
2419 if (!StateIsStoppedState(state, must_be_alive))
2421 error.SetErrorStringWithFormat("process isn't stopped: %s", StateAsCString(state));
2428 error2.SetErrorStringWithFormat("process resume at entry point failed: %s", error.AsCString());
2434 error.SetErrorStringWithFormat ("initial process state wasn't stopped: %s", StateAsCString(state));
2437 m_process_sp->RestoreProcessEvents ();
2442 error2.SetErrorStringWithFormat ("process launch failed: %s", error.AsCString());
2447 //--------------------------------------------------------------
2449 //--------------------------------------------------------------
2450 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2452 m_target_sp (target_sp),
2460 Target::StopHook::StopHook (const StopHook &rhs) :
2461 UserID (rhs.GetID()),
2462 m_target_sp (rhs.m_target_sp),
2463 m_commands (rhs.m_commands),
2464 m_specifier_sp (rhs.m_specifier_sp),
2465 m_thread_spec_ap (),
2466 m_active (rhs.m_active)
2468 if (rhs.m_thread_spec_ap.get() != NULL)
2469 m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2473 Target::StopHook::~StopHook ()
2478 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2480 m_thread_spec_ap.reset (specifier);
2485 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2487 int indent_level = s->GetIndentLevel();
2489 s->SetIndentLevel(indent_level + 2);
2491 s->Printf ("Hook: %" PRIu64 "\n", GetID());
2493 s->Indent ("State: enabled\n");
2495 s->Indent ("State: disabled\n");
2500 s->PutCString ("Specifier:\n");
2501 s->SetIndentLevel (indent_level + 4);
2502 m_specifier_sp->GetDescription (s, level);
2503 s->SetIndentLevel (indent_level + 2);
2506 if (m_thread_spec_ap.get() != NULL)
2509 s->Indent("Thread:\n");
2510 m_thread_spec_ap->GetDescription (&tmp, level);
2511 s->SetIndentLevel (indent_level + 4);
2512 s->Indent (tmp.GetData());
2513 s->PutCString ("\n");
2514 s->SetIndentLevel (indent_level + 2);
2517 s->Indent ("Commands: \n");
2518 s->SetIndentLevel (indent_level + 4);
2519 uint32_t num_commands = m_commands.GetSize();
2520 for (uint32_t i = 0; i < num_commands; i++)
2522 s->Indent(m_commands.GetStringAtIndex(i));
2523 s->PutCString ("\n");
2525 s->SetIndentLevel (indent_level);
2528 //--------------------------------------------------------------
2529 // class TargetProperties
2530 //--------------------------------------------------------------
2532 OptionEnumValueElement
2533 lldb_private::g_dynamic_value_types[] =
2535 { eNoDynamicValues, "no-dynamic-values", "Don't calculate the dynamic type of values"},
2536 { eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values even if you have to run the target."},
2537 { eDynamicDontRunTarget, "no-run-target", "Calculate the dynamic type of values, but don't run the target."},
2541 static OptionEnumValueElement
2542 g_inline_breakpoint_enums[] =
2544 { 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."},
2545 { eInlineBreakpointsHeaders, "headers", "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2546 { eInlineBreakpointsAlways, "always", "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2550 typedef enum x86DisassemblyFlavor
2552 eX86DisFlavorDefault,
2555 } x86DisassemblyFlavor;
2557 static OptionEnumValueElement
2558 g_x86_dis_flavor_value_types[] =
2560 { eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
2561 { eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
2562 { eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
2566 static OptionEnumValueElement
2567 g_hex_immediate_style_values[] =
2569 { Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
2570 { Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
2574 static OptionEnumValueElement
2575 g_load_script_from_sym_file_values[] =
2577 { eLoadScriptFromSymFileTrue, "true", "Load debug scripts inside symbol files"},
2578 { eLoadScriptFromSymFileFalse, "false", "Do not load debug scripts inside symbol files."},
2579 { eLoadScriptFromSymFileWarn, "warn", "Warn about debug scripts inside symbol files but do not load them."},
2584 static OptionEnumValueElement
2585 g_memory_module_load_level_values[] =
2587 { eMemoryModuleLoadLevelMinimal, "minimal" , "Load minimal information when loading modules from memory. Currently this setting loads sections only."},
2588 { eMemoryModuleLoadLevelPartial, "partial" , "Load partial information when loading modules from memory. Currently this setting loads sections and function bounds."},
2589 { eMemoryModuleLoadLevelComplete, "complete", "Load complete information when loading modules from memory. Currently this setting loads sections and all symbols."},
2593 static PropertyDefinition
2596 { "default-arch" , OptionValue::eTypeArch , true , 0 , NULL, NULL, "Default architecture to choose, when there's a choice." },
2597 { "expr-prefix" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2598 { "prefer-dynamic-value" , OptionValue::eTypeEnum , false, eNoDynamicValues , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2599 { "enable-synthetic-value" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Should synthetic values be used by default whenever available." },
2600 { "skip-prologue" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2601 { "source-map" , OptionValue::eTypePathMap , false, 0 , NULL, NULL, "Source path remappings used to track the change of location between a source file when built, and "
2602 "where it exists on the current system. It consists of an array of duples, the first element of each duple is "
2603 "some part (starting at the root) of the path to the file when it was built, "
2604 "and the second is where the remainder of the original build hierarchy is rooted on the local system. "
2605 "Each element of the array is checked in order and the first one that results in a match wins." },
2606 { "exec-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , NULL, NULL, "Executable search paths to use when locating executable files whose paths don't match the local file system." },
2607 { "debug-file-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , NULL, NULL, "List of directories to be searched when locating debug symbol files." },
2608 { "max-children-count" , OptionValue::eTypeSInt64 , false, 256 , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2609 { "max-string-summary-length" , OptionValue::eTypeSInt64 , false, 1024 , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2610 { "max-memory-read-size" , OptionValue::eTypeSInt64 , false, 1024 , NULL, NULL, "Maximum number of bytes that 'memory read' will fetch before --force must be specified." },
2611 { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean , false, true , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2612 { "arg0" , OptionValue::eTypeString , false, 0 , NULL, NULL, "The first argument passed to the program in the argument array which can be different from the executable itself." },
2613 { "run-args" , OptionValue::eTypeArgs , false, 0 , NULL, NULL, "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." },
2614 { "env-vars" , OptionValue::eTypeDictionary, false, OptionValue::eTypeString , NULL, NULL, "A list of all the environment variables to be passed to the executable's environment, and their values." },
2615 { "inherit-env" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2616 { "input-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2617 { "output-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2618 { "error-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2619 { "disable-aslr" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2620 { "disable-stdio" , OptionValue::eTypeBoolean , false, false , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2621 { "inline-breakpoint-strategy" , OptionValue::eTypeEnum , false, eInlineBreakpointsHeaders , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2622 "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. "
2623 "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2624 "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2625 "Always checking for inlined breakpoint locations can be expensive (memory and time), so we try to minimize the "
2626 "times we look for inlined locations. This setting allows you to control exactly which strategy is used when settings "
2627 "file and line breakpoints." },
2628 // 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.
2629 { "x86-disassembly-flavor" , OptionValue::eTypeEnum , false, eX86DisFlavorDefault, NULL, g_x86_dis_flavor_value_types, "The default disassembly flavor to use for x86 or x86-64 targets." },
2630 { "use-hex-immediates" , OptionValue::eTypeBoolean , false, true, NULL, NULL, "Show immediates in disassembly as hexadecimal." },
2631 { "hex-immediate-style" , OptionValue::eTypeEnum , false, Disassembler::eHexStyleC, NULL, g_hex_immediate_style_values, "Which style to use for printing hexadecimal disassembly values." },
2632 { "use-fast-stepping" , OptionValue::eTypeBoolean , false, true, NULL, NULL, "Use a fast stepping algorithm based on running from branch to branch rather than instruction single-stepping." },
2633 { "load-script-from-symbol-file" , OptionValue::eTypeEnum , false, eLoadScriptFromSymFileWarn, NULL, g_load_script_from_sym_file_values, "Allow LLDB to load scripting resources embedded in symbol files when available." },
2634 { "memory-module-load-level" , OptionValue::eTypeEnum , false, eMemoryModuleLoadLevelComplete, NULL, g_memory_module_load_level_values,
2635 "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. "
2636 "This setting helps users control how much information gets loaded when loading modules from memory."
2637 "'complete' is the default value for this setting which will load all sections and symbols by reading them from memory (slowest, most accurate). "
2638 "'partial' will load sections and attempt to find function bounds without downloading the symbol table (faster, still accurate, missing symbol names). "
2639 "'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). " },
2640 { "display-expression-in-crashlogs" , OptionValue::eTypeBoolean , false, false, NULL, NULL, "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." },
2641 { "trap-handler-names" , OptionValue::eTypeArray , true, OptionValue::eTypeString, NULL, NULL, "A list of trap handler function names, e.g. a common Unix user process one is _sigtramp." },
2642 { NULL , OptionValue::eTypeInvalid , false, 0 , NULL, NULL, NULL }
2646 ePropertyDefaultArch,
2647 ePropertyExprPrefix,
2648 ePropertyPreferDynamic,
2649 ePropertyEnableSynthetic,
2650 ePropertySkipPrologue,
2652 ePropertyExecutableSearchPaths,
2653 ePropertyDebugFileSearchPaths,
2654 ePropertyMaxChildrenCount,
2655 ePropertyMaxSummaryLength,
2656 ePropertyMaxMemReadSize,
2657 ePropertyBreakpointUseAvoidList,
2661 ePropertyInheritEnv,
2663 ePropertyOutputPath,
2665 ePropertyDisableASLR,
2666 ePropertyDisableSTDIO,
2667 ePropertyInlineStrategy,
2668 ePropertyDisassemblyFlavor,
2669 ePropertyUseHexImmediates,
2670 ePropertyHexImmediateStyle,
2671 ePropertyUseFastStepping,
2672 ePropertyLoadScriptFromSymbolFile,
2673 ePropertyMemoryModuleLoadLevel,
2674 ePropertyDisplayExpressionsInCrashlogs,
2675 ePropertyTrapHandlerNames
2679 class TargetOptionValueProperties : public OptionValueProperties
2682 TargetOptionValueProperties (const ConstString &name) :
2683 OptionValueProperties (name),
2685 m_got_host_env (false)
2689 // This constructor is used when creating TargetOptionValueProperties when it
2690 // is part of a new lldb_private::Target instance. It will copy all current
2691 // global property values as needed
2692 TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
2693 OptionValueProperties(*target_properties_sp->GetValueProperties()),
2695 m_got_host_env (false)
2699 virtual const Property *
2700 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
2702 // When gettings the value for a key from the target options, we will always
2703 // try and grab the setting from the current target if there is one. Else we just
2704 // use the one from this instance.
2705 if (idx == ePropertyEnvVars)
2706 GetHostEnvironmentIfNeeded ();
2710 Target *target = exe_ctx->GetTargetPtr();
2713 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
2714 if (this != target_properties)
2715 return target_properties->ProtectedGetPropertyAtIndex (idx);
2718 return ProtectedGetPropertyAtIndex (idx);
2724 return m_target->shared_from_this();
2730 GetHostEnvironmentIfNeeded () const
2732 if (!m_got_host_env)
2736 m_got_host_env = true;
2737 const uint32_t idx = ePropertyInheritEnv;
2738 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
2740 PlatformSP platform_sp (m_target->GetPlatform());
2744 if (platform_sp->GetEnvironment(env))
2746 OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
2749 const bool can_replace = false;
2750 const size_t envc = env.GetSize();
2751 for (size_t idx=0; idx<envc; idx++)
2753 const char *env_entry = env.GetStringAtIndex (idx);
2756 const char *equal_pos = ::strchr(env_entry, '=');
2758 // It is ok to have environment variables with no values
2759 const char *value = NULL;
2762 key.SetCStringWithLength(env_entry, equal_pos - env_entry);
2764 value = equal_pos + 1;
2768 key.SetCString(env_entry);
2770 // Don't allow existing keys to be replaced with ones we get from the platform environment
2771 env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
2782 mutable bool m_got_host_env;
2785 //----------------------------------------------------------------------
2787 //----------------------------------------------------------------------
2788 TargetProperties::TargetProperties (Target *target) :
2793 m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
2797 m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
2798 m_collection_sp->Initialize(g_properties);
2799 m_collection_sp->AppendProperty(ConstString("process"),
2800 ConstString("Settings specify to processes."),
2802 Process::GetGlobalProperties()->GetValueProperties());
2806 TargetProperties::~TargetProperties ()
2810 TargetProperties::GetDefaultArchitecture () const
2812 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2814 return value->GetCurrentValue();
2819 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
2821 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2823 return value->SetCurrentValue(arch, true);
2826 lldb::DynamicValueType
2827 TargetProperties::GetPreferDynamicValue() const
2829 const uint32_t idx = ePropertyPreferDynamic;
2830 return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2834 TargetProperties::GetDisableASLR () const
2836 const uint32_t idx = ePropertyDisableASLR;
2837 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2841 TargetProperties::SetDisableASLR (bool b)
2843 const uint32_t idx = ePropertyDisableASLR;
2844 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2848 TargetProperties::GetDisableSTDIO () const
2850 const uint32_t idx = ePropertyDisableSTDIO;
2851 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2855 TargetProperties::SetDisableSTDIO (bool b)
2857 const uint32_t idx = ePropertyDisableSTDIO;
2858 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2862 TargetProperties::GetDisassemblyFlavor () const
2864 const uint32_t idx = ePropertyDisassemblyFlavor;
2865 const char *return_value;
2867 x86DisassemblyFlavor flavor_value = (x86DisassemblyFlavor) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2868 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
2869 return return_value;
2873 TargetProperties::GetInlineStrategy () const
2875 const uint32_t idx = ePropertyInlineStrategy;
2876 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2880 TargetProperties::GetArg0 () const
2882 const uint32_t idx = ePropertyArg0;
2883 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
2887 TargetProperties::SetArg0 (const char *arg)
2889 const uint32_t idx = ePropertyArg0;
2890 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
2894 TargetProperties::GetRunArguments (Args &args) const
2896 const uint32_t idx = ePropertyRunArgs;
2897 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
2901 TargetProperties::SetRunArguments (const Args &args)
2903 const uint32_t idx = ePropertyRunArgs;
2904 m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
2908 TargetProperties::GetEnvironmentAsArgs (Args &env) const
2910 const uint32_t idx = ePropertyEnvVars;
2911 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
2915 TargetProperties::GetSkipPrologue() const
2917 const uint32_t idx = ePropertySkipPrologue;
2918 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2922 TargetProperties::GetSourcePathMap () const
2924 const uint32_t idx = ePropertySourceMap;
2925 OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
2926 assert(option_value);
2927 return option_value->GetCurrentValue();
2931 TargetProperties::GetExecutableSearchPaths ()
2933 const uint32_t idx = ePropertyExecutableSearchPaths;
2934 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2935 assert(option_value);
2936 return option_value->GetCurrentValue();
2940 TargetProperties::GetDebugFileSearchPaths ()
2942 const uint32_t idx = ePropertyDebugFileSearchPaths;
2943 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2944 assert(option_value);
2945 return option_value->GetCurrentValue();
2949 TargetProperties::GetEnableSyntheticValue () const
2951 const uint32_t idx = ePropertyEnableSynthetic;
2952 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2956 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
2958 const uint32_t idx = ePropertyMaxChildrenCount;
2959 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2963 TargetProperties::GetMaximumSizeOfStringSummary() const
2965 const uint32_t idx = ePropertyMaxSummaryLength;
2966 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2970 TargetProperties::GetMaximumMemReadSize () const
2972 const uint32_t idx = ePropertyMaxMemReadSize;
2973 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2977 TargetProperties::GetStandardInputPath () const
2979 const uint32_t idx = ePropertyInputPath;
2980 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2984 TargetProperties::SetStandardInputPath (const char *p)
2986 const uint32_t idx = ePropertyInputPath;
2987 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2991 TargetProperties::GetStandardOutputPath () const
2993 const uint32_t idx = ePropertyOutputPath;
2994 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2998 TargetProperties::SetStandardOutputPath (const char *p)
3000 const uint32_t idx = ePropertyOutputPath;
3001 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3005 TargetProperties::GetStandardErrorPath () const
3007 const uint32_t idx = ePropertyErrorPath;
3008 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
3012 TargetProperties::GetExpressionPrefixContentsAsCString ()
3014 const uint32_t idx = ePropertyExprPrefix;
3015 OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
3018 const bool null_terminate = true;
3019 DataBufferSP data_sp(file->GetFileContents(null_terminate));
3021 return (const char *) data_sp->GetBytes();
3027 TargetProperties::SetStandardErrorPath (const char *p)
3029 const uint32_t idx = ePropertyErrorPath;
3030 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3034 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
3036 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3037 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3041 TargetProperties::GetUseHexImmediates () const
3043 const uint32_t idx = ePropertyUseHexImmediates;
3044 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3048 TargetProperties::GetUseFastStepping () const
3050 const uint32_t idx = ePropertyUseFastStepping;
3051 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3055 TargetProperties::GetDisplayExpressionsInCrashlogs () const
3057 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3058 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3061 LoadScriptFromSymFile
3062 TargetProperties::GetLoadScriptFromSymbolFile () const
3064 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3065 return (LoadScriptFromSymFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3068 Disassembler::HexImmediateStyle
3069 TargetProperties::GetHexImmediateStyle () const
3071 const uint32_t idx = ePropertyHexImmediateStyle;
3072 return (Disassembler::HexImmediateStyle)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3075 MemoryModuleLoadLevel
3076 TargetProperties::GetMemoryModuleLoadLevel() const
3078 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3079 return (MemoryModuleLoadLevel)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3083 TargetProperties::GetUserSpecifiedTrapHandlerNames (Args &args) const
3085 const uint32_t idx = ePropertyTrapHandlerNames;
3086 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
3090 TargetProperties::SetUserSpecifiedTrapHandlerNames (const Args &args)
3092 const uint32_t idx = ePropertyTrapHandlerNames;
3093 m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
3096 //----------------------------------------------------------------------
3097 // Target::TargetEventData
3098 //----------------------------------------------------------------------
3100 Target::TargetEventData::GetFlavorString ()
3102 static ConstString g_flavor ("Target::TargetEventData");
3107 Target::TargetEventData::GetFlavor () const
3109 return TargetEventData::GetFlavorString ();
3112 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
3114 m_target_sp (new_target_sp)
3118 Target::TargetEventData::~TargetEventData()
3124 Target::TargetEventData::Dump (Stream *s) const
3130 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
3134 const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
3136 target_sp = data->m_target_sp;
3141 const Target::TargetEventData *
3142 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
3146 const EventData *event_data = event_ptr->GetData();
3147 if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
3148 return static_cast <const TargetEventData *> (event_ptr->GetData());