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