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 (this),
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 static void
958 LoadScriptingResourceForModule (const ModuleSP &module_sp, Target *target)
959 {
960     Error error;
961     if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error))
962     {
963         target->GetDebugger().GetOutputStream().Printf("unable to load scripting data for module %s - error reported was %s\n",
964                                                        module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
965                                                        error.AsCString());
966     }
967 }
968 
969 void
970 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
971 {
972     m_images.Clear();
973     m_scratch_ast_context_ap.reset();
974     m_scratch_ast_source_ap.reset();
975     m_ast_importer_ap.reset();
976 
977     if (executable_sp.get())
978     {
979         Timer scoped_timer (__PRETTY_FUNCTION__,
980                             "Target::SetExecutableModule (executable = '%s/%s')",
981                             executable_sp->GetFileSpec().GetDirectory().AsCString(),
982                             executable_sp->GetFileSpec().GetFilename().AsCString());
983 
984         m_images.Append(executable_sp); // The first image is our exectuable file
985 
986         // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
987         if (!m_arch.IsValid())
988             m_arch = executable_sp->GetArchitecture();
989 
990         FileSpecList dependent_files;
991         ObjectFile *executable_objfile = executable_sp->GetObjectFile();
992 
993         if (executable_objfile && get_dependent_files)
994         {
995             executable_objfile->GetDependentModules(dependent_files);
996             for (uint32_t i=0; i<dependent_files.GetSize(); i++)
997             {
998                 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
999                 FileSpec platform_dependent_file_spec;
1000                 if (m_platform_sp)
1001                     m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec);
1002                 else
1003                     platform_dependent_file_spec = dependent_file_spec;
1004 
1005                 ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
1006                 ModuleSP image_module_sp(GetSharedModule (module_spec));
1007                 if (image_module_sp.get())
1008                 {
1009                     ObjectFile *objfile = image_module_sp->GetObjectFile();
1010                     if (objfile)
1011                         objfile->GetDependentModules(dependent_files);
1012                 }
1013             }
1014         }
1015     }
1016 }
1017 
1018 
1019 bool
1020 Target::SetArchitecture (const ArchSpec &arch_spec)
1021 {
1022     if (m_arch == arch_spec || !m_arch.IsValid())
1023     {
1024         // If we haven't got a valid arch spec, or the architectures are
1025         // compatible, so just update the architecture. Architectures can be
1026         // equal, yet the triple OS and vendor might change, so we need to do
1027         // the assignment here just in case.
1028         m_arch = arch_spec;
1029         return true;
1030     }
1031     else
1032     {
1033         // If we have an executable file, try to reset the executable to the desired architecture
1034         m_arch = arch_spec;
1035         ModuleSP executable_sp = GetExecutableModule ();
1036         m_images.Clear();
1037         m_scratch_ast_context_ap.reset();
1038         m_scratch_ast_source_ap.reset();
1039         m_ast_importer_ap.reset();
1040         // Need to do something about unsetting breakpoints.
1041 
1042         if (executable_sp)
1043         {
1044             ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec);
1045             Error error = ModuleList::GetSharedModule (module_spec,
1046                                                        executable_sp,
1047                                                        &GetExecutableSearchPaths(),
1048                                                        NULL,
1049                                                        NULL);
1050 
1051             if (!error.Fail() && executable_sp)
1052             {
1053                 SetExecutableModule (executable_sp, true);
1054                 return true;
1055             }
1056         }
1057     }
1058     return false;
1059 }
1060 
1061 void
1062 Target::WillClearList (const ModuleList& module_list)
1063 {
1064 }
1065 
1066 void
1067 Target::ModuleAdded (const ModuleList& module_list, const ModuleSP &module_sp)
1068 {
1069     // A module is being added to this target for the first time
1070     ModuleList my_module_list;
1071     my_module_list.Append(module_sp);
1072     LoadScriptingResourceForModule(module_sp, this);
1073     ModulesDidLoad (my_module_list);
1074 }
1075 
1076 void
1077 Target::ModuleRemoved (const ModuleList& module_list, const ModuleSP &module_sp)
1078 {
1079     // A module is being added to this target for the first time
1080     ModuleList my_module_list;
1081     my_module_list.Append(module_sp);
1082     ModulesDidUnload (my_module_list);
1083 }
1084 
1085 void
1086 Target::ModuleUpdated (const ModuleList& module_list, const ModuleSP &old_module_sp, const ModuleSP &new_module_sp)
1087 {
1088     // A module is replacing an already added module
1089     m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1090 }
1091 
1092 void
1093 Target::ModulesDidLoad (ModuleList &module_list)
1094 {
1095     if (module_list.GetSize())
1096     {
1097         m_breakpoint_list.UpdateBreakpoints (module_list, true);
1098         // TODO: make event data that packages up the module_list
1099         BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
1100     }
1101 }
1102 
1103 void
1104 Target::ModulesDidUnload (ModuleList &module_list)
1105 {
1106     if (module_list.GetSize())
1107     {
1108         m_breakpoint_list.UpdateBreakpoints (module_list, false);
1109         // TODO: make event data that packages up the module_list
1110         BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
1111     }
1112 }
1113 
1114 bool
1115 Target::ModuleIsExcludedForNonModuleSpecificSearches (const FileSpec &module_file_spec)
1116 {
1117     if (GetBreakpointsConsultPlatformAvoidList())
1118     {
1119         ModuleList matchingModules;
1120         ModuleSpec module_spec (module_file_spec);
1121         size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1122 
1123         // If there is more than one module for this file spec, only return true if ALL the modules are on the
1124         // black list.
1125         if (num_modules > 0)
1126         {
1127             for (int i  = 0; i < num_modules; i++)
1128             {
1129                 if (!ModuleIsExcludedForNonModuleSpecificSearches (matchingModules.GetModuleAtIndex(i)))
1130                     return false;
1131             }
1132             return true;
1133         }
1134     }
1135     return false;
1136 }
1137 
1138 bool
1139 Target::ModuleIsExcludedForNonModuleSpecificSearches (const lldb::ModuleSP &module_sp)
1140 {
1141     if (GetBreakpointsConsultPlatformAvoidList())
1142     {
1143         if (m_platform_sp)
1144             return m_platform_sp->ModuleIsExcludedForNonModuleSpecificSearches (*this, module_sp);
1145     }
1146     return false;
1147 }
1148 
1149 size_t
1150 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
1151 {
1152     SectionSP section_sp (addr.GetSection());
1153     if (section_sp)
1154     {
1155         // If the contents of this section are encrypted, the on-disk file is unusuable.  Read only from live memory.
1156         if (section_sp->IsEncrypted())
1157         {
1158             error.SetErrorString("section is encrypted");
1159             return 0;
1160         }
1161         ModuleSP module_sp (section_sp->GetModule());
1162         if (module_sp)
1163         {
1164             ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1165             if (objfile)
1166             {
1167                 size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
1168                                                               addr.GetOffset(),
1169                                                               dst,
1170                                                               dst_len);
1171                 if (bytes_read > 0)
1172                     return bytes_read;
1173                 else
1174                     error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
1175             }
1176             else
1177                 error.SetErrorString("address isn't from a object file");
1178         }
1179         else
1180             error.SetErrorString("address isn't in a module");
1181     }
1182     else
1183         error.SetErrorString("address doesn't contain a section that points to a section in a object file");
1184 
1185     return 0;
1186 }
1187 
1188 size_t
1189 Target::ReadMemory (const Address& addr,
1190                     bool prefer_file_cache,
1191                     void *dst,
1192                     size_t dst_len,
1193                     Error &error,
1194                     lldb::addr_t *load_addr_ptr)
1195 {
1196     error.Clear();
1197 
1198     // if we end up reading this from process memory, we will fill this
1199     // with the actual load address
1200     if (load_addr_ptr)
1201         *load_addr_ptr = LLDB_INVALID_ADDRESS;
1202 
1203     size_t bytes_read = 0;
1204 
1205     addr_t load_addr = LLDB_INVALID_ADDRESS;
1206     addr_t file_addr = LLDB_INVALID_ADDRESS;
1207     Address resolved_addr;
1208     if (!addr.IsSectionOffset())
1209     {
1210         if (m_section_load_list.IsEmpty())
1211         {
1212             // No sections are loaded, so we must assume we are not running
1213             // yet and anything we are given is a file address.
1214             file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
1215             m_images.ResolveFileAddress (file_addr, resolved_addr);
1216         }
1217         else
1218         {
1219             // We have at least one section loaded. This can be becuase
1220             // we have manually loaded some sections with "target modules load ..."
1221             // or because we have have a live process that has sections loaded
1222             // through the dynamic loader
1223             load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1224             m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1225         }
1226     }
1227     if (!resolved_addr.IsValid())
1228         resolved_addr = addr;
1229 
1230 
1231     if (prefer_file_cache)
1232     {
1233         bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1234         if (bytes_read > 0)
1235             return bytes_read;
1236     }
1237 
1238     if (ProcessIsValid())
1239     {
1240         if (load_addr == LLDB_INVALID_ADDRESS)
1241             load_addr = resolved_addr.GetLoadAddress (this);
1242 
1243         if (load_addr == LLDB_INVALID_ADDRESS)
1244         {
1245             ModuleSP addr_module_sp (resolved_addr.GetModule());
1246             if (addr_module_sp && addr_module_sp->GetFileSpec())
1247                 error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded",
1248                                                addr_module_sp->GetFileSpec().GetFilename().AsCString(),
1249                                                resolved_addr.GetFileAddress(),
1250                                                addr_module_sp->GetFileSpec().GetFilename().AsCString());
1251             else
1252                 error.SetErrorStringWithFormat("0x%llx can't be resolved", resolved_addr.GetFileAddress());
1253         }
1254         else
1255         {
1256             bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1257             if (bytes_read != dst_len)
1258             {
1259                 if (error.Success())
1260                 {
1261                     if (bytes_read == 0)
1262                         error.SetErrorStringWithFormat("read memory from 0x%llx failed", load_addr);
1263                     else
1264                         error.SetErrorStringWithFormat("only %llu of %llu bytes were read from memory at 0x%llx", (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1265                 }
1266             }
1267             if (bytes_read)
1268             {
1269                 if (load_addr_ptr)
1270                     *load_addr_ptr = load_addr;
1271                 return bytes_read;
1272             }
1273             // If the address is not section offset we have an address that
1274             // doesn't resolve to any address in any currently loaded shared
1275             // libaries and we failed to read memory so there isn't anything
1276             // more we can do. If it is section offset, we might be able to
1277             // read cached memory from the object file.
1278             if (!resolved_addr.IsSectionOffset())
1279                 return 0;
1280         }
1281     }
1282 
1283     if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1284     {
1285         // If we didn't already try and read from the object file cache, then
1286         // try it after failing to read from the process.
1287         return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1288     }
1289     return 0;
1290 }
1291 
1292 size_t
1293 Target::ReadScalarIntegerFromMemory (const Address& addr,
1294                                      bool prefer_file_cache,
1295                                      uint32_t byte_size,
1296                                      bool is_signed,
1297                                      Scalar &scalar,
1298                                      Error &error)
1299 {
1300     uint64_t uval;
1301 
1302     if (byte_size <= sizeof(uval))
1303     {
1304         size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1305         if (bytes_read == byte_size)
1306         {
1307             DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1308             uint32_t offset = 0;
1309             if (byte_size <= 4)
1310                 scalar = data.GetMaxU32 (&offset, byte_size);
1311             else
1312                 scalar = data.GetMaxU64 (&offset, byte_size);
1313 
1314             if (is_signed)
1315                 scalar.SignExtend(byte_size * 8);
1316             return bytes_read;
1317         }
1318     }
1319     else
1320     {
1321         error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1322     }
1323     return 0;
1324 }
1325 
1326 uint64_t
1327 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1328                                        bool prefer_file_cache,
1329                                        size_t integer_byte_size,
1330                                        uint64_t fail_value,
1331                                        Error &error)
1332 {
1333     Scalar scalar;
1334     if (ReadScalarIntegerFromMemory (addr,
1335                                      prefer_file_cache,
1336                                      integer_byte_size,
1337                                      false,
1338                                      scalar,
1339                                      error))
1340         return scalar.ULongLong(fail_value);
1341     return fail_value;
1342 }
1343 
1344 bool
1345 Target::ReadPointerFromMemory (const Address& addr,
1346                                bool prefer_file_cache,
1347                                Error &error,
1348                                Address &pointer_addr)
1349 {
1350     Scalar scalar;
1351     if (ReadScalarIntegerFromMemory (addr,
1352                                      prefer_file_cache,
1353                                      m_arch.GetAddressByteSize(),
1354                                      false,
1355                                      scalar,
1356                                      error))
1357     {
1358         addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1359         if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1360         {
1361             if (m_section_load_list.IsEmpty())
1362             {
1363                 // No sections are loaded, so we must assume we are not running
1364                 // yet and anything we are given is a file address.
1365                 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1366             }
1367             else
1368             {
1369                 // We have at least one section loaded. This can be becuase
1370                 // we have manually loaded some sections with "target modules load ..."
1371                 // or because we have have a live process that has sections loaded
1372                 // through the dynamic loader
1373                 m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1374             }
1375             // We weren't able to resolve the pointer value, so just return
1376             // an address with no section
1377             if (!pointer_addr.IsValid())
1378                 pointer_addr.SetOffset (pointer_vm_addr);
1379             return true;
1380 
1381         }
1382     }
1383     return false;
1384 }
1385 
1386 ModuleSP
1387 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
1388 {
1389     ModuleSP module_sp;
1390 
1391     Error error;
1392 
1393     // First see if we already have this module in our module list.  If we do, then we're done, we don't need
1394     // to consult the shared modules list.  But only do this if we are passed a UUID.
1395 
1396     if (module_spec.GetUUID().IsValid())
1397         module_sp = m_images.FindFirstModule(module_spec);
1398 
1399     if (!module_sp)
1400     {
1401         ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1402         bool did_create_module = false;
1403 
1404         // If there are image search path entries, try to use them first to acquire a suitable image.
1405         if (m_image_search_paths.GetSize())
1406         {
1407             ModuleSpec transformed_spec (module_spec);
1408             if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
1409             {
1410                 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
1411                 error = ModuleList::GetSharedModule (transformed_spec,
1412                                                      module_sp,
1413                                                      &GetExecutableSearchPaths(),
1414                                                      &old_module_sp,
1415                                                      &did_create_module);
1416             }
1417         }
1418 
1419         if (!module_sp)
1420         {
1421             // If we have a UUID, we can check our global shared module list in case
1422             // we already have it. If we don't have a valid UUID, then we can't since
1423             // the path in "module_spec" will be a platform path, and we will need to
1424             // let the platform find that file. For example, we could be asking for
1425             // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1426             // the local copy of "/usr/lib/dyld" since our platform could be a remote
1427             // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1428             // cache.
1429             if (module_spec.GetUUID().IsValid())
1430             {
1431                 // We have a UUID, it is OK to check the global module list...
1432                 error = ModuleList::GetSharedModule (module_spec,
1433                                                      module_sp,
1434                                                      &GetExecutableSearchPaths(),
1435                                                      &old_module_sp,
1436                                                      &did_create_module);
1437             }
1438 
1439             if (!module_sp)
1440             {
1441                 // The platform is responsible for finding and caching an appropriate
1442                 // module in the shared module cache.
1443                 if (m_platform_sp)
1444                 {
1445                     FileSpec platform_file_spec;
1446                     error = m_platform_sp->GetSharedModule (module_spec,
1447                                                             module_sp,
1448                                                             &GetExecutableSearchPaths(),
1449                                                             &old_module_sp,
1450                                                             &did_create_module);
1451                 }
1452                 else
1453                 {
1454                     error.SetErrorString("no platform is currently set");
1455                 }
1456             }
1457         }
1458 
1459         // We found a module that wasn't in our target list.  Let's make sure that there wasn't an equivalent
1460         // module in the list already, and if there was, let's remove it.
1461         if (module_sp)
1462         {
1463             // GetSharedModule is not guaranteed to find the old shared module, for instance
1464             // in the common case where you pass in the UUID, it is only going to find the one
1465             // module matching the UUID.  In fact, it has no good way to know what the "old module"
1466             // relevant to this target is, since there might be many copies of a module with this file spec
1467             // in various running debug sessions, but only one of them will belong to this target.
1468             // So let's remove the UUID from the module list, and look in the target's module list.
1469             // Only do this if there is SOMETHING else in the module spec...
1470             if (!old_module_sp)
1471             {
1472                 if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
1473                 {
1474                     ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1475                     module_spec_copy.GetUUID().Clear();
1476 
1477                     ModuleList found_modules;
1478                     size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
1479                     if (num_found == 1)
1480                     {
1481                         old_module_sp = found_modules.GetModuleAtIndex(0);
1482                     }
1483                 }
1484             }
1485 
1486             if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1487             {
1488                 m_images.ReplaceModule(old_module_sp, module_sp);
1489                 Module *old_module_ptr = old_module_sp.get();
1490                 old_module_sp.reset();
1491                 ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
1492             }
1493             else
1494                 m_images.Append(module_sp);
1495         }
1496     }
1497     if (error_ptr)
1498         *error_ptr = error;
1499     return module_sp;
1500 }
1501 
1502 
1503 TargetSP
1504 Target::CalculateTarget ()
1505 {
1506     return shared_from_this();
1507 }
1508 
1509 ProcessSP
1510 Target::CalculateProcess ()
1511 {
1512     return ProcessSP();
1513 }
1514 
1515 ThreadSP
1516 Target::CalculateThread ()
1517 {
1518     return ThreadSP();
1519 }
1520 
1521 StackFrameSP
1522 Target::CalculateStackFrame ()
1523 {
1524     return StackFrameSP();
1525 }
1526 
1527 void
1528 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1529 {
1530     exe_ctx.Clear();
1531     exe_ctx.SetTargetPtr(this);
1532 }
1533 
1534 PathMappingList &
1535 Target::GetImageSearchPathList ()
1536 {
1537     return m_image_search_paths;
1538 }
1539 
1540 void
1541 Target::ImageSearchPathsChanged
1542 (
1543     const PathMappingList &path_list,
1544     void *baton
1545 )
1546 {
1547     Target *target = (Target *)baton;
1548     ModuleSP exe_module_sp (target->GetExecutableModule());
1549     if (exe_module_sp)
1550     {
1551         target->m_images.Clear();
1552         target->SetExecutableModule (exe_module_sp, true);
1553     }
1554 }
1555 
1556 ClangASTContext *
1557 Target::GetScratchClangASTContext(bool create_on_demand)
1558 {
1559     // Now see if we know the target triple, and if so, create our scratch AST context:
1560     if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand)
1561     {
1562         m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1563         m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this()));
1564         m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext());
1565         llvm::OwningPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy());
1566         m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source);
1567     }
1568     return m_scratch_ast_context_ap.get();
1569 }
1570 
1571 ClangASTImporter *
1572 Target::GetClangASTImporter()
1573 {
1574     ClangASTImporter *ast_importer = m_ast_importer_ap.get();
1575 
1576     if (!ast_importer)
1577     {
1578         ast_importer = new ClangASTImporter();
1579         m_ast_importer_ap.reset(ast_importer);
1580     }
1581 
1582     return ast_importer;
1583 }
1584 
1585 void
1586 Target::SettingsInitialize ()
1587 {
1588     Process::SettingsInitialize ();
1589 }
1590 
1591 void
1592 Target::SettingsTerminate ()
1593 {
1594     Process::SettingsTerminate ();
1595 }
1596 
1597 FileSpecList
1598 Target::GetDefaultExecutableSearchPaths ()
1599 {
1600     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1601     if (properties_sp)
1602         return properties_sp->GetExecutableSearchPaths();
1603     return FileSpecList();
1604 }
1605 
1606 ArchSpec
1607 Target::GetDefaultArchitecture ()
1608 {
1609     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1610     if (properties_sp)
1611         return properties_sp->GetDefaultArchitecture();
1612     return ArchSpec();
1613 }
1614 
1615 void
1616 Target::SetDefaultArchitecture (const ArchSpec &arch)
1617 {
1618     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1619     if (properties_sp)
1620         return properties_sp->SetDefaultArchitecture(arch);
1621 }
1622 
1623 Target *
1624 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1625 {
1626     // The target can either exist in the "process" of ExecutionContext, or in
1627     // the "target_sp" member of SymbolContext. This accessor helper function
1628     // will get the target from one of these locations.
1629 
1630     Target *target = NULL;
1631     if (sc_ptr != NULL)
1632         target = sc_ptr->target_sp.get();
1633     if (target == NULL && exe_ctx_ptr)
1634         target = exe_ctx_ptr->GetTargetPtr();
1635     return target;
1636 }
1637 
1638 ExecutionResults
1639 Target::EvaluateExpression
1640 (
1641     const char *expr_cstr,
1642     StackFrame *frame,
1643     lldb::ValueObjectSP &result_valobj_sp,
1644     const EvaluateExpressionOptions& options
1645 )
1646 {
1647     result_valobj_sp.reset();
1648 
1649     ExecutionResults execution_results = eExecutionSetupError;
1650 
1651     if (expr_cstr == NULL || expr_cstr[0] == '\0')
1652         return execution_results;
1653 
1654     // We shouldn't run stop hooks in expressions.
1655     // Be sure to reset this if you return anywhere within this function.
1656     bool old_suppress_value = m_suppress_stop_hooks;
1657     m_suppress_stop_hooks = true;
1658 
1659     ExecutionContext exe_ctx;
1660 
1661     const size_t expr_cstr_len = ::strlen (expr_cstr);
1662 
1663     if (frame)
1664     {
1665         frame->CalculateExecutionContext(exe_ctx);
1666         Error error;
1667         const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember |
1668                                            StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
1669                                            StackFrame::eExpressionPathOptionsNoSyntheticChildren;
1670         lldb::VariableSP var_sp;
1671 
1672         // Make sure we don't have any things that we know a variable expression
1673         // won't be able to deal with before calling into it
1674         if (::strcspn (expr_cstr, "()+*&|!~<=/^%,?") == expr_cstr_len)
1675         {
1676             result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr,
1677                                                                          options.GetUseDynamic(),
1678                                                                          expr_path_options,
1679                                                                          var_sp,
1680                                                                          error);
1681             // if this expression results in a bitfield, we give up and let the IR handle it
1682             if (result_valobj_sp && result_valobj_sp->IsBitfield())
1683                 result_valobj_sp.reset();
1684         }
1685     }
1686     else if (m_process_sp)
1687     {
1688         m_process_sp->CalculateExecutionContext(exe_ctx);
1689     }
1690     else
1691     {
1692         CalculateExecutionContext(exe_ctx);
1693     }
1694 
1695     if (result_valobj_sp)
1696     {
1697         execution_results = eExecutionCompleted;
1698         // We got a result from the frame variable expression path above...
1699         ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName());
1700 
1701         lldb::ValueObjectSP const_valobj_sp;
1702 
1703         // Check in case our value is already a constant value
1704         if (result_valobj_sp->GetIsConstant())
1705         {
1706             const_valobj_sp = result_valobj_sp;
1707             const_valobj_sp->SetName (persistent_variable_name);
1708         }
1709         else
1710         {
1711             if (options.GetUseDynamic() != lldb::eNoDynamicValues)
1712             {
1713                 ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(options.GetUseDynamic());
1714                 if (dynamic_sp)
1715                     result_valobj_sp = dynamic_sp;
1716             }
1717 
1718             const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name);
1719         }
1720 
1721         lldb::ValueObjectSP live_valobj_sp = result_valobj_sp;
1722 
1723         result_valobj_sp = const_valobj_sp;
1724 
1725         ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp));
1726         assert (clang_expr_variable_sp.get());
1727 
1728         // Set flags and live data as appropriate
1729 
1730         const Value &result_value = live_valobj_sp->GetValue();
1731 
1732         switch (result_value.GetValueType())
1733         {
1734         case Value::eValueTypeHostAddress:
1735         case Value::eValueTypeFileAddress:
1736             // we don't do anything with these for now
1737             break;
1738         case Value::eValueTypeScalar:
1739         case Value::eValueTypeVector:
1740             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1741             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1742             break;
1743         case Value::eValueTypeLoadAddress:
1744             clang_expr_variable_sp->m_live_sp = live_valobj_sp;
1745             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
1746             break;
1747         }
1748     }
1749     else
1750     {
1751         // Make sure we aren't just trying to see the value of a persistent
1752         // variable (something like "$0")
1753         lldb::ClangExpressionVariableSP persistent_var_sp;
1754         // Only check for persistent variables the expression starts with a '$'
1755         if (expr_cstr[0] == '$')
1756             persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1757 
1758         if (persistent_var_sp)
1759         {
1760             result_valobj_sp = persistent_var_sp->GetValueObject ();
1761             execution_results = eExecutionCompleted;
1762         }
1763         else
1764         {
1765             const char *prefix = GetExpressionPrefixContentsAsCString();
1766 
1767             execution_results = ClangUserExpression::Evaluate (exe_ctx,
1768                                                                options.GetExecutionPolicy(),
1769                                                                lldb::eLanguageTypeUnknown,
1770                                                                options.DoesCoerceToId() ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny,
1771                                                                options.DoesUnwindOnError(),
1772                                                                expr_cstr,
1773                                                                prefix,
1774                                                                result_valobj_sp,
1775                                                                options.GetRunOthers(),
1776                                                                options.GetTimeoutUsec());
1777         }
1778     }
1779 
1780     m_suppress_stop_hooks = old_suppress_value;
1781 
1782     return execution_results;
1783 }
1784 
1785 lldb::addr_t
1786 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1787 {
1788     addr_t code_addr = load_addr;
1789     switch (m_arch.GetMachine())
1790     {
1791     case llvm::Triple::arm:
1792     case llvm::Triple::thumb:
1793         switch (addr_class)
1794         {
1795         case eAddressClassData:
1796         case eAddressClassDebug:
1797             return LLDB_INVALID_ADDRESS;
1798 
1799         case eAddressClassUnknown:
1800         case eAddressClassInvalid:
1801         case eAddressClassCode:
1802         case eAddressClassCodeAlternateISA:
1803         case eAddressClassRuntime:
1804             // Check if bit zero it no set?
1805             if ((code_addr & 1ull) == 0)
1806             {
1807                 // Bit zero isn't set, check if the address is a multiple of 2?
1808                 if (code_addr & 2ull)
1809                 {
1810                     // The address is a multiple of 2 so it must be thumb, set bit zero
1811                     code_addr |= 1ull;
1812                 }
1813                 else if (addr_class == eAddressClassCodeAlternateISA)
1814                 {
1815                     // We checked the address and the address claims to be the alternate ISA
1816                     // which means thumb, so set bit zero.
1817                     code_addr |= 1ull;
1818                 }
1819             }
1820             break;
1821         }
1822         break;
1823 
1824     default:
1825         break;
1826     }
1827     return code_addr;
1828 }
1829 
1830 lldb::addr_t
1831 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1832 {
1833     addr_t opcode_addr = load_addr;
1834     switch (m_arch.GetMachine())
1835     {
1836     case llvm::Triple::arm:
1837     case llvm::Triple::thumb:
1838         switch (addr_class)
1839         {
1840         case eAddressClassData:
1841         case eAddressClassDebug:
1842             return LLDB_INVALID_ADDRESS;
1843 
1844         case eAddressClassInvalid:
1845         case eAddressClassUnknown:
1846         case eAddressClassCode:
1847         case eAddressClassCodeAlternateISA:
1848         case eAddressClassRuntime:
1849             opcode_addr &= ~(1ull);
1850             break;
1851         }
1852         break;
1853 
1854     default:
1855         break;
1856     }
1857     return opcode_addr;
1858 }
1859 
1860 lldb::user_id_t
1861 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1862 {
1863     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1864     new_hook_sp.reset (new StopHook(shared_from_this(), new_uid));
1865     m_stop_hooks[new_uid] = new_hook_sp;
1866     return new_uid;
1867 }
1868 
1869 bool
1870 Target::RemoveStopHookByID (lldb::user_id_t user_id)
1871 {
1872     size_t num_removed;
1873     num_removed = m_stop_hooks.erase (user_id);
1874     if (num_removed == 0)
1875         return false;
1876     else
1877         return true;
1878 }
1879 
1880 void
1881 Target::RemoveAllStopHooks ()
1882 {
1883     m_stop_hooks.clear();
1884 }
1885 
1886 Target::StopHookSP
1887 Target::GetStopHookByID (lldb::user_id_t user_id)
1888 {
1889     StopHookSP found_hook;
1890 
1891     StopHookCollection::iterator specified_hook_iter;
1892     specified_hook_iter = m_stop_hooks.find (user_id);
1893     if (specified_hook_iter != m_stop_hooks.end())
1894         found_hook = (*specified_hook_iter).second;
1895     return found_hook;
1896 }
1897 
1898 bool
1899 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1900 {
1901     StopHookCollection::iterator specified_hook_iter;
1902     specified_hook_iter = m_stop_hooks.find (user_id);
1903     if (specified_hook_iter == m_stop_hooks.end())
1904         return false;
1905 
1906     (*specified_hook_iter).second->SetIsActive (active_state);
1907     return true;
1908 }
1909 
1910 void
1911 Target::SetAllStopHooksActiveState (bool active_state)
1912 {
1913     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1914     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1915     {
1916         (*pos).second->SetIsActive (active_state);
1917     }
1918 }
1919 
1920 void
1921 Target::RunStopHooks ()
1922 {
1923     if (m_suppress_stop_hooks)
1924         return;
1925 
1926     if (!m_process_sp)
1927         return;
1928 
1929     // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
1930     // since in that case we do not want to run the stop-hooks
1931     if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
1932         return;
1933 
1934     if (m_stop_hooks.empty())
1935         return;
1936 
1937     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1938 
1939     // If there aren't any active stop hooks, don't bother either:
1940     bool any_active_hooks = false;
1941     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1942     {
1943         if ((*pos).second->IsActive())
1944         {
1945             any_active_hooks = true;
1946             break;
1947         }
1948     }
1949     if (!any_active_hooks)
1950         return;
1951 
1952     CommandReturnObject result;
1953 
1954     std::vector<ExecutionContext> exc_ctx_with_reasons;
1955     std::vector<SymbolContext> sym_ctx_with_reasons;
1956 
1957     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1958     size_t num_threads = cur_threadlist.GetSize();
1959     for (size_t i = 0; i < num_threads; i++)
1960     {
1961         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1962         if (cur_thread_sp->ThreadStoppedForAReason())
1963         {
1964             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1965             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1966             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1967         }
1968     }
1969 
1970     // If no threads stopped for a reason, don't run the stop-hooks.
1971     size_t num_exe_ctx = exc_ctx_with_reasons.size();
1972     if (num_exe_ctx == 0)
1973         return;
1974 
1975     result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
1976     result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
1977 
1978     bool keep_going = true;
1979     bool hooks_ran = false;
1980     bool print_hook_header;
1981     bool print_thread_header;
1982 
1983     if (num_exe_ctx == 1)
1984         print_thread_header = false;
1985     else
1986         print_thread_header = true;
1987 
1988     if (m_stop_hooks.size() == 1)
1989         print_hook_header = false;
1990     else
1991         print_hook_header = true;
1992 
1993     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
1994     {
1995         // result.Clear();
1996         StopHookSP cur_hook_sp = (*pos).second;
1997         if (!cur_hook_sp->IsActive())
1998             continue;
1999 
2000         bool any_thread_matched = false;
2001         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2002         {
2003             if ((cur_hook_sp->GetSpecifier () == NULL
2004                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2005                 && (cur_hook_sp->GetThreadSpecifier() == NULL
2006                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2007             {
2008                 if (!hooks_ran)
2009                 {
2010                     hooks_ran = true;
2011                 }
2012                 if (print_hook_header && !any_thread_matched)
2013                 {
2014                     const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2015                                        cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2016                                        NULL);
2017                     if (cmd)
2018                         result.AppendMessageWithFormat("\n- Hook %llu (%s)\n", cur_hook_sp->GetID(), cmd);
2019                     else
2020                         result.AppendMessageWithFormat("\n- Hook %llu\n", cur_hook_sp->GetID());
2021                     any_thread_matched = true;
2022                 }
2023 
2024                 if (print_thread_header)
2025                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2026 
2027                 bool stop_on_continue = true;
2028                 bool stop_on_error = true;
2029                 bool echo_commands = false;
2030                 bool print_results = true;
2031                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2032                                                                       &exc_ctx_with_reasons[i],
2033                                                                       stop_on_continue,
2034                                                                       stop_on_error,
2035                                                                       echo_commands,
2036                                                                       print_results,
2037                                                                       eLazyBoolNo,
2038                                                                       result);
2039 
2040                 // If the command started the target going again, we should bag out of
2041                 // running the stop hooks.
2042                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2043                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2044                 {
2045                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %llu set the program running.", cur_hook_sp->GetID());
2046                     keep_going = false;
2047                 }
2048             }
2049         }
2050     }
2051 
2052     result.GetImmediateOutputStream()->Flush();
2053     result.GetImmediateErrorStream()->Flush();
2054 }
2055 
2056 
2057 //--------------------------------------------------------------
2058 // class Target::StopHook
2059 //--------------------------------------------------------------
2060 
2061 
2062 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2063         UserID (uid),
2064         m_target_sp (target_sp),
2065         m_commands (),
2066         m_specifier_sp (),
2067         m_thread_spec_ap(NULL),
2068         m_active (true)
2069 {
2070 }
2071 
2072 Target::StopHook::StopHook (const StopHook &rhs) :
2073         UserID (rhs.GetID()),
2074         m_target_sp (rhs.m_target_sp),
2075         m_commands (rhs.m_commands),
2076         m_specifier_sp (rhs.m_specifier_sp),
2077         m_thread_spec_ap (NULL),
2078         m_active (rhs.m_active)
2079 {
2080     if (rhs.m_thread_spec_ap.get() != NULL)
2081         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2082 }
2083 
2084 
2085 Target::StopHook::~StopHook ()
2086 {
2087 }
2088 
2089 void
2090 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2091 {
2092     m_thread_spec_ap.reset (specifier);
2093 }
2094 
2095 
2096 void
2097 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2098 {
2099     int indent_level = s->GetIndentLevel();
2100 
2101     s->SetIndentLevel(indent_level + 2);
2102 
2103     s->Printf ("Hook: %llu\n", GetID());
2104     if (m_active)
2105         s->Indent ("State: enabled\n");
2106     else
2107         s->Indent ("State: disabled\n");
2108 
2109     if (m_specifier_sp)
2110     {
2111         s->Indent();
2112         s->PutCString ("Specifier:\n");
2113         s->SetIndentLevel (indent_level + 4);
2114         m_specifier_sp->GetDescription (s, level);
2115         s->SetIndentLevel (indent_level + 2);
2116     }
2117 
2118     if (m_thread_spec_ap.get() != NULL)
2119     {
2120         StreamString tmp;
2121         s->Indent("Thread:\n");
2122         m_thread_spec_ap->GetDescription (&tmp, level);
2123         s->SetIndentLevel (indent_level + 4);
2124         s->Indent (tmp.GetData());
2125         s->PutCString ("\n");
2126         s->SetIndentLevel (indent_level + 2);
2127     }
2128 
2129     s->Indent ("Commands: \n");
2130     s->SetIndentLevel (indent_level + 4);
2131     uint32_t num_commands = m_commands.GetSize();
2132     for (uint32_t i = 0; i < num_commands; i++)
2133     {
2134         s->Indent(m_commands.GetStringAtIndex(i));
2135         s->PutCString ("\n");
2136     }
2137     s->SetIndentLevel (indent_level);
2138 }
2139 
2140 //--------------------------------------------------------------
2141 // class TargetProperties
2142 //--------------------------------------------------------------
2143 
2144 OptionEnumValueElement
2145 lldb_private::g_dynamic_value_types[] =
2146 {
2147     { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2148     { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2149     { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2150     { 0, NULL, NULL }
2151 };
2152 
2153 static OptionEnumValueElement
2154 g_inline_breakpoint_enums[] =
2155 {
2156     { 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."},
2157     { eInlineBreakpointsHeaders, "headers",   "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2158     { eInlineBreakpointsAlways,  "always",    "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2159     { 0, NULL, NULL }
2160 };
2161 
2162 static PropertyDefinition
2163 g_properties[] =
2164 {
2165     { "default-arch"                       , OptionValue::eTypeArch      , true , 0                         , NULL, NULL, "Default architecture to choose, when there's a choice." },
2166     { "expr-prefix"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2167     { "prefer-dynamic-value"               , OptionValue::eTypeEnum      , false, eNoDynamicValues          , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2168     { "enable-synthetic-value"             , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Should synthetic values be used by default whenever available." },
2169     { "skip-prologue"                      , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2170     { "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 "
2171       "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
2172       "some part (starting at the root) of the path to the file when it was built, "
2173       "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
2174       "Each element of the array is checked in order and the first one that results in a match wins." },
2175     { "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." },
2176     { "max-children-count"                 , OptionValue::eTypeSInt64    , false, 256                       , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2177     { "max-string-summary-length"          , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2178     { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2179     { "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." },
2180     { "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." },
2181     { "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." },
2182     { "inherit-env"                        , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2183     { "input-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2184     { "output-path"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2185     { "error-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2186     { "disable-aslr"                       , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2187     { "disable-stdio"                      , OptionValue::eTypeBoolean   , false, false                     , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2188     { "inline-breakpoint-strategy"         , OptionValue::eTypeEnum      , false, eInlineBreakpointsHeaders , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2189         "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. "
2190         "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2191         "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2192         "Always checking for inlined breakpoint locations can be expensive (memory and time), so we try to minimize the "
2193         "times we look for inlined locations. This setting allows you to control exactly which strategy is used when settings "
2194         "file and line breakpoints." },
2195     { NULL                                 , OptionValue::eTypeInvalid   , false, 0                         , NULL, NULL, NULL }
2196 };
2197 enum
2198 {
2199     ePropertyDefaultArch,
2200     ePropertyExprPrefix,
2201     ePropertyPreferDynamic,
2202     ePropertyEnableSynthetic,
2203     ePropertySkipPrologue,
2204     ePropertySourceMap,
2205     ePropertyExecutableSearchPaths,
2206     ePropertyMaxChildrenCount,
2207     ePropertyMaxSummaryLength,
2208     ePropertyBreakpointUseAvoidList,
2209     ePropertyArg0,
2210     ePropertyRunArgs,
2211     ePropertyEnvVars,
2212     ePropertyInheritEnv,
2213     ePropertyInputPath,
2214     ePropertyOutputPath,
2215     ePropertyErrorPath,
2216     ePropertyDisableASLR,
2217     ePropertyDisableSTDIO,
2218     ePropertyInlineStrategy
2219 };
2220 
2221 
2222 class TargetOptionValueProperties : public OptionValueProperties
2223 {
2224 public:
2225     TargetOptionValueProperties (const ConstString &name) :
2226         OptionValueProperties (name),
2227         m_target (NULL),
2228         m_got_host_env (false)
2229     {
2230     }
2231 
2232     // This constructor is used when creating TargetOptionValueProperties when it
2233     // is part of a new lldb_private::Target instance. It will copy all current
2234     // global property values as needed
2235     TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
2236         OptionValueProperties(*target_properties_sp->GetValueProperties()),
2237         m_target (target),
2238         m_got_host_env (false)
2239     {
2240     }
2241 
2242     virtual const Property *
2243     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
2244     {
2245         // When gettings the value for a key from the target options, we will always
2246         // try and grab the setting from the current target if there is one. Else we just
2247         // use the one from this instance.
2248         if (idx == ePropertyEnvVars)
2249             GetHostEnvironmentIfNeeded ();
2250 
2251         if (exe_ctx)
2252         {
2253             Target *target = exe_ctx->GetTargetPtr();
2254             if (target)
2255             {
2256                 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
2257                 if (this != target_properties)
2258                     return target_properties->ProtectedGetPropertyAtIndex (idx);
2259             }
2260         }
2261         return ProtectedGetPropertyAtIndex (idx);
2262     }
2263 protected:
2264 
2265     void
2266     GetHostEnvironmentIfNeeded () const
2267     {
2268         if (!m_got_host_env)
2269         {
2270             if (m_target)
2271             {
2272                 m_got_host_env = true;
2273                 const uint32_t idx = ePropertyInheritEnv;
2274                 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
2275                 {
2276                     PlatformSP platform_sp (m_target->GetPlatform());
2277                     if (platform_sp)
2278                     {
2279                         StringList env;
2280                         if (platform_sp->GetEnvironment(env))
2281                         {
2282                             OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
2283                             if (env_dict)
2284                             {
2285                                 const bool can_replace = false;
2286                                 const size_t envc = env.GetSize();
2287                                 for (size_t idx=0; idx<envc; idx++)
2288                                 {
2289                                     const char *env_entry = env.GetStringAtIndex (idx);
2290                                     if (env_entry)
2291                                     {
2292                                         const char *equal_pos = ::strchr(env_entry, '=');
2293                                         ConstString key;
2294                                         // It is ok to have environment variables with no values
2295                                         const char *value = NULL;
2296                                         if (equal_pos)
2297                                         {
2298                                             key.SetCStringWithLength(env_entry, equal_pos - env_entry);
2299                                             if (equal_pos[1])
2300                                                 value = equal_pos + 1;
2301                                         }
2302                                         else
2303                                         {
2304                                             key.SetCString(env_entry);
2305                                         }
2306                                         // Don't allow existing keys to be replaced with ones we get from the platform environment
2307                                         env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
2308                                     }
2309                                 }
2310                             }
2311                         }
2312                     }
2313                 }
2314             }
2315         }
2316     }
2317     Target *m_target;
2318     mutable bool m_got_host_env;
2319 };
2320 
2321 TargetProperties::TargetProperties (Target *target) :
2322     Properties ()
2323 {
2324     if (target)
2325     {
2326         m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
2327     }
2328     else
2329     {
2330         m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
2331         m_collection_sp->Initialize(g_properties);
2332         m_collection_sp->AppendProperty(ConstString("process"),
2333                                         ConstString("Settings specify to processes."),
2334                                         true,
2335                                         Process::GetGlobalProperties()->GetValueProperties());
2336     }
2337 }
2338 
2339 TargetProperties::~TargetProperties ()
2340 {
2341 }
2342 ArchSpec
2343 TargetProperties::GetDefaultArchitecture () const
2344 {
2345     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2346     if (value)
2347         return value->GetCurrentValue();
2348     return ArchSpec();
2349 }
2350 
2351 void
2352 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
2353 {
2354     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2355     if (value)
2356         return value->SetCurrentValue(arch, true);
2357 }
2358 
2359 lldb::DynamicValueType
2360 TargetProperties::GetPreferDynamicValue() const
2361 {
2362     const uint32_t idx = ePropertyPreferDynamic;
2363     return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2364 }
2365 
2366 bool
2367 TargetProperties::GetDisableASLR () const
2368 {
2369     const uint32_t idx = ePropertyDisableASLR;
2370     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2371 }
2372 
2373 void
2374 TargetProperties::SetDisableASLR (bool b)
2375 {
2376     const uint32_t idx = ePropertyDisableASLR;
2377     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2378 }
2379 
2380 bool
2381 TargetProperties::GetDisableSTDIO () const
2382 {
2383     const uint32_t idx = ePropertyDisableSTDIO;
2384     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2385 }
2386 
2387 void
2388 TargetProperties::SetDisableSTDIO (bool b)
2389 {
2390     const uint32_t idx = ePropertyDisableSTDIO;
2391     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2392 }
2393 
2394 InlineStrategy
2395 TargetProperties::GetInlineStrategy () const
2396 {
2397     const uint32_t idx = ePropertyInlineStrategy;
2398     return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2399 }
2400 
2401 const char *
2402 TargetProperties::GetArg0 () const
2403 {
2404     const uint32_t idx = ePropertyArg0;
2405     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
2406 }
2407 
2408 void
2409 TargetProperties::SetArg0 (const char *arg)
2410 {
2411     const uint32_t idx = ePropertyArg0;
2412     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
2413 }
2414 
2415 bool
2416 TargetProperties::GetRunArguments (Args &args) const
2417 {
2418     const uint32_t idx = ePropertyRunArgs;
2419     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
2420 }
2421 
2422 void
2423 TargetProperties::SetRunArguments (const Args &args)
2424 {
2425     const uint32_t idx = ePropertyRunArgs;
2426     m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
2427 }
2428 
2429 size_t
2430 TargetProperties::GetEnvironmentAsArgs (Args &env) const
2431 {
2432     const uint32_t idx = ePropertyEnvVars;
2433     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
2434 }
2435 
2436 bool
2437 TargetProperties::GetSkipPrologue() const
2438 {
2439     const uint32_t idx = ePropertySkipPrologue;
2440     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2441 }
2442 
2443 PathMappingList &
2444 TargetProperties::GetSourcePathMap () const
2445 {
2446     const uint32_t idx = ePropertySourceMap;
2447     OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
2448     assert(option_value);
2449     return option_value->GetCurrentValue();
2450 }
2451 
2452 FileSpecList &
2453 TargetProperties::GetExecutableSearchPaths ()
2454 {
2455     const uint32_t idx = ePropertyExecutableSearchPaths;
2456     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2457     assert(option_value);
2458     return option_value->GetCurrentValue();
2459 }
2460 
2461 bool
2462 TargetProperties::GetEnableSyntheticValue () const
2463 {
2464     const uint32_t idx = ePropertyEnableSynthetic;
2465     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2466 }
2467 
2468 uint32_t
2469 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
2470 {
2471     const uint32_t idx = ePropertyMaxChildrenCount;
2472     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2473 }
2474 
2475 uint32_t
2476 TargetProperties::GetMaximumSizeOfStringSummary() const
2477 {
2478     const uint32_t idx = ePropertyMaxSummaryLength;
2479     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2480 }
2481 
2482 FileSpec
2483 TargetProperties::GetStandardInputPath () const
2484 {
2485     const uint32_t idx = ePropertyInputPath;
2486     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2487 }
2488 
2489 void
2490 TargetProperties::SetStandardInputPath (const char *p)
2491 {
2492     const uint32_t idx = ePropertyInputPath;
2493     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2494 }
2495 
2496 FileSpec
2497 TargetProperties::GetStandardOutputPath () const
2498 {
2499     const uint32_t idx = ePropertyOutputPath;
2500     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2501 }
2502 
2503 void
2504 TargetProperties::SetStandardOutputPath (const char *p)
2505 {
2506     const uint32_t idx = ePropertyOutputPath;
2507     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2508 }
2509 
2510 FileSpec
2511 TargetProperties::GetStandardErrorPath () const
2512 {
2513     const uint32_t idx = ePropertyErrorPath;
2514     return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
2515 }
2516 
2517 const char *
2518 TargetProperties::GetExpressionPrefixContentsAsCString ()
2519 {
2520     const uint32_t idx = ePropertyExprPrefix;
2521     OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
2522     if (file)
2523     {
2524         const bool null_terminate = true;
2525         DataBufferSP data_sp(file->GetFileContents(null_terminate));
2526         if (data_sp)
2527             return (const char *) data_sp->GetBytes();
2528     }
2529     return NULL;
2530 }
2531 
2532 void
2533 TargetProperties::SetStandardErrorPath (const char *p)
2534 {
2535     const uint32_t idx = ePropertyErrorPath;
2536     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2537 }
2538 
2539 bool
2540 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
2541 {
2542     const uint32_t idx = ePropertyBreakpointUseAvoidList;
2543     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2544 }
2545 
2546 const TargetPropertiesSP &
2547 Target::GetGlobalProperties()
2548 {
2549     static TargetPropertiesSP g_settings_sp;
2550     if (!g_settings_sp)
2551     {
2552         g_settings_sp.reset (new TargetProperties (NULL));
2553     }
2554     return g_settings_sp;
2555 }
2556 
2557 const ConstString &
2558 Target::TargetEventData::GetFlavorString ()
2559 {
2560     static ConstString g_flavor ("Target::TargetEventData");
2561     return g_flavor;
2562 }
2563 
2564 const ConstString &
2565 Target::TargetEventData::GetFlavor () const
2566 {
2567     return TargetEventData::GetFlavorString ();
2568 }
2569 
2570 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
2571     EventData(),
2572     m_target_sp (new_target_sp)
2573 {
2574 }
2575 
2576 Target::TargetEventData::~TargetEventData()
2577 {
2578 
2579 }
2580 
2581 void
2582 Target::TargetEventData::Dump (Stream *s) const
2583 {
2584 
2585 }
2586 
2587 const TargetSP
2588 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
2589 {
2590     TargetSP target_sp;
2591 
2592     const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
2593     if (data)
2594         target_sp = data->m_target_sp;
2595 
2596     return target_sp;
2597 }
2598 
2599 const Target::TargetEventData *
2600 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
2601 {
2602     if (event_ptr)
2603     {
2604         const EventData *event_data = event_ptr->GetData();
2605         if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
2606             return static_cast <const TargetEventData *> (event_ptr->GetData());
2607     }
2608     return NULL;
2609 }
2610 
2611