1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Target/Target.h"
14 // Other libraries and framework includes
16 #include "lldb/Breakpoint/BreakpointResolver.h"
17 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
18 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
19 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
20 #include "lldb/Breakpoint/BreakpointResolverName.h"
21 #include "lldb/Breakpoint/Watchpoint.h"
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/Event.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/Module.h"
26 #include "lldb/Core/ModuleSpec.h"
27 #include "lldb/Core/Section.h"
28 #include "lldb/Core/SourceManager.h"
29 #include "lldb/Core/State.h"
30 #include "lldb/Core/StreamFile.h"
31 #include "lldb/Core/StreamString.h"
32 #include "lldb/Core/Timer.h"
33 #include "lldb/Core/ValueObject.h"
34 #include "lldb/Expression/ClangASTSource.h"
35 #include "lldb/Expression/ClangPersistentVariables.h"
36 #include "lldb/Expression/ClangUserExpression.h"
37 #include "lldb/Expression/ClangModulesDeclVendor.h"
38 #include "lldb/Host/FileSpec.h"
39 #include "lldb/Host/Host.h"
40 #include "lldb/Interpreter/CommandInterpreter.h"
41 #include "lldb/Interpreter/CommandReturnObject.h"
42 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
43 #include "lldb/Interpreter/OptionValues.h"
44 #include "lldb/Interpreter/Property.h"
45 #include "lldb/Symbol/ClangASTContext.h"
46 #include "lldb/Symbol/ObjectFile.h"
47 #include "lldb/Target/LanguageRuntime.h"
48 #include "lldb/Target/ObjCLanguageRuntime.h"
49 #include "lldb/Target/Process.h"
50 #include "lldb/Target/SectionLoadList.h"
51 #include "lldb/Target/StackFrame.h"
52 #include "lldb/Target/SystemRuntime.h"
53 #include "lldb/Target/Thread.h"
54 #include "lldb/Target/ThreadSpec.h"
57 using namespace lldb_private;
60 Target::GetStaticBroadcasterClass ()
62 static ConstString class_name ("lldb.target");
66 //----------------------------------------------------------------------
68 //----------------------------------------------------------------------
69 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp, bool is_dummy_target) :
70 TargetProperties (this),
71 Broadcaster (&debugger, Target::GetStaticBroadcasterClass().AsCString()),
72 ExecutionContextScope (),
73 m_debugger (debugger),
74 m_platform_sp (platform_sp),
75 m_mutex (Mutex::eMutexTypeRecursive),
78 m_section_load_history (),
79 m_breakpoint_list (false),
80 m_internal_breakpoint_list (true),
83 m_search_filter_sp (),
84 m_image_search_paths (ImageSearchPathsChanged, this),
85 m_scratch_ast_context_ap (),
86 m_scratch_ast_source_ap (),
88 m_persistent_variables (new ClangPersistentVariables),
89 m_source_manager_ap(),
91 m_stop_hook_next_id (0),
93 m_suppress_stop_hooks (false),
94 m_is_dummy_target(is_dummy_target)
97 SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
98 SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
99 SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
100 SetEventName (eBroadcastBitWatchpointChanged, "watchpoint-changed");
101 SetEventName (eBroadcastBitSymbolsLoaded, "symbols-loaded");
103 CheckInWithManager();
105 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
107 log->Printf ("%p Target::Target()", static_cast<void*>(this));
108 if (m_arch.IsValid())
110 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::Target created with architecture %s (%s)", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
115 Target::PrimeFromDummyTarget(Target *target)
120 m_stop_hooks = target->m_stop_hooks;
122 for (BreakpointSP breakpoint_sp : target->m_breakpoint_list.Breakpoints())
124 if (breakpoint_sp->IsInternal())
127 BreakpointSP new_bp (new Breakpoint (*this, *breakpoint_sp.get()));
128 AddBreakpoint (new_bp, false);
132 //----------------------------------------------------------------------
134 //----------------------------------------------------------------------
137 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
139 log->Printf ("%p Target::~Target()", static_cast<void*>(this));
140 DeleteCurrentProcess ();
144 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
146 // s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
147 if (description_level != lldb::eDescriptionLevelBrief)
150 s->PutCString("Target\n");
153 m_breakpoint_list.Dump(s);
154 m_internal_breakpoint_list.Dump(s);
159 Module *exe_module = GetExecutableModulePointer();
161 s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
163 s->PutCString ("No executable module.");
168 Target::CleanupProcess ()
170 // Do any cleanup of the target we need to do between process instances.
171 // NB It is better to do this before destroying the process in case the
172 // clean up needs some help from the process.
173 m_breakpoint_list.ClearAllBreakpointSites();
174 m_internal_breakpoint_list.ClearAllBreakpointSites();
175 // Disable watchpoints just on the debugger side.
176 Mutex::Locker locker;
177 this->GetWatchpointList().GetListMutex(locker);
178 DisableAllWatchpoints(false);
179 ClearAllWatchpointHitCounts();
180 ClearAllWatchpointHistoricValues();
184 Target::DeleteCurrentProcess ()
186 if (m_process_sp.get())
188 m_section_load_history.Clear();
189 if (m_process_sp->IsAlive())
190 m_process_sp->Destroy(false);
192 m_process_sp->Finalize();
196 m_process_sp.reset();
200 const lldb::ProcessSP &
201 Target::CreateProcess (Listener &listener, const char *plugin_name, const FileSpec *crash_file)
203 DeleteCurrentProcess ();
204 m_process_sp = Process::FindPlugin(*this, plugin_name, listener, crash_file);
208 const lldb::ProcessSP &
209 Target::GetProcessSP () const
217 Mutex::Locker locker (m_mutex);
219 DeleteCurrentProcess ();
220 m_platform_sp.reset();
223 m_section_load_history.Clear();
224 const bool notify = false;
225 m_breakpoint_list.RemoveAll(notify);
226 m_internal_breakpoint_list.RemoveAll(notify);
227 m_last_created_breakpoint.reset();
228 m_last_created_watchpoint.reset();
229 m_search_filter_sp.reset();
230 m_image_search_paths.Clear(notify);
231 m_persistent_variables->Clear();
232 m_stop_hooks.clear();
233 m_stop_hook_next_id = 0;
234 m_suppress_stop_hooks = false;
239 Target::GetBreakpointList(bool internal)
242 return m_internal_breakpoint_list;
244 return m_breakpoint_list;
247 const BreakpointList &
248 Target::GetBreakpointList(bool internal) const
251 return m_internal_breakpoint_list;
253 return m_breakpoint_list;
257 Target::GetBreakpointByID (break_id_t break_id)
261 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
262 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
264 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
270 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
271 const FileSpecList *source_file_spec_list,
272 RegularExpression &source_regex,
275 LazyBool move_to_nearest_code)
277 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list));
278 if (move_to_nearest_code == eLazyBoolCalculate)
279 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
280 BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex (NULL, source_regex, !static_cast<bool>(move_to_nearest_code)));
281 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
286 Target::CreateBreakpoint (const FileSpecList *containingModules,
287 const FileSpec &file,
289 LazyBool check_inlines,
290 LazyBool skip_prologue,
293 LazyBool move_to_nearest_code)
295 if (check_inlines == eLazyBoolCalculate)
297 const InlineStrategy inline_strategy = GetInlineStrategy();
298 switch (inline_strategy)
300 case eInlineBreakpointsNever:
301 check_inlines = eLazyBoolNo;
304 case eInlineBreakpointsHeaders:
305 if (file.IsSourceImplementationFile())
306 check_inlines = eLazyBoolNo;
308 check_inlines = eLazyBoolYes;
311 case eInlineBreakpointsAlways:
312 check_inlines = eLazyBoolYes;
316 SearchFilterSP filter_sp;
317 if (check_inlines == eLazyBoolNo)
319 // Not checking for inlines, we are looking only for matching compile units
320 FileSpecList compile_unit_list;
321 compile_unit_list.Append (file);
322 filter_sp = GetSearchFilterForModuleAndCUList (containingModules, &compile_unit_list);
326 filter_sp = GetSearchFilterForModuleList (containingModules);
328 if (skip_prologue == eLazyBoolCalculate)
329 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
330 if (move_to_nearest_code == eLazyBoolCalculate)
331 move_to_nearest_code = GetMoveToNearestCode() ? eLazyBoolYes : eLazyBoolNo;
333 BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL,
338 !static_cast<bool>(move_to_nearest_code)));
339 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
344 Target::CreateBreakpoint (lldb::addr_t addr, bool internal, bool hardware)
347 // Attempt to resolve our load address if possible, though it is ok if
348 // it doesn't resolve to section/offset.
350 // Try and resolve as a load address if possible
351 GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
352 if (!so_addr.IsValid())
354 // The address didn't resolve, so just set this as an absolute address
355 so_addr.SetOffset (addr);
357 BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal, hardware));
362 Target::CreateBreakpoint (Address &addr, bool internal, bool hardware)
364 SearchFilterSP filter_sp(new SearchFilterForUnconstrainedSearches (shared_from_this()));
365 BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
366 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, false);
370 Target::CreateBreakpoint (const FileSpecList *containingModules,
371 const FileSpecList *containingSourceFiles,
372 const char *func_name,
373 uint32_t func_name_type_mask,
374 LazyBool skip_prologue,
381 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
383 if (skip_prologue == eLazyBoolCalculate)
384 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
386 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
391 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
397 Target::CreateBreakpoint (const FileSpecList *containingModules,
398 const FileSpecList *containingSourceFiles,
399 const std::vector<std::string> &func_names,
400 uint32_t func_name_type_mask,
401 LazyBool skip_prologue,
406 size_t num_names = func_names.size();
409 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
411 if (skip_prologue == eLazyBoolCalculate)
412 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
414 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
418 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
424 Target::CreateBreakpoint (const FileSpecList *containingModules,
425 const FileSpecList *containingSourceFiles,
426 const char *func_names[],
428 uint32_t func_name_type_mask,
429 LazyBool skip_prologue,
436 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
438 if (skip_prologue == eLazyBoolCalculate)
439 skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
441 BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
446 bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
452 Target::GetSearchFilterForModule (const FileSpec *containingModule)
454 SearchFilterSP filter_sp;
455 if (containingModule != NULL)
457 // TODO: We should look into sharing module based search filters
458 // across many breakpoints like we do for the simple target based one
459 filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule));
463 if (m_search_filter_sp.get() == NULL)
464 m_search_filter_sp.reset (new SearchFilterForUnconstrainedSearches (shared_from_this()));
465 filter_sp = m_search_filter_sp;
471 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules)
473 SearchFilterSP filter_sp;
474 if (containingModules && containingModules->GetSize() != 0)
476 // TODO: We should look into sharing module based search filters
477 // across many breakpoints like we do for the simple target based one
478 filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules));
482 if (m_search_filter_sp.get() == NULL)
483 m_search_filter_sp.reset (new SearchFilterForUnconstrainedSearches (shared_from_this()));
484 filter_sp = m_search_filter_sp;
490 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules,
491 const FileSpecList *containingSourceFiles)
493 if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0)
494 return GetSearchFilterForModuleList(containingModules);
496 SearchFilterSP filter_sp;
497 if (containingModules == NULL)
499 // We could make a special "CU List only SearchFilter". Better yet was if these could be composable,
500 // but that will take a little reworking.
502 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles));
506 filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles));
512 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
513 const FileSpecList *containingSourceFiles,
514 RegularExpression &func_regex,
515 LazyBool skip_prologue,
519 SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
521 (skip_prologue == eLazyBoolCalculate) ? GetSkipPrologue()
522 : static_cast<bool>(skip_prologue);
523 BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
527 return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
531 Target::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal, Args *additional_args, Error *error)
533 BreakpointSP exc_bkpt_sp = LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal);
534 if (exc_bkpt_sp && additional_args)
536 Breakpoint::BreakpointPreconditionSP precondition_sp = exc_bkpt_sp->GetPrecondition();
537 if (precondition_sp && additional_args)
540 *error = precondition_sp->ConfigurePrecondition(*additional_args);
542 precondition_sp->ConfigurePrecondition(*additional_args);
549 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal, bool request_hardware, bool resolve_indirect_symbols)
552 if (filter_sp && resolver_sp)
554 bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp, request_hardware, resolve_indirect_symbols));
555 resolver_sp->SetBreakpoint (bp_sp.get());
556 AddBreakpoint (bp_sp, internal);
562 Target::AddBreakpoint (lldb::BreakpointSP bp_sp, bool internal)
567 m_internal_breakpoint_list.Add (bp_sp, false);
569 m_breakpoint_list.Add (bp_sp, true);
571 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
575 bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
576 log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, bp_sp->IsInternal() ? "yes" : "no", s.GetData());
579 bp_sp->ResolveBreakpoint();
583 m_last_created_breakpoint = bp_sp;
588 Target::ProcessIsValid()
590 return (m_process_sp && m_process_sp->IsAlive());
594 CheckIfWatchpointsExhausted(Target *target, Error &error)
596 uint32_t num_supported_hardware_watchpoints;
597 Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints);
600 uint32_t num_current_watchpoints = target->GetWatchpointList().GetSize();
601 if (num_current_watchpoints >= num_supported_hardware_watchpoints)
602 error.SetErrorStringWithFormat("number of supported hardware watchpoints (%u) has been reached",
603 num_supported_hardware_watchpoints);
608 // See also Watchpoint::SetWatchpointType(uint32_t type) and
609 // the OptionGroupWatchpoint::WatchType enum type.
611 Target::CreateWatchpoint(lldb::addr_t addr, size_t size, const ClangASTType *type, uint32_t kind, Error &error)
613 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
615 log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64 " type = %u)\n",
616 __FUNCTION__, addr, (uint64_t)size, kind);
619 if (!ProcessIsValid())
621 error.SetErrorString("process is not alive");
625 if (addr == LLDB_INVALID_ADDRESS || size == 0)
628 error.SetErrorString("cannot set a watchpoint with watch_size of 0");
630 error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
634 if (!LLDB_WATCH_TYPE_IS_VALID(kind))
636 error.SetErrorStringWithFormat ("invalid watchpoint type: %d", kind);
639 // Currently we only support one watchpoint per address, with total number
640 // of watchpoints limited by the hardware which the inferior is running on.
642 // Grab the list mutex while doing operations.
643 const bool notify = false; // Don't notify about all the state changes we do on creating the watchpoint.
644 Mutex::Locker locker;
645 this->GetWatchpointList().GetListMutex(locker);
646 WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
649 size_t old_size = matched_sp->GetByteSize();
651 (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
652 (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
653 // Return the existing watchpoint if both size and type match.
654 if (size == old_size && kind == old_type)
657 wp_sp->SetEnabled(false, notify);
661 // Nil the matched watchpoint; we will be creating a new one.
662 m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
663 m_watchpoint_list.Remove(matched_sp->GetID(), true);
669 wp_sp.reset(new Watchpoint(*this, addr, size, type));
670 wp_sp->SetWatchpointType(kind, notify);
671 m_watchpoint_list.Add (wp_sp, true);
674 error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
676 log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
678 error.Success() ? "succeeded" : "failed",
683 // Enabling the watchpoint on the device side failed.
684 // Remove the said watchpoint from the list maintained by the target instance.
685 m_watchpoint_list.Remove (wp_sp->GetID(), true);
686 // See if we could provide more helpful error message.
687 if (!CheckIfWatchpointsExhausted(this, error))
689 if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
690 error.SetErrorStringWithFormat("watch size of %" PRIu64 " is not supported", (uint64_t)size);
695 m_last_created_watchpoint = wp_sp;
700 Target::RemoveAllBreakpoints (bool internal_also)
702 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
704 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
706 m_breakpoint_list.RemoveAll (true);
708 m_internal_breakpoint_list.RemoveAll (false);
710 m_last_created_breakpoint.reset();
714 Target::DisableAllBreakpoints (bool internal_also)
716 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
718 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
720 m_breakpoint_list.SetEnabledAll (false);
722 m_internal_breakpoint_list.SetEnabledAll (false);
726 Target::EnableAllBreakpoints (bool internal_also)
728 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
730 log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
732 m_breakpoint_list.SetEnabledAll (true);
734 m_internal_breakpoint_list.SetEnabledAll (true);
738 Target::RemoveBreakpointByID (break_id_t break_id)
740 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
742 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
744 if (DisableBreakpointByID (break_id))
746 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
747 m_internal_breakpoint_list.Remove(break_id, false);
750 if (m_last_created_breakpoint)
752 if (m_last_created_breakpoint->GetID() == break_id)
753 m_last_created_breakpoint.reset();
755 m_breakpoint_list.Remove(break_id, true);
763 Target::DisableBreakpointByID (break_id_t break_id)
765 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
767 log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
771 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
772 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
774 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
777 bp_sp->SetEnabled (false);
784 Target::EnableBreakpointByID (break_id_t break_id)
786 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
788 log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
791 LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
795 if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
796 bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
798 bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
802 bp_sp->SetEnabled (true);
808 // The flag 'end_to_end', default to true, signifies that the operation is
809 // performed end to end, for both the debugger and the debuggee.
811 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
812 // to end operations.
814 Target::RemoveAllWatchpoints (bool end_to_end)
816 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
818 log->Printf ("Target::%s\n", __FUNCTION__);
821 m_watchpoint_list.RemoveAll(true);
825 // Otherwise, it's an end to end operation.
827 if (!ProcessIsValid())
830 size_t num_watchpoints = m_watchpoint_list.GetSize();
831 for (size_t i = 0; i < num_watchpoints; ++i)
833 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
837 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
841 m_watchpoint_list.RemoveAll (true);
842 m_last_created_watchpoint.reset();
843 return true; // Success!
846 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
849 Target::DisableAllWatchpoints (bool end_to_end)
851 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
853 log->Printf ("Target::%s\n", __FUNCTION__);
856 m_watchpoint_list.SetEnabledAll(false);
860 // Otherwise, it's an end to end operation.
862 if (!ProcessIsValid())
865 size_t num_watchpoints = m_watchpoint_list.GetSize();
866 for (size_t i = 0; i < num_watchpoints; ++i)
868 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
872 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
876 return true; // Success!
879 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
882 Target::EnableAllWatchpoints (bool end_to_end)
884 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
886 log->Printf ("Target::%s\n", __FUNCTION__);
889 m_watchpoint_list.SetEnabledAll(true);
893 // Otherwise, it's an end to end operation.
895 if (!ProcessIsValid())
898 size_t num_watchpoints = m_watchpoint_list.GetSize();
899 for (size_t i = 0; i < num_watchpoints; ++i)
901 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
905 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
909 return true; // Success!
912 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
914 Target::ClearAllWatchpointHitCounts ()
916 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
918 log->Printf ("Target::%s\n", __FUNCTION__);
920 size_t num_watchpoints = m_watchpoint_list.GetSize();
921 for (size_t i = 0; i < num_watchpoints; ++i)
923 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
927 wp_sp->ResetHitCount();
929 return true; // Success!
932 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
934 Target::ClearAllWatchpointHistoricValues ()
936 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
938 log->Printf ("Target::%s\n", __FUNCTION__);
940 size_t num_watchpoints = m_watchpoint_list.GetSize();
941 for (size_t i = 0; i < num_watchpoints; ++i)
943 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
947 wp_sp->ResetHistoricValues();
949 return true; // Success!
952 // Assumption: Caller holds the list mutex lock for m_watchpoint_list
953 // during these operations.
955 Target::IgnoreAllWatchpoints (uint32_t ignore_count)
957 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
959 log->Printf ("Target::%s\n", __FUNCTION__);
961 if (!ProcessIsValid())
964 size_t num_watchpoints = m_watchpoint_list.GetSize();
965 for (size_t i = 0; i < num_watchpoints; ++i)
967 WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
971 wp_sp->SetIgnoreCount(ignore_count);
973 return true; // Success!
976 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
978 Target::DisableWatchpointByID (lldb::watch_id_t watch_id)
980 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
982 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
984 if (!ProcessIsValid())
987 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
990 Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
994 // Else, fallthrough.
999 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1001 Target::EnableWatchpointByID (lldb::watch_id_t watch_id)
1003 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1005 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1007 if (!ProcessIsValid())
1010 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
1013 Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
1017 // Else, fallthrough.
1022 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1024 Target::RemoveWatchpointByID (lldb::watch_id_t watch_id)
1026 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1028 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1030 WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
1031 if (watch_to_remove_sp == m_last_created_watchpoint)
1032 m_last_created_watchpoint.reset();
1034 if (DisableWatchpointByID (watch_id))
1036 m_watchpoint_list.Remove(watch_id, true);
1042 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
1044 Target::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
1046 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
1048 log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
1050 if (!ProcessIsValid())
1053 WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
1056 wp_sp->SetIgnoreCount(ignore_count);
1063 Target::GetExecutableModule ()
1065 // search for the first executable in the module list
1066 for (size_t i = 0; i < m_images.GetSize(); ++i)
1068 ModuleSP module_sp = m_images.GetModuleAtIndex (i);
1069 lldb_private::ObjectFile * obj = module_sp->GetObjectFile();
1072 if (obj->GetType() == ObjectFile::Type::eTypeExecutable)
1075 // as fall back return the first module loaded
1076 return m_images.GetModuleAtIndex (0);
1080 Target::GetExecutableModulePointer ()
1082 return GetExecutableModule().get();
1086 LoadScriptingResourceForModule (const ModuleSP &module_sp, Target *target)
1089 StreamString feedback_stream;
1090 if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error, &feedback_stream))
1092 if (error.AsCString())
1093 target->GetDebugger().GetErrorFile()->Printf("unable to load scripting data for module %s - error reported was %s\n",
1094 module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1097 if (feedback_stream.GetSize())
1098 target->GetDebugger().GetErrorFile()->Printf("%s\n",
1099 feedback_stream.GetData());
1103 Target::ClearModules(bool delete_locations)
1105 ModulesDidUnload (m_images, delete_locations);
1106 m_section_load_history.Clear();
1108 m_scratch_ast_context_ap.reset();
1109 m_scratch_ast_source_ap.reset();
1110 m_ast_importer_ap.reset();
1116 // When a process exec's we need to know about it so we can do some cleanup.
1117 m_breakpoint_list.RemoveInvalidLocations(m_arch);
1118 m_internal_breakpoint_list.RemoveInvalidLocations(m_arch);
1122 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
1124 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1125 ClearModules(false);
1127 if (executable_sp.get())
1129 Timer scoped_timer (__PRETTY_FUNCTION__,
1130 "Target::SetExecutableModule (executable = '%s')",
1131 executable_sp->GetFileSpec().GetPath().c_str());
1133 m_images.Append(executable_sp); // The first image is our executable file
1135 // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
1136 if (!m_arch.IsValid())
1138 m_arch = executable_sp->GetArchitecture();
1140 log->Printf ("Target::SetExecutableModule setting architecture to %s (%s) based on executable file", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
1143 FileSpecList dependent_files;
1144 ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1146 if (executable_objfile && get_dependent_files)
1148 executable_objfile->GetDependentModules(dependent_files);
1149 for (uint32_t i=0; i<dependent_files.GetSize(); i++)
1151 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
1152 FileSpec platform_dependent_file_spec;
1154 m_platform_sp->GetFileWithUUID (dependent_file_spec, NULL, platform_dependent_file_spec);
1156 platform_dependent_file_spec = dependent_file_spec;
1158 ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
1159 ModuleSP image_module_sp(GetSharedModule (module_spec));
1160 if (image_module_sp.get())
1162 ObjectFile *objfile = image_module_sp->GetObjectFile();
1164 objfile->GetDependentModules(dependent_files);
1173 Target::SetArchitecture (const ArchSpec &arch_spec)
1175 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1176 if (m_arch.IsCompatibleMatch(arch_spec) || !m_arch.IsValid())
1178 // If we haven't got a valid arch spec, or the architectures are
1179 // compatible, so just update the architecture. Architectures can be
1180 // equal, yet the triple OS and vendor might change, so we need to do
1181 // the assignment here just in case.
1184 log->Printf ("Target::SetArchitecture setting architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1189 // If we have an executable file, try to reset the executable to the desired architecture
1191 log->Printf ("Target::SetArchitecture changing architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1193 ModuleSP executable_sp = GetExecutableModule ();
1196 // Need to do something about unsetting breakpoints.
1201 log->Printf("Target::SetArchitecture Trying to select executable file architecture %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1202 ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec);
1203 Error error = ModuleList::GetSharedModule (module_spec,
1205 &GetExecutableSearchPaths(),
1209 if (!error.Fail() && executable_sp)
1211 SetExecutableModule (executable_sp, true);
1220 Target::MergeArchitecture (const ArchSpec &arch_spec)
1222 if (arch_spec.IsValid())
1224 if (m_arch.IsCompatibleMatch(arch_spec))
1226 // The current target arch is compatible with "arch_spec", see if we
1227 // can improve our current architecture using bits from "arch_spec"
1229 // Merge bits from arch_spec into "merged_arch" and set our architecture
1230 ArchSpec merged_arch (m_arch);
1231 merged_arch.MergeFrom (arch_spec);
1232 return SetArchitecture(merged_arch);
1236 // The new architecture is different, we just need to replace it
1237 return SetArchitecture(arch_spec);
1244 Target::WillClearList (const ModuleList& module_list)
1249 Target::ModuleAdded (const ModuleList& module_list, const ModuleSP &module_sp)
1251 // A module is being added to this target for the first time
1254 ModuleList my_module_list;
1255 my_module_list.Append(module_sp);
1256 LoadScriptingResourceForModule(module_sp, this);
1257 ModulesDidLoad (my_module_list);
1262 Target::ModuleRemoved (const ModuleList& module_list, const ModuleSP &module_sp)
1264 // A module is being added to this target for the first time
1267 ModuleList my_module_list;
1268 my_module_list.Append(module_sp);
1269 ModulesDidUnload (my_module_list, false);
1274 Target::ModuleUpdated (const ModuleList& module_list, const ModuleSP &old_module_sp, const ModuleSP &new_module_sp)
1276 // A module is replacing an already added module
1278 m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1282 Target::ModulesDidLoad (ModuleList &module_list)
1284 if (m_valid && module_list.GetSize())
1286 m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1289 m_process_sp->ModulesDidLoad (module_list);
1291 BroadcastEvent (eBroadcastBitModulesLoaded, new TargetEventData (this->shared_from_this(), module_list));
1296 Target::SymbolsDidLoad (ModuleList &module_list)
1298 if (m_valid && module_list.GetSize())
1302 LanguageRuntime* runtime = m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1305 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime*)runtime;
1306 objc_runtime->SymbolsDidLoad(module_list);
1310 m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1311 BroadcastEvent (eBroadcastBitSymbolsLoaded, new TargetEventData (this->shared_from_this(), module_list));
1316 Target::ModulesDidUnload (ModuleList &module_list, bool delete_locations)
1318 if (m_valid && module_list.GetSize())
1320 UnloadModuleSections (module_list);
1321 m_breakpoint_list.UpdateBreakpoints (module_list, false, delete_locations);
1322 BroadcastEvent (eBroadcastBitModulesUnloaded, new TargetEventData (this->shared_from_this(), module_list));
1327 Target::ModuleIsExcludedForUnconstrainedSearches (const FileSpec &module_file_spec)
1329 if (GetBreakpointsConsultPlatformAvoidList())
1331 ModuleList matchingModules;
1332 ModuleSpec module_spec (module_file_spec);
1333 size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1335 // If there is more than one module for this file spec, only return true if ALL the modules are on the
1337 if (num_modules > 0)
1339 for (size_t i = 0; i < num_modules; i++)
1341 if (!ModuleIsExcludedForUnconstrainedSearches (matchingModules.GetModuleAtIndex(i)))
1351 Target::ModuleIsExcludedForUnconstrainedSearches (const lldb::ModuleSP &module_sp)
1353 if (GetBreakpointsConsultPlatformAvoidList())
1356 return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches (*this, module_sp);
1362 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
1364 SectionSP section_sp (addr.GetSection());
1367 // If the contents of this section are encrypted, the on-disk file is unusable. Read only from live memory.
1368 if (section_sp->IsEncrypted())
1370 error.SetErrorString("section is encrypted");
1373 ModuleSP module_sp (section_sp->GetModule());
1376 ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1379 size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
1386 error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
1389 error.SetErrorString("address isn't from a object file");
1392 error.SetErrorString("address isn't in a module");
1395 error.SetErrorString("address doesn't contain a section that points to a section in a object file");
1401 Target::ReadMemory (const Address& addr,
1402 bool prefer_file_cache,
1406 lldb::addr_t *load_addr_ptr)
1410 // if we end up reading this from process memory, we will fill this
1411 // with the actual load address
1413 *load_addr_ptr = LLDB_INVALID_ADDRESS;
1415 size_t bytes_read = 0;
1417 addr_t load_addr = LLDB_INVALID_ADDRESS;
1418 addr_t file_addr = LLDB_INVALID_ADDRESS;
1419 Address resolved_addr;
1420 if (!addr.IsSectionOffset())
1422 SectionLoadList §ion_load_list = GetSectionLoadList();
1423 if (section_load_list.IsEmpty())
1425 // No sections are loaded, so we must assume we are not running
1426 // yet and anything we are given is a file address.
1427 file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
1428 m_images.ResolveFileAddress (file_addr, resolved_addr);
1432 // We have at least one section loaded. This can be because
1433 // we have manually loaded some sections with "target modules load ..."
1434 // or because we have have a live process that has sections loaded
1435 // through the dynamic loader
1436 load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1437 section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1440 if (!resolved_addr.IsValid())
1441 resolved_addr = addr;
1444 if (prefer_file_cache)
1446 bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1451 if (ProcessIsValid())
1453 if (load_addr == LLDB_INVALID_ADDRESS)
1454 load_addr = resolved_addr.GetLoadAddress (this);
1456 if (load_addr == LLDB_INVALID_ADDRESS)
1458 ModuleSP addr_module_sp (resolved_addr.GetModule());
1459 if (addr_module_sp && addr_module_sp->GetFileSpec())
1460 error.SetErrorStringWithFormat("%s[0x%" PRIx64 "] can't be resolved, %s in not currently loaded",
1461 addr_module_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"),
1462 resolved_addr.GetFileAddress(),
1463 addr_module_sp->GetFileSpec().GetFilename().AsCString("<Unknonw>"));
1465 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
1469 bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1470 if (bytes_read != dst_len)
1472 if (error.Success())
1474 if (bytes_read == 0)
1475 error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed", load_addr);
1477 error.SetErrorStringWithFormat("only %" PRIu64 " of %" PRIu64 " bytes were read from memory at 0x%" PRIx64, (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1483 *load_addr_ptr = load_addr;
1486 // If the address is not section offset we have an address that
1487 // doesn't resolve to any address in any currently loaded shared
1488 // libraries and we failed to read memory so there isn't anything
1489 // more we can do. If it is section offset, we might be able to
1490 // read cached memory from the object file.
1491 if (!resolved_addr.IsSectionOffset())
1496 if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1498 // If we didn't already try and read from the object file cache, then
1499 // try it after failing to read from the process.
1500 return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1506 Target::ReadCStringFromMemory (const Address& addr, std::string &out_str, Error &error)
1510 addr_t curr_addr = addr.GetLoadAddress(this);
1511 Address address(addr);
1514 size_t length = ReadCStringFromMemory (address, buf, sizeof(buf), error);
1517 out_str.append(buf, length);
1518 // If we got "length - 1" bytes, we didn't get the whole C string, we
1519 // need to read some more characters
1520 if (length == sizeof(buf) - 1)
1521 curr_addr += length;
1524 address = Address(curr_addr);
1526 return out_str.size();
1531 Target::ReadCStringFromMemory (const Address& addr, char *dst, size_t dst_max_len, Error &result_error)
1533 size_t total_cstr_len = 0;
1534 if (dst && dst_max_len)
1536 result_error.Clear();
1537 // NULL out everything just to be safe
1538 memset (dst, 0, dst_max_len);
1540 addr_t curr_addr = addr.GetLoadAddress(this);
1541 Address address(addr);
1543 // We could call m_process_sp->GetMemoryCacheLineSize() but I don't
1544 // think this really needs to be tied to the memory cache subsystem's
1545 // cache line size, so leave this as a fixed constant.
1546 const size_t cache_line_size = 512;
1548 size_t bytes_left = dst_max_len - 1;
1549 char *curr_dst = dst;
1551 while (bytes_left > 0)
1553 addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1554 addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1555 size_t bytes_read = ReadMemory (address, false, curr_dst, bytes_to_read, error);
1557 if (bytes_read == 0)
1559 result_error = error;
1560 dst[total_cstr_len] = '\0';
1563 const size_t len = strlen(curr_dst);
1565 total_cstr_len += len;
1567 if (len < bytes_to_read)
1570 curr_dst += bytes_read;
1571 curr_addr += bytes_read;
1572 bytes_left -= bytes_read;
1573 address = Address(curr_addr);
1579 result_error.SetErrorString("invalid arguments");
1581 result_error.Clear();
1583 return total_cstr_len;
1587 Target::ReadScalarIntegerFromMemory (const Address& addr,
1588 bool prefer_file_cache,
1596 if (byte_size <= sizeof(uval))
1598 size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1599 if (bytes_read == byte_size)
1601 DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1602 lldb::offset_t offset = 0;
1604 scalar = data.GetMaxU32 (&offset, byte_size);
1606 scalar = data.GetMaxU64 (&offset, byte_size);
1609 scalar.SignExtend(byte_size * 8);
1615 error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1621 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1622 bool prefer_file_cache,
1623 size_t integer_byte_size,
1624 uint64_t fail_value,
1628 if (ReadScalarIntegerFromMemory (addr,
1634 return scalar.ULongLong(fail_value);
1639 Target::ReadPointerFromMemory (const Address& addr,
1640 bool prefer_file_cache,
1642 Address &pointer_addr)
1645 if (ReadScalarIntegerFromMemory (addr,
1647 m_arch.GetAddressByteSize(),
1652 addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1653 if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1655 SectionLoadList §ion_load_list = GetSectionLoadList();
1656 if (section_load_list.IsEmpty())
1658 // No sections are loaded, so we must assume we are not running
1659 // yet and anything we are given is a file address.
1660 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1664 // We have at least one section loaded. This can be because
1665 // we have manually loaded some sections with "target modules load ..."
1666 // or because we have have a live process that has sections loaded
1667 // through the dynamic loader
1668 section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1670 // We weren't able to resolve the pointer value, so just return
1671 // an address with no section
1672 if (!pointer_addr.IsValid())
1673 pointer_addr.SetOffset (pointer_vm_addr);
1682 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
1688 // First see if we already have this module in our module list. If we do, then we're done, we don't need
1689 // to consult the shared modules list. But only do this if we are passed a UUID.
1691 if (module_spec.GetUUID().IsValid())
1692 module_sp = m_images.FindFirstModule(module_spec);
1696 ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1697 bool did_create_module = false;
1699 // If there are image search path entries, try to use them first to acquire a suitable image.
1700 if (m_image_search_paths.GetSize())
1702 ModuleSpec transformed_spec (module_spec);
1703 if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
1705 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
1706 error = ModuleList::GetSharedModule (transformed_spec,
1708 &GetExecutableSearchPaths(),
1710 &did_create_module);
1716 // If we have a UUID, we can check our global shared module list in case
1717 // we already have it. If we don't have a valid UUID, then we can't since
1718 // the path in "module_spec" will be a platform path, and we will need to
1719 // let the platform find that file. For example, we could be asking for
1720 // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1721 // the local copy of "/usr/lib/dyld" since our platform could be a remote
1722 // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1724 if (module_spec.GetUUID().IsValid())
1726 // We have a UUID, it is OK to check the global module list...
1727 error = ModuleList::GetSharedModule (module_spec,
1729 &GetExecutableSearchPaths(),
1731 &did_create_module);
1736 // The platform is responsible for finding and caching an appropriate
1737 // module in the shared module cache.
1740 error = m_platform_sp->GetSharedModule (module_spec,
1743 &GetExecutableSearchPaths(),
1745 &did_create_module);
1749 error.SetErrorString("no platform is currently set");
1754 // We found a module that wasn't in our target list. Let's make sure that there wasn't an equivalent
1755 // module in the list already, and if there was, let's remove it.
1758 ObjectFile *objfile = module_sp->GetObjectFile();
1761 switch (objfile->GetType())
1763 case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of a program's execution state
1764 case ObjectFile::eTypeExecutable: /// A normal executable
1765 case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker executable
1766 case ObjectFile::eTypeObjectFile: /// An intermediate object file
1767 case ObjectFile::eTypeSharedLibrary: /// A shared library that can be used during execution
1769 case ObjectFile::eTypeDebugInfo: /// An object file that contains only debug information
1771 error_ptr->SetErrorString("debug info files aren't valid target modules, please specify an executable");
1773 case ObjectFile::eTypeStubLibrary: /// A library that can be linked against but not used for execution
1775 error_ptr->SetErrorString("stub libraries aren't valid target modules, please specify an executable");
1779 error_ptr->SetErrorString("unsupported file type, please specify an executable");
1782 // GetSharedModule is not guaranteed to find the old shared module, for instance
1783 // in the common case where you pass in the UUID, it is only going to find the one
1784 // module matching the UUID. In fact, it has no good way to know what the "old module"
1785 // relevant to this target is, since there might be many copies of a module with this file spec
1786 // in various running debug sessions, but only one of them will belong to this target.
1787 // So let's remove the UUID from the module list, and look in the target's module list.
1788 // Only do this if there is SOMETHING else in the module spec...
1791 if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
1793 ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1794 module_spec_copy.GetUUID().Clear();
1796 ModuleList found_modules;
1797 size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
1800 old_module_sp = found_modules.GetModuleAtIndex(0);
1805 if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1807 m_images.ReplaceModule(old_module_sp, module_sp);
1808 Module *old_module_ptr = old_module_sp.get();
1809 old_module_sp.reset();
1810 ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
1813 m_images.Append(module_sp);
1826 Target::CalculateTarget ()
1828 return shared_from_this();
1832 Target::CalculateProcess ()
1838 Target::CalculateThread ()
1844 Target::CalculateStackFrame ()
1846 return StackFrameSP();
1850 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1853 exe_ctx.SetTargetPtr(this);
1857 Target::GetImageSearchPathList ()
1859 return m_image_search_paths;
1863 Target::ImageSearchPathsChanged
1865 const PathMappingList &path_list,
1869 Target *target = (Target *)baton;
1870 ModuleSP exe_module_sp (target->GetExecutableModule());
1872 target->SetExecutableModule (exe_module_sp, true);
1876 Target::GetScratchClangASTContext(bool create_on_demand)
1878 // Now see if we know the target triple, and if so, create our scratch AST context:
1879 if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand)
1881 m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1882 m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this()));
1883 m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext());
1884 llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy());
1885 m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source);
1887 return m_scratch_ast_context_ap.get();
1891 Target::GetClangASTImporter()
1893 ClangASTImporter *ast_importer = m_ast_importer_ap.get();
1897 ast_importer = new ClangASTImporter();
1898 m_ast_importer_ap.reset(ast_importer);
1901 return ast_importer;
1905 Target::SettingsInitialize ()
1907 Process::SettingsInitialize ();
1911 Target::SettingsTerminate ()
1913 Process::SettingsTerminate ();
1917 Target::GetDefaultExecutableSearchPaths ()
1919 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1921 return properties_sp->GetExecutableSearchPaths();
1922 return FileSpecList();
1926 Target::GetDefaultDebugFileSearchPaths ()
1928 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1930 return properties_sp->GetDebugFileSearchPaths();
1931 return FileSpecList();
1935 Target::GetDefaultClangModuleSearchPaths ()
1937 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1939 return properties_sp->GetClangModuleSearchPaths();
1940 return FileSpecList();
1944 Target::GetDefaultArchitecture ()
1946 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1948 return properties_sp->GetDefaultArchitecture();
1953 Target::SetDefaultArchitecture (const ArchSpec &arch)
1955 TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1958 LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's default architecture to %s (%s)", arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
1959 return properties_sp->SetDefaultArchitecture(arch);
1964 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1966 // The target can either exist in the "process" of ExecutionContext, or in
1967 // the "target_sp" member of SymbolContext. This accessor helper function
1968 // will get the target from one of these locations.
1970 Target *target = NULL;
1972 target = sc_ptr->target_sp.get();
1973 if (target == NULL && exe_ctx_ptr)
1974 target = exe_ctx_ptr->GetTargetPtr();
1979 Target::EvaluateExpression
1981 const char *expr_cstr,
1983 lldb::ValueObjectSP &result_valobj_sp,
1984 const EvaluateExpressionOptions& options
1987 result_valobj_sp.reset();
1989 ExpressionResults execution_results = eExpressionSetupError;
1991 if (expr_cstr == NULL || expr_cstr[0] == '\0')
1992 return execution_results;
1994 // We shouldn't run stop hooks in expressions.
1995 // Be sure to reset this if you return anywhere within this function.
1996 bool old_suppress_value = m_suppress_stop_hooks;
1997 m_suppress_stop_hooks = true;
1999 ExecutionContext exe_ctx;
2003 frame->CalculateExecutionContext(exe_ctx);
2005 else if (m_process_sp)
2007 m_process_sp->CalculateExecutionContext(exe_ctx);
2011 CalculateExecutionContext(exe_ctx);
2014 // Make sure we aren't just trying to see the value of a persistent
2015 // variable (something like "$0")
2016 lldb::ClangExpressionVariableSP persistent_var_sp;
2017 // Only check for persistent variables the expression starts with a '$'
2018 if (expr_cstr[0] == '$')
2019 persistent_var_sp = m_persistent_variables->GetVariable (expr_cstr);
2021 if (persistent_var_sp)
2023 result_valobj_sp = persistent_var_sp->GetValueObject ();
2024 execution_results = eExpressionCompleted;
2028 const char *prefix = GetExpressionPrefixContentsAsCString();
2030 execution_results = ClangUserExpression::Evaluate (exe_ctx,
2038 m_suppress_stop_hooks = old_suppress_value;
2040 return execution_results;
2043 ClangPersistentVariables &
2044 Target::GetPersistentVariables()
2046 return *m_persistent_variables;
2050 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
2052 addr_t code_addr = load_addr;
2053 switch (m_arch.GetMachine())
2055 case llvm::Triple::arm:
2056 case llvm::Triple::thumb:
2059 case eAddressClassData:
2060 case eAddressClassDebug:
2061 return LLDB_INVALID_ADDRESS;
2063 case eAddressClassUnknown:
2064 case eAddressClassInvalid:
2065 case eAddressClassCode:
2066 case eAddressClassCodeAlternateISA:
2067 case eAddressClassRuntime:
2068 // Check if bit zero it no set?
2069 if ((code_addr & 1ull) == 0)
2071 // Bit zero isn't set, check if the address is a multiple of 2?
2072 if (code_addr & 2ull)
2074 // The address is a multiple of 2 so it must be thumb, set bit zero
2077 else if (addr_class == eAddressClassCodeAlternateISA)
2079 // We checked the address and the address claims to be the alternate ISA
2080 // which means thumb, so set bit zero.
2095 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
2097 addr_t opcode_addr = load_addr;
2098 switch (m_arch.GetMachine())
2100 case llvm::Triple::arm:
2101 case llvm::Triple::thumb:
2104 case eAddressClassData:
2105 case eAddressClassDebug:
2106 return LLDB_INVALID_ADDRESS;
2108 case eAddressClassInvalid:
2109 case eAddressClassUnknown:
2110 case eAddressClassCode:
2111 case eAddressClassCodeAlternateISA:
2112 case eAddressClassRuntime:
2113 opcode_addr &= ~(1ull);
2125 Target::GetSourceManager ()
2127 if (m_source_manager_ap.get() == NULL)
2128 m_source_manager_ap.reset (new SourceManager(shared_from_this()));
2129 return *m_source_manager_ap;
2132 ClangModulesDeclVendor *
2133 Target::GetClangModulesDeclVendor ()
2135 static Mutex s_clang_modules_decl_vendor_mutex; // If this is contended we can make it per-target
2138 Mutex::Locker clang_modules_decl_vendor_locker(s_clang_modules_decl_vendor_mutex);
2140 if (!m_clang_modules_decl_vendor_ap)
2142 m_clang_modules_decl_vendor_ap.reset(ClangModulesDeclVendor::Create(*this));
2146 return m_clang_modules_decl_vendor_ap.get();
2150 Target::CreateStopHook ()
2152 lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2153 Target::StopHookSP stop_hook_sp (new StopHook(shared_from_this(), new_uid));
2154 m_stop_hooks[new_uid] = stop_hook_sp;
2155 return stop_hook_sp;
2159 Target::RemoveStopHookByID (lldb::user_id_t user_id)
2162 num_removed = m_stop_hooks.erase (user_id);
2163 if (num_removed == 0)
2170 Target::RemoveAllStopHooks ()
2172 m_stop_hooks.clear();
2176 Target::GetStopHookByID (lldb::user_id_t user_id)
2178 StopHookSP found_hook;
2180 StopHookCollection::iterator specified_hook_iter;
2181 specified_hook_iter = m_stop_hooks.find (user_id);
2182 if (specified_hook_iter != m_stop_hooks.end())
2183 found_hook = (*specified_hook_iter).second;
2188 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
2190 StopHookCollection::iterator specified_hook_iter;
2191 specified_hook_iter = m_stop_hooks.find (user_id);
2192 if (specified_hook_iter == m_stop_hooks.end())
2195 (*specified_hook_iter).second->SetIsActive (active_state);
2200 Target::SetAllStopHooksActiveState (bool active_state)
2202 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2203 for (pos = m_stop_hooks.begin(); pos != end; pos++)
2205 (*pos).second->SetIsActive (active_state);
2210 Target::RunStopHooks ()
2212 if (m_suppress_stop_hooks)
2218 // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
2219 // since in that case we do not want to run the stop-hooks
2220 if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2223 if (m_stop_hooks.empty())
2226 StopHookCollection::iterator pos, end = m_stop_hooks.end();
2228 // If there aren't any active stop hooks, don't bother either:
2229 bool any_active_hooks = false;
2230 for (pos = m_stop_hooks.begin(); pos != end; pos++)
2232 if ((*pos).second->IsActive())
2234 any_active_hooks = true;
2238 if (!any_active_hooks)
2241 CommandReturnObject result;
2243 std::vector<ExecutionContext> exc_ctx_with_reasons;
2244 std::vector<SymbolContext> sym_ctx_with_reasons;
2246 ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2247 size_t num_threads = cur_threadlist.GetSize();
2248 for (size_t i = 0; i < num_threads; i++)
2250 lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
2251 if (cur_thread_sp->ThreadStoppedForAReason())
2253 lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2254 exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2255 sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2259 // If no threads stopped for a reason, don't run the stop-hooks.
2260 size_t num_exe_ctx = exc_ctx_with_reasons.size();
2261 if (num_exe_ctx == 0)
2264 result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
2265 result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
2267 bool keep_going = true;
2268 bool hooks_ran = false;
2269 bool print_hook_header;
2270 bool print_thread_header;
2272 if (num_exe_ctx == 1)
2273 print_thread_header = false;
2275 print_thread_header = true;
2277 if (m_stop_hooks.size() == 1)
2278 print_hook_header = false;
2280 print_hook_header = true;
2282 for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
2285 StopHookSP cur_hook_sp = (*pos).second;
2286 if (!cur_hook_sp->IsActive())
2289 bool any_thread_matched = false;
2290 for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2292 if ((cur_hook_sp->GetSpecifier () == NULL
2293 || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2294 && (cur_hook_sp->GetThreadSpecifier() == NULL
2295 || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2301 if (print_hook_header && !any_thread_matched)
2303 const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2304 cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2307 result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(), cmd);
2309 result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2310 any_thread_matched = true;
2313 if (print_thread_header)
2314 result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2316 CommandInterpreterRunOptions options;
2317 options.SetStopOnContinue (true);
2318 options.SetStopOnError (true);
2319 options.SetEchoCommands (false);
2320 options.SetPrintResults (true);
2321 options.SetAddToHistory (false);
2323 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2324 &exc_ctx_with_reasons[i],
2328 // If the command started the target going again, we should bag out of
2329 // running the stop hooks.
2330 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2331 (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2333 result.AppendMessageWithFormat ("Aborting stop hooks, hook %" PRIu64 " set the program running.", cur_hook_sp->GetID());
2340 result.GetImmediateOutputStream()->Flush();
2341 result.GetImmediateErrorStream()->Flush();
2344 const TargetPropertiesSP &
2345 Target::GetGlobalProperties()
2347 static TargetPropertiesSP g_settings_sp;
2350 g_settings_sp.reset (new TargetProperties (NULL));
2352 return g_settings_sp;
2356 Target::Install (ProcessLaunchInfo *launch_info)
2359 PlatformSP platform_sp (GetPlatform());
2362 if (platform_sp->IsRemote())
2364 if (platform_sp->IsConnected())
2366 // Install all files that have an install path, and always install the
2367 // main executable when connected to a remote platform
2368 const ModuleList& modules = GetImages();
2369 const size_t num_images = modules.GetSize();
2370 for (size_t idx = 0; idx < num_images; ++idx)
2372 const bool is_main_executable = idx == 0;
2373 ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2376 FileSpec local_file (module_sp->GetFileSpec());
2379 FileSpec remote_file (module_sp->GetRemoteInstallFileSpec());
2382 if (is_main_executable) // TODO: add setting for always installing main executable???
2384 // Always install the main executable
2385 remote_file = platform_sp->GetRemoteWorkingDirectory();
2386 remote_file.AppendPathComponent(module_sp->GetFileSpec().GetFilename().GetCString());
2391 error = platform_sp->Install(local_file, remote_file);
2392 if (error.Success())
2394 module_sp->SetPlatformFileSpec(remote_file);
2395 if (is_main_executable)
2397 platform_sp->SetFilePermissions(remote_file, 0700);
2399 launch_info->SetExecutableFile(remote_file, false);
2415 Target::ResolveLoadAddress (addr_t load_addr, Address &so_addr, uint32_t stop_id)
2417 return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2421 Target::ResolveFileAddress (lldb::addr_t file_addr, Address &resolved_addr)
2423 return m_images.ResolveFileAddress(file_addr, resolved_addr);
2427 Target::SetSectionLoadAddress (const SectionSP §ion_sp, addr_t new_section_load_addr, bool warn_multiple)
2429 const addr_t old_section_load_addr = m_section_load_history.GetSectionLoadAddress (SectionLoadHistory::eStopIDNow, section_sp);
2430 if (old_section_load_addr != new_section_load_addr)
2432 uint32_t stop_id = 0;
2433 ProcessSP process_sp(GetProcessSP());
2435 stop_id = process_sp->GetStopID();
2437 stop_id = m_section_load_history.GetLastStopID();
2438 if (m_section_load_history.SetSectionLoadAddress (stop_id, section_sp, new_section_load_addr, warn_multiple))
2439 return true; // Return true if the section load address was changed...
2441 return false; // Return false to indicate nothing changed
2446 Target::UnloadModuleSections (const ModuleList &module_list)
2448 size_t section_unload_count = 0;
2449 size_t num_modules = module_list.GetSize();
2450 for (size_t i=0; i<num_modules; ++i)
2452 section_unload_count += UnloadModuleSections (module_list.GetModuleAtIndex(i));
2454 return section_unload_count;
2458 Target::UnloadModuleSections (const lldb::ModuleSP &module_sp)
2460 uint32_t stop_id = 0;
2461 ProcessSP process_sp(GetProcessSP());
2463 stop_id = process_sp->GetStopID();
2465 stop_id = m_section_load_history.GetLastStopID();
2466 SectionList *sections = module_sp->GetSectionList();
2467 size_t section_unload_count = 0;
2470 const uint32_t num_sections = sections->GetNumSections(0);
2471 for (uint32_t i = 0; i < num_sections; ++i)
2473 section_unload_count += m_section_load_history.SetSectionUnloaded(stop_id, sections->GetSectionAtIndex(i));
2476 return section_unload_count;
2480 Target::SetSectionUnloaded (const lldb::SectionSP §ion_sp)
2482 uint32_t stop_id = 0;
2483 ProcessSP process_sp(GetProcessSP());
2485 stop_id = process_sp->GetStopID();
2487 stop_id = m_section_load_history.GetLastStopID();
2488 return m_section_load_history.SetSectionUnloaded (stop_id, section_sp);
2492 Target::SetSectionUnloaded (const lldb::SectionSP §ion_sp, addr_t load_addr)
2494 uint32_t stop_id = 0;
2495 ProcessSP process_sp(GetProcessSP());
2497 stop_id = process_sp->GetStopID();
2499 stop_id = m_section_load_history.GetLastStopID();
2500 return m_section_load_history.SetSectionUnloaded (stop_id, section_sp, load_addr);
2504 Target::ClearAllLoadedSections ()
2506 m_section_load_history.Clear();
2511 Target::Launch (ProcessLaunchInfo &launch_info, Stream *stream)
2514 Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
2517 log->Printf ("Target::%s() called for %s", __FUNCTION__, launch_info.GetExecutableFile().GetPath().c_str ());
2519 StateType state = eStateInvalid;
2521 // Scope to temporarily get the process state in case someone has manually
2522 // remotely connected already to a process and we can skip the platform
2525 ProcessSP process_sp (GetProcessSP());
2529 state = process_sp->GetState();
2531 log->Printf ("Target::%s the process exists, and its current state is %s", __FUNCTION__, StateAsCString (state));
2536 log->Printf ("Target::%s the process instance doesn't currently exist.", __FUNCTION__);
2540 launch_info.GetFlags().Set (eLaunchFlagDebug);
2542 // Get the value of synchronous execution here. If you wait till after you have started to
2543 // run, then you could have hit a breakpoint, whose command might switch the value, and
2544 // then you'll pick up that incorrect value.
2545 Debugger &debugger = GetDebugger();
2546 const bool synchronous_execution = debugger.GetCommandInterpreter().GetSynchronous ();
2548 PlatformSP platform_sp (GetPlatform());
2550 // Finalize the file actions, and if none were given, default to opening
2551 // up a pseudo terminal
2552 const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2554 log->Printf ("Target::%s have platform=%s, platform_sp->IsHost()=%s, default_to_use_pty=%s",
2556 platform_sp ? "true" : "false",
2557 platform_sp ? (platform_sp->IsHost () ? "true" : "false") : "n/a",
2558 default_to_use_pty ? "true" : "false");
2560 launch_info.FinalizeFileActions (this, default_to_use_pty);
2562 if (state == eStateConnected)
2564 if (launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY))
2566 error.SetErrorString("can't launch in tty when launching through a remote connection");
2571 if (!launch_info.GetArchitecture().IsValid())
2572 launch_info.GetArchitecture() = GetArchitecture();
2574 // If we're not already connected to the process, and if we have a platform that can launch a process for debugging, go ahead and do that here.
2575 if (state != eStateConnected && platform_sp && platform_sp->CanDebugProcess ())
2578 log->Printf ("Target::%s asking the platform to debug the process", __FUNCTION__);
2580 // Get a weak pointer to the previous process if we have one
2581 ProcessWP process_wp;
2583 process_wp = m_process_sp;
2584 m_process_sp = GetPlatform()->DebugProcess (launch_info,
2589 // Cleanup the old process since someone might still have a strong
2590 // reference to this process and we would like to allow it to cleanup
2591 // as much as it can without the object being destroyed. We try to
2592 // lock the shared pointer and if that works, then someone else still
2593 // has a strong reference to the process.
2595 ProcessSP old_process_sp(process_wp.lock());
2597 old_process_sp->Finalize();
2602 log->Printf ("Target::%s the platform doesn't know how to debug a process, getting a process plugin to do this for us.", __FUNCTION__);
2604 if (state == eStateConnected)
2606 assert(m_process_sp);
2610 // Use a Process plugin to construct the process.
2611 const char *plugin_name = launch_info.GetProcessPluginName();
2612 CreateProcess (launch_info.GetListenerForProcess(debugger), plugin_name, NULL);
2615 // Since we didn't have a platform launch the process, launch it here.
2617 error = m_process_sp->Launch (launch_info);
2622 if (error.Success())
2623 error.SetErrorString("failed to launch or debug process");
2627 if (error.Success())
2629 if (synchronous_execution || launch_info.GetFlags().Test(eLaunchFlagStopAtEntry) == false)
2631 ListenerSP hijack_listener_sp (launch_info.GetHijackListener());
2632 if (!hijack_listener_sp)
2634 hijack_listener_sp.reset(new Listener("lldb.Target.Launch.hijack"));
2635 launch_info.SetHijackListener(hijack_listener_sp);
2636 m_process_sp->HijackProcessEvents(hijack_listener_sp.get());
2639 StateType state = m_process_sp->WaitForProcessToStop (NULL, NULL, false, hijack_listener_sp.get(), NULL);
2641 if (state == eStateStopped)
2643 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2645 if (synchronous_execution)
2647 error = m_process_sp->PrivateResume();
2648 if (error.Success())
2650 state = m_process_sp->WaitForProcessToStop (NULL, NULL, true, hijack_listener_sp.get(), stream);
2651 const bool must_be_alive = false; // eStateExited is ok, so this must be false
2652 if (!StateIsStoppedState(state, must_be_alive))
2654 error.SetErrorStringWithFormat("process isn't stopped: %s", StateAsCString(state));
2660 m_process_sp->RestoreProcessEvents();
2661 error = m_process_sp->PrivateResume();
2663 if (!error.Success())
2666 error2.SetErrorStringWithFormat("process resume at entry point failed: %s", error.AsCString());
2671 else if (state == eStateExited)
2673 bool with_shell = !!launch_info.GetShell();
2674 const int exit_status = m_process_sp->GetExitStatus();
2675 const char *exit_desc = m_process_sp->GetExitDescription();
2676 #define LAUNCH_SHELL_MESSAGE "\n'r' and 'run' are aliases that default to launching through a shell.\nTry launching without going through a shell by using 'process launch'."
2677 if (exit_desc && exit_desc[0])
2680 error.SetErrorStringWithFormat ("process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE, exit_status, exit_desc);
2682 error.SetErrorStringWithFormat ("process exited with status %i (%s)", exit_status, exit_desc);
2687 error.SetErrorStringWithFormat ("process exited with status %i" LAUNCH_SHELL_MESSAGE, exit_status);
2689 error.SetErrorStringWithFormat ("process exited with status %i", exit_status);
2694 error.SetErrorStringWithFormat ("initial process state wasn't stopped: %s", StateAsCString(state));
2697 m_process_sp->RestoreProcessEvents ();
2702 error2.SetErrorStringWithFormat ("process launch failed: %s", error.AsCString());
2709 Target::Attach (ProcessAttachInfo &attach_info, Stream *stream)
2711 auto state = eStateInvalid;
2712 auto process_sp = GetProcessSP ();
2715 state = process_sp->GetState ();
2716 if (process_sp->IsAlive () && state != eStateConnected)
2718 if (state == eStateAttaching)
2719 return Error ("process attach is in progress");
2720 return Error ("a process is already being debugged");
2724 ListenerSP hijack_listener_sp (new Listener ("lldb.Target.Attach.attach.hijack"));
2725 attach_info.SetHijackListener (hijack_listener_sp);
2727 const ModuleSP old_exec_module_sp = GetExecutableModule ();
2729 // If no process info was specified, then use the target executable
2730 // name as the process to attach to by default
2731 if (!attach_info.ProcessInfoSpecified ())
2733 if (old_exec_module_sp)
2734 attach_info.GetExecutableFile ().GetFilename () = old_exec_module_sp->GetPlatformFileSpec ().GetFilename ();
2736 if (!attach_info.ProcessInfoSpecified ())
2738 return Error ("no process specified, create a target with a file, or specify the --pid or --name");
2742 const auto platform_sp = GetDebugger ().GetPlatformList ().GetSelectedPlatform ();
2745 if (state != eStateConnected && platform_sp != nullptr && platform_sp->CanDebugProcess ())
2747 SetPlatform (platform_sp);
2748 process_sp = platform_sp->Attach (attach_info, GetDebugger (), this, error);
2752 if (state != eStateConnected)
2754 const char *plugin_name = attach_info.GetProcessPluginName ();
2755 process_sp = CreateProcess (attach_info.GetListenerForProcess (GetDebugger ()), plugin_name, nullptr);
2756 if (process_sp == nullptr)
2758 error.SetErrorStringWithFormat ("failed to create process using plugin %s", (plugin_name) ? plugin_name : "null");
2762 process_sp->HijackProcessEvents (hijack_listener_sp.get ());
2763 error = process_sp->Attach (attach_info);
2766 if (error.Success () && process_sp)
2768 state = process_sp->WaitForProcessToStop (nullptr, nullptr, false, attach_info.GetHijackListener ().get (), stream);
2769 process_sp->RestoreProcessEvents ();
2771 if (state != eStateStopped)
2773 const char *exit_desc = process_sp->GetExitDescription ();
2775 error.SetErrorStringWithFormat ("attach failed: %s", exit_desc);
2777 error.SetErrorString ("attach failed: process did not stop (no such process or permission problem?)");
2778 process_sp->Destroy (false);
2784 //--------------------------------------------------------------
2786 //--------------------------------------------------------------
2787 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2789 m_target_sp (target_sp),
2797 Target::StopHook::StopHook (const StopHook &rhs) :
2798 UserID (rhs.GetID()),
2799 m_target_sp (rhs.m_target_sp),
2800 m_commands (rhs.m_commands),
2801 m_specifier_sp (rhs.m_specifier_sp),
2802 m_thread_spec_ap (),
2803 m_active (rhs.m_active)
2805 if (rhs.m_thread_spec_ap.get() != NULL)
2806 m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2810 Target::StopHook::~StopHook ()
2815 Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier)
2817 m_specifier_sp.reset(specifier);
2821 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2823 m_thread_spec_ap.reset (specifier);
2828 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2830 int indent_level = s->GetIndentLevel();
2832 s->SetIndentLevel(indent_level + 2);
2834 s->Printf ("Hook: %" PRIu64 "\n", GetID());
2836 s->Indent ("State: enabled\n");
2838 s->Indent ("State: disabled\n");
2843 s->PutCString ("Specifier:\n");
2844 s->SetIndentLevel (indent_level + 4);
2845 m_specifier_sp->GetDescription (s, level);
2846 s->SetIndentLevel (indent_level + 2);
2849 if (m_thread_spec_ap.get() != NULL)
2852 s->Indent("Thread:\n");
2853 m_thread_spec_ap->GetDescription (&tmp, level);
2854 s->SetIndentLevel (indent_level + 4);
2855 s->Indent (tmp.GetData());
2856 s->PutCString ("\n");
2857 s->SetIndentLevel (indent_level + 2);
2860 s->Indent ("Commands: \n");
2861 s->SetIndentLevel (indent_level + 4);
2862 uint32_t num_commands = m_commands.GetSize();
2863 for (uint32_t i = 0; i < num_commands; i++)
2865 s->Indent(m_commands.GetStringAtIndex(i));
2866 s->PutCString ("\n");
2868 s->SetIndentLevel (indent_level);
2871 //--------------------------------------------------------------
2872 // class TargetProperties
2873 //--------------------------------------------------------------
2875 OptionEnumValueElement
2876 lldb_private::g_dynamic_value_types[] =
2878 { eNoDynamicValues, "no-dynamic-values", "Don't calculate the dynamic type of values"},
2879 { eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values even if you have to run the target."},
2880 { eDynamicDontRunTarget, "no-run-target", "Calculate the dynamic type of values, but don't run the target."},
2884 static OptionEnumValueElement
2885 g_inline_breakpoint_enums[] =
2887 { 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."},
2888 { eInlineBreakpointsHeaders, "headers", "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2889 { eInlineBreakpointsAlways, "always", "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2893 typedef enum x86DisassemblyFlavor
2895 eX86DisFlavorDefault,
2898 } x86DisassemblyFlavor;
2900 static OptionEnumValueElement
2901 g_x86_dis_flavor_value_types[] =
2903 { eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
2904 { eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
2905 { eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
2909 static OptionEnumValueElement
2910 g_hex_immediate_style_values[] =
2912 { Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
2913 { Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
2917 static OptionEnumValueElement
2918 g_load_script_from_sym_file_values[] =
2920 { eLoadScriptFromSymFileTrue, "true", "Load debug scripts inside symbol files"},
2921 { eLoadScriptFromSymFileFalse, "false", "Do not load debug scripts inside symbol files."},
2922 { eLoadScriptFromSymFileWarn, "warn", "Warn about debug scripts inside symbol files but do not load them."},
2927 static OptionEnumValueElement
2928 g_memory_module_load_level_values[] =
2930 { eMemoryModuleLoadLevelMinimal, "minimal" , "Load minimal information when loading modules from memory. Currently this setting loads sections only."},
2931 { eMemoryModuleLoadLevelPartial, "partial" , "Load partial information when loading modules from memory. Currently this setting loads sections and function bounds."},
2932 { eMemoryModuleLoadLevelComplete, "complete", "Load complete information when loading modules from memory. Currently this setting loads sections and all symbols."},
2936 static PropertyDefinition
2939 { "default-arch" , OptionValue::eTypeArch , true , 0 , NULL, NULL, "Default architecture to choose, when there's a choice." },
2940 { "move-to-nearest-code" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Move breakpoints to nearest code." },
2941 { "expr-prefix" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2942 { "prefer-dynamic-value" , OptionValue::eTypeEnum , false, eDynamicDontRunTarget , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2943 { "enable-synthetic-value" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Should synthetic values be used by default whenever available." },
2944 { "skip-prologue" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2945 { "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 "
2946 "where it exists on the current system. It consists of an array of duples, the first element of each duple is "
2947 "some part (starting at the root) of the path to the file when it was built, "
2948 "and the second is where the remainder of the original build hierarchy is rooted on the local system. "
2949 "Each element of the array is checked in order and the first one that results in a match wins." },
2950 { "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." },
2951 { "debug-file-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , NULL, NULL, "List of directories to be searched when locating debug symbol files." },
2952 { "clang-module-search-paths" , OptionValue::eTypeFileSpecList, false, 0 , NULL, NULL, "List of directories to be searched when locating modules for Clang." },
2953 { "auto-import-clang-modules" , OptionValue::eTypeBoolean , false, false , NULL, NULL, "Automatically load Clang modules referred to by the program." },
2954 { "max-children-count" , OptionValue::eTypeSInt64 , false, 256 , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2955 { "max-string-summary-length" , OptionValue::eTypeSInt64 , false, 1024 , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2956 { "max-memory-read-size" , OptionValue::eTypeSInt64 , false, 1024 , NULL, NULL, "Maximum number of bytes that 'memory read' will fetch before --force must be specified." },
2957 { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean , false, true , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2958 { "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." },
2959 { "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." },
2960 { "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." },
2961 { "inherit-env" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2962 { "input-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2963 { "output-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2964 { "error-path" , OptionValue::eTypeFileSpec , false, 0 , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2965 { "detach-on-error" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "debugserver will detach (rather than killing) a process if it loses connection with lldb." },
2966 { "disable-aslr" , OptionValue::eTypeBoolean , false, true , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2967 { "disable-stdio" , OptionValue::eTypeBoolean , false, false , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2968 { "inline-breakpoint-strategy" , OptionValue::eTypeEnum , false, eInlineBreakpointsAlways , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2969 "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. "
2970 "Usually this is limited to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2971 "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2972 "Always checking for inlined breakpoint locations can be expensive (memory and time), so if you have a project with many headers "
2973 "and find that setting breakpoints is slow, then you can change this setting to headers. "
2974 "This setting allows you to control exactly which strategy is used when setting "
2975 "file and line breakpoints." },
2976 // 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.
2977 { "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." },
2978 { "use-hex-immediates" , OptionValue::eTypeBoolean , false, true, NULL, NULL, "Show immediates in disassembly as hexadecimal." },
2979 { "hex-immediate-style" , OptionValue::eTypeEnum , false, Disassembler::eHexStyleC, NULL, g_hex_immediate_style_values, "Which style to use for printing hexadecimal disassembly values." },
2980 { "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." },
2981 { "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." },
2982 { "memory-module-load-level" , OptionValue::eTypeEnum , false, eMemoryModuleLoadLevelComplete, NULL, g_memory_module_load_level_values,
2983 "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. "
2984 "This setting helps users control how much information gets loaded when loading modules from memory."
2985 "'complete' is the default value for this setting which will load all sections and symbols by reading them from memory (slowest, most accurate). "
2986 "'partial' will load sections and attempt to find function bounds without downloading the symbol table (faster, still accurate, missing symbol names). "
2987 "'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). " },
2988 { "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." },
2989 { "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." },
2990 { "display-runtime-support-values" , OptionValue::eTypeBoolean , false, false, NULL, NULL, "If true, LLDB will show variables that are meant to support the operation of a language's runtime support." },
2991 { "non-stop-mode" , OptionValue::eTypeBoolean , false, 0, NULL, NULL, "Disable lock-step debugging, instead control threads independently." },
2992 { NULL , OptionValue::eTypeInvalid , false, 0 , NULL, NULL, NULL }
2997 ePropertyDefaultArch,
2998 ePropertyMoveToNearestCode,
2999 ePropertyExprPrefix,
3000 ePropertyPreferDynamic,
3001 ePropertyEnableSynthetic,
3002 ePropertySkipPrologue,
3004 ePropertyExecutableSearchPaths,
3005 ePropertyDebugFileSearchPaths,
3006 ePropertyClangModuleSearchPaths,
3007 ePropertyAutoImportClangModules,
3008 ePropertyMaxChildrenCount,
3009 ePropertyMaxSummaryLength,
3010 ePropertyMaxMemReadSize,
3011 ePropertyBreakpointUseAvoidList,
3015 ePropertyInheritEnv,
3017 ePropertyOutputPath,
3019 ePropertyDetachOnError,
3020 ePropertyDisableASLR,
3021 ePropertyDisableSTDIO,
3022 ePropertyInlineStrategy,
3023 ePropertyDisassemblyFlavor,
3024 ePropertyUseHexImmediates,
3025 ePropertyHexImmediateStyle,
3026 ePropertyUseFastStepping,
3027 ePropertyLoadScriptFromSymbolFile,
3028 ePropertyMemoryModuleLoadLevel,
3029 ePropertyDisplayExpressionsInCrashlogs,
3030 ePropertyTrapHandlerNames,
3031 ePropertyDisplayRuntimeSupportValues,
3032 ePropertyNonStopModeEnabled
3036 class TargetOptionValueProperties : public OptionValueProperties
3039 TargetOptionValueProperties (const ConstString &name) :
3040 OptionValueProperties (name),
3042 m_got_host_env (false)
3046 // This constructor is used when creating TargetOptionValueProperties when it
3047 // is part of a new lldb_private::Target instance. It will copy all current
3048 // global property values as needed
3049 TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
3050 OptionValueProperties(*target_properties_sp->GetValueProperties()),
3052 m_got_host_env (false)
3056 virtual const Property *
3057 GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
3059 // When getting the value for a key from the target options, we will always
3060 // try and grab the setting from the current target if there is one. Else we just
3061 // use the one from this instance.
3062 if (idx == ePropertyEnvVars)
3063 GetHostEnvironmentIfNeeded ();
3067 Target *target = exe_ctx->GetTargetPtr();
3070 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
3071 if (this != target_properties)
3072 return target_properties->ProtectedGetPropertyAtIndex (idx);
3075 return ProtectedGetPropertyAtIndex (idx);
3081 return m_target->shared_from_this();
3087 GetHostEnvironmentIfNeeded () const
3089 if (!m_got_host_env)
3093 m_got_host_env = true;
3094 const uint32_t idx = ePropertyInheritEnv;
3095 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
3097 PlatformSP platform_sp (m_target->GetPlatform());
3101 if (platform_sp->GetEnvironment(env))
3103 OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
3106 const bool can_replace = false;
3107 const size_t envc = env.GetSize();
3108 for (size_t idx=0; idx<envc; idx++)
3110 const char *env_entry = env.GetStringAtIndex (idx);
3113 const char *equal_pos = ::strchr(env_entry, '=');
3115 // It is ok to have environment variables with no values
3116 const char *value = NULL;
3119 key.SetCStringWithLength(env_entry, equal_pos - env_entry);
3121 value = equal_pos + 1;
3125 key.SetCString(env_entry);
3127 // Don't allow existing keys to be replaced with ones we get from the platform environment
3128 env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
3139 mutable bool m_got_host_env;
3142 //----------------------------------------------------------------------
3144 //----------------------------------------------------------------------
3145 TargetProperties::TargetProperties (Target *target) :
3151 m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
3153 // Set callbacks to update launch_info whenever "settins set" updated any of these properties
3154 m_collection_sp->SetValueChangedCallback(ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3155 m_collection_sp->SetValueChangedCallback(ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3156 m_collection_sp->SetValueChangedCallback(ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3157 m_collection_sp->SetValueChangedCallback(ePropertyInputPath, TargetProperties::InputPathValueChangedCallback, this);
3158 m_collection_sp->SetValueChangedCallback(ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback, this);
3159 m_collection_sp->SetValueChangedCallback(ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback, this);
3160 m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, TargetProperties::DetachOnErrorValueChangedCallback, this);
3161 m_collection_sp->SetValueChangedCallback(ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback, this);
3162 m_collection_sp->SetValueChangedCallback(ePropertyDisableSTDIO, TargetProperties::DisableSTDIOValueChangedCallback, this);
3164 // Update m_launch_info once it was created
3165 Arg0ValueChangedCallback(this, NULL);
3166 RunArgsValueChangedCallback(this, NULL);
3167 //EnvVarsValueChangedCallback(this, NULL); // FIXME: cause segfault in Target::GetPlatform()
3168 InputPathValueChangedCallback(this, NULL);
3169 OutputPathValueChangedCallback(this, NULL);
3170 ErrorPathValueChangedCallback(this, NULL);
3171 DetachOnErrorValueChangedCallback(this, NULL);
3172 DisableASLRValueChangedCallback(this, NULL);
3173 DisableSTDIOValueChangedCallback(this, NULL);
3177 m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
3178 m_collection_sp->Initialize(g_properties);
3179 m_collection_sp->AppendProperty(ConstString("process"),
3180 ConstString("Settings specify to processes."),
3182 Process::GetGlobalProperties()->GetValueProperties());
3187 TargetProperties::~TargetProperties ()
3191 TargetProperties::GetDefaultArchitecture () const
3193 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
3195 return value->GetCurrentValue();
3200 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
3202 OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
3204 return value->SetCurrentValue(arch, true);
3208 TargetProperties::GetMoveToNearestCode() const
3210 const uint32_t idx = ePropertyMoveToNearestCode;
3211 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3214 lldb::DynamicValueType
3215 TargetProperties::GetPreferDynamicValue() const
3217 const uint32_t idx = ePropertyPreferDynamic;
3218 return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
3222 TargetProperties::SetPreferDynamicValue (lldb::DynamicValueType d)
3224 const uint32_t idx = ePropertyPreferDynamic;
3225 return m_collection_sp->SetPropertyAtIndexAsEnumeration(NULL, idx, d);
3230 TargetProperties::GetDisableASLR () const
3232 const uint32_t idx = ePropertyDisableASLR;
3233 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3237 TargetProperties::SetDisableASLR (bool b)
3239 const uint32_t idx = ePropertyDisableASLR;
3240 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3244 TargetProperties::GetDetachOnError () const
3246 const uint32_t idx = ePropertyDetachOnError;
3247 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3251 TargetProperties::SetDetachOnError (bool b)
3253 const uint32_t idx = ePropertyDetachOnError;
3254 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3258 TargetProperties::GetDisableSTDIO () const
3260 const uint32_t idx = ePropertyDisableSTDIO;
3261 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3265 TargetProperties::SetDisableSTDIO (bool b)
3267 const uint32_t idx = ePropertyDisableSTDIO;
3268 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3272 TargetProperties::GetDisassemblyFlavor () const
3274 const uint32_t idx = ePropertyDisassemblyFlavor;
3275 const char *return_value;
3277 x86DisassemblyFlavor flavor_value = (x86DisassemblyFlavor) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
3278 return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3279 return return_value;
3283 TargetProperties::GetInlineStrategy () const
3285 const uint32_t idx = ePropertyInlineStrategy;
3286 return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
3290 TargetProperties::GetArg0 () const
3292 const uint32_t idx = ePropertyArg0;
3293 return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
3297 TargetProperties::SetArg0 (const char *arg)
3299 const uint32_t idx = ePropertyArg0;
3300 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
3301 m_launch_info.SetArg0(arg);
3305 TargetProperties::GetRunArguments (Args &args) const
3307 const uint32_t idx = ePropertyRunArgs;
3308 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
3312 TargetProperties::SetRunArguments (const Args &args)
3314 const uint32_t idx = ePropertyRunArgs;
3315 m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
3316 m_launch_info.GetArguments() = args;
3320 TargetProperties::GetEnvironmentAsArgs (Args &env) const
3322 const uint32_t idx = ePropertyEnvVars;
3323 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
3327 TargetProperties::SetEnvironmentFromArgs (const Args &env)
3329 const uint32_t idx = ePropertyEnvVars;
3330 m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, env);
3331 m_launch_info.GetEnvironmentEntries() = env;
3335 TargetProperties::GetSkipPrologue() const
3337 const uint32_t idx = ePropertySkipPrologue;
3338 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3342 TargetProperties::GetSourcePathMap () const
3344 const uint32_t idx = ePropertySourceMap;
3345 OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
3346 assert(option_value);
3347 return option_value->GetCurrentValue();
3351 TargetProperties::GetExecutableSearchPaths ()
3353 const uint32_t idx = ePropertyExecutableSearchPaths;
3354 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
3355 assert(option_value);
3356 return option_value->GetCurrentValue();
3360 TargetProperties::GetDebugFileSearchPaths ()
3362 const uint32_t idx = ePropertyDebugFileSearchPaths;
3363 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
3364 assert(option_value);
3365 return option_value->GetCurrentValue();
3369 TargetProperties::GetClangModuleSearchPaths ()
3371 const uint32_t idx = ePropertyClangModuleSearchPaths;
3372 OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
3373 assert(option_value);
3374 return option_value->GetCurrentValue();
3378 TargetProperties::GetEnableAutoImportClangModules() const
3380 const uint32_t idx = ePropertyAutoImportClangModules;
3381 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3385 TargetProperties::GetEnableSyntheticValue () const
3387 const uint32_t idx = ePropertyEnableSynthetic;
3388 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3392 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
3394 const uint32_t idx = ePropertyMaxChildrenCount;
3395 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
3399 TargetProperties::GetMaximumSizeOfStringSummary() const
3401 const uint32_t idx = ePropertyMaxSummaryLength;
3402 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
3406 TargetProperties::GetMaximumMemReadSize () const
3408 const uint32_t idx = ePropertyMaxMemReadSize;
3409 return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
3413 TargetProperties::GetStandardInputPath () const
3415 const uint32_t idx = ePropertyInputPath;
3416 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
3420 TargetProperties::SetStandardInputPath (const char *p)
3422 const uint32_t idx = ePropertyInputPath;
3423 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3427 TargetProperties::GetStandardOutputPath () const
3429 const uint32_t idx = ePropertyOutputPath;
3430 return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
3434 TargetProperties::SetStandardOutputPath (const char *p)
3436 const uint32_t idx = ePropertyOutputPath;
3437 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3441 TargetProperties::GetStandardErrorPath () const
3443 const uint32_t idx = ePropertyErrorPath;
3444 return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
3448 TargetProperties::GetExpressionPrefixContentsAsCString ()
3450 const uint32_t idx = ePropertyExprPrefix;
3451 OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
3454 const bool null_terminate = true;
3455 DataBufferSP data_sp(file->GetFileContents(null_terminate));
3457 return (const char *) data_sp->GetBytes();
3463 TargetProperties::SetStandardErrorPath (const char *p)
3465 const uint32_t idx = ePropertyErrorPath;
3466 m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3470 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
3472 const uint32_t idx = ePropertyBreakpointUseAvoidList;
3473 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3477 TargetProperties::GetUseHexImmediates () const
3479 const uint32_t idx = ePropertyUseHexImmediates;
3480 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3484 TargetProperties::GetUseFastStepping () const
3486 const uint32_t idx = ePropertyUseFastStepping;
3487 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3491 TargetProperties::GetDisplayExpressionsInCrashlogs () const
3493 const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3494 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3497 LoadScriptFromSymFile
3498 TargetProperties::GetLoadScriptFromSymbolFile () const
3500 const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3501 return (LoadScriptFromSymFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3504 Disassembler::HexImmediateStyle
3505 TargetProperties::GetHexImmediateStyle () const
3507 const uint32_t idx = ePropertyHexImmediateStyle;
3508 return (Disassembler::HexImmediateStyle)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3511 MemoryModuleLoadLevel
3512 TargetProperties::GetMemoryModuleLoadLevel() const
3514 const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3515 return (MemoryModuleLoadLevel)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3519 TargetProperties::GetUserSpecifiedTrapHandlerNames (Args &args) const
3521 const uint32_t idx = ePropertyTrapHandlerNames;
3522 return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
3526 TargetProperties::SetUserSpecifiedTrapHandlerNames (const Args &args)
3528 const uint32_t idx = ePropertyTrapHandlerNames;
3529 m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
3533 TargetProperties::GetDisplayRuntimeSupportValues () const
3535 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3536 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, false);
3540 TargetProperties::SetDisplayRuntimeSupportValues (bool b)
3542 const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3543 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3547 TargetProperties::GetNonStopModeEnabled () const
3549 const uint32_t idx = ePropertyNonStopModeEnabled;
3550 return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, false);
3554 TargetProperties::SetNonStopModeEnabled (bool b)
3556 const uint32_t idx = ePropertyNonStopModeEnabled;
3557 m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3560 const ProcessLaunchInfo &
3561 TargetProperties::GetProcessLaunchInfo ()
3563 m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3564 return m_launch_info;
3568 TargetProperties::SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
3570 m_launch_info = launch_info;
3571 SetArg0(launch_info.GetArg0());
3572 SetRunArguments(launch_info.GetArguments());
3573 SetEnvironmentFromArgs(launch_info.GetEnvironmentEntries());
3574 const FileAction *input_file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
3575 if (input_file_action)
3577 const char *input_path = input_file_action->GetPath();
3579 SetStandardInputPath(input_path);
3581 const FileAction *output_file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
3582 if (output_file_action)
3584 const char *output_path = output_file_action->GetPath();
3586 SetStandardOutputPath(output_path);
3588 const FileAction *error_file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
3589 if (error_file_action)
3591 const char *error_path = error_file_action->GetPath();
3593 SetStandardErrorPath(error_path);
3595 SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3596 SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3597 SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
3601 TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr, OptionValue *)
3603 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3604 this_->m_launch_info.SetArg0(this_->GetArg0());
3608 TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr, OptionValue *)
3610 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3612 if (this_->GetRunArguments(args))
3613 this_->m_launch_info.GetArguments() = args;
3617 TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr, OptionValue *)
3619 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3621 if (this_->GetEnvironmentAsArgs(args))
3622 this_->m_launch_info.GetEnvironmentEntries() = args;
3626 TargetProperties::InputPathValueChangedCallback(void *target_property_ptr, OptionValue *)
3628 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3629 this_->m_launch_info.AppendOpenFileAction(STDIN_FILENO, this_->GetStandardInputPath(), true, false);
3633 TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr, OptionValue *)
3635 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3636 this_->m_launch_info.AppendOpenFileAction(STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
3640 TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr, OptionValue *)
3642 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3643 this_->m_launch_info.AppendOpenFileAction(STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
3647 TargetProperties::DetachOnErrorValueChangedCallback(void *target_property_ptr, OptionValue *)
3649 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3650 if (this_->GetDetachOnError())
3651 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
3653 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
3657 TargetProperties::DisableASLRValueChangedCallback(void *target_property_ptr, OptionValue *)
3659 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3660 if (this_->GetDisableASLR())
3661 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
3663 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
3667 TargetProperties::DisableSTDIOValueChangedCallback(void *target_property_ptr, OptionValue *)
3669 TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3670 if (this_->GetDisableSTDIO())
3671 this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
3673 this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
3676 //----------------------------------------------------------------------
3677 // Target::TargetEventData
3678 //----------------------------------------------------------------------
3680 Target::TargetEventData::TargetEventData (const lldb::TargetSP &target_sp) :
3682 m_target_sp (target_sp),
3687 Target::TargetEventData::TargetEventData (const lldb::TargetSP &target_sp, const ModuleList &module_list) :
3689 m_target_sp (target_sp),
3690 m_module_list (module_list)
3694 Target::TargetEventData::~TargetEventData()
3699 Target::TargetEventData::GetFlavorString ()
3701 static ConstString g_flavor ("Target::TargetEventData");
3706 Target::TargetEventData::Dump (Stream *s) const
3710 const Target::TargetEventData *
3711 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
3715 const EventData *event_data = event_ptr->GetData();
3716 if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
3717 return static_cast <const TargetEventData *> (event_ptr->GetData());
3723 Target::TargetEventData::GetTargetFromEvent (const Event *event_ptr)
3726 const TargetEventData *event_data = GetEventDataFromEvent (event_ptr);
3728 target_sp = event_data->m_target_sp;
3733 Target::TargetEventData::GetModuleListFromEvent (const Event *event_ptr)
3735 ModuleList module_list;
3736 const TargetEventData *event_data = GetEventDataFromEvent (event_ptr);
3738 module_list = event_data->m_module_list;