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