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