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