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