1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Target/Target.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project 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/StreamString.h"
29 #include "lldb/Core/Timer.h"
30 #include "lldb/Core/ValueObject.h"
31 #include "lldb/Expression/ClangASTSource.h"
32 #include "lldb/Expression/ClangUserExpression.h"
33 #include "lldb/Host/Host.h"
34 #include "lldb/Interpreter/CommandInterpreter.h"
35 #include "lldb/Interpreter/CommandReturnObject.h"
36 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
37 #include "lldb/Interpreter/OptionValues.h"
38 #include "lldb/Interpreter/Property.h"
39 #include "lldb/lldb-private-log.h"
40 #include "lldb/Symbol/ObjectFile.h"
41 #include "lldb/Target/Process.h"
42 #include "lldb/Target/StackFrame.h"
43 #include "lldb/Target/Thread.h"
44 #include "lldb/Target/ThreadSpec.h"
45 
46 using namespace lldb;
47 using namespace lldb_private;
48 
49 ConstString &
50 Target::GetStaticBroadcasterClass ()
51 {
52     static ConstString class_name ("lldb.target");
53     return class_name;
54 }
55 
56 //----------------------------------------------------------------------
57 // Target constructor
58 //----------------------------------------------------------------------
59 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
60     TargetProperties (this),
61     Broadcaster (&debugger, Target::GetStaticBroadcasterClass().AsCString()),
62     ExecutionContextScope (),
63     m_debugger (debugger),
64     m_platform_sp (platform_sp),
65     m_mutex (Mutex::eMutexTypeRecursive),
66     m_arch (target_arch),
67     m_images (),
68     m_section_load_list (),
69     m_breakpoint_list (false),
70     m_internal_breakpoint_list (true),
71     m_watchpoint_list (),
72     m_process_sp (),
73     m_valid (true),
74     m_search_filter_sp (),
75     m_image_search_paths (ImageSearchPathsChanged, this),
76     m_scratch_ast_context_ap (NULL),
77     m_scratch_ast_source_ap (NULL),
78     m_ast_importer_ap (NULL),
79     m_persistent_variables (),
80     m_source_manager(*this),
81     m_stop_hooks (),
82     m_stop_hook_next_id (0),
83     m_suppress_stop_hooks (false),
84     m_suppress_synthetic_value(false)
85 {
86     SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
87     SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
88     SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
89 
90     CheckInWithManager();
91 
92     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
93     if (log)
94         log->Printf ("%p Target::Target()", this);
95 }
96 
97 //----------------------------------------------------------------------
98 // Destructor
99 //----------------------------------------------------------------------
100 Target::~Target()
101 {
102     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
103     if (log)
104         log->Printf ("%p Target::~Target()", this);
105     DeleteCurrentProcess ();
106 }
107 
108 void
109 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
110 {
111 //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
112     if (description_level != lldb::eDescriptionLevelBrief)
113     {
114         s->Indent();
115         s->PutCString("Target\n");
116         s->IndentMore();
117             m_images.Dump(s);
118             m_breakpoint_list.Dump(s);
119             m_internal_breakpoint_list.Dump(s);
120         s->IndentLess();
121     }
122     else
123     {
124         Module *exe_module = GetExecutableModulePointer();
125         if (exe_module)
126             s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
127         else
128             s->PutCString ("No executable module.");
129     }
130 }
131 
132 void
133 Target::DeleteCurrentProcess ()
134 {
135     if (m_process_sp.get())
136     {
137         m_section_load_list.Clear();
138         if (m_process_sp->IsAlive())
139             m_process_sp->Destroy();
140 
141         m_process_sp->Finalize();
142 
143         // Do any cleanup of the target we need to do between process instances.
144         // NB It is better to do this before destroying the process in case the
145         // clean up needs some help from the process.
146         m_breakpoint_list.ClearAllBreakpointSites();
147         m_internal_breakpoint_list.ClearAllBreakpointSites();
148         // Disable watchpoints just on the debugger side.
149         Mutex::Locker locker;
150         this->GetWatchpointList().GetListMutex(locker);
151         DisableAllWatchpoints(false);
152         ClearAllWatchpointHitCounts();
153         m_process_sp.reset();
154     }
155 }
156 
157 const lldb::ProcessSP &
158 Target::CreateProcess (Listener &listener, const char *plugin_name, const FileSpec *crash_file)
159 {
160     DeleteCurrentProcess ();
161     m_process_sp = Process::FindPlugin(*this, plugin_name, listener, crash_file);
162     return m_process_sp;
163 }
164 
165 const lldb::ProcessSP &
166 Target::GetProcessSP () const
167 {
168     return m_process_sp;
169 }
170 
171 void
172 Target::Destroy()
173 {
174     Mutex::Locker locker (m_mutex);
175     m_valid = false;
176     DeleteCurrentProcess ();
177     m_platform_sp.reset();
178     m_arch.Clear();
179     m_images.Clear();
180     m_section_load_list.Clear();
181     const bool notify = false;
182     m_breakpoint_list.RemoveAll(notify);
183     m_internal_breakpoint_list.RemoveAll(notify);
184     m_last_created_breakpoint.reset();
185     m_last_created_watchpoint.reset();
186     m_search_filter_sp.reset();
187     m_image_search_paths.Clear(notify);
188     m_scratch_ast_context_ap.reset();
189     m_scratch_ast_source_ap.reset();
190     m_ast_importer_ap.reset();
191     m_persistent_variables.Clear();
192     m_stop_hooks.clear();
193     m_stop_hook_next_id = 0;
194     m_suppress_stop_hooks = false;
195     m_suppress_synthetic_value = false;
196 }
197 
198 
199 BreakpointList &
200 Target::GetBreakpointList(bool internal)
201 {
202     if (internal)
203         return m_internal_breakpoint_list;
204     else
205         return m_breakpoint_list;
206 }
207 
208 const BreakpointList &
209 Target::GetBreakpointList(bool internal) const
210 {
211     if (internal)
212         return m_internal_breakpoint_list;
213     else
214         return m_breakpoint_list;
215 }
216 
217 BreakpointSP
218 Target::GetBreakpointByID (break_id_t break_id)
219 {
220     BreakpointSP bp_sp;
221 
222     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
223         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
224     else
225         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
226 
227     return bp_sp;
228 }
229 
230 BreakpointSP
231 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
232                                      const FileSpecList *source_file_spec_list,
233                                      RegularExpression &source_regex,
234                                      bool internal)
235 {
236     SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list));
237     BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex (NULL, source_regex));
238     return CreateBreakpoint (filter_sp, resolver_sp, internal);
239 }
240 
241 
242 BreakpointSP
243 Target::CreateBreakpoint (const FileSpecList *containingModules,
244                           const FileSpec &file,
245                           uint32_t line_no,
246                           LazyBool check_inlines,
247                           LazyBool skip_prologue,
248                           bool internal)
249 {
250     if (check_inlines == eLazyBoolCalculate)
251     {
252         const InlineStrategy inline_strategy = GetInlineStrategy();
253         switch (inline_strategy)
254         {
255             case eInlineBreakpointsNever:
256                 check_inlines = eLazyBoolNo;
257                 break;
258 
259             case eInlineBreakpointsHeaders:
260                 if (file.IsSourceImplementationFile())
261                     check_inlines = eLazyBoolNo;
262                 else
263                     check_inlines = eLazyBoolYes;
264                 break;
265 
266             case eInlineBreakpointsAlways:
267                 check_inlines = eLazyBoolYes;
268                 break;
269         }
270     }
271     SearchFilterSP filter_sp;
272     if (check_inlines == eLazyBoolNo)
273     {
274         // Not checking for inlines, we are looking only for matching compile units
275         FileSpecList compile_unit_list;
276         compile_unit_list.Append (file);
277         filter_sp = GetSearchFilterForModuleAndCUList (containingModules, &compile_unit_list);
278     }
279     else
280     {
281         filter_sp = GetSearchFilterForModuleList (containingModules);
282     }
283     BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL,
284                                                                      file,
285                                                                      line_no,
286                                                                      check_inlines,
287                                                                      skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
288     return CreateBreakpoint (filter_sp, resolver_sp, internal);
289 }
290 
291 
292 BreakpointSP
293 Target::CreateBreakpoint (lldb::addr_t addr, bool internal)
294 {
295     Address so_addr;
296     // Attempt to resolve our load address if possible, though it is ok if
297     // it doesn't resolve to section/offset.
298 
299     // Try and resolve as a load address if possible
300     m_section_load_list.ResolveLoadAddress(addr, so_addr);
301     if (!so_addr.IsValid())
302     {
303         // The address didn't resolve, so just set this as an absolute address
304         so_addr.SetOffset (addr);
305     }
306     BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal));
307     return bp_sp;
308 }
309 
310 BreakpointSP
311 Target::CreateBreakpoint (Address &addr, bool internal)
312 {
313     SearchFilterSP filter_sp(new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
314     BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
315     return CreateBreakpoint (filter_sp, resolver_sp, internal);
316 }
317 
318 BreakpointSP
319 Target::CreateBreakpoint (const FileSpecList *containingModules,
320                           const FileSpecList *containingSourceFiles,
321                           const char *func_name,
322                           uint32_t func_name_type_mask,
323                           LazyBool skip_prologue,
324                           bool internal)
325 {
326     BreakpointSP bp_sp;
327     if (func_name)
328     {
329         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
330 
331         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
332                                                                       func_name,
333                                                                       func_name_type_mask,
334                                                                       Breakpoint::Exact,
335                                                                       skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
336         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
337     }
338     return bp_sp;
339 }
340 
341 lldb::BreakpointSP
342 Target::CreateBreakpoint (const FileSpecList *containingModules,
343                           const FileSpecList *containingSourceFiles,
344                           const std::vector<std::string> &func_names,
345                           uint32_t func_name_type_mask,
346                           LazyBool skip_prologue,
347                           bool internal)
348 {
349     BreakpointSP bp_sp;
350     size_t num_names = func_names.size();
351     if (num_names > 0)
352     {
353         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
354 
355         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
356                                                                       func_names,
357                                                                       func_name_type_mask,
358                                                                       skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
359         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
360     }
361     return bp_sp;
362 }
363 
364 BreakpointSP
365 Target::CreateBreakpoint (const FileSpecList *containingModules,
366                           const FileSpecList *containingSourceFiles,
367                           const char *func_names[],
368                           size_t num_names,
369                           uint32_t func_name_type_mask,
370                           LazyBool skip_prologue,
371                           bool internal)
372 {
373     BreakpointSP bp_sp;
374     if (num_names > 0)
375     {
376         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
377 
378         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
379                                                                       func_names,
380                                                                       num_names,
381                                                                       func_name_type_mask,
382                                                                       skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
383         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
384     }
385     return bp_sp;
386 }
387 
388 SearchFilterSP
389 Target::GetSearchFilterForModule (const FileSpec *containingModule)
390 {
391     SearchFilterSP filter_sp;
392     if (containingModule != NULL)
393     {
394         // TODO: We should look into sharing module based search filters
395         // across many breakpoints like we do for the simple target based one
396         filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule));
397     }
398     else
399     {
400         if (m_search_filter_sp.get() == NULL)
401             m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
402         filter_sp = m_search_filter_sp;
403     }
404     return filter_sp;
405 }
406 
407 SearchFilterSP
408 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules)
409 {
410     SearchFilterSP filter_sp;
411     if (containingModules && containingModules->GetSize() != 0)
412     {
413         // TODO: We should look into sharing module based search filters
414         // across many breakpoints like we do for the simple target based one
415         filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules));
416     }
417     else
418     {
419         if (m_search_filter_sp.get() == NULL)
420             m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
421         filter_sp = m_search_filter_sp;
422     }
423     return filter_sp;
424 }
425 
426 SearchFilterSP
427 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules,
428                                            const FileSpecList *containingSourceFiles)
429 {
430     if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0)
431         return GetSearchFilterForModuleList(containingModules);
432 
433     SearchFilterSP filter_sp;
434     if (containingModules == NULL)
435     {
436         // We could make a special "CU List only SearchFilter".  Better yet was if these could be composable,
437         // but that will take a little reworking.
438 
439         filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles));
440     }
441     else
442     {
443         filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles));
444     }
445     return filter_sp;
446 }
447 
448 BreakpointSP
449 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
450                                    const FileSpecList *containingSourceFiles,
451                                    RegularExpression &func_regex,
452                                    LazyBool skip_prologue,
453                                    bool internal)
454 {
455     SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
456     BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
457                                                                  func_regex,
458                                                                  skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
459 
460     return CreateBreakpoint (filter_sp, resolver_sp, internal);
461 }
462 
463 lldb::BreakpointSP
464 Target::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal)
465 {
466     return LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal);
467 }
468 
469 BreakpointSP
470 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal)
471 {
472     BreakpointSP bp_sp;
473     if (filter_sp && resolver_sp)
474     {
475         bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp));
476         resolver_sp->SetBreakpoint (bp_sp.get());
477 
478         if (internal)
479             m_internal_breakpoint_list.Add (bp_sp, false);
480         else
481             m_breakpoint_list.Add (bp_sp, true);
482 
483         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
484         if (log)
485         {
486             StreamString s;
487             bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
488             log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
489         }
490 
491         bp_sp->ResolveBreakpoint();
492     }
493 
494     if (!internal && bp_sp)
495     {
496         m_last_created_breakpoint = bp_sp;
497     }
498 
499     return bp_sp;
500 }
501 
502 bool
503 Target::ProcessIsValid()
504 {
505     return (m_process_sp && m_process_sp->IsAlive());
506 }
507 
508 static bool
509 CheckIfWatchpointsExhausted(Target *target, Error &error)
510 {
511     uint32_t num_supported_hardware_watchpoints;
512     Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints);
513     if (rc.Success())
514     {
515         uint32_t num_current_watchpoints = target->GetWatchpointList().GetSize();
516         if (num_current_watchpoints >= num_supported_hardware_watchpoints)
517             error.SetErrorStringWithFormat("number of supported hardware watchpoints (%u) has been reached",
518                                            num_supported_hardware_watchpoints);
519     }
520     return false;
521 }
522 
523 // See also Watchpoint::SetWatchpointType(uint32_t type) and
524 // the OptionGroupWatchpoint::WatchType enum type.
525 WatchpointSP
526 Target::CreateWatchpoint(lldb::addr_t addr, size_t size, const ClangASTType *type, uint32_t kind, Error &error)
527 {
528     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
529     if (log)
530         log->Printf("Target::%s (addr = 0x%8.8llx size = %llu type = %u)\n",
531                     __FUNCTION__, addr, (uint64_t)size, kind);
532 
533     WatchpointSP wp_sp;
534     if (!ProcessIsValid())
535     {
536         error.SetErrorString("process is not alive");
537         return wp_sp;
538     }
539     if (addr == LLDB_INVALID_ADDRESS || size == 0)
540     {
541         if (size == 0)
542             error.SetErrorString("cannot set a watchpoint with watch_size of 0");
543         else
544             error.SetErrorStringWithFormat("invalid watch address: %llu", addr);
545         return wp_sp;
546     }
547 
548     // Currently we only support one watchpoint per address, with total number
549     // of watchpoints limited by the hardware which the inferior is running on.
550 
551     // Grab the list mutex while doing operations.
552     Mutex::Locker locker;
553     this->GetWatchpointList().GetListMutex(locker);
554     WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
555     if (matched_sp)
556     {
557         size_t old_size = matched_sp->GetByteSize();
558         uint32_t old_type =
559             (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
560             (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
561         // Return the existing watchpoint if both size and type match.
562         if (size == old_size && kind == old_type) {
563             wp_sp = matched_sp;
564             wp_sp->SetEnabled(false);
565         } else {
566             // Nil the matched watchpoint; we will be creating a new one.
567             m_process_sp->DisableWatchpoint(matched_sp.get());
568             m_watchpoint_list.Remove(matched_sp->GetID());
569         }
570     }
571 
572     if (!wp_sp) {
573         Watchpoint *new_wp = new Watchpoint(*this, addr, size, type);
574         if (!new_wp) {
575             printf("Watchpoint ctor failed, out of memory?\n");
576             return wp_sp;
577         }
578         new_wp->SetWatchpointType(kind);
579         wp_sp.reset(new_wp);
580         m_watchpoint_list.Add(wp_sp);
581     }
582 
583     error = m_process_sp->EnableWatchpoint(wp_sp.get());
584     if (log)
585             log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
586                         __FUNCTION__,
587                         error.Success() ? "succeeded" : "failed",
588                         wp_sp->GetID());
589 
590     if (error.Fail()) {
591         // Enabling the watchpoint on the device side failed.
592         // Remove the said watchpoint from the list maintained by the target instance.
593         m_watchpoint_list.Remove(wp_sp->GetID());
594         // See if we could provide more helpful error message.
595         if (!CheckIfWatchpointsExhausted(this, error))
596         {
597             if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
598                 error.SetErrorStringWithFormat("watch size of %lu is not supported", size);
599         }
600         wp_sp.reset();
601     }
602     else
603         m_last_created_watchpoint = wp_sp;
604     return wp_sp;
605 }
606 
607 void
608 Target::RemoveAllBreakpoints (bool internal_also)
609 {
610     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
611     if (log)
612         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
613 
614     m_breakpoint_list.RemoveAll (true);
615     if (internal_also)
616         m_internal_breakpoint_list.RemoveAll (false);
617 
618     m_last_created_breakpoint.reset();
619 }
620 
621 void
622 Target::DisableAllBreakpoints (bool internal_also)
623 {
624     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
625     if (log)
626         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
627 
628     m_breakpoint_list.SetEnabledAll (false);
629     if (internal_also)
630         m_internal_breakpoint_list.SetEnabledAll (false);
631 }
632 
633 void
634 Target::EnableAllBreakpoints (bool internal_also)
635 {
636     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
637     if (log)
638         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
639 
640     m_breakpoint_list.SetEnabledAll (true);
641     if (internal_also)
642         m_internal_breakpoint_list.SetEnabledAll (true);
643 }
644 
645 bool
646 Target::RemoveBreakpointByID (break_id_t break_id)
647 {
648     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
649     if (log)
650         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
651 
652     if (DisableBreakpointByID (break_id))
653     {
654         if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
655             m_internal_breakpoint_list.Remove(break_id, false);
656         else
657         {
658             if (m_last_created_breakpoint)
659             {
660                 if (m_last_created_breakpoint->GetID() == break_id)
661                     m_last_created_breakpoint.reset();
662             }
663             m_breakpoint_list.Remove(break_id, true);
664         }
665         return true;
666     }
667     return false;
668 }
669 
670 bool
671 Target::DisableBreakpointByID (break_id_t break_id)
672 {
673     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
674     if (log)
675         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
676 
677     BreakpointSP bp_sp;
678 
679     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
680         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
681     else
682         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
683     if (bp_sp)
684     {
685         bp_sp->SetEnabled (false);
686         return true;
687     }
688     return false;
689 }
690 
691 bool
692 Target::EnableBreakpointByID (break_id_t break_id)
693 {
694     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
695     if (log)
696         log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
697                      __FUNCTION__,
698                      break_id,
699                      LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
700 
701     BreakpointSP bp_sp;
702 
703     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
704         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
705     else
706         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
707 
708     if (bp_sp)
709     {
710         bp_sp->SetEnabled (true);
711         return true;
712     }
713     return false;
714 }
715 
716 // The flag 'end_to_end', default to true, signifies that the operation is
717 // performed end to end, for both the debugger and the debuggee.
718 
719 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
720 // to end operations.
721 bool
722 Target::RemoveAllWatchpoints (bool end_to_end)
723 {
724     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
725     if (log)
726         log->Printf ("Target::%s\n", __FUNCTION__);
727 
728     if (!end_to_end) {
729         m_watchpoint_list.RemoveAll();
730         return true;
731     }
732 
733     // Otherwise, it's an end to end operation.
734 
735     if (!ProcessIsValid())
736         return false;
737 
738     size_t num_watchpoints = m_watchpoint_list.GetSize();
739     for (size_t i = 0; i < num_watchpoints; ++i)
740     {
741         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
742         if (!wp_sp)
743             return false;
744 
745         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
746         if (rc.Fail())
747             return false;
748     }
749     m_watchpoint_list.RemoveAll ();
750     return true; // Success!
751 }
752 
753 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
754 // end operations.
755 bool
756 Target::DisableAllWatchpoints (bool end_to_end)
757 {
758     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
759     if (log)
760         log->Printf ("Target::%s\n", __FUNCTION__);
761 
762     if (!end_to_end) {
763         m_watchpoint_list.SetEnabledAll(false);
764         return true;
765     }
766 
767     // Otherwise, it's an end to end operation.
768 
769     if (!ProcessIsValid())
770         return false;
771 
772     size_t num_watchpoints = m_watchpoint_list.GetSize();
773     for (size_t i = 0; i < num_watchpoints; ++i)
774     {
775         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
776         if (!wp_sp)
777             return false;
778 
779         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
780         if (rc.Fail())
781             return false;
782     }
783     return true; // Success!
784 }
785 
786 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
787 // end operations.
788 bool
789 Target::EnableAllWatchpoints (bool end_to_end)
790 {
791     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
792     if (log)
793         log->Printf ("Target::%s\n", __FUNCTION__);
794 
795     if (!end_to_end) {
796         m_watchpoint_list.SetEnabledAll(true);
797         return true;
798     }
799 
800     // Otherwise, it's an end to end operation.
801 
802     if (!ProcessIsValid())
803         return false;
804 
805     size_t num_watchpoints = m_watchpoint_list.GetSize();
806     for (size_t i = 0; i < num_watchpoints; ++i)
807     {
808         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
809         if (!wp_sp)
810             return false;
811 
812         Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
813         if (rc.Fail())
814             return false;
815     }
816     return true; // Success!
817 }
818 
819 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
820 bool
821 Target::ClearAllWatchpointHitCounts ()
822 {
823     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
824     if (log)
825         log->Printf ("Target::%s\n", __FUNCTION__);
826 
827     size_t num_watchpoints = m_watchpoint_list.GetSize();
828     for (size_t i = 0; i < num_watchpoints; ++i)
829     {
830         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
831         if (!wp_sp)
832             return false;
833 
834         wp_sp->ResetHitCount();
835     }
836     return true; // Success!
837 }
838 
839 // Assumption: Caller holds the list mutex lock for m_watchpoint_list
840 // during these operations.
841 bool
842 Target::IgnoreAllWatchpoints (uint32_t ignore_count)
843 {
844     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
845     if (log)
846         log->Printf ("Target::%s\n", __FUNCTION__);
847 
848     if (!ProcessIsValid())
849         return false;
850 
851     size_t num_watchpoints = m_watchpoint_list.GetSize();
852     for (size_t i = 0; i < num_watchpoints; ++i)
853     {
854         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
855         if (!wp_sp)
856             return false;
857 
858         wp_sp->SetIgnoreCount(ignore_count);
859     }
860     return true; // Success!
861 }
862 
863 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
864 bool
865 Target::DisableWatchpointByID (lldb::watch_id_t watch_id)
866 {
867     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
868     if (log)
869         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
870 
871     if (!ProcessIsValid())
872         return false;
873 
874     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
875     if (wp_sp)
876     {
877         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
878         if (rc.Success())
879             return true;
880 
881         // Else, fallthrough.
882     }
883     return false;
884 }
885 
886 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
887 bool
888 Target::EnableWatchpointByID (lldb::watch_id_t watch_id)
889 {
890     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
891     if (log)
892         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
893 
894     if (!ProcessIsValid())
895         return false;
896 
897     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
898     if (wp_sp)
899     {
900         Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
901         if (rc.Success())
902             return true;
903 
904         // Else, fallthrough.
905     }
906     return false;
907 }
908 
909 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
910 bool
911 Target::RemoveWatchpointByID (lldb::watch_id_t watch_id)
912 {
913     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
914     if (log)
915         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
916 
917     if (DisableWatchpointByID (watch_id))
918     {
919         m_watchpoint_list.Remove(watch_id);
920         return true;
921     }
922     return false;
923 }
924 
925 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
926 bool
927 Target::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
928 {
929     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
930     if (log)
931         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
932 
933     if (!ProcessIsValid())
934         return false;
935 
936     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
937     if (wp_sp)
938     {
939         wp_sp->SetIgnoreCount(ignore_count);
940         return true;
941     }
942     return false;
943 }
944 
945 ModuleSP
946 Target::GetExecutableModule ()
947 {
948     return m_images.GetModuleAtIndex(0);
949 }
950 
951 Module*
952 Target::GetExecutableModulePointer ()
953 {
954     return m_images.GetModulePointerAtIndex(0);
955 }
956 
957 void
958 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
959 {
960     m_images.Clear();
961     m_scratch_ast_context_ap.reset();
962     m_scratch_ast_source_ap.reset();
963     m_ast_importer_ap.reset();
964 
965     if (executable_sp.get())
966     {
967         Timer scoped_timer (__PRETTY_FUNCTION__,
968                             "Target::SetExecutableModule (executable = '%s/%s')",
969                             executable_sp->GetFileSpec().GetDirectory().AsCString(),
970                             executable_sp->GetFileSpec().GetFilename().AsCString());
971 
972         m_images.Append(executable_sp); // The first image is our exectuable file
973 
974         // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
975         if (!m_arch.IsValid())
976             m_arch = executable_sp->GetArchitecture();
977 
978         FileSpecList dependent_files;
979         ObjectFile *executable_objfile = executable_sp->GetObjectFile();
980 
981         if (executable_objfile && get_dependent_files)
982         {
983             executable_objfile->GetDependentModules(dependent_files);
984             for (uint32_t i=0; i<dependent_files.GetSize(); i++)
985             {
986                 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
987                 FileSpec platform_dependent_file_spec;
988                 if (m_platform_sp)
989                     m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec);
990                 else
991                     platform_dependent_file_spec = dependent_file_spec;
992 
993                 ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
994                 ModuleSP image_module_sp(GetSharedModule (module_spec));
995                 if (image_module_sp.get())
996                 {
997                     ObjectFile *objfile = image_module_sp->GetObjectFile();
998                     if (objfile)
999                         objfile->GetDependentModules(dependent_files);
1000                 }
1001             }
1002         }
1003     }
1004 }
1005 
1006 
1007 bool
1008 Target::SetArchitecture (const ArchSpec &arch_spec)
1009 {
1010     if (m_arch == arch_spec || !m_arch.IsValid())
1011     {
1012         // If we haven't got a valid arch spec, or the architectures are
1013         // compatible, so just update the architecture. Architectures can be
1014         // equal, yet the triple OS and vendor might change, so we need to do
1015         // the assignment here just in case.
1016         m_arch = arch_spec;
1017         return true;
1018     }
1019     else
1020     {
1021         // If we have an executable file, try to reset the executable to the desired architecture
1022         m_arch = arch_spec;
1023         ModuleSP executable_sp = GetExecutableModule ();
1024         m_images.Clear();
1025         m_scratch_ast_context_ap.reset();
1026         m_scratch_ast_source_ap.reset();
1027         m_ast_importer_ap.reset();
1028         // Need to do something about unsetting breakpoints.
1029 
1030         if (executable_sp)
1031         {
1032             ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec);
1033             Error error = ModuleList::GetSharedModule (module_spec,
1034                                                        executable_sp,
1035                                                        &GetExecutableSearchPaths(),
1036                                                        NULL,
1037                                                        NULL);
1038 
1039             if (!error.Fail() && executable_sp)
1040             {
1041                 SetExecutableModule (executable_sp, true);
1042                 return true;
1043             }
1044         }
1045     }
1046     return false;
1047 }
1048 
1049 void
1050 Target::ModuleAdded (ModuleSP &module_sp)
1051 {
1052     // A module is being added to this target for the first time
1053     ModuleList module_list;
1054     module_list.Append(module_sp);
1055     ModulesDidLoad (module_list);
1056 }
1057 
1058 void
1059 Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp)
1060 {
1061     // A module is replacing an already added module
1062     m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1063 }
1064 
1065 void
1066 Target::ModulesDidLoad (ModuleList &module_list)
1067 {
1068     m_breakpoint_list.UpdateBreakpoints (module_list, true);
1069     // TODO: make event data that packages up the module_list
1070     BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
1071 }
1072 
1073 void
1074 Target::ModulesDidUnload (ModuleList &module_list)
1075 {
1076     m_breakpoint_list.UpdateBreakpoints (module_list, false);
1077 
1078     // Remove the images from the target image list
1079     m_images.Remove(module_list);
1080 
1081     // TODO: make event data that packages up the module_list
1082     BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
1083 }
1084 
1085 
1086 bool
1087 Target::ModuleIsExcludedForNonModuleSpecificSearches (const FileSpec &module_file_spec)
1088 {
1089 
1090     if (GetBreakpointsConsultPlatformAvoidList())
1091     {
1092         ModuleList matchingModules;
1093         ModuleSpec module_spec (module_file_spec);
1094         size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1095 
1096         // If there is more than one module for this file spec, only return true if ALL the modules are on the
1097         // black list.
1098         if (num_modules > 0)
1099         {
1100             for (int i  = 0; i < num_modules; i++)
1101             {
1102                 if (!ModuleIsExcludedForNonModuleSpecificSearches (matchingModules.GetModuleAtIndex(i)))
1103                     return false;
1104             }
1105             return true;
1106         }
1107     }
1108     return false;
1109 }
1110 
1111 bool
1112 Target::ModuleIsExcludedForNonModuleSpecificSearches (const lldb::ModuleSP &module_sp)
1113 {
1114     if (GetBreakpointsConsultPlatformAvoidList())
1115     {
1116         if (m_platform_sp)
1117             return m_platform_sp->ModuleIsExcludedForNonModuleSpecificSearches (*this, module_sp);
1118     }
1119     return false;
1120 }
1121 
1122 size_t
1123 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
1124 {
1125     SectionSP section_sp (addr.GetSection());
1126     if (section_sp)
1127     {
1128         // If the contents of this section are encrypted, the on-disk file is unusuable.  Read only from live memory.
1129         if (section_sp->IsEncrypted())
1130         {
1131             error.SetErrorString("section is encrypted");
1132             return 0;
1133         }
1134         ModuleSP module_sp (section_sp->GetModule());
1135         if (module_sp)
1136         {
1137             ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1138             if (objfile)
1139             {
1140                 size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
1141                                                               addr.GetOffset(),
1142                                                               dst,
1143                                                               dst_len);
1144                 if (bytes_read > 0)
1145                     return bytes_read;
1146                 else
1147                     error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
1148             }
1149             else
1150                 error.SetErrorString("address isn't from a object file");
1151         }
1152         else
1153             error.SetErrorString("address isn't in a module");
1154     }
1155     else
1156         error.SetErrorString("address doesn't contain a section that points to a section in a object file");
1157 
1158     return 0;
1159 }
1160 
1161 size_t
1162 Target::ReadMemory (const Address& addr,
1163                     bool prefer_file_cache,
1164                     void *dst,
1165                     size_t dst_len,
1166                     Error &error,
1167                     lldb::addr_t *load_addr_ptr)
1168 {
1169     error.Clear();
1170 
1171     // if we end up reading this from process memory, we will fill this
1172     // with the actual load address
1173     if (load_addr_ptr)
1174         *load_addr_ptr = LLDB_INVALID_ADDRESS;
1175 
1176     size_t bytes_read = 0;
1177 
1178     addr_t load_addr = LLDB_INVALID_ADDRESS;
1179     addr_t file_addr = LLDB_INVALID_ADDRESS;
1180     Address resolved_addr;
1181     if (!addr.IsSectionOffset())
1182     {
1183         if (m_section_load_list.IsEmpty())
1184         {
1185             // No sections are loaded, so we must assume we are not running
1186             // yet and anything we are given is a file address.
1187             file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
1188             m_images.ResolveFileAddress (file_addr, resolved_addr);
1189         }
1190         else
1191         {
1192             // We have at least one section loaded. This can be becuase
1193             // we have manually loaded some sections with "target modules load ..."
1194             // or because we have have a live process that has sections loaded
1195             // through the dynamic loader
1196             load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1197             m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1198         }
1199     }
1200     if (!resolved_addr.IsValid())
1201         resolved_addr = addr;
1202 
1203 
1204     if (prefer_file_cache)
1205     {
1206         bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1207         if (bytes_read > 0)
1208             return bytes_read;
1209     }
1210 
1211     if (ProcessIsValid())
1212     {
1213         if (load_addr == LLDB_INVALID_ADDRESS)
1214             load_addr = resolved_addr.GetLoadAddress (this);
1215 
1216         if (load_addr == LLDB_INVALID_ADDRESS)
1217         {
1218             ModuleSP addr_module_sp (resolved_addr.GetModule());
1219             if (addr_module_sp && addr_module_sp->GetFileSpec())
1220                 error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded",
1221                                                addr_module_sp->GetFileSpec().GetFilename().AsCString(),
1222                                                resolved_addr.GetFileAddress(),
1223                                                addr_module_sp->GetFileSpec().GetFilename().AsCString());
1224             else
1225                 error.SetErrorStringWithFormat("0x%llx can't be resolved", resolved_addr.GetFileAddress());
1226         }
1227         else
1228         {
1229             bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1230             if (bytes_read != dst_len)
1231             {
1232                 if (error.Success())
1233                 {
1234                     if (bytes_read == 0)
1235                         error.SetErrorStringWithFormat("read memory from 0x%llx failed", load_addr);
1236                     else
1237                         error.SetErrorStringWithFormat("only %llu of %llu bytes were read from memory at 0x%llx", (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1238                 }
1239             }
1240             if (bytes_read)
1241             {
1242                 if (load_addr_ptr)
1243                     *load_addr_ptr = load_addr;
1244                 return bytes_read;
1245             }
1246             // If the address is not section offset we have an address that
1247             // doesn't resolve to any address in any currently loaded shared
1248             // libaries and we failed to read memory so there isn't anything
1249             // more we can do. If it is section offset, we might be able to
1250             // read cached memory from the object file.
1251             if (!resolved_addr.IsSectionOffset())
1252                 return 0;
1253         }
1254     }
1255 
1256     if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1257     {
1258         // If we didn't already try and read from the object file cache, then
1259         // try it after failing to read from the process.
1260         return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1261     }
1262     return 0;
1263 }
1264 
1265 size_t
1266 Target::ReadScalarIntegerFromMemory (const Address& addr,
1267                                      bool prefer_file_cache,
1268                                      uint32_t byte_size,
1269                                      bool is_signed,
1270                                      Scalar &scalar,
1271                                      Error &error)
1272 {
1273     uint64_t uval;
1274 
1275     if (byte_size <= sizeof(uval))
1276     {
1277         size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1278         if (bytes_read == byte_size)
1279         {
1280             DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1281             uint32_t offset = 0;
1282             if (byte_size <= 4)
1283                 scalar = data.GetMaxU32 (&offset, byte_size);
1284             else
1285                 scalar = data.GetMaxU64 (&offset, byte_size);
1286 
1287             if (is_signed)
1288                 scalar.SignExtend(byte_size * 8);
1289             return bytes_read;
1290         }
1291     }
1292     else
1293     {
1294         error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1295     }
1296     return 0;
1297 }
1298 
1299 uint64_t
1300 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1301                                        bool prefer_file_cache,
1302                                        size_t integer_byte_size,
1303                                        uint64_t fail_value,
1304                                        Error &error)
1305 {
1306     Scalar scalar;
1307     if (ReadScalarIntegerFromMemory (addr,
1308                                      prefer_file_cache,
1309                                      integer_byte_size,
1310                                      false,
1311                                      scalar,
1312                                      error))
1313         return scalar.ULongLong(fail_value);
1314     return fail_value;
1315 }
1316 
1317 bool
1318 Target::ReadPointerFromMemory (const Address& addr,
1319                                bool prefer_file_cache,
1320                                Error &error,
1321                                Address &pointer_addr)
1322 {
1323     Scalar scalar;
1324     if (ReadScalarIntegerFromMemory (addr,
1325                                      prefer_file_cache,
1326                                      m_arch.GetAddressByteSize(),
1327                                      false,
1328                                      scalar,
1329                                      error))
1330     {
1331         addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1332         if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1333         {
1334             if (m_section_load_list.IsEmpty())
1335             {
1336                 // No sections are loaded, so we must assume we are not running
1337                 // yet and anything we are given is a file address.
1338                 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1339             }
1340             else
1341             {
1342                 // We have at least one section loaded. This can be becuase
1343                 // we have manually loaded some sections with "target modules load ..."
1344                 // or because we have have a live process that has sections loaded
1345                 // through the dynamic loader
1346                 m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1347             }
1348             // We weren't able to resolve the pointer value, so just return
1349             // an address with no section
1350             if (!pointer_addr.IsValid())
1351                 pointer_addr.SetOffset (pointer_vm_addr);
1352             return true;
1353 
1354         }
1355     }
1356     return false;
1357 }
1358 
1359 ModuleSP
1360 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
1361 {
1362     ModuleSP module_sp;
1363 
1364     Error error;
1365 
1366     // First see if we already have this module in our module list.  If we do, then we're done, we don't need
1367     // to consult the shared modules list.  But only do this if we are passed a UUID.
1368 
1369     if (module_spec.GetUUID().IsValid())
1370         module_sp = m_images.FindFirstModule(module_spec);
1371 
1372     if (!module_sp)
1373     {
1374         ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1375         bool did_create_module = false;
1376 
1377         // If there are image search path entries, try to use them first to acquire a suitable image.
1378         if (m_image_search_paths.GetSize())
1379         {
1380             ModuleSpec transformed_spec (module_spec);
1381             if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
1382             {
1383                 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
1384                 error = ModuleList::GetSharedModule (transformed_spec,
1385                                                      module_sp,
1386                                                      &GetExecutableSearchPaths(),
1387                                                      &old_module_sp,
1388                                                      &did_create_module);
1389             }
1390         }
1391 
1392         if (!module_sp)
1393         {
1394             // If we have a UUID, we can check our global shared module list in case
1395             // we already have it. If we don't have a valid UUID, then we can't since
1396             // the path in "module_spec" will be a platform path, and we will need to
1397             // let the platform find that file. For example, we could be asking for
1398             // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1399             // the local copy of "/usr/lib/dyld" since our platform could be a remote
1400             // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1401             // cache.
1402             if (module_spec.GetUUID().IsValid())
1403             {
1404                 // We have a UUID, it is OK to check the global module list...
1405                 error = ModuleList::GetSharedModule (module_spec,
1406                                                      module_sp,
1407                                                      &GetExecutableSearchPaths(),
1408                                                      &old_module_sp,
1409                                                      &did_create_module);
1410             }
1411 
1412             if (!module_sp)
1413             {
1414                 // The platform is responsible for finding and caching an appropriate
1415                 // module in the shared module cache.
1416                 if (m_platform_sp)
1417                 {
1418                     FileSpec platform_file_spec;
1419                     error = m_platform_sp->GetSharedModule (module_spec,
1420                                                             module_sp,
1421                                                             &GetExecutableSearchPaths(),
1422                                                             &old_module_sp,
1423                                                             &did_create_module);
1424                 }
1425                 else
1426                 {
1427                     error.SetErrorString("no platform is currently set");
1428                 }
1429             }
1430         }
1431 
1432         // We found a module that wasn't in our target list.  Let's make sure that there wasn't an equivalent
1433         // module in the list already, and if there was, let's remove it.
1434         if (module_sp)
1435         {
1436             // GetSharedModule is not guaranteed to find the old shared module, for instance
1437             // in the common case where you pass in the UUID, it is only going to find the one
1438             // module matching the UUID.  In fact, it has no good way to know what the "old module"
1439             // relevant to this target is, since there might be many copies of a module with this file spec
1440             // in various running debug sessions, but only one of them will belong to this target.
1441             // So let's remove the UUID from the module list, and look in the target's module list.
1442             // Only do this if there is SOMETHING else in the module spec...
1443             if (!old_module_sp)
1444             {
1445                 if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
1446                 {
1447                     ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1448                     module_spec_copy.GetUUID().Clear();
1449 
1450                     ModuleList found_modules;
1451                     size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
1452                     if (num_found == 1)
1453                     {
1454                         old_module_sp = found_modules.GetModuleAtIndex(0);
1455                     }
1456                 }
1457             }
1458 
1459             m_images.Append (module_sp);
1460             if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1461             {
1462                 ModuleUpdated(old_module_sp, module_sp);
1463                 m_images.Remove (old_module_sp);
1464                 Module *old_module_ptr = old_module_sp.get();
1465                 old_module_sp.reset();
1466                 ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
1467             }
1468             else
1469                 ModuleAdded(module_sp);
1470         }
1471     }
1472     if (error_ptr)
1473         *error_ptr = error;
1474     return module_sp;
1475 }
1476 
1477 
1478 TargetSP
1479 Target::CalculateTarget ()
1480 {
1481     return shared_from_this();
1482 }
1483 
1484 ProcessSP
1485 Target::CalculateProcess ()
1486 {
1487     return ProcessSP();
1488 }
1489 
1490 ThreadSP
1491 Target::CalculateThread ()
1492 {
1493     return ThreadSP();
1494 }
1495 
1496 StackFrameSP
1497 Target::CalculateStackFrame ()
1498 {
1499     return StackFrameSP();
1500 }
1501 
1502 void
1503 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1504 {
1505     exe_ctx.Clear();
1506     exe_ctx.SetTargetPtr(this);
1507 }
1508 
1509 PathMappingList &
1510 Target::GetImageSearchPathList ()
1511 {
1512     return m_image_search_paths;
1513 }
1514 
1515 void
1516 Target::ImageSearchPathsChanged
1517 (
1518     const PathMappingList &path_list,
1519     void *baton
1520 )
1521 {
1522     Target *target = (Target *)baton;
1523     ModuleSP exe_module_sp (target->GetExecutableModule());
1524     if (exe_module_sp)
1525     {
1526         target->m_images.Clear();
1527         target->SetExecutableModule (exe_module_sp, true);
1528     }
1529 }
1530 
1531 ClangASTContext *
1532 Target::GetScratchClangASTContext(bool create_on_demand)
1533 {
1534     // Now see if we know the target triple, and if so, create our scratch AST context:
1535     if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand)
1536     {
1537         m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1538         m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this()));
1539         m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext());
1540         llvm::OwningPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy());
1541         m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source);
1542     }
1543     return m_scratch_ast_context_ap.get();
1544 }
1545 
1546 ClangASTImporter *
1547 Target::GetClangASTImporter()
1548 {
1549     ClangASTImporter *ast_importer = m_ast_importer_ap.get();
1550 
1551     if (!ast_importer)
1552     {
1553         ast_importer = new ClangASTImporter();
1554         m_ast_importer_ap.reset(ast_importer);
1555     }
1556 
1557     return ast_importer;
1558 }
1559 
1560 void
1561 Target::SettingsInitialize ()
1562 {
1563     Process::SettingsInitialize ();
1564 }
1565 
1566 void
1567 Target::SettingsTerminate ()
1568 {
1569     Process::SettingsTerminate ();
1570 }
1571 
1572 FileSpecList
1573 Target::GetDefaultExecutableSearchPaths ()
1574 {
1575     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1576     if (properties_sp)
1577         return properties_sp->GetExecutableSearchPaths();
1578     return FileSpecList();
1579 }
1580 
1581 ArchSpec
1582 Target::GetDefaultArchitecture ()
1583 {
1584     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1585     if (properties_sp)
1586         return properties_sp->GetDefaultArchitecture();
1587     return ArchSpec();
1588 }
1589 
1590 void
1591 Target::SetDefaultArchitecture (const ArchSpec &arch)
1592 {
1593     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1594     if (properties_sp)
1595         return properties_sp->SetDefaultArchitecture(arch);
1596 }
1597 
1598 Target *
1599 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1600 {
1601     // The target can either exist in the "process" of ExecutionContext, or in
1602     // the "target_sp" member of SymbolContext. This accessor helper function
1603     // will get the target from one of these locations.
1604 
1605     Target *target = NULL;
1606     if (sc_ptr != NULL)
1607         target = sc_ptr->target_sp.get();
1608     if (target == NULL && exe_ctx_ptr)
1609         target = exe_ctx_ptr->GetTargetPtr();
1610     return target;
1611 }
1612 
1613 ExecutionResults
1614 Target::EvaluateExpression
1615 (
1616     const char *expr_cstr,
1617     StackFrame *frame,
1618     lldb::ValueObjectSP &result_valobj_sp,
1619     const EvaluateExpressionOptions& options
1620 )
1621 {
1622     result_valobj_sp.reset();
1623 
1624     ExecutionResults execution_results = eExecutionSetupError;
1625 
1626     if (expr_cstr == NULL || expr_cstr[0] == '\0')
1627         return execution_results;
1628 
1629     // We shouldn't run stop hooks in expressions.
1630     // Be sure to reset this if you return anywhere within this function.
1631     bool old_suppress_value = m_suppress_stop_hooks;
1632     m_suppress_stop_hooks = true;
1633 
1634     ExecutionContext exe_ctx;
1635 
1636     const size_t expr_cstr_len = ::strlen (expr_cstr);
1637 
1638     if (frame)
1639     {
1640         frame->CalculateExecutionContext(exe_ctx);
1641         Error error;
1642         const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember |
1643                                            StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
1644                                            StackFrame::eExpressionPathOptionsNoSyntheticChildren;
1645         lldb::VariableSP var_sp;
1646 
1647         // Make sure we don't have any things that we know a variable expression
1648         // won't be able to deal with before calling into it
1649         if (::strcspn (expr_cstr, "()+*&|!~<=/^%,?") == expr_cstr_len)
1650         {
1651             result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr,
1652                                                                          options.GetUseDynamic(),
1653                                                                          expr_path_options,
1654                                                                          var_sp,
1655                                                                          error);
1656             // if this expression results in a bitfield, we give up and let the IR handle it
1657             if (result_valobj_sp && result_valobj_sp->IsBitfield())
1658                 result_valobj_sp.reset();
1659         }
1660     }
1661     else if (m_process_sp)
1662     {
1663         m_process_sp->CalculateExecutionContext(exe_ctx);
1664     }
1665     else
1666     {
1667         CalculateExecutionContext(exe_ctx);
1668     }
1669 
1670     if (result_valobj_sp)
1671     {
1672         execution_results = eExecutionCompleted;
1673         // We got a result from the frame variable expression path above...
1674         ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName());
1675 
1676         lldb::ValueObjectSP const_valobj_sp;
1677 
1678         // Check in case our value is already a constant value
1679         if (result_valobj_sp->GetIsConstant())
1680         {
1681             const_valobj_sp = result_valobj_sp;
1682             const_valobj_sp->SetName (persistent_variable_name);
1683         }
1684         else
1685         {
1686             if (options.GetUseDynamic() != lldb::eNoDynamicValues)
1687             {
1688                 ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(options.GetUseDynamic());
1689                 if (dynamic_sp)
1690                     result_valobj_sp = dynamic_sp;
1691             }
1692 
1693             const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name);
1694         }
1695 
1696         lldb::ValueObjectSP live_valobj_sp = result_valobj_sp;
1697 
1698         result_valobj_sp = const_valobj_sp;
1699 
1700         ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp));
1701         assert (clang_expr_variable_sp.get());
1702 
1703         // Set flags and live data as appropriate
1704 
1705         const Value &result_value = live_valobj_sp->GetValue();
1706 
1707         switch (result_value.GetValueType())
1708         {
1709         case Value::eValueTypeHostAddress:
1710         case Value::eValueTypeFileAddress:
1711             // we don't do anything with these for now
1712             break;
1713         case Value::eValueTypeScalar:
1714             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1715             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1716             break;
1717         case Value::eValueTypeLoadAddress:
1718             clang_expr_variable_sp->m_live_sp = live_valobj_sp;
1719             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
1720             break;
1721         }
1722     }
1723     else
1724     {
1725         // Make sure we aren't just trying to see the value of a persistent
1726         // variable (something like "$0")
1727         lldb::ClangExpressionVariableSP persistent_var_sp;
1728         // Only check for persistent variables the expression starts with a '$'
1729         if (expr_cstr[0] == '$')
1730             persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1731 
1732         if (persistent_var_sp)
1733         {
1734             result_valobj_sp = persistent_var_sp->GetValueObject ();
1735             execution_results = eExecutionCompleted;
1736         }
1737         else
1738         {
1739             const char *prefix = GetExpressionPrefixContentsAsCString();
1740 
1741             execution_results = ClangUserExpression::Evaluate (exe_ctx,
1742                                                                options.GetExecutionPolicy(),
1743                                                                lldb::eLanguageTypeUnknown,
1744                                                                options.DoesCoerceToId() ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny,
1745                                                                options.DoesUnwindOnError(),
1746                                                                expr_cstr,
1747                                                                prefix,
1748                                                                result_valobj_sp,
1749                                                                options.GetRunOthers(),
1750                                                                options.GetTimeoutUsec());
1751         }
1752     }
1753 
1754     m_suppress_stop_hooks = old_suppress_value;
1755 
1756     return execution_results;
1757 }
1758 
1759 lldb::addr_t
1760 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1761 {
1762     addr_t code_addr = load_addr;
1763     switch (m_arch.GetMachine())
1764     {
1765     case llvm::Triple::arm:
1766     case llvm::Triple::thumb:
1767         switch (addr_class)
1768         {
1769         case eAddressClassData:
1770         case eAddressClassDebug:
1771             return LLDB_INVALID_ADDRESS;
1772 
1773         case eAddressClassUnknown:
1774         case eAddressClassInvalid:
1775         case eAddressClassCode:
1776         case eAddressClassCodeAlternateISA:
1777         case eAddressClassRuntime:
1778             // Check if bit zero it no set?
1779             if ((code_addr & 1ull) == 0)
1780             {
1781                 // Bit zero isn't set, check if the address is a multiple of 2?
1782                 if (code_addr & 2ull)
1783                 {
1784                     // The address is a multiple of 2 so it must be thumb, set bit zero
1785                     code_addr |= 1ull;
1786                 }
1787                 else if (addr_class == eAddressClassCodeAlternateISA)
1788                 {
1789                     // We checked the address and the address claims to be the alternate ISA
1790                     // which means thumb, so set bit zero.
1791                     code_addr |= 1ull;
1792                 }
1793             }
1794             break;
1795         }
1796         break;
1797 
1798     default:
1799         break;
1800     }
1801     return code_addr;
1802 }
1803 
1804 lldb::addr_t
1805 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1806 {
1807     addr_t opcode_addr = load_addr;
1808     switch (m_arch.GetMachine())
1809     {
1810     case llvm::Triple::arm:
1811     case llvm::Triple::thumb:
1812         switch (addr_class)
1813         {
1814         case eAddressClassData:
1815         case eAddressClassDebug:
1816             return LLDB_INVALID_ADDRESS;
1817 
1818         case eAddressClassInvalid:
1819         case eAddressClassUnknown:
1820         case eAddressClassCode:
1821         case eAddressClassCodeAlternateISA:
1822         case eAddressClassRuntime:
1823             opcode_addr &= ~(1ull);
1824             break;
1825         }
1826         break;
1827 
1828     default:
1829         break;
1830     }
1831     return opcode_addr;
1832 }
1833 
1834 lldb::user_id_t
1835 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1836 {
1837     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1838     new_hook_sp.reset (new StopHook(shared_from_this(), new_uid));
1839     m_stop_hooks[new_uid] = new_hook_sp;
1840     return new_uid;
1841 }
1842 
1843 bool
1844 Target::RemoveStopHookByID (lldb::user_id_t user_id)
1845 {
1846     size_t num_removed;
1847     num_removed = m_stop_hooks.erase (user_id);
1848     if (num_removed == 0)
1849         return false;
1850     else
1851         return true;
1852 }
1853 
1854 void
1855 Target::RemoveAllStopHooks ()
1856 {
1857     m_stop_hooks.clear();
1858 }
1859 
1860 Target::StopHookSP
1861 Target::GetStopHookByID (lldb::user_id_t user_id)
1862 {
1863     StopHookSP found_hook;
1864 
1865     StopHookCollection::iterator specified_hook_iter;
1866     specified_hook_iter = m_stop_hooks.find (user_id);
1867     if (specified_hook_iter != m_stop_hooks.end())
1868         found_hook = (*specified_hook_iter).second;
1869     return found_hook;
1870 }
1871 
1872 bool
1873 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1874 {
1875     StopHookCollection::iterator specified_hook_iter;
1876     specified_hook_iter = m_stop_hooks.find (user_id);
1877     if (specified_hook_iter == m_stop_hooks.end())
1878         return false;
1879 
1880     (*specified_hook_iter).second->SetIsActive (active_state);
1881     return true;
1882 }
1883 
1884 void
1885 Target::SetAllStopHooksActiveState (bool active_state)
1886 {
1887     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1888     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1889     {
1890         (*pos).second->SetIsActive (active_state);
1891     }
1892 }
1893 
1894 void
1895 Target::RunStopHooks ()
1896 {
1897     if (m_suppress_stop_hooks)
1898         return;
1899 
1900     if (!m_process_sp)
1901         return;
1902 
1903     // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
1904     // since in that case we do not want to run the stop-hooks
1905     if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
1906         return;
1907 
1908     if (m_stop_hooks.empty())
1909         return;
1910 
1911     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1912 
1913     // If there aren't any active stop hooks, don't bother either:
1914     bool any_active_hooks = false;
1915     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1916     {
1917         if ((*pos).second->IsActive())
1918         {
1919             any_active_hooks = true;
1920             break;
1921         }
1922     }
1923     if (!any_active_hooks)
1924         return;
1925 
1926     CommandReturnObject result;
1927 
1928     std::vector<ExecutionContext> exc_ctx_with_reasons;
1929     std::vector<SymbolContext> sym_ctx_with_reasons;
1930 
1931     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1932     size_t num_threads = cur_threadlist.GetSize();
1933     for (size_t i = 0; i < num_threads; i++)
1934     {
1935         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1936         if (cur_thread_sp->ThreadStoppedForAReason())
1937         {
1938             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1939             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1940             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1941         }
1942     }
1943 
1944     // If no threads stopped for a reason, don't run the stop-hooks.
1945     size_t num_exe_ctx = exc_ctx_with_reasons.size();
1946     if (num_exe_ctx == 0)
1947         return;
1948 
1949     result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
1950     result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
1951 
1952     bool keep_going = true;
1953     bool hooks_ran = false;
1954     bool print_hook_header;
1955     bool print_thread_header;
1956 
1957     if (num_exe_ctx == 1)
1958         print_thread_header = false;
1959     else
1960         print_thread_header = true;
1961 
1962     if (m_stop_hooks.size() == 1)
1963         print_hook_header = false;
1964     else
1965         print_hook_header = true;
1966 
1967     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
1968     {
1969         // result.Clear();
1970         StopHookSP cur_hook_sp = (*pos).second;
1971         if (!cur_hook_sp->IsActive())
1972             continue;
1973 
1974         bool any_thread_matched = false;
1975         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
1976         {
1977             if ((cur_hook_sp->GetSpecifier () == NULL
1978                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
1979                 && (cur_hook_sp->GetThreadSpecifier() == NULL
1980                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
1981             {
1982                 if (!hooks_ran)
1983                 {
1984                     hooks_ran = true;
1985                 }
1986                 if (print_hook_header && !any_thread_matched)
1987                 {
1988                     const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
1989                                        cur_hook_sp->GetCommands().GetStringAtIndex(0) :
1990                                        NULL);
1991                     if (cmd)
1992                         result.AppendMessageWithFormat("\n- Hook %llu (%s)\n", cur_hook_sp->GetID(), cmd);
1993                     else
1994                         result.AppendMessageWithFormat("\n- Hook %llu\n", cur_hook_sp->GetID());
1995                     any_thread_matched = true;
1996                 }
1997 
1998                 if (print_thread_header)
1999                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2000 
2001                 bool stop_on_continue = true;
2002                 bool stop_on_error = true;
2003                 bool echo_commands = false;
2004                 bool print_results = true;
2005                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2006                                                                       &exc_ctx_with_reasons[i],
2007                                                                       stop_on_continue,
2008                                                                       stop_on_error,
2009                                                                       echo_commands,
2010                                                                       print_results,
2011                                                                       eLazyBoolNo,
2012                                                                       result);
2013 
2014                 // If the command started the target going again, we should bag out of
2015                 // running the stop hooks.
2016                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2017                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2018                 {
2019                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %llu set the program running.", cur_hook_sp->GetID());
2020                     keep_going = false;
2021                 }
2022             }
2023         }
2024     }
2025 
2026     result.GetImmediateOutputStream()->Flush();
2027     result.GetImmediateErrorStream()->Flush();
2028 }
2029 
2030 
2031 //--------------------------------------------------------------
2032 // class Target::StopHook
2033 //--------------------------------------------------------------
2034 
2035 
2036 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2037         UserID (uid),
2038         m_target_sp (target_sp),
2039         m_commands (),
2040         m_specifier_sp (),
2041         m_thread_spec_ap(NULL),
2042         m_active (true)
2043 {
2044 }
2045 
2046 Target::StopHook::StopHook (const StopHook &rhs) :
2047         UserID (rhs.GetID()),
2048         m_target_sp (rhs.m_target_sp),
2049         m_commands (rhs.m_commands),
2050         m_specifier_sp (rhs.m_specifier_sp),
2051         m_thread_spec_ap (NULL),
2052         m_active (rhs.m_active)
2053 {
2054     if (rhs.m_thread_spec_ap.get() != NULL)
2055         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2056 }
2057 
2058 
2059 Target::StopHook::~StopHook ()
2060 {
2061 }
2062 
2063 void
2064 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2065 {
2066     m_thread_spec_ap.reset (specifier);
2067 }
2068 
2069 
2070 void
2071 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2072 {
2073     int indent_level = s->GetIndentLevel();
2074 
2075     s->SetIndentLevel(indent_level + 2);
2076 
2077     s->Printf ("Hook: %llu\n", GetID());
2078     if (m_active)
2079         s->Indent ("State: enabled\n");
2080     else
2081         s->Indent ("State: disabled\n");
2082 
2083     if (m_specifier_sp)
2084     {
2085         s->Indent();
2086         s->PutCString ("Specifier:\n");
2087         s->SetIndentLevel (indent_level + 4);
2088         m_specifier_sp->GetDescription (s, level);
2089         s->SetIndentLevel (indent_level + 2);
2090     }
2091 
2092     if (m_thread_spec_ap.get() != NULL)
2093     {
2094         StreamString tmp;
2095         s->Indent("Thread:\n");
2096         m_thread_spec_ap->GetDescription (&tmp, level);
2097         s->SetIndentLevel (indent_level + 4);
2098         s->Indent (tmp.GetData());
2099         s->PutCString ("\n");
2100         s->SetIndentLevel (indent_level + 2);
2101     }
2102 
2103     s->Indent ("Commands: \n");
2104     s->SetIndentLevel (indent_level + 4);
2105     uint32_t num_commands = m_commands.GetSize();
2106     for (uint32_t i = 0; i < num_commands; i++)
2107     {
2108         s->Indent(m_commands.GetStringAtIndex(i));
2109         s->PutCString ("\n");
2110     }
2111     s->SetIndentLevel (indent_level);
2112 }
2113 
2114 //--------------------------------------------------------------
2115 // class TargetProperties
2116 //--------------------------------------------------------------
2117 
2118 OptionEnumValueElement
2119 lldb_private::g_dynamic_value_types[] =
2120 {
2121     { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2122     { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2123     { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2124     { 0, NULL, NULL }
2125 };
2126 
2127 static OptionEnumValueElement
2128 g_inline_breakpoint_enums[] =
2129 {
2130     { 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."},
2131     { eInlineBreakpointsHeaders, "headers",   "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2132     { eInlineBreakpointsAlways,  "always",    "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2133     { 0, NULL, NULL }
2134 };
2135 
2136 static PropertyDefinition
2137 g_properties[] =
2138 {
2139     { "default-arch"                       , OptionValue::eTypeArch      , true , 0                         , NULL, NULL, "Default architecture to choose, when there's a choice." },
2140     { "expr-prefix"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2141     { "prefer-dynamic-value"               , OptionValue::eTypeEnum      , false, eNoDynamicValues          , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2142     { "enable-synthetic-value"             , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Should synthetic values be used by default whenever available." },
2143     { "skip-prologue"                      , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2144     { "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 "
2145       "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
2146       "some part (starting at the root) of the path to the file when it was built, "
2147       "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
2148       "Each element of the array is checked in order and the first one that results in a match wins." },
2149     { "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." },
2150     { "max-children-count"                 , OptionValue::eTypeSInt64    , false, 256                       , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2151     { "max-string-summary-length"          , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2152     { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2153     { "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." },
2154     { "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." },
2155     { "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." },
2156     { "inherit-env"                        , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2157     { "input-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2158     { "output-path"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2159     { "error-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2160     { "disable-aslr"                       , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2161     { "disable-stdio"                      , OptionValue::eTypeBoolean   , false, false                     , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2162     { "inline-breakpoint-strategy"         , OptionValue::eTypeEnum      , false, eInlineBreakpointsHeaders , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2163         "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. "
2164         "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2165         "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2166         "Always checking for inlined breakpoint locations can be expensive (memory and time), so we try to minimize the "
2167         "times we look for inlined locations. This setting allows you to control exactly which strategy is used when settings "
2168         "file and line breakpoints." },
2169     { NULL                                 , OptionValue::eTypeInvalid   , false, 0                         , NULL, NULL, NULL }
2170 };
2171 enum
2172 {
2173     ePropertyDefaultArch,
2174     ePropertyExprPrefix,
2175     ePropertyPreferDynamic,
2176     ePropertyEnableSynthetic,
2177     ePropertySkipPrologue,
2178     ePropertySourceMap,
2179     ePropertyExecutableSearchPaths,
2180     ePropertyMaxChildrenCount,
2181     ePropertyMaxSummaryLength,
2182     ePropertyBreakpointUseAvoidList,
2183     ePropertyArg0,
2184     ePropertyRunArgs,
2185     ePropertyEnvVars,
2186     ePropertyInheritEnv,
2187     ePropertyInputPath,
2188     ePropertyOutputPath,
2189     ePropertyErrorPath,
2190     ePropertyDisableASLR,
2191     ePropertyDisableSTDIO,
2192     ePropertyInlineStrategy
2193 };
2194 
2195 
2196 class TargetOptionValueProperties : public OptionValueProperties
2197 {
2198 public:
2199     TargetOptionValueProperties (const ConstString &name) :
2200         OptionValueProperties (name),
2201         m_target (NULL),
2202         m_got_host_env (false)
2203     {
2204     }
2205 
2206     // This constructor is used when creating TargetOptionValueProperties when it
2207     // is part of a new lldb_private::Target instance. It will copy all current
2208     // global property values as needed
2209     TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
2210         OptionValueProperties(*target_properties_sp->GetValueProperties()),
2211         m_target (target),
2212         m_got_host_env (false)
2213     {
2214     }
2215 
2216     virtual const Property *
2217     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
2218     {
2219         // When gettings the value for a key from the target options, we will always
2220         // try and grab the setting from the current target if there is one. Else we just
2221         // use the one from this instance.
2222         if (idx == ePropertyEnvVars)
2223             GetHostEnvironmentIfNeeded ();
2224 
2225         if (exe_ctx)
2226         {
2227             Target *target = exe_ctx->GetTargetPtr();
2228             if (target)
2229             {
2230                 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
2231                 if (this != target_properties)
2232                     return target_properties->ProtectedGetPropertyAtIndex (idx);
2233             }
2234         }
2235         return ProtectedGetPropertyAtIndex (idx);
2236     }
2237 protected:
2238 
2239     void
2240     GetHostEnvironmentIfNeeded () const
2241     {
2242         if (!m_got_host_env)
2243         {
2244             if (m_target)
2245             {
2246                 m_got_host_env = true;
2247                 const uint32_t idx = ePropertyInheritEnv;
2248                 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
2249                 {
2250                     PlatformSP platform_sp (m_target->GetPlatform());
2251                     if (platform_sp)
2252                     {
2253                         StringList env;
2254                         if (platform_sp->GetEnvironment(env))
2255                         {
2256                             OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
2257                             if (env_dict)
2258                             {
2259                                 const bool can_replace = false;
2260                                 const size_t envc = env.GetSize();
2261                                 for (size_t idx=0; idx<envc; idx++)
2262                                 {
2263                                     const char *env_entry = env.GetStringAtIndex (idx);
2264                                     if (env_entry)
2265                                     {
2266                                         const char *equal_pos = ::strchr(env_entry, '=');
2267                                         ConstString key;
2268                                         // It is ok to have environment variables with no values
2269                                         const char *value = NULL;
2270                                         if (equal_pos)
2271                                         {
2272                                             key.SetCStringWithLength(env_entry, equal_pos - env_entry);
2273                                             if (equal_pos[1])
2274                                                 value = equal_pos + 1;
2275                                         }
2276                                         else
2277                                         {
2278                                             key.SetCString(env_entry);
2279                                         }
2280                                         // Don't allow existing keys to be replaced with ones we get from the platform environment
2281                                         env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
2282                                     }
2283                                 }
2284                             }
2285                         }
2286                     }
2287                 }
2288             }
2289         }
2290     }
2291     Target *m_target;
2292     mutable bool m_got_host_env;
2293 };
2294 
2295 TargetProperties::TargetProperties (Target *target) :
2296     Properties ()
2297 {
2298     if (target)
2299     {
2300         m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
2301     }
2302     else
2303     {
2304         m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
2305         m_collection_sp->Initialize(g_properties);
2306         m_collection_sp->AppendProperty(ConstString("process"),
2307                                         ConstString("Settings specify to processes."),
2308                                         true,
2309                                         Process::GetGlobalProperties()->GetValueProperties());
2310     }
2311 }
2312 
2313 TargetProperties::~TargetProperties ()
2314 {
2315 }
2316 ArchSpec
2317 TargetProperties::GetDefaultArchitecture () const
2318 {
2319     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2320     if (value)
2321         return value->GetCurrentValue();
2322     return ArchSpec();
2323 }
2324 
2325 void
2326 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
2327 {
2328     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2329     if (value)
2330         return value->SetCurrentValue(arch, true);
2331 }
2332 
2333 lldb::DynamicValueType
2334 TargetProperties::GetPreferDynamicValue() const
2335 {
2336     const uint32_t idx = ePropertyPreferDynamic;
2337     return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2338 }
2339 
2340 bool
2341 TargetProperties::GetDisableASLR () const
2342 {
2343     const uint32_t idx = ePropertyDisableASLR;
2344     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2345 }
2346 
2347 void
2348 TargetProperties::SetDisableASLR (bool b)
2349 {
2350     const uint32_t idx = ePropertyDisableASLR;
2351     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2352 }
2353 
2354 bool
2355 TargetProperties::GetDisableSTDIO () const
2356 {
2357     const uint32_t idx = ePropertyDisableSTDIO;
2358     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2359 }
2360 
2361 void
2362 TargetProperties::SetDisableSTDIO (bool b)
2363 {
2364     const uint32_t idx = ePropertyDisableSTDIO;
2365     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2366 }
2367 
2368 InlineStrategy
2369 TargetProperties::GetInlineStrategy () const
2370 {
2371     const uint32_t idx = ePropertyInlineStrategy;
2372     return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2373 }
2374 
2375 const char *
2376 TargetProperties::GetArg0 () const
2377 {
2378     const uint32_t idx = ePropertyArg0;
2379     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
2380 }
2381 
2382 void
2383 TargetProperties::SetArg0 (const char *arg)
2384 {
2385     const uint32_t idx = ePropertyArg0;
2386     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
2387 }
2388 
2389 bool
2390 TargetProperties::GetRunArguments (Args &args) const
2391 {
2392     const uint32_t idx = ePropertyRunArgs;
2393     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
2394 }
2395 
2396 void
2397 TargetProperties::SetRunArguments (const Args &args)
2398 {
2399     const uint32_t idx = ePropertyRunArgs;
2400     m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
2401 }
2402 
2403 size_t
2404 TargetProperties::GetEnvironmentAsArgs (Args &env) const
2405 {
2406     const uint32_t idx = ePropertyEnvVars;
2407     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
2408 }
2409 
2410 bool
2411 TargetProperties::GetSkipPrologue() const
2412 {
2413     const uint32_t idx = ePropertySkipPrologue;
2414     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2415 }
2416 
2417 PathMappingList &
2418 TargetProperties::GetSourcePathMap () const
2419 {
2420     const uint32_t idx = ePropertySourceMap;
2421     OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
2422     assert(option_value);
2423     return option_value->GetCurrentValue();
2424 }
2425 
2426 FileSpecList &
2427 TargetProperties::GetExecutableSearchPaths ()
2428 {
2429     const uint32_t idx = ePropertyExecutableSearchPaths;
2430     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2431     assert(option_value);
2432     return option_value->GetCurrentValue();
2433 }
2434 
2435 bool
2436 TargetProperties::GetEnableSyntheticValue () const
2437 {
2438     const uint32_t idx = ePropertyEnableSynthetic;
2439     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2440 }
2441 
2442 uint32_t
2443 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
2444 {
2445     const uint32_t idx = ePropertyMaxChildrenCount;
2446     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2447 }
2448 
2449 uint32_t
2450 TargetProperties::GetMaximumSizeOfStringSummary() const
2451 {
2452     const uint32_t idx = ePropertyMaxSummaryLength;
2453     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2454 }
2455 
2456 FileSpec
2457 TargetProperties::GetStandardInputPath () const
2458 {
2459     const uint32_t idx = ePropertyInputPath;
2460     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2461 }
2462 
2463 void
2464 TargetProperties::SetStandardInputPath (const char *p)
2465 {
2466     const uint32_t idx = ePropertyInputPath;
2467     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2468 }
2469 
2470 FileSpec
2471 TargetProperties::GetStandardOutputPath () const
2472 {
2473     const uint32_t idx = ePropertyOutputPath;
2474     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2475 }
2476 
2477 void
2478 TargetProperties::SetStandardOutputPath (const char *p)
2479 {
2480     const uint32_t idx = ePropertyOutputPath;
2481     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2482 }
2483 
2484 FileSpec
2485 TargetProperties::GetStandardErrorPath () const
2486 {
2487     const uint32_t idx = ePropertyErrorPath;
2488     return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
2489 }
2490 
2491 const char *
2492 TargetProperties::GetExpressionPrefixContentsAsCString ()
2493 {
2494     const uint32_t idx = ePropertyExprPrefix;
2495     OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
2496     if (file)
2497     {
2498         const bool null_terminate = true;
2499         DataBufferSP data_sp(file->GetFileContents(null_terminate));
2500         if (data_sp)
2501             return (const char *) data_sp->GetBytes();
2502     }
2503     return NULL;
2504 }
2505 
2506 void
2507 TargetProperties::SetStandardErrorPath (const char *p)
2508 {
2509     const uint32_t idx = ePropertyErrorPath;
2510     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2511 }
2512 
2513 bool
2514 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
2515 {
2516     const uint32_t idx = ePropertyBreakpointUseAvoidList;
2517     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2518 }
2519 
2520 const TargetPropertiesSP &
2521 Target::GetGlobalProperties()
2522 {
2523     static TargetPropertiesSP g_settings_sp;
2524     if (!g_settings_sp)
2525     {
2526         g_settings_sp.reset (new TargetProperties (NULL));
2527     }
2528     return g_settings_sp;
2529 }
2530 
2531 const ConstString &
2532 Target::TargetEventData::GetFlavorString ()
2533 {
2534     static ConstString g_flavor ("Target::TargetEventData");
2535     return g_flavor;
2536 }
2537 
2538 const ConstString &
2539 Target::TargetEventData::GetFlavor () const
2540 {
2541     return TargetEventData::GetFlavorString ();
2542 }
2543 
2544 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
2545     EventData(),
2546     m_target_sp (new_target_sp)
2547 {
2548 }
2549 
2550 Target::TargetEventData::~TargetEventData()
2551 {
2552 
2553 }
2554 
2555 void
2556 Target::TargetEventData::Dump (Stream *s) const
2557 {
2558 
2559 }
2560 
2561 const TargetSP
2562 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
2563 {
2564     TargetSP target_sp;
2565 
2566     const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
2567     if (data)
2568         target_sp = data->m_target_sp;
2569 
2570     return target_sp;
2571 }
2572 
2573 const Target::TargetEventData *
2574 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
2575 {
2576     if (event_ptr)
2577     {
2578         const EventData *event_data = event_ptr->GetData();
2579         if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
2580             return static_cast <const TargetEventData *> (event_ptr->GetData());
2581     }
2582     return NULL;
2583 }
2584 
2585