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