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