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