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