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