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