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         case Value::eValueTypeVector:
1715             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1716             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1717             break;
1718         case Value::eValueTypeLoadAddress:
1719             clang_expr_variable_sp->m_live_sp = live_valobj_sp;
1720             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
1721             break;
1722         }
1723     }
1724     else
1725     {
1726         // Make sure we aren't just trying to see the value of a persistent
1727         // variable (something like "$0")
1728         lldb::ClangExpressionVariableSP persistent_var_sp;
1729         // Only check for persistent variables the expression starts with a '$'
1730         if (expr_cstr[0] == '$')
1731             persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1732 
1733         if (persistent_var_sp)
1734         {
1735             result_valobj_sp = persistent_var_sp->GetValueObject ();
1736             execution_results = eExecutionCompleted;
1737         }
1738         else
1739         {
1740             const char *prefix = GetExpressionPrefixContentsAsCString();
1741 
1742             execution_results = ClangUserExpression::Evaluate (exe_ctx,
1743                                                                options.GetExecutionPolicy(),
1744                                                                lldb::eLanguageTypeUnknown,
1745                                                                options.DoesCoerceToId() ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny,
1746                                                                options.DoesUnwindOnError(),
1747                                                                expr_cstr,
1748                                                                prefix,
1749                                                                result_valobj_sp,
1750                                                                options.GetRunOthers(),
1751                                                                options.GetTimeoutUsec());
1752         }
1753     }
1754 
1755     m_suppress_stop_hooks = old_suppress_value;
1756 
1757     return execution_results;
1758 }
1759 
1760 lldb::addr_t
1761 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1762 {
1763     addr_t code_addr = load_addr;
1764     switch (m_arch.GetMachine())
1765     {
1766     case llvm::Triple::arm:
1767     case llvm::Triple::thumb:
1768         switch (addr_class)
1769         {
1770         case eAddressClassData:
1771         case eAddressClassDebug:
1772             return LLDB_INVALID_ADDRESS;
1773 
1774         case eAddressClassUnknown:
1775         case eAddressClassInvalid:
1776         case eAddressClassCode:
1777         case eAddressClassCodeAlternateISA:
1778         case eAddressClassRuntime:
1779             // Check if bit zero it no set?
1780             if ((code_addr & 1ull) == 0)
1781             {
1782                 // Bit zero isn't set, check if the address is a multiple of 2?
1783                 if (code_addr & 2ull)
1784                 {
1785                     // The address is a multiple of 2 so it must be thumb, set bit zero
1786                     code_addr |= 1ull;
1787                 }
1788                 else if (addr_class == eAddressClassCodeAlternateISA)
1789                 {
1790                     // We checked the address and the address claims to be the alternate ISA
1791                     // which means thumb, so set bit zero.
1792                     code_addr |= 1ull;
1793                 }
1794             }
1795             break;
1796         }
1797         break;
1798 
1799     default:
1800         break;
1801     }
1802     return code_addr;
1803 }
1804 
1805 lldb::addr_t
1806 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1807 {
1808     addr_t opcode_addr = load_addr;
1809     switch (m_arch.GetMachine())
1810     {
1811     case llvm::Triple::arm:
1812     case llvm::Triple::thumb:
1813         switch (addr_class)
1814         {
1815         case eAddressClassData:
1816         case eAddressClassDebug:
1817             return LLDB_INVALID_ADDRESS;
1818 
1819         case eAddressClassInvalid:
1820         case eAddressClassUnknown:
1821         case eAddressClassCode:
1822         case eAddressClassCodeAlternateISA:
1823         case eAddressClassRuntime:
1824             opcode_addr &= ~(1ull);
1825             break;
1826         }
1827         break;
1828 
1829     default:
1830         break;
1831     }
1832     return opcode_addr;
1833 }
1834 
1835 lldb::user_id_t
1836 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1837 {
1838     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1839     new_hook_sp.reset (new StopHook(shared_from_this(), new_uid));
1840     m_stop_hooks[new_uid] = new_hook_sp;
1841     return new_uid;
1842 }
1843 
1844 bool
1845 Target::RemoveStopHookByID (lldb::user_id_t user_id)
1846 {
1847     size_t num_removed;
1848     num_removed = m_stop_hooks.erase (user_id);
1849     if (num_removed == 0)
1850         return false;
1851     else
1852         return true;
1853 }
1854 
1855 void
1856 Target::RemoveAllStopHooks ()
1857 {
1858     m_stop_hooks.clear();
1859 }
1860 
1861 Target::StopHookSP
1862 Target::GetStopHookByID (lldb::user_id_t user_id)
1863 {
1864     StopHookSP found_hook;
1865 
1866     StopHookCollection::iterator specified_hook_iter;
1867     specified_hook_iter = m_stop_hooks.find (user_id);
1868     if (specified_hook_iter != m_stop_hooks.end())
1869         found_hook = (*specified_hook_iter).second;
1870     return found_hook;
1871 }
1872 
1873 bool
1874 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1875 {
1876     StopHookCollection::iterator specified_hook_iter;
1877     specified_hook_iter = m_stop_hooks.find (user_id);
1878     if (specified_hook_iter == m_stop_hooks.end())
1879         return false;
1880 
1881     (*specified_hook_iter).second->SetIsActive (active_state);
1882     return true;
1883 }
1884 
1885 void
1886 Target::SetAllStopHooksActiveState (bool active_state)
1887 {
1888     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1889     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1890     {
1891         (*pos).second->SetIsActive (active_state);
1892     }
1893 }
1894 
1895 void
1896 Target::RunStopHooks ()
1897 {
1898     if (m_suppress_stop_hooks)
1899         return;
1900 
1901     if (!m_process_sp)
1902         return;
1903 
1904     // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
1905     // since in that case we do not want to run the stop-hooks
1906     if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
1907         return;
1908 
1909     if (m_stop_hooks.empty())
1910         return;
1911 
1912     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1913 
1914     // If there aren't any active stop hooks, don't bother either:
1915     bool any_active_hooks = false;
1916     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1917     {
1918         if ((*pos).second->IsActive())
1919         {
1920             any_active_hooks = true;
1921             break;
1922         }
1923     }
1924     if (!any_active_hooks)
1925         return;
1926 
1927     CommandReturnObject result;
1928 
1929     std::vector<ExecutionContext> exc_ctx_with_reasons;
1930     std::vector<SymbolContext> sym_ctx_with_reasons;
1931 
1932     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1933     size_t num_threads = cur_threadlist.GetSize();
1934     for (size_t i = 0; i < num_threads; i++)
1935     {
1936         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1937         if (cur_thread_sp->ThreadStoppedForAReason())
1938         {
1939             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1940             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1941             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1942         }
1943     }
1944 
1945     // If no threads stopped for a reason, don't run the stop-hooks.
1946     size_t num_exe_ctx = exc_ctx_with_reasons.size();
1947     if (num_exe_ctx == 0)
1948         return;
1949 
1950     result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
1951     result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
1952 
1953     bool keep_going = true;
1954     bool hooks_ran = false;
1955     bool print_hook_header;
1956     bool print_thread_header;
1957 
1958     if (num_exe_ctx == 1)
1959         print_thread_header = false;
1960     else
1961         print_thread_header = true;
1962 
1963     if (m_stop_hooks.size() == 1)
1964         print_hook_header = false;
1965     else
1966         print_hook_header = true;
1967 
1968     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
1969     {
1970         // result.Clear();
1971         StopHookSP cur_hook_sp = (*pos).second;
1972         if (!cur_hook_sp->IsActive())
1973             continue;
1974 
1975         bool any_thread_matched = false;
1976         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
1977         {
1978             if ((cur_hook_sp->GetSpecifier () == NULL
1979                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
1980                 && (cur_hook_sp->GetThreadSpecifier() == NULL
1981                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
1982             {
1983                 if (!hooks_ran)
1984                 {
1985                     hooks_ran = true;
1986                 }
1987                 if (print_hook_header && !any_thread_matched)
1988                 {
1989                     const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
1990                                        cur_hook_sp->GetCommands().GetStringAtIndex(0) :
1991                                        NULL);
1992                     if (cmd)
1993                         result.AppendMessageWithFormat("\n- Hook %llu (%s)\n", cur_hook_sp->GetID(), cmd);
1994                     else
1995                         result.AppendMessageWithFormat("\n- Hook %llu\n", cur_hook_sp->GetID());
1996                     any_thread_matched = true;
1997                 }
1998 
1999                 if (print_thread_header)
2000                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2001 
2002                 bool stop_on_continue = true;
2003                 bool stop_on_error = true;
2004                 bool echo_commands = false;
2005                 bool print_results = true;
2006                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2007                                                                       &exc_ctx_with_reasons[i],
2008                                                                       stop_on_continue,
2009                                                                       stop_on_error,
2010                                                                       echo_commands,
2011                                                                       print_results,
2012                                                                       eLazyBoolNo,
2013                                                                       result);
2014 
2015                 // If the command started the target going again, we should bag out of
2016                 // running the stop hooks.
2017                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2018                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2019                 {
2020                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %llu set the program running.", cur_hook_sp->GetID());
2021                     keep_going = false;
2022                 }
2023             }
2024         }
2025     }
2026 
2027     result.GetImmediateOutputStream()->Flush();
2028     result.GetImmediateErrorStream()->Flush();
2029 }
2030 
2031 
2032 //--------------------------------------------------------------
2033 // class Target::StopHook
2034 //--------------------------------------------------------------
2035 
2036 
2037 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2038         UserID (uid),
2039         m_target_sp (target_sp),
2040         m_commands (),
2041         m_specifier_sp (),
2042         m_thread_spec_ap(NULL),
2043         m_active (true)
2044 {
2045 }
2046 
2047 Target::StopHook::StopHook (const StopHook &rhs) :
2048         UserID (rhs.GetID()),
2049         m_target_sp (rhs.m_target_sp),
2050         m_commands (rhs.m_commands),
2051         m_specifier_sp (rhs.m_specifier_sp),
2052         m_thread_spec_ap (NULL),
2053         m_active (rhs.m_active)
2054 {
2055     if (rhs.m_thread_spec_ap.get() != NULL)
2056         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2057 }
2058 
2059 
2060 Target::StopHook::~StopHook ()
2061 {
2062 }
2063 
2064 void
2065 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2066 {
2067     m_thread_spec_ap.reset (specifier);
2068 }
2069 
2070 
2071 void
2072 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2073 {
2074     int indent_level = s->GetIndentLevel();
2075 
2076     s->SetIndentLevel(indent_level + 2);
2077 
2078     s->Printf ("Hook: %llu\n", GetID());
2079     if (m_active)
2080         s->Indent ("State: enabled\n");
2081     else
2082         s->Indent ("State: disabled\n");
2083 
2084     if (m_specifier_sp)
2085     {
2086         s->Indent();
2087         s->PutCString ("Specifier:\n");
2088         s->SetIndentLevel (indent_level + 4);
2089         m_specifier_sp->GetDescription (s, level);
2090         s->SetIndentLevel (indent_level + 2);
2091     }
2092 
2093     if (m_thread_spec_ap.get() != NULL)
2094     {
2095         StreamString tmp;
2096         s->Indent("Thread:\n");
2097         m_thread_spec_ap->GetDescription (&tmp, level);
2098         s->SetIndentLevel (indent_level + 4);
2099         s->Indent (tmp.GetData());
2100         s->PutCString ("\n");
2101         s->SetIndentLevel (indent_level + 2);
2102     }
2103 
2104     s->Indent ("Commands: \n");
2105     s->SetIndentLevel (indent_level + 4);
2106     uint32_t num_commands = m_commands.GetSize();
2107     for (uint32_t i = 0; i < num_commands; i++)
2108     {
2109         s->Indent(m_commands.GetStringAtIndex(i));
2110         s->PutCString ("\n");
2111     }
2112     s->SetIndentLevel (indent_level);
2113 }
2114 
2115 //--------------------------------------------------------------
2116 // class TargetProperties
2117 //--------------------------------------------------------------
2118 
2119 OptionEnumValueElement
2120 lldb_private::g_dynamic_value_types[] =
2121 {
2122     { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2123     { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2124     { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2125     { 0, NULL, NULL }
2126 };
2127 
2128 static OptionEnumValueElement
2129 g_inline_breakpoint_enums[] =
2130 {
2131     { 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."},
2132     { eInlineBreakpointsHeaders, "headers",   "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2133     { eInlineBreakpointsAlways,  "always",    "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2134     { 0, NULL, NULL }
2135 };
2136 
2137 static PropertyDefinition
2138 g_properties[] =
2139 {
2140     { "default-arch"                       , OptionValue::eTypeArch      , true , 0                         , NULL, NULL, "Default architecture to choose, when there's a choice." },
2141     { "expr-prefix"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2142     { "prefer-dynamic-value"               , OptionValue::eTypeEnum      , false, eNoDynamicValues          , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2143     { "enable-synthetic-value"             , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Should synthetic values be used by default whenever available." },
2144     { "skip-prologue"                      , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2145     { "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 "
2146       "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
2147       "some part (starting at the root) of the path to the file when it was built, "
2148       "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
2149       "Each element of the array is checked in order and the first one that results in a match wins." },
2150     { "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." },
2151     { "max-children-count"                 , OptionValue::eTypeSInt64    , false, 256                       , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2152     { "max-string-summary-length"          , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2153     { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2154     { "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." },
2155     { "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." },
2156     { "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." },
2157     { "inherit-env"                        , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2158     { "input-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2159     { "output-path"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2160     { "error-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2161     { "disable-aslr"                       , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2162     { "disable-stdio"                      , OptionValue::eTypeBoolean   , false, false                     , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2163     { "inline-breakpoint-strategy"         , OptionValue::eTypeEnum      , false, eInlineBreakpointsHeaders , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2164         "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. "
2165         "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2166         "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2167         "Always checking for inlined breakpoint locations can be expensive (memory and time), so we try to minimize the "
2168         "times we look for inlined locations. This setting allows you to control exactly which strategy is used when settings "
2169         "file and line breakpoints." },
2170     { NULL                                 , OptionValue::eTypeInvalid   , false, 0                         , NULL, NULL, NULL }
2171 };
2172 enum
2173 {
2174     ePropertyDefaultArch,
2175     ePropertyExprPrefix,
2176     ePropertyPreferDynamic,
2177     ePropertyEnableSynthetic,
2178     ePropertySkipPrologue,
2179     ePropertySourceMap,
2180     ePropertyExecutableSearchPaths,
2181     ePropertyMaxChildrenCount,
2182     ePropertyMaxSummaryLength,
2183     ePropertyBreakpointUseAvoidList,
2184     ePropertyArg0,
2185     ePropertyRunArgs,
2186     ePropertyEnvVars,
2187     ePropertyInheritEnv,
2188     ePropertyInputPath,
2189     ePropertyOutputPath,
2190     ePropertyErrorPath,
2191     ePropertyDisableASLR,
2192     ePropertyDisableSTDIO,
2193     ePropertyInlineStrategy
2194 };
2195 
2196 
2197 class TargetOptionValueProperties : public OptionValueProperties
2198 {
2199 public:
2200     TargetOptionValueProperties (const ConstString &name) :
2201         OptionValueProperties (name),
2202         m_target (NULL),
2203         m_got_host_env (false)
2204     {
2205     }
2206 
2207     // This constructor is used when creating TargetOptionValueProperties when it
2208     // is part of a new lldb_private::Target instance. It will copy all current
2209     // global property values as needed
2210     TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
2211         OptionValueProperties(*target_properties_sp->GetValueProperties()),
2212         m_target (target),
2213         m_got_host_env (false)
2214     {
2215     }
2216 
2217     virtual const Property *
2218     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
2219     {
2220         // When gettings the value for a key from the target options, we will always
2221         // try and grab the setting from the current target if there is one. Else we just
2222         // use the one from this instance.
2223         if (idx == ePropertyEnvVars)
2224             GetHostEnvironmentIfNeeded ();
2225 
2226         if (exe_ctx)
2227         {
2228             Target *target = exe_ctx->GetTargetPtr();
2229             if (target)
2230             {
2231                 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
2232                 if (this != target_properties)
2233                     return target_properties->ProtectedGetPropertyAtIndex (idx);
2234             }
2235         }
2236         return ProtectedGetPropertyAtIndex (idx);
2237     }
2238 protected:
2239 
2240     void
2241     GetHostEnvironmentIfNeeded () const
2242     {
2243         if (!m_got_host_env)
2244         {
2245             if (m_target)
2246             {
2247                 m_got_host_env = true;
2248                 const uint32_t idx = ePropertyInheritEnv;
2249                 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
2250                 {
2251                     PlatformSP platform_sp (m_target->GetPlatform());
2252                     if (platform_sp)
2253                     {
2254                         StringList env;
2255                         if (platform_sp->GetEnvironment(env))
2256                         {
2257                             OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
2258                             if (env_dict)
2259                             {
2260                                 const bool can_replace = false;
2261                                 const size_t envc = env.GetSize();
2262                                 for (size_t idx=0; idx<envc; idx++)
2263                                 {
2264                                     const char *env_entry = env.GetStringAtIndex (idx);
2265                                     if (env_entry)
2266                                     {
2267                                         const char *equal_pos = ::strchr(env_entry, '=');
2268                                         ConstString key;
2269                                         // It is ok to have environment variables with no values
2270                                         const char *value = NULL;
2271                                         if (equal_pos)
2272                                         {
2273                                             key.SetCStringWithLength(env_entry, equal_pos - env_entry);
2274                                             if (equal_pos[1])
2275                                                 value = equal_pos + 1;
2276                                         }
2277                                         else
2278                                         {
2279                                             key.SetCString(env_entry);
2280                                         }
2281                                         // Don't allow existing keys to be replaced with ones we get from the platform environment
2282                                         env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
2283                                     }
2284                                 }
2285                             }
2286                         }
2287                     }
2288                 }
2289             }
2290         }
2291     }
2292     Target *m_target;
2293     mutable bool m_got_host_env;
2294 };
2295 
2296 TargetProperties::TargetProperties (Target *target) :
2297     Properties ()
2298 {
2299     if (target)
2300     {
2301         m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
2302     }
2303     else
2304     {
2305         m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
2306         m_collection_sp->Initialize(g_properties);
2307         m_collection_sp->AppendProperty(ConstString("process"),
2308                                         ConstString("Settings specify to processes."),
2309                                         true,
2310                                         Process::GetGlobalProperties()->GetValueProperties());
2311     }
2312 }
2313 
2314 TargetProperties::~TargetProperties ()
2315 {
2316 }
2317 ArchSpec
2318 TargetProperties::GetDefaultArchitecture () const
2319 {
2320     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2321     if (value)
2322         return value->GetCurrentValue();
2323     return ArchSpec();
2324 }
2325 
2326 void
2327 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
2328 {
2329     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2330     if (value)
2331         return value->SetCurrentValue(arch, true);
2332 }
2333 
2334 lldb::DynamicValueType
2335 TargetProperties::GetPreferDynamicValue() const
2336 {
2337     const uint32_t idx = ePropertyPreferDynamic;
2338     return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2339 }
2340 
2341 bool
2342 TargetProperties::GetDisableASLR () const
2343 {
2344     const uint32_t idx = ePropertyDisableASLR;
2345     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2346 }
2347 
2348 void
2349 TargetProperties::SetDisableASLR (bool b)
2350 {
2351     const uint32_t idx = ePropertyDisableASLR;
2352     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2353 }
2354 
2355 bool
2356 TargetProperties::GetDisableSTDIO () const
2357 {
2358     const uint32_t idx = ePropertyDisableSTDIO;
2359     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2360 }
2361 
2362 void
2363 TargetProperties::SetDisableSTDIO (bool b)
2364 {
2365     const uint32_t idx = ePropertyDisableSTDIO;
2366     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2367 }
2368 
2369 InlineStrategy
2370 TargetProperties::GetInlineStrategy () const
2371 {
2372     const uint32_t idx = ePropertyInlineStrategy;
2373     return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2374 }
2375 
2376 const char *
2377 TargetProperties::GetArg0 () const
2378 {
2379     const uint32_t idx = ePropertyArg0;
2380     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
2381 }
2382 
2383 void
2384 TargetProperties::SetArg0 (const char *arg)
2385 {
2386     const uint32_t idx = ePropertyArg0;
2387     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
2388 }
2389 
2390 bool
2391 TargetProperties::GetRunArguments (Args &args) const
2392 {
2393     const uint32_t idx = ePropertyRunArgs;
2394     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
2395 }
2396 
2397 void
2398 TargetProperties::SetRunArguments (const Args &args)
2399 {
2400     const uint32_t idx = ePropertyRunArgs;
2401     m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
2402 }
2403 
2404 size_t
2405 TargetProperties::GetEnvironmentAsArgs (Args &env) const
2406 {
2407     const uint32_t idx = ePropertyEnvVars;
2408     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
2409 }
2410 
2411 bool
2412 TargetProperties::GetSkipPrologue() const
2413 {
2414     const uint32_t idx = ePropertySkipPrologue;
2415     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2416 }
2417 
2418 PathMappingList &
2419 TargetProperties::GetSourcePathMap () const
2420 {
2421     const uint32_t idx = ePropertySourceMap;
2422     OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
2423     assert(option_value);
2424     return option_value->GetCurrentValue();
2425 }
2426 
2427 FileSpecList &
2428 TargetProperties::GetExecutableSearchPaths ()
2429 {
2430     const uint32_t idx = ePropertyExecutableSearchPaths;
2431     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2432     assert(option_value);
2433     return option_value->GetCurrentValue();
2434 }
2435 
2436 bool
2437 TargetProperties::GetEnableSyntheticValue () const
2438 {
2439     const uint32_t idx = ePropertyEnableSynthetic;
2440     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2441 }
2442 
2443 uint32_t
2444 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
2445 {
2446     const uint32_t idx = ePropertyMaxChildrenCount;
2447     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2448 }
2449 
2450 uint32_t
2451 TargetProperties::GetMaximumSizeOfStringSummary() const
2452 {
2453     const uint32_t idx = ePropertyMaxSummaryLength;
2454     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2455 }
2456 
2457 FileSpec
2458 TargetProperties::GetStandardInputPath () const
2459 {
2460     const uint32_t idx = ePropertyInputPath;
2461     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2462 }
2463 
2464 void
2465 TargetProperties::SetStandardInputPath (const char *p)
2466 {
2467     const uint32_t idx = ePropertyInputPath;
2468     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2469 }
2470 
2471 FileSpec
2472 TargetProperties::GetStandardOutputPath () const
2473 {
2474     const uint32_t idx = ePropertyOutputPath;
2475     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2476 }
2477 
2478 void
2479 TargetProperties::SetStandardOutputPath (const char *p)
2480 {
2481     const uint32_t idx = ePropertyOutputPath;
2482     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2483 }
2484 
2485 FileSpec
2486 TargetProperties::GetStandardErrorPath () const
2487 {
2488     const uint32_t idx = ePropertyErrorPath;
2489     return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
2490 }
2491 
2492 const char *
2493 TargetProperties::GetExpressionPrefixContentsAsCString ()
2494 {
2495     const uint32_t idx = ePropertyExprPrefix;
2496     OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
2497     if (file)
2498     {
2499         const bool null_terminate = true;
2500         DataBufferSP data_sp(file->GetFileContents(null_terminate));
2501         if (data_sp)
2502             return (const char *) data_sp->GetBytes();
2503     }
2504     return NULL;
2505 }
2506 
2507 void
2508 TargetProperties::SetStandardErrorPath (const char *p)
2509 {
2510     const uint32_t idx = ePropertyErrorPath;
2511     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2512 }
2513 
2514 bool
2515 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
2516 {
2517     const uint32_t idx = ePropertyBreakpointUseAvoidList;
2518     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2519 }
2520 
2521 const TargetPropertiesSP &
2522 Target::GetGlobalProperties()
2523 {
2524     static TargetPropertiesSP g_settings_sp;
2525     if (!g_settings_sp)
2526     {
2527         g_settings_sp.reset (new TargetProperties (NULL));
2528     }
2529     return g_settings_sp;
2530 }
2531 
2532 const ConstString &
2533 Target::TargetEventData::GetFlavorString ()
2534 {
2535     static ConstString g_flavor ("Target::TargetEventData");
2536     return g_flavor;
2537 }
2538 
2539 const ConstString &
2540 Target::TargetEventData::GetFlavor () const
2541 {
2542     return TargetEventData::GetFlavorString ();
2543 }
2544 
2545 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
2546     EventData(),
2547     m_target_sp (new_target_sp)
2548 {
2549 }
2550 
2551 Target::TargetEventData::~TargetEventData()
2552 {
2553 
2554 }
2555 
2556 void
2557 Target::TargetEventData::Dump (Stream *s) const
2558 {
2559 
2560 }
2561 
2562 const TargetSP
2563 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
2564 {
2565     TargetSP target_sp;
2566 
2567     const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
2568     if (data)
2569         target_sp = data->m_target_sp;
2570 
2571     return target_sp;
2572 }
2573 
2574 const Target::TargetEventData *
2575 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
2576 {
2577     if (event_ptr)
2578     {
2579         const EventData *event_data = event_ptr->GetData();
2580         if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
2581             return static_cast <const TargetEventData *> (event_ptr->GetData());
2582     }
2583     return NULL;
2584 }
2585 
2586