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/StreamString.h"
32 #include "lldb/Core/Timer.h"
33 #include "lldb/Core/ValueObject.h"
34 #include "lldb/Expression/ClangASTSource.h"
35 #include "lldb/Expression/ClangUserExpression.h"
36 #include "lldb/Host/Host.h"
37 #include "lldb/Interpreter/CommandInterpreter.h"
38 #include "lldb/Interpreter/CommandReturnObject.h"
39 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
40 #include "lldb/Interpreter/OptionValues.h"
41 #include "lldb/Interpreter/Property.h"
42 #include "lldb/lldb-private-log.h"
43 #include "lldb/Symbol/ObjectFile.h"
44 #include "lldb/Target/Process.h"
45 #include "lldb/Target/StackFrame.h"
46 #include "lldb/Target/Thread.h"
47 #include "lldb/Target/ThreadSpec.h"
50 using namespace lldb_private;
53 Target::GetStaticBroadcasterClass ()
55 static ConstString class_name ("lldb.target");
59 //----------------------------------------------------------------------
61 //----------------------------------------------------------------------
62 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
63 TargetProperties (this),
64 Broadcaster (&debugger, Target::GetStaticBroadcasterClass().AsCString()),
65 ExecutionContextScope (),
66 m_debugger (debugger),
67 m_platform_sp (platform_sp),
68 m_mutex (Mutex::eMutexTypeRecursive),
71 m_section_load_list (),
72 m_breakpoint_list (false),
73 m_internal_breakpoint_list (true),
77 m_search_filter_sp (),
78 m_image_search_paths (ImageSearchPathsChanged, this),
79 m_scratch_ast_context_ap (),
80 m_scratch_ast_source_ap (),
82 m_persistent_variables (),
83 m_source_manager_ap(),
85 m_stop_hook_next_id (0),
86 m_suppress_stop_hooks (false),
87 m_suppress_synthetic_value(false)
89 SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
90 SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
91 SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
92 SetEventName (eBroadcastBitWatchpointChanged, "watchpoint-changed");
93 SetEventName (eBroadcastBitSymbolsLoaded, "symbols-loaded");
97 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
99 log->Printf ("%p Target::Target()", this);
100 if (m_arch.IsValid())
102 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::Target created with architecture %s (%s)", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
106 //----------------------------------------------------------------------
108 //----------------------------------------------------------------------
111 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
113 log->Printf ("%p Target::~Target()", this);
114 DeleteCurrentProcess ();
118 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
120 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
121 if (description_level != lldb::eDescriptionLevelBrief)
124 s->PutCString("Target\n");
127 m_breakpoint_list.Dump(s);
128 m_internal_breakpoint_list.Dump(s);
133 Module *exe_module = GetExecutableModulePointer();
135 s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
137 s->PutCString ("No executable module.");
142 Target::CleanupProcess ()
144 // Do any cleanup of the target we need to do between process instances.
145 // NB It is better to do this before destroying the process in case the
146 // clean up needs some help from the process.
147 m_breakpoint_list.ClearAllBreakpointSites();
148 m_internal_breakpoint_list.ClearAllBreakpointSites();
149 // Disable watchpoints just on the debugger side.
150 Mutex::Locker locker;
151 this->GetWatchpointList().GetListMutex(locker);
152 DisableAllWatchpoints(false);
153 ClearAllWatchpointHitCounts();
157 Target::DeleteCurrentProcess ()
159 if (m_process_sp.get())
161 m_section_load_list.Clear();
162 if (m_process_sp->IsAlive())
163 m_process_sp->Destroy();
165 m_process_sp->Finalize();
169 m_process_sp.reset();
173 const lldb::ProcessSP &
174 Target::CreateProcess (Listener &listener, const char *plugin_name, const FileSpec *crash_file)
176 DeleteCurrentProcess ();
177 m_process_sp = Process::FindPlugin(*this, plugin_name, listener, crash_file);
181 const lldb::ProcessSP &
182 Target::GetProcessSP () const
190 Mutex::Locker locker (m_mutex);
192 DeleteCurrentProcess ();
193 m_platform_sp.reset();
196 m_section_load_list.Clear();
197 const bool notify = false;
198 m_breakpoint_list.RemoveAll(notify);
199 m_internal_breakpoint_list.RemoveAll(notify);
200 m_last_created_breakpoint.reset();
201 m_last_created_watchpoint.reset();
202 m_search_filter_sp.reset();
203 m_image_search_paths.Clear(notify);
204 m_scratch_ast_context_ap.reset();
205 m_scratch_ast_source_ap.reset();
206 m_ast_importer_ap.reset();
207 m_persistent_variables.Clear();
208 m_stop_hooks.clear();
209 m_stop_hook_next_id = 0;
210 m_suppress_stop_hooks = false;
211 m_suppress_synthetic_value = false;
216 Target::GetBreakpointList(bool internal)
219 return m_internal_breakpoint_list;
221 return m_breakpoint_list;
224 const BreakpointList &
225 Target::GetBreakpointList(bool internal) const
228 return m_internal_breakpoint_list;
230 return m_breakpoint_list;
234 Target::GetBreakpointByID (break_id_t break_id)
238 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
239 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
241 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
247 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
248 const FileSpecList *source_file_spec_list,
249 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);
259 Target::CreateBreakpoint (const FileSpecList *containingModules,
260 const FileSpec &file,
262 LazyBool check_inlines,
263 LazyBool skip_prologue,
266 if (check_inlines == eLazyBoolCalculate)
268 const InlineStrategy inline_strategy = GetInlineStrategy();
269 switch (inline_strategy)
271 case eInlineBreakpointsNever:
272 check_inlines = eLazyBoolNo;
275 case eInlineBreakpointsHeaders:
276 if (file.IsSourceImplementationFile())
277 check_inlines = eLazyBoolNo;
279 check_inlines = eLazyBoolYes;
282 case eInlineBreakpointsAlways:
283 check_inlines = eLazyBoolYes;
287 SearchFilterSP filter_sp;
288 if (check_inlines == eLazyBoolNo)
290 // Not checking for inlines, we are looking only for matching compile units
291 FileSpecList compile_unit_list;
292 compile_unit_list.Append (file);
293 filter_sp = GetSearchFilterForModuleAndCUList (containingModules, &compile_unit_list);
297 filter_sp = GetSearchFilterForModuleList (containingModules);
299 if (skip_prologue == eLazyBoolCalculate)
300 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
302 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL,
307 return CreateBreakpoint (filter_sp, resolver_sp, internal);
312 Target::CreateBreakpoint (lldb::addr_t addr, bool internal)
315 // Attempt to resolve our load address if possible, though it is ok if
316 // it doesn't resolve to section/offset.
318 // Try and resolve as a load address if possible
319 m_section_load_list.ResolveLoadAddress(addr, so_addr);
320 if (!so_addr.IsValid())
322 // The address didn't resolve, so just set this as an absolute address
323 so_addr.SetOffset (addr);
325 BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal));
330 Target::CreateBreakpoint (Address &addr, bool internal)
332 SearchFilterSP filter_sp(new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
333 BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
334 return CreateBreakpoint (filter_sp, resolver_sp, internal);
338 Target::CreateBreakpoint (const FileSpecList *containingModules,
339 const FileSpecList *containingSourceFiles,
340 const char *func_name,
341 uint32_t func_name_type_mask,
342 LazyBool skip_prologue,
348 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
350 if (skip_prologue == eLazyBoolCalculate)
351 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
353 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
358 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
364 Target::CreateBreakpoint (const FileSpecList *containingModules,
365 const FileSpecList *containingSourceFiles,
366 const std::vector<std::string> &func_names,
367 uint32_t func_name_type_mask,
368 LazyBool skip_prologue,
372 size_t num_names = func_names.size();
375 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
377 if (skip_prologue == eLazyBoolCalculate)
378 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
380 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
384 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
390 Target::CreateBreakpoint (const FileSpecList *containingModules,
391 const FileSpecList *containingSourceFiles,
392 const char *func_names[],
394 uint32_t func_name_type_mask,
395 LazyBool skip_prologue,
401 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
403 if (skip_prologue == eLazyBoolCalculate)
404 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
406 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
411 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
417 Target::GetSearchFilterForModule (const FileSpec *containingModule)
419 SearchFilterSP filter_sp;
420 if (containingModule != NULL)
422 // TODO: We should look into sharing module based search filters
423 // across many breakpoints like we do for the simple target based one
424 filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule));
428 if (m_search_filter_sp.get() == NULL)
429 m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
430 filter_sp = m_search_filter_sp;
436 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules)
438 SearchFilterSP filter_sp;
439 if (containingModules && containingModules->GetSize() != 0)
441 // TODO: We should look into sharing module based search filters
442 // across many breakpoints like we do for the simple target based one
443 filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules));
447 if (m_search_filter_sp.get() == NULL)
448 m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
449 filter_sp = m_search_filter_sp;
455 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules,
456 const FileSpecList *containingSourceFiles)
458 if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0)
459 return GetSearchFilterForModuleList(containingModules);
461 SearchFilterSP filter_sp;
462 if (containingModules == NULL)
464 // We could make a special "CU List only SearchFilter". Better yet was if these could be composable,
465 // but that will take a little reworking.
467 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles));
471 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles));
477 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
478 const FileSpecList *containingSourceFiles,
479 RegularExpression &func_regex,
480 LazyBool skip_prologue,
483 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
484 BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
486 skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
488 return CreateBreakpoint (filter_sp, resolver_sp, internal);
492 Target::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal)
494 return LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal);
498 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal)
501 if (filter_sp && resolver_sp)
503 bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp));
504 resolver_sp->SetBreakpoint (bp_sp.get());
507 m_internal_breakpoint_list.Add (bp_sp, false);
509 m_breakpoint_list.Add (bp_sp, true);
511 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
515 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
516 log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
519 bp_sp->ResolveBreakpoint();
522 if (!internal && bp_sp)
524 m_last_created_breakpoint = bp_sp;
531 Target::ProcessIsValid()
533 return (m_process_sp && m_process_sp->IsAlive());
537 CheckIfWatchpointsExhausted(Target *target, Error &error)
539 uint32_t num_supported_hardware_watchpoints;
540 Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints);
543 uint32_t num_current_watchpoints = target->GetWatchpointList().GetSize();
544 if (num_current_watchpoints >= num_supported_hardware_watchpoints)
545 error.SetErrorStringWithFormat("number of supported hardware watchpoints (%u) has been reached",
546 num_supported_hardware_watchpoints);
551 // See also Watchpoint::SetWatchpointType(uint32_t type) and
552 // the OptionGroupWatchpoint::WatchType enum type.
554 Target::CreateWatchpoint(lldb::addr_t addr, size_t size, const ClangASTType *type, uint32_t kind, Error &error)
556 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
558 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64 " type = %u)\n",
559 __FUNCTION__, addr, (uint64_t)size, kind);
562 if (!ProcessIsValid())
564 error.SetErrorString("process is not alive");
568 if (addr == LLDB_INVALID_ADDRESS || size == 0)
571 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
573 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
577 if (!LLDB_WATCH_TYPE_IS_VALID(kind))
579 error.SetErrorStringWithFormat ("invalid watchpoint type: %d", kind);
582 // Currently we only support one watchpoint per address, with total number
583 // of watchpoints limited by the hardware which the inferior is running on.
585 // Grab the list mutex while doing operations.
586 const bool notify = false; // Don't notify about all the state changes we do on creating the watchpoint.
587 Mutex::Locker locker;
588 this->GetWatchpointList().GetListMutex(locker);
589 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
592 size_t old_size = matched_sp->GetByteSize();
594 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
595 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
596 // Return the existing watchpoint if both size and type match.
597 if (size == old_size && kind == old_type)
600 wp_sp->SetEnabled(false, notify);
604 // Nil the matched watchpoint; we will be creating a new one.
605 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
606 m_watchpoint_list.Remove(matched_sp->GetID(), true);
612 wp_sp.reset(new Watchpoint(*this, addr, size, type));
613 wp_sp->SetWatchpointType(kind, notify);
614 m_watchpoint_list.Add (wp_sp, true);
617 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
619 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
621 error.Success() ? "succeeded" : "failed",
626 // Enabling the watchpoint on the device side failed.
627 // Remove the said watchpoint from the list maintained by the target instance.
628 m_watchpoint_list.Remove (wp_sp->GetID(), true);
629 // See if we could provide more helpful error message.
630 if (!CheckIfWatchpointsExhausted(this, error))
632 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
633 error.SetErrorStringWithFormat("watch size of %lu is not supported", size);
638 m_last_created_watchpoint = wp_sp;
643 Target::RemoveAllBreakpoints (bool internal_also)
645 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
647 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
649 m_breakpoint_list.RemoveAll (true);
651 m_internal_breakpoint_list.RemoveAll (false);
653 m_last_created_breakpoint.reset();
657 Target::DisableAllBreakpoints (bool internal_also)
659 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
661 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
663 m_breakpoint_list.SetEnabledAll (false);
665 m_internal_breakpoint_list.SetEnabledAll (false);
669 Target::EnableAllBreakpoints (bool internal_also)
671 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
673 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
675 m_breakpoint_list.SetEnabledAll (true);
677 m_internal_breakpoint_list.SetEnabledAll (true);
681 Target::RemoveBreakpointByID (break_id_t break_id)
683 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
685 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
687 if (DisableBreakpointByID (break_id))
689 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
690 m_internal_breakpoint_list.Remove(break_id, false);
693 if (m_last_created_breakpoint)
695 if (m_last_created_breakpoint->GetID() == break_id)
696 m_last_created_breakpoint.reset();
698 m_breakpoint_list.Remove(break_id, true);
706 Target::DisableBreakpointByID (break_id_t break_id)
708 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
710 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
714 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
715 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
717 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
720 bp_sp->SetEnabled (false);
727 Target::EnableBreakpointByID (break_id_t break_id)
729 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
731 log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
734 LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
738 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
739 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
741 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
745 bp_sp->SetEnabled (true);
751 // The flag 'end_to_end', default to true, signifies that the operation is
752 // performed end to end, for both the debugger and the debuggee.
754 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
755 // to end operations.
757 Target::RemoveAllWatchpoints (bool end_to_end)
759 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
761 log->Printf ("Target::%s\n", __FUNCTION__);
764 m_watchpoint_list.RemoveAll(true);
768 // Otherwise, it's an end to end operation.
770 if (!ProcessIsValid())
773 size_t num_watchpoints = m_watchpoint_list.GetSize();
774 for (size_t i = 0; i < num_watchpoints; ++i)
776 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
780 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
784 m_watchpoint_list.RemoveAll (true);
785 m_last_created_watchpoint.reset();
786 return true; // Success!
789 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
792 Target::DisableAllWatchpoints (bool end_to_end)
794 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
796 log->Printf ("Target::%s\n", __FUNCTION__);
799 m_watchpoint_list.SetEnabledAll(false);
803 // Otherwise, it's an end to end operation.
805 if (!ProcessIsValid())
808 size_t num_watchpoints = m_watchpoint_list.GetSize();
809 for (size_t i = 0; i < num_watchpoints; ++i)
811 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
815 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
819 return true; // Success!
822 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
825 Target::EnableAllWatchpoints (bool end_to_end)
827 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
829 log->Printf ("Target::%s\n", __FUNCTION__);
832 m_watchpoint_list.SetEnabledAll(true);
836 // Otherwise, it's an end to end operation.
838 if (!ProcessIsValid())
841 size_t num_watchpoints = m_watchpoint_list.GetSize();
842 for (size_t i = 0; i < num_watchpoints; ++i)
844 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
848 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
852 return true; // Success!
855 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
857 Target::ClearAllWatchpointHitCounts ()
859 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
861 log->Printf ("Target::%s\n", __FUNCTION__);
863 size_t num_watchpoints = m_watchpoint_list.GetSize();
864 for (size_t i = 0; i < num_watchpoints; ++i)
866 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
870 wp_sp->ResetHitCount();
872 return true; // Success!
875 // Assumption: Caller holds the list mutex lock for m_watchpoint_list
876 // during these operations.
878 Target::IgnoreAllWatchpoints (uint32_t ignore_count)
880 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
882 log->Printf ("Target::%s\n", __FUNCTION__);
884 if (!ProcessIsValid())
887 size_t num_watchpoints = m_watchpoint_list.GetSize();
888 for (size_t i = 0; i < num_watchpoints; ++i)
890 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
894 wp_sp->SetIgnoreCount(ignore_count);
896 return true; // Success!
899 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
901 Target::DisableWatchpointByID (lldb::watch_id_t watch_id)
903 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
905 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
907 if (!ProcessIsValid())
910 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
913 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
917 // Else, fallthrough.
922 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
924 Target::EnableWatchpointByID (lldb::watch_id_t watch_id)
926 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
928 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
930 if (!ProcessIsValid())
933 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
936 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
940 // Else, fallthrough.
945 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
947 Target::RemoveWatchpointByID (lldb::watch_id_t watch_id)
949 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
951 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
953 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
954 if (watch_to_remove_sp == m_last_created_watchpoint)
955 m_last_created_watchpoint.reset();
957 if (DisableWatchpointByID (watch_id))
959 m_watchpoint_list.Remove(watch_id, true);
965 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
967 Target::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
969 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
971 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
973 if (!ProcessIsValid())
976 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
979 wp_sp->SetIgnoreCount(ignore_count);
986 Target::GetExecutableModule ()
988 return m_images.GetModuleAtIndex(0);
992 Target::GetExecutableModulePointer ()
994 return m_images.GetModulePointerAtIndex(0);
998 LoadScriptingResourceForModule (const ModuleSP &module_sp, Target *target)
1001 StreamString feedback_stream;
1002 if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error, &feedback_stream))
1004 if (error.AsCString())
1005 target->GetDebugger().GetErrorStream().Printf("unable to load scripting data for module %s - error reported was %s\n",
1006 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1008 if (feedback_stream.GetSize())
1009 target->GetDebugger().GetOutputStream().Printf("%s\n",
1010 feedback_stream.GetData());
1015 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
1017 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1019 m_scratch_ast_context_ap.reset();
1020 m_scratch_ast_source_ap.reset();
1021 m_ast_importer_ap.reset();
1023 if (executable_sp.get())
1025 Timer scoped_timer (__PRETTY_FUNCTION__,
1026 "Target::SetExecutableModule (executable = '%s')",
1027 executable_sp->GetFileSpec().GetPath().c_str());
1029 m_images.Append(executable_sp); // The first image is our exectuable file
1031 // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
1032 if (!m_arch.IsValid())
1034 m_arch = executable_sp->GetArchitecture();
1036 log->Printf ("Target::SetExecutableModule setting architecture to %s (%s) based on executable file", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
1039 FileSpecList dependent_files;
1040 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1042 if (executable_objfile && get_dependent_files)
1044 executable_objfile->GetDependentModules(dependent_files);
1045 for (uint32_t i=0; i<dependent_files.GetSize(); i++)
1047 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
1048 FileSpec platform_dependent_file_spec;
1050 m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec);
1052 platform_dependent_file_spec = dependent_file_spec;
1054 ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
1055 ModuleSP image_module_sp(GetSharedModule (module_spec));
1056 if (image_module_sp.get())
1058 ObjectFile *objfile = image_module_sp->GetObjectFile();
1060 objfile->GetDependentModules(dependent_files);
1069 Target::SetArchitecture (const ArchSpec &arch_spec)
1071 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1072 if (m_arch.IsCompatibleMatch(arch_spec) || !m_arch.IsValid())
1074 // If we haven't got a valid arch spec, or the architectures are
1075 // compatible, so just update the architecture. Architectures can be
1076 // equal, yet the triple OS and vendor might change, so we need to do
1077 // the assignment here just in case.
1080 log->Printf ("Target::SetArchitecture setting architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1085 // If we have an executable file, try to reset the executable to the desired architecture
1087 log->Printf ("Target::SetArchitecture changing architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1089 ModuleSP executable_sp = GetExecutableModule ();
1091 m_scratch_ast_context_ap.reset();
1092 m_scratch_ast_source_ap.reset();
1093 m_ast_importer_ap.reset();
1094 // Need to do something about unsetting breakpoints.
1099 log->Printf("Target::SetArchitecture Trying to select executable file architecture %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1100 ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec);
1101 Error error = ModuleList::GetSharedModule (module_spec,
1103 &GetExecutableSearchPaths(),
1107 if (!error.Fail() && executable_sp)
1109 SetExecutableModule (executable_sp, true);
1118 Target::WillClearList (const ModuleList& module_list)
1123 Target::ModuleAdded (const ModuleList& module_list, const ModuleSP &module_sp)
1125 // A module is being added to this target for the first time
1126 ModuleList my_module_list;
1127 my_module_list.Append(module_sp);
1128 LoadScriptingResourceForModule(module_sp, this);
1129 ModulesDidLoad (my_module_list);
1133 Target::ModuleRemoved (const ModuleList& module_list, const ModuleSP &module_sp)
1135 // A module is being added to this target for the first time
1136 ModuleList my_module_list;
1137 my_module_list.Append(module_sp);
1138 ModulesDidUnload (my_module_list);
1142 Target::ModuleUpdated (const ModuleList& module_list, const ModuleSP &old_module_sp, const ModuleSP &new_module_sp)
1144 // A module is replacing an already added module
1145 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1149 Target::ModulesDidLoad (ModuleList &module_list)
1151 if (module_list.GetSize())
1153 m_breakpoint_list.UpdateBreakpoints (module_list, true);
1154 // TODO: make event data that packages up the module_list
1155 BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
1160 Target::SymbolsDidLoad (ModuleList &module_list)
1162 if (module_list.GetSize())
1166 LanguageRuntime* runtime = m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1169 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime*)runtime;
1170 objc_runtime->SymbolsDidLoad(module_list);
1174 m_breakpoint_list.UpdateBreakpoints (module_list, true);
1175 BroadcastEvent(eBroadcastBitSymbolsLoaded, NULL);
1180 Target::ModulesDidUnload (ModuleList &module_list)
1182 if (module_list.GetSize())
1184 m_breakpoint_list.UpdateBreakpoints (module_list, false);
1185 // TODO: make event data that packages up the module_list
1186 BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
1191 Target::ModuleIsExcludedForNonModuleSpecificSearches (const FileSpec &module_file_spec)
1193 if (GetBreakpointsConsultPlatformAvoidList())
1195 ModuleList matchingModules;
1196 ModuleSpec module_spec (module_file_spec);
1197 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1199 // If there is more than one module for this file spec, only return true if ALL the modules are on the
1201 if (num_modules > 0)
1203 for (size_t i = 0; i < num_modules; i++)
1205 if (!ModuleIsExcludedForNonModuleSpecificSearches (matchingModules.GetModuleAtIndex(i)))
1215 Target::ModuleIsExcludedForNonModuleSpecificSearches (const lldb::ModuleSP &module_sp)
1217 if (GetBreakpointsConsultPlatformAvoidList())
1220 return m_platform_sp->ModuleIsExcludedForNonModuleSpecificSearches (*this, module_sp);
1226 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
1228 SectionSP section_sp (addr.GetSection());
1231 // If the contents of this section are encrypted, the on-disk file is unusuable. Read only from live memory.
1232 if (section_sp->IsEncrypted())
1234 error.SetErrorString("section is encrypted");
1237 ModuleSP module_sp (section_sp->GetModule());
1240 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1243 size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
1250 error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
1253 error.SetErrorString("address isn't from a object file");
1256 error.SetErrorString("address isn't in a module");
1259 error.SetErrorString("address doesn't contain a section that points to a section in a object file");
1265 Target::ReadMemory (const Address& addr,
1266 bool prefer_file_cache,
1270 lldb::addr_t *load_addr_ptr)
1274 // if we end up reading this from process memory, we will fill this
1275 // with the actual load address
1277 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1279 size_t bytes_read = 0;
1281 addr_t load_addr = LLDB_INVALID_ADDRESS;
1282 addr_t file_addr = LLDB_INVALID_ADDRESS;
1283 Address resolved_addr;
1284 if (!addr.IsSectionOffset())
1286 if (m_section_load_list.IsEmpty())
1288 // No sections are loaded, so we must assume we are not running
1289 // yet and anything we are given is a file address.
1290 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
1291 m_images.ResolveFileAddress (file_addr, resolved_addr);
1295 // We have at least one section loaded. This can be becuase
1296 // we have manually loaded some sections with "target modules load ..."
1297 // or because we have have a live process that has sections loaded
1298 // through the dynamic loader
1299 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1300 m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1303 if (!resolved_addr.IsValid())
1304 resolved_addr = addr;
1307 if (prefer_file_cache)
1309 bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1314 if (ProcessIsValid())
1316 if (load_addr == LLDB_INVALID_ADDRESS)
1317 load_addr = resolved_addr.GetLoadAddress (this);
1319 if (load_addr == LLDB_INVALID_ADDRESS)
1321 ModuleSP addr_module_sp (resolved_addr.GetModule());
1322 if (addr_module_sp && addr_module_sp->GetFileSpec())
1323 error.SetErrorStringWithFormat("%s[0x%" PRIx64 "] can't be resolved, %s in not currently loaded",
1324 addr_module_sp->GetFileSpec().GetFilename().AsCString(),
1325 resolved_addr.GetFileAddress(),
1326 addr_module_sp->GetFileSpec().GetFilename().AsCString());
1328 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
1332 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1333 if (bytes_read != dst_len)
1335 if (error.Success())
1337 if (bytes_read == 0)
1338 error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed", load_addr);
1340 error.SetErrorStringWithFormat("only %" PRIu64 " of %" PRIu64 " bytes were read from memory at 0x%" PRIx64, (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1346 *load_addr_ptr = load_addr;
1349 // If the address is not section offset we have an address that
1350 // doesn't resolve to any address in any currently loaded shared
1351 // libaries and we failed to read memory so there isn't anything
1352 // more we can do. If it is section offset, we might be able to
1353 // read cached memory from the object file.
1354 if (!resolved_addr.IsSectionOffset())
1359 if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1361 // If we didn't already try and read from the object file cache, then
1362 // try it after failing to read from the process.
1363 return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1369 Target::ReadCStringFromMemory (const Address& addr, std::string &out_str, Error &error)
1373 addr_t curr_addr = addr.GetLoadAddress(this);
1374 Address address(addr);
1377 size_t length = ReadCStringFromMemory (address, buf, sizeof(buf), error);
1380 out_str.append(buf, length);
1381 // If we got "length - 1" bytes, we didn't get the whole C string, we
1382 // need to read some more characters
1383 if (length == sizeof(buf) - 1)
1384 curr_addr += length;
1387 address = Address(curr_addr);
1389 return out_str.size();
1394 Target::ReadCStringFromMemory (const Address& addr, char *dst, size_t dst_max_len, Error &result_error)
1396 size_t total_cstr_len = 0;
1397 if (dst && dst_max_len)
1399 result_error.Clear();
1400 // NULL out everything just to be safe
1401 memset (dst, 0, dst_max_len);
1403 addr_t curr_addr = addr.GetLoadAddress(this);
1404 Address address(addr);
1405 const size_t cache_line_size = 512;
1406 size_t bytes_left = dst_max_len - 1;
1407 char *curr_dst = dst;
1409 while (bytes_left > 0)
1411 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1412 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1413 size_t bytes_read = ReadMemory (address, false, curr_dst, bytes_to_read, error);
1415 if (bytes_read == 0)
1417 result_error = error;
1418 dst[total_cstr_len] = '\0';
1421 const size_t len = strlen(curr_dst);
1423 total_cstr_len += len;
1425 if (len < bytes_to_read)
1428 curr_dst += bytes_read;
1429 curr_addr += bytes_read;
1430 bytes_left -= bytes_read;
1431 address = Address(curr_addr);
1437 result_error.SetErrorString("invalid arguments");
1439 result_error.Clear();
1441 return total_cstr_len;
1445 Target::ReadScalarIntegerFromMemory (const Address& addr,
1446 bool prefer_file_cache,
1454 if (byte_size <= sizeof(uval))
1456 size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1457 if (bytes_read == byte_size)
1459 DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1460 lldb::offset_t offset = 0;
1462 scalar = data.GetMaxU32 (&offset, byte_size);
1464 scalar = data.GetMaxU64 (&offset, byte_size);
1467 scalar.SignExtend(byte_size * 8);
1473 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1479 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1480 bool prefer_file_cache,
1481 size_t integer_byte_size,
1482 uint64_t fail_value,
1486 if (ReadScalarIntegerFromMemory (addr,
1492 return scalar.ULongLong(fail_value);
1497 Target::ReadPointerFromMemory (const Address& addr,
1498 bool prefer_file_cache,
1500 Address &pointer_addr)
1503 if (ReadScalarIntegerFromMemory (addr,
1505 m_arch.GetAddressByteSize(),
1510 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1511 if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1513 if (m_section_load_list.IsEmpty())
1515 // No sections are loaded, so we must assume we are not running
1516 // yet and anything we are given is a file address.
1517 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1521 // We have at least one section loaded. This can be becuase
1522 // we have manually loaded some sections with "target modules load ..."
1523 // or because we have have a live process that has sections loaded
1524 // through the dynamic loader
1525 m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1527 // We weren't able to resolve the pointer value, so just return
1528 // an address with no section
1529 if (!pointer_addr.IsValid())
1530 pointer_addr.SetOffset (pointer_vm_addr);
1539 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
1545 // First see if we already have this module in our module list. If we do, then we're done, we don't need
1546 // to consult the shared modules list. But only do this if we are passed a UUID.
1548 if (module_spec.GetUUID().IsValid())
1549 module_sp = m_images.FindFirstModule(module_spec);
1553 ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1554 bool did_create_module = false;
1556 // If there are image search path entries, try to use them first to acquire a suitable image.
1557 if (m_image_search_paths.GetSize())
1559 ModuleSpec transformed_spec (module_spec);
1560 if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
1562 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
1563 error = ModuleList::GetSharedModule (transformed_spec,
1565 &GetExecutableSearchPaths(),
1567 &did_create_module);
1573 // If we have a UUID, we can check our global shared module list in case
1574 // we already have it. If we don't have a valid UUID, then we can't since
1575 // the path in "module_spec" will be a platform path, and we will need to
1576 // let the platform find that file. For example, we could be asking for
1577 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1578 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1579 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1581 if (module_spec.GetUUID().IsValid())
1583 // We have a UUID, it is OK to check the global module list...
1584 error = ModuleList::GetSharedModule (module_spec,
1586 &GetExecutableSearchPaths(),
1588 &did_create_module);
1593 // The platform is responsible for finding and caching an appropriate
1594 // module in the shared module cache.
1597 FileSpec platform_file_spec;
1598 error = m_platform_sp->GetSharedModule (module_spec,
1600 &GetExecutableSearchPaths(),
1602 &did_create_module);
1606 error.SetErrorString("no platform is currently set");
1611 // We found a module that wasn't in our target list. Let's make sure that there wasn't an equivalent
1612 // module in the list already, and if there was, let's remove it.
1615 ObjectFile *objfile = module_sp->GetObjectFile();
1618 switch (objfile->GetType())
1620 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of a program's execution state
1621 case ObjectFile::eTypeExecutable: /// A normal executable
1622 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker executable
1623 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1624 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be used during execution
1626 case ObjectFile::eTypeDebugInfo: /// An object file that contains only debug information
1628 error_ptr->SetErrorString("debug info files aren't valid target modules, please specify an executable");
1630 case ObjectFile::eTypeStubLibrary: /// A library that can be linked against but not used for execution
1632 error_ptr->SetErrorString("stub libraries aren't valid target modules, please specify an executable");
1636 error_ptr->SetErrorString("unsupported file type, please specify an executable");
1639 // GetSharedModule is not guaranteed to find the old shared module, for instance
1640 // in the common case where you pass in the UUID, it is only going to find the one
1641 // module matching the UUID. In fact, it has no good way to know what the "old module"
1642 // relevant to this target is, since there might be many copies of a module with this file spec
1643 // in various running debug sessions, but only one of them will belong to this target.
1644 // So let's remove the UUID from the module list, and look in the target's module list.
1645 // Only do this if there is SOMETHING else in the module spec...
1648 if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
1650 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1651 module_spec_copy.GetUUID().Clear();
1653 ModuleList found_modules;
1654 size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
1657 old_module_sp = found_modules.GetModuleAtIndex(0);
1662 if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1664 m_images.ReplaceModule(old_module_sp, module_sp);
1665 Module *old_module_ptr = old_module_sp.get();
1666 old_module_sp.reset();
1667 ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
1670 m_images.Append(module_sp);
1681 Target::CalculateTarget ()
1683 return shared_from_this();
1687 Target::CalculateProcess ()
1693 Target::CalculateThread ()
1699 Target::CalculateStackFrame ()
1701 return StackFrameSP();
1705 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1708 exe_ctx.SetTargetPtr(this);
1712 Target::GetImageSearchPathList ()
1714 return m_image_search_paths;
1718 Target::ImageSearchPathsChanged
1720 const PathMappingList &path_list,
1724 Target *target = (Target *)baton;
1725 ModuleSP exe_module_sp (target->GetExecutableModule());
1728 target->m_images.Clear();
1729 target->SetExecutableModule (exe_module_sp, true);
1734 Target::GetScratchClangASTContext(bool create_on_demand)
1736 // Now see if we know the target triple, and if so, create our scratch AST context:
1737 if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand)
1739 m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1740 m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this()));
1741 m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext());
1742 llvm::OwningPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy());
1743 m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source);
1745 return m_scratch_ast_context_ap.get();
1749 Target::GetClangASTImporter()
1751 ClangASTImporter *ast_importer = m_ast_importer_ap.get();
1755 ast_importer = new ClangASTImporter();
1756 m_ast_importer_ap.reset(ast_importer);
1759 return ast_importer;
1763 Target::SettingsInitialize ()
1765 Process::SettingsInitialize ();
1769 Target::SettingsTerminate ()
1771 Process::SettingsTerminate ();
1775 Target::GetDefaultExecutableSearchPaths ()
1777 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1779 return properties_sp->GetExecutableSearchPaths();
1780 return FileSpecList();
1784 Target::GetDefaultDebugFileSearchPaths ()
1786 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1788 return properties_sp->GetDebugFileSearchPaths();
1789 return FileSpecList();
1793 Target::GetDefaultArchitecture ()
1795 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1797 return properties_sp->GetDefaultArchitecture();
1802 Target::SetDefaultArchitecture (const ArchSpec &arch)
1804 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1807 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's default architecture to %s (%s)", arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
1808 return properties_sp->SetDefaultArchitecture(arch);
1813 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1815 // The target can either exist in the "process" of ExecutionContext, or in
1816 // the "target_sp" member of SymbolContext. This accessor helper function
1817 // will get the target from one of these locations.
1819 Target *target = NULL;
1821 target = sc_ptr->target_sp.get();
1822 if (target == NULL && exe_ctx_ptr)
1823 target = exe_ctx_ptr->GetTargetPtr();
1828 Target::EvaluateExpression
1830 const char *expr_cstr,
1832 lldb::ValueObjectSP &result_valobj_sp,
1833 const EvaluateExpressionOptions& options
1836 result_valobj_sp.reset();
1838 ExecutionResults execution_results = eExecutionSetupError;
1840 if (expr_cstr == NULL || expr_cstr[0] == '\0')
1841 return execution_results;
1843 // We shouldn't run stop hooks in expressions.
1844 // Be sure to reset this if you return anywhere within this function.
1845 bool old_suppress_value = m_suppress_stop_hooks;
1846 m_suppress_stop_hooks = true;
1848 ExecutionContext exe_ctx;
1852 frame->CalculateExecutionContext(exe_ctx);
1854 else if (m_process_sp)
1856 m_process_sp->CalculateExecutionContext(exe_ctx);
1860 CalculateExecutionContext(exe_ctx);
1863 // Make sure we aren't just trying to see the value of a persistent
1864 // variable (something like "$0")
1865 lldb::ClangExpressionVariableSP persistent_var_sp;
1866 // Only check for persistent variables the expression starts with a '$'
1867 if (expr_cstr[0] == '$')
1868 persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1870 if (persistent_var_sp)
1872 result_valobj_sp = persistent_var_sp->GetValueObject ();
1873 execution_results = eExecutionCompleted;
1877 const char *prefix = GetExpressionPrefixContentsAsCString();
1879 execution_results = ClangUserExpression::Evaluate (exe_ctx,
1880 options.GetExecutionPolicy(),
1881 lldb::eLanguageTypeUnknown,
1882 options.DoesCoerceToId() ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny,
1883 options.DoesUnwindOnError(),
1884 options.DoesIgnoreBreakpoints(),
1888 options.GetRunOthers(),
1889 options.GetTimeoutUsec());
1892 m_suppress_stop_hooks = old_suppress_value;
1894 return execution_results;
1898 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1900 addr_t code_addr = load_addr;
1901 switch (m_arch.GetMachine())
1903 case llvm::Triple::arm:
1904 case llvm::Triple::thumb:
1907 case eAddressClassData:
1908 case eAddressClassDebug:
1909 return LLDB_INVALID_ADDRESS;
1911 case eAddressClassUnknown:
1912 case eAddressClassInvalid:
1913 case eAddressClassCode:
1914 case eAddressClassCodeAlternateISA:
1915 case eAddressClassRuntime:
1916 // Check if bit zero it no set?
1917 if ((code_addr & 1ull) == 0)
1919 // Bit zero isn't set, check if the address is a multiple of 2?
1920 if (code_addr & 2ull)
1922 // The address is a multiple of 2 so it must be thumb, set bit zero
1925 else if (addr_class == eAddressClassCodeAlternateISA)
1927 // We checked the address and the address claims to be the alternate ISA
1928 // which means thumb, so set bit zero.
1943 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1945 addr_t opcode_addr = load_addr;
1946 switch (m_arch.GetMachine())
1948 case llvm::Triple::arm:
1949 case llvm::Triple::thumb:
1952 case eAddressClassData:
1953 case eAddressClassDebug:
1954 return LLDB_INVALID_ADDRESS;
1956 case eAddressClassInvalid:
1957 case eAddressClassUnknown:
1958 case eAddressClassCode:
1959 case eAddressClassCodeAlternateISA:
1960 case eAddressClassRuntime:
1961 opcode_addr &= ~(1ull);
1973 Target::GetSourceManager ()
1975 if (m_source_manager_ap.get() == NULL)
1976 m_source_manager_ap.reset (new SourceManager(shared_from_this()));
1977 return *m_source_manager_ap;
1982 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1984 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1985 new_hook_sp.reset (new StopHook(shared_from_this(), new_uid));
1986 m_stop_hooks[new_uid] = new_hook_sp;
1991 Target::RemoveStopHookByID (lldb::user_id_t user_id)
1994 num_removed = m_stop_hooks.erase (user_id);
1995 if (num_removed == 0)
2002 Target::RemoveAllStopHooks ()
2004 m_stop_hooks.clear();
2008 Target::GetStopHookByID (lldb::user_id_t user_id)
2010 StopHookSP found_hook;
2012 StopHookCollection::iterator specified_hook_iter;
2013 specified_hook_iter = m_stop_hooks.find (user_id);
2014 if (specified_hook_iter != m_stop_hooks.end())
2015 found_hook = (*specified_hook_iter).second;
2020 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
2022 StopHookCollection::iterator specified_hook_iter;
2023 specified_hook_iter = m_stop_hooks.find (user_id);
2024 if (specified_hook_iter == m_stop_hooks.end())
2027 (*specified_hook_iter).second->SetIsActive (active_state);
2032 Target::SetAllStopHooksActiveState (bool active_state)
2034 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2035 for (pos = m_stop_hooks.begin(); pos != end; pos++)
2037 (*pos).second->SetIsActive (active_state);
2042 Target::RunStopHooks ()
2044 if (m_suppress_stop_hooks)
2050 // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
2051 // since in that case we do not want to run the stop-hooks
2052 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2055 if (m_stop_hooks.empty())
2058 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2060 // If there aren't any active stop hooks, don't bother either:
2061 bool any_active_hooks = false;
2062 for (pos = m_stop_hooks.begin(); pos != end; pos++)
2064 if ((*pos).second->IsActive())
2066 any_active_hooks = true;
2070 if (!any_active_hooks)
2073 CommandReturnObject result;
2075 std::vector<ExecutionContext> exc_ctx_with_reasons;
2076 std::vector<SymbolContext> sym_ctx_with_reasons;
2078 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2079 size_t num_threads = cur_threadlist.GetSize();
2080 for (size_t i = 0; i < num_threads; i++)
2082 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
2083 if (cur_thread_sp->ThreadStoppedForAReason())
2085 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2086 exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2087 sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2091 // If no threads stopped for a reason, don't run the stop-hooks.
2092 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2093 if (num_exe_ctx == 0)
2096 result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
2097 result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
2099 bool keep_going = true;
2100 bool hooks_ran = false;
2101 bool print_hook_header;
2102 bool print_thread_header;
2104 if (num_exe_ctx == 1)
2105 print_thread_header = false;
2107 print_thread_header = true;
2109 if (m_stop_hooks.size() == 1)
2110 print_hook_header = false;
2112 print_hook_header = true;
2114 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
2117 StopHookSP cur_hook_sp = (*pos).second;
2118 if (!cur_hook_sp->IsActive())
2121 bool any_thread_matched = false;
2122 for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2124 if ((cur_hook_sp->GetSpecifier () == NULL
2125 || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2126 && (cur_hook_sp->GetThreadSpecifier() == NULL
2127 || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2133 if (print_hook_header && !any_thread_matched)
2135 const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2136 cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2139 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(), cmd);
2141 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2142 any_thread_matched = true;
2145 if (print_thread_header)
2146 result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2148 bool stop_on_continue = true;
2149 bool stop_on_error = true;
2150 bool echo_commands = false;
2151 bool print_results = true;
2152 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2153 &exc_ctx_with_reasons[i],
2161 // If the command started the target going again, we should bag out of
2162 // running the stop hooks.
2163 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2164 (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2166 result.AppendMessageWithFormat ("Aborting stop hooks, hook %" PRIu64 " set the program running.", cur_hook_sp->GetID());
2173 result.GetImmediateOutputStream()->Flush();
2174 result.GetImmediateErrorStream()->Flush();
2178 //--------------------------------------------------------------
2179 // class Target::StopHook
2180 //--------------------------------------------------------------
2183 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2185 m_target_sp (target_sp),
2193 Target::StopHook::StopHook (const StopHook &rhs) :
2194 UserID (rhs.GetID()),
2195 m_target_sp (rhs.m_target_sp),
2196 m_commands (rhs.m_commands),
2197 m_specifier_sp (rhs.m_specifier_sp),
2198 m_thread_spec_ap (),
2199 m_active (rhs.m_active)
2201 if (rhs.m_thread_spec_ap.get() != NULL)
2202 m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2206 Target::StopHook::~StopHook ()
2211 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2213 m_thread_spec_ap.reset (specifier);
2218 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2220 int indent_level = s->GetIndentLevel();
2222 s->SetIndentLevel(indent_level + 2);
2224 s->Printf ("Hook: %" PRIu64 "\n", GetID());
2226 s->Indent ("State: enabled\n");
2228 s->Indent ("State: disabled\n");
2233 s->PutCString ("Specifier:\n");
2234 s->SetIndentLevel (indent_level + 4);
2235 m_specifier_sp->GetDescription (s, level);
2236 s->SetIndentLevel (indent_level + 2);
2239 if (m_thread_spec_ap.get() != NULL)
2242 s->Indent("Thread:\n");
2243 m_thread_spec_ap->GetDescription (&tmp, level);
2244 s->SetIndentLevel (indent_level + 4);
2245 s->Indent (tmp.GetData());
2246 s->PutCString ("\n");
2247 s->SetIndentLevel (indent_level + 2);
2250 s->Indent ("Commands: \n");
2251 s->SetIndentLevel (indent_level + 4);
2252 uint32_t num_commands = m_commands.GetSize();
2253 for (uint32_t i = 0; i < num_commands; i++)
2255 s->Indent(m_commands.GetStringAtIndex(i));
2256 s->PutCString ("\n");
2258 s->SetIndentLevel (indent_level);
2261 //--------------------------------------------------------------
2262 // class TargetProperties
2263 //--------------------------------------------------------------
2265 OptionEnumValueElement
2266 lldb_private::g_dynamic_value_types[] =
2268 { eNoDynamicValues, "no-dynamic-values", "Don't calculate the dynamic type of values"},
2269 { eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values even if you have to run the target."},
2270 { eDynamicDontRunTarget, "no-run-target", "Calculate the dynamic type of values, but don't run the target."},
2274 static OptionEnumValueElement
2275 g_inline_breakpoint_enums[] =
2277 { 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."},
2278 { eInlineBreakpointsHeaders, "headers", "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2279 { eInlineBreakpointsAlways, "always", "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2283 typedef enum x86DisassemblyFlavor
2285 eX86DisFlavorDefault,
2288 } x86DisassemblyFlavor;
2290 static OptionEnumValueElement
2291 g_x86_dis_flavor_value_types[] =
2293 { eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
2294 { eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
2295 { eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
2299 static OptionEnumValueElement
2300 g_hex_immediate_style_values[] =
2302 { Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
2303 { Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
2307 static OptionEnumValueElement
2308 g_load_script_from_sym_file_values[] =
2310 { eLoadScriptFromSymFileTrue, "true", "Load debug scripts inside symbol files"},
2311 { eLoadScriptFromSymFileFalse, "false", "Do not load debug scripts inside symbol files."},
2312 { eLoadScriptFromSymFileWarn, "warn", "Warn about debug scripts inside symbol files but do not load them."},
2317 static OptionEnumValueElement
2318 g_memory_module_load_level_values[] =
2320 { eMemoryModuleLoadLevelMinimal, "minimal" , "Load minimal information when loading modules from memory. Currently this setting loads sections only."},
2321 { eMemoryModuleLoadLevelPartial, "partial" , "Load partial information when loading modules from memory. Currently this setting loads sections and function bounds."},
2322 { eMemoryModuleLoadLevelComplete, "complete", "Load complete information when loading modules from memory. Currently this setting loads sections and all symbols."},
2326 static PropertyDefinition
2329 { "default-arch" , OptionValue::eTypeArch , true , 0 , NULL, NULL, "Default architecture to choose, when there's a choice." },
2330 { "expr-prefix" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2331 { "prefer-dynamic-value" , OptionValue::eTypeEnum , false, eNoDynamicValues , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2332 { "enable-synthetic-value" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Should synthetic values be used by default whenever available." },
2333 { "skip-prologue" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2334 { "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 "
2335 "where it exists on the current system. It consists of an array of duples, the first element of each duple is "
2336 "some part (starting at the root) of the path to the file when it was built, "
2337 "and the second is where the remainder of the original build hierarchy is rooted on the local system. "
2338 "Each element of the array is checked in order and the first one that results in a match wins." },
2339 { "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." },
2340 { "debug-file-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , NULL, NULL, "List of directories to be searched when locating debug symbol files." },
2341 { "max-children-count" , OptionValue::eTypeSInt64 , false, 256 , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2342 { "max-string-summary-length" , OptionValue::eTypeSInt64 , false, 1024 , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2343 { "max-memory-read-size" , OptionValue::eTypeSInt64 , false, 1024 , NULL, NULL, "Maximum number of bytes that 'memory read' will fetch before --force must be specified." },
2344 { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean , false, true , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2345 { "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." },
2346 { "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." },
2347 { "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." },
2348 { "inherit-env" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2349 { "input-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2350 { "output-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2351 { "error-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2352 { "disable-aslr" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2353 { "disable-stdio" , OptionValue::eTypeBoolean , false, false , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2354 { "inline-breakpoint-strategy" , OptionValue::eTypeEnum , false, eInlineBreakpointsHeaders , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2355 "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. "
2356 "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2357 "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2358 "Always checking for inlined breakpoint locations can be expensive (memory and time), so we try to minimize the "
2359 "times we look for inlined locations. This setting allows you to control exactly which strategy is used when settings "
2360 "file and line breakpoints." },
2361 // 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.
2362 { "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." },
2363 { "use-hex-immediates" , OptionValue::eTypeBoolean , false, true, NULL, NULL, "Show immediates in disassembly as hexadecimal." },
2364 { "hex-immediate-style" , OptionValue::eTypeEnum , false, Disassembler::eHexStyleC, NULL, g_hex_immediate_style_values, "Which style to use for printing hexadecimal disassembly values." },
2365 { "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." },
2366 { "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." },
2367 { "memory-module-load-level" , OptionValue::eTypeEnum , false, eMemoryModuleLoadLevelComplete, NULL, g_memory_module_load_level_values,
2368 "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. "
2369 "This setting helps users control how much information gets loaded when loading modules from memory."
2370 "'complete' is the default value for this setting which will load all sections and symbols by reading them from memory (slowest, most accurate). "
2371 "'partial' will load sections and attempt to find function bounds without downloading the symbol table (faster, still accurate, missing symbol names). "
2372 "'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). " },
2373 { NULL , OptionValue::eTypeInvalid , false, 0 , NULL, NULL, NULL }
2377 ePropertyDefaultArch,
2378 ePropertyExprPrefix,
2379 ePropertyPreferDynamic,
2380 ePropertyEnableSynthetic,
2381 ePropertySkipPrologue,
2383 ePropertyExecutableSearchPaths,
2384 ePropertyDebugFileSearchPaths,
2385 ePropertyMaxChildrenCount,
2386 ePropertyMaxSummaryLength,
2387 ePropertyMaxMemReadSize,
2388 ePropertyBreakpointUseAvoidList,
2392 ePropertyInheritEnv,
2394 ePropertyOutputPath,
2396 ePropertyDisableASLR,
2397 ePropertyDisableSTDIO,
2398 ePropertyInlineStrategy,
2399 ePropertyDisassemblyFlavor,
2400 ePropertyUseHexImmediates,
2401 ePropertyHexImmediateStyle,
2402 ePropertyUseFastStepping,
2403 ePropertyLoadScriptFromSymbolFile,
2404 ePropertyMemoryModuleLoadLevel
2408 class TargetOptionValueProperties : public OptionValueProperties
2411 TargetOptionValueProperties (const ConstString &name) :
2412 OptionValueProperties (name),
2414 m_got_host_env (false)
2418 // This constructor is used when creating TargetOptionValueProperties when it
2419 // is part of a new lldb_private::Target instance. It will copy all current
2420 // global property values as needed
2421 TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
2422 OptionValueProperties(*target_properties_sp->GetValueProperties()),
2424 m_got_host_env (false)
2428 virtual const Property *
2429 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
2431 // When gettings the value for a key from the target options, we will always
2432 // try and grab the setting from the current target if there is one. Else we just
2433 // use the one from this instance.
2434 if (idx == ePropertyEnvVars)
2435 GetHostEnvironmentIfNeeded ();
2439 Target *target = exe_ctx->GetTargetPtr();
2442 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
2443 if (this != target_properties)
2444 return target_properties->ProtectedGetPropertyAtIndex (idx);
2447 return ProtectedGetPropertyAtIndex (idx);
2453 return m_target->shared_from_this();
2459 GetHostEnvironmentIfNeeded () const
2461 if (!m_got_host_env)
2465 m_got_host_env = true;
2466 const uint32_t idx = ePropertyInheritEnv;
2467 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
2469 PlatformSP platform_sp (m_target->GetPlatform());
2473 if (platform_sp->GetEnvironment(env))
2475 OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
2478 const bool can_replace = false;
2479 const size_t envc = env.GetSize();
2480 for (size_t idx=0; idx<envc; idx++)
2482 const char *env_entry = env.GetStringAtIndex (idx);
2485 const char *equal_pos = ::strchr(env_entry, '=');
2487 // It is ok to have environment variables with no values
2488 const char *value = NULL;
2491 key.SetCStringWithLength(env_entry, equal_pos - env_entry);
2493 value = equal_pos + 1;
2497 key.SetCString(env_entry);
2499 // Don't allow existing keys to be replaced with ones we get from the platform environment
2500 env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
2511 mutable bool m_got_host_env;
2514 TargetProperties::TargetProperties (Target *target) :
2519 m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
2523 m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
2524 m_collection_sp->Initialize(g_properties);
2525 m_collection_sp->AppendProperty(ConstString("process"),
2526 ConstString("Settings specify to processes."),
2528 Process::GetGlobalProperties()->GetValueProperties());
2532 TargetProperties::~TargetProperties ()
2536 TargetProperties::GetDefaultArchitecture () const
2538 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2540 return value->GetCurrentValue();
2545 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
2547 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2549 return value->SetCurrentValue(arch, true);
2552 lldb::DynamicValueType
2553 TargetProperties::GetPreferDynamicValue() const
2555 const uint32_t idx = ePropertyPreferDynamic;
2556 return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2560 TargetProperties::GetDisableASLR () const
2562 const uint32_t idx = ePropertyDisableASLR;
2563 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2567 TargetProperties::SetDisableASLR (bool b)
2569 const uint32_t idx = ePropertyDisableASLR;
2570 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2574 TargetProperties::GetDisableSTDIO () const
2576 const uint32_t idx = ePropertyDisableSTDIO;
2577 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2581 TargetProperties::SetDisableSTDIO (bool b)
2583 const uint32_t idx = ePropertyDisableSTDIO;
2584 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2588 TargetProperties::GetDisassemblyFlavor () const
2590 const uint32_t idx = ePropertyDisassemblyFlavor;
2591 const char *return_value;
2593 x86DisassemblyFlavor flavor_value = (x86DisassemblyFlavor) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2594 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
2595 return return_value;
2599 TargetProperties::GetInlineStrategy () const
2601 const uint32_t idx = ePropertyInlineStrategy;
2602 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2606 TargetProperties::GetArg0 () const
2608 const uint32_t idx = ePropertyArg0;
2609 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
2613 TargetProperties::SetArg0 (const char *arg)
2615 const uint32_t idx = ePropertyArg0;
2616 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
2620 TargetProperties::GetRunArguments (Args &args) const
2622 const uint32_t idx = ePropertyRunArgs;
2623 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
2627 TargetProperties::SetRunArguments (const Args &args)
2629 const uint32_t idx = ePropertyRunArgs;
2630 m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
2634 TargetProperties::GetEnvironmentAsArgs (Args &env) const
2636 const uint32_t idx = ePropertyEnvVars;
2637 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
2641 TargetProperties::GetSkipPrologue() const
2643 const uint32_t idx = ePropertySkipPrologue;
2644 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2648 TargetProperties::GetSourcePathMap () const
2650 const uint32_t idx = ePropertySourceMap;
2651 OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
2652 assert(option_value);
2653 return option_value->GetCurrentValue();
2657 TargetProperties::GetExecutableSearchPaths ()
2659 const uint32_t idx = ePropertyExecutableSearchPaths;
2660 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2661 assert(option_value);
2662 return option_value->GetCurrentValue();
2666 TargetProperties::GetDebugFileSearchPaths ()
2668 const uint32_t idx = ePropertyDebugFileSearchPaths;
2669 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2670 assert(option_value);
2671 return option_value->GetCurrentValue();
2675 TargetProperties::GetEnableSyntheticValue () const
2677 const uint32_t idx = ePropertyEnableSynthetic;
2678 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2682 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
2684 const uint32_t idx = ePropertyMaxChildrenCount;
2685 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2689 TargetProperties::GetMaximumSizeOfStringSummary() const
2691 const uint32_t idx = ePropertyMaxSummaryLength;
2692 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2696 TargetProperties::GetMaximumMemReadSize () const
2698 const uint32_t idx = ePropertyMaxMemReadSize;
2699 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2703 TargetProperties::GetStandardInputPath () const
2705 const uint32_t idx = ePropertyInputPath;
2706 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2710 TargetProperties::SetStandardInputPath (const char *p)
2712 const uint32_t idx = ePropertyInputPath;
2713 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2717 TargetProperties::GetStandardOutputPath () const
2719 const uint32_t idx = ePropertyOutputPath;
2720 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2724 TargetProperties::SetStandardOutputPath (const char *p)
2726 const uint32_t idx = ePropertyOutputPath;
2727 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2731 TargetProperties::GetStandardErrorPath () const
2733 const uint32_t idx = ePropertyErrorPath;
2734 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
2738 TargetProperties::GetExpressionPrefixContentsAsCString ()
2740 const uint32_t idx = ePropertyExprPrefix;
2741 OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
2744 const bool null_terminate = true;
2745 DataBufferSP data_sp(file->GetFileContents(null_terminate));
2747 return (const char *) data_sp->GetBytes();
2753 TargetProperties::SetStandardErrorPath (const char *p)
2755 const uint32_t idx = ePropertyErrorPath;
2756 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2760 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
2762 const uint32_t idx = ePropertyBreakpointUseAvoidList;
2763 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2767 TargetProperties::GetUseHexImmediates () const
2769 const uint32_t idx = ePropertyUseHexImmediates;
2770 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2774 TargetProperties::GetUseFastStepping () const
2776 const uint32_t idx = ePropertyUseFastStepping;
2777 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2780 LoadScriptFromSymFile
2781 TargetProperties::GetLoadScriptFromSymbolFile () const
2783 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
2784 return (LoadScriptFromSymFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
2787 Disassembler::HexImmediateStyle
2788 TargetProperties::GetHexImmediateStyle () const
2790 const uint32_t idx = ePropertyHexImmediateStyle;
2791 return (Disassembler::HexImmediateStyle)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
2794 MemoryModuleLoadLevel
2795 TargetProperties::GetMemoryModuleLoadLevel() const
2797 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
2798 return (MemoryModuleLoadLevel)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
2802 const TargetPropertiesSP &
2803 Target::GetGlobalProperties()
2805 static TargetPropertiesSP g_settings_sp;
2808 g_settings_sp.reset (new TargetProperties (NULL));
2810 return g_settings_sp;
2814 Target::TargetEventData::GetFlavorString ()
2816 static ConstString g_flavor ("Target::TargetEventData");
2821 Target::TargetEventData::GetFlavor () const
2823 return TargetEventData::GetFlavorString ();
2826 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
2828 m_target_sp (new_target_sp)
2832 Target::TargetEventData::~TargetEventData()
2838 Target::TargetEventData::Dump (Stream *s) const
2844 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
2848 const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
2850 target_sp = data->m_target_sp;
2855 const Target::TargetEventData *
2856 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
2860 const EventData *event_data = event_ptr->GetData();
2861 if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
2862 return static_cast <const TargetEventData *> (event_ptr->GetData());