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