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     uint32_t single_thread_timeout_usec
1657 )
1658 {
1659     ExecutionResults execution_results = eExecutionSetupError;
1660 
1661     result_valobj_sp.reset();
1662 
1663     if (expr_cstr == NULL || expr_cstr[0] == '\0')
1664         return execution_results;
1665 
1666     // We shouldn't run stop hooks in expressions.
1667     // Be sure to reset this if you return anywhere within this function.
1668     bool old_suppress_value = m_suppress_stop_hooks;
1669     m_suppress_stop_hooks = true;
1670 
1671     ExecutionContext exe_ctx;
1672 
1673     const size_t expr_cstr_len = ::strlen (expr_cstr);
1674 
1675     if (frame)
1676     {
1677         frame->CalculateExecutionContext(exe_ctx);
1678         Error error;
1679         const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember |
1680                                            StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
1681                                            StackFrame::eExpressionPathOptionsNoSyntheticChildren;
1682         lldb::VariableSP var_sp;
1683 
1684         // Make sure we don't have any things that we know a variable expression
1685         // won't be able to deal with before calling into it
1686         if (::strcspn (expr_cstr, "()+*&|!~<=/^%,?") == expr_cstr_len)
1687         {
1688             result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr,
1689                                                                          use_dynamic,
1690                                                                          expr_path_options,
1691                                                                          var_sp,
1692                                                                          error);
1693             // if this expression results in a bitfield, we give up and let the IR handle it
1694             if (result_valobj_sp && result_valobj_sp->IsBitfield())
1695                 result_valobj_sp.reset();
1696         }
1697     }
1698     else if (m_process_sp)
1699     {
1700         m_process_sp->CalculateExecutionContext(exe_ctx);
1701     }
1702     else
1703     {
1704         CalculateExecutionContext(exe_ctx);
1705     }
1706 
1707     if (result_valobj_sp)
1708     {
1709         execution_results = eExecutionCompleted;
1710         // We got a result from the frame variable expression path above...
1711         ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName());
1712 
1713         lldb::ValueObjectSP const_valobj_sp;
1714 
1715         // Check in case our value is already a constant value
1716         if (result_valobj_sp->GetIsConstant())
1717         {
1718             const_valobj_sp = result_valobj_sp;
1719             const_valobj_sp->SetName (persistent_variable_name);
1720         }
1721         else
1722         {
1723             if (use_dynamic != lldb::eNoDynamicValues)
1724             {
1725                 ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(use_dynamic);
1726                 if (dynamic_sp)
1727                     result_valobj_sp = dynamic_sp;
1728             }
1729 
1730             const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name);
1731         }
1732 
1733         lldb::ValueObjectSP live_valobj_sp = result_valobj_sp;
1734 
1735         result_valobj_sp = const_valobj_sp;
1736 
1737         ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp));
1738         assert (clang_expr_variable_sp.get());
1739 
1740         // Set flags and live data as appropriate
1741 
1742         const Value &result_value = live_valobj_sp->GetValue();
1743 
1744         switch (result_value.GetValueType())
1745         {
1746         case Value::eValueTypeHostAddress:
1747         case Value::eValueTypeFileAddress:
1748             // we don't do anything with these for now
1749             break;
1750         case Value::eValueTypeScalar:
1751             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1752             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1753             break;
1754         case Value::eValueTypeLoadAddress:
1755             clang_expr_variable_sp->m_live_sp = live_valobj_sp;
1756             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
1757             break;
1758         }
1759     }
1760     else
1761     {
1762         // Make sure we aren't just trying to see the value of a persistent
1763         // variable (something like "$0")
1764         lldb::ClangExpressionVariableSP persistent_var_sp;
1765         // Only check for persistent variables the expression starts with a '$'
1766         if (expr_cstr[0] == '$')
1767             persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1768 
1769         if (persistent_var_sp)
1770         {
1771             result_valobj_sp = persistent_var_sp->GetValueObject ();
1772             execution_results = eExecutionCompleted;
1773         }
1774         else
1775         {
1776             const char *prefix = GetExpressionPrefixContentsAsCString();
1777 
1778             execution_results = ClangUserExpression::Evaluate (exe_ctx,
1779                                                                execution_policy,
1780                                                                lldb::eLanguageTypeUnknown,
1781                                                                coerce_to_id ? ClangUserExpression::eResultTypeId : ClangUserExpression::eResultTypeAny,
1782                                                                unwind_on_error,
1783                                                                expr_cstr,
1784                                                                prefix,
1785                                                                result_valobj_sp,
1786                                                                single_thread_timeout_usec);
1787         }
1788     }
1789 
1790     m_suppress_stop_hooks = old_suppress_value;
1791 
1792     return execution_results;
1793 }
1794 
1795 lldb::addr_t
1796 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1797 {
1798     addr_t code_addr = load_addr;
1799     switch (m_arch.GetMachine())
1800     {
1801     case llvm::Triple::arm:
1802     case llvm::Triple::thumb:
1803         switch (addr_class)
1804         {
1805         case eAddressClassData:
1806         case eAddressClassDebug:
1807             return LLDB_INVALID_ADDRESS;
1808 
1809         case eAddressClassUnknown:
1810         case eAddressClassInvalid:
1811         case eAddressClassCode:
1812         case eAddressClassCodeAlternateISA:
1813         case eAddressClassRuntime:
1814             // Check if bit zero it no set?
1815             if ((code_addr & 1ull) == 0)
1816             {
1817                 // Bit zero isn't set, check if the address is a multiple of 2?
1818                 if (code_addr & 2ull)
1819                 {
1820                     // The address is a multiple of 2 so it must be thumb, set bit zero
1821                     code_addr |= 1ull;
1822                 }
1823                 else if (addr_class == eAddressClassCodeAlternateISA)
1824                 {
1825                     // We checked the address and the address claims to be the alternate ISA
1826                     // which means thumb, so set bit zero.
1827                     code_addr |= 1ull;
1828                 }
1829             }
1830             break;
1831         }
1832         break;
1833 
1834     default:
1835         break;
1836     }
1837     return code_addr;
1838 }
1839 
1840 lldb::addr_t
1841 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1842 {
1843     addr_t opcode_addr = load_addr;
1844     switch (m_arch.GetMachine())
1845     {
1846     case llvm::Triple::arm:
1847     case llvm::Triple::thumb:
1848         switch (addr_class)
1849         {
1850         case eAddressClassData:
1851         case eAddressClassDebug:
1852             return LLDB_INVALID_ADDRESS;
1853 
1854         case eAddressClassInvalid:
1855         case eAddressClassUnknown:
1856         case eAddressClassCode:
1857         case eAddressClassCodeAlternateISA:
1858         case eAddressClassRuntime:
1859             opcode_addr &= ~(1ull);
1860             break;
1861         }
1862         break;
1863 
1864     default:
1865         break;
1866     }
1867     return opcode_addr;
1868 }
1869 
1870 lldb::user_id_t
1871 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1872 {
1873     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1874     new_hook_sp.reset (new StopHook(shared_from_this(), new_uid));
1875     m_stop_hooks[new_uid] = new_hook_sp;
1876     return new_uid;
1877 }
1878 
1879 bool
1880 Target::RemoveStopHookByID (lldb::user_id_t user_id)
1881 {
1882     size_t num_removed;
1883     num_removed = m_stop_hooks.erase (user_id);
1884     if (num_removed == 0)
1885         return false;
1886     else
1887         return true;
1888 }
1889 
1890 void
1891 Target::RemoveAllStopHooks ()
1892 {
1893     m_stop_hooks.clear();
1894 }
1895 
1896 Target::StopHookSP
1897 Target::GetStopHookByID (lldb::user_id_t user_id)
1898 {
1899     StopHookSP found_hook;
1900 
1901     StopHookCollection::iterator specified_hook_iter;
1902     specified_hook_iter = m_stop_hooks.find (user_id);
1903     if (specified_hook_iter != m_stop_hooks.end())
1904         found_hook = (*specified_hook_iter).second;
1905     return found_hook;
1906 }
1907 
1908 bool
1909 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1910 {
1911     StopHookCollection::iterator specified_hook_iter;
1912     specified_hook_iter = m_stop_hooks.find (user_id);
1913     if (specified_hook_iter == m_stop_hooks.end())
1914         return false;
1915 
1916     (*specified_hook_iter).second->SetIsActive (active_state);
1917     return true;
1918 }
1919 
1920 void
1921 Target::SetAllStopHooksActiveState (bool active_state)
1922 {
1923     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1924     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1925     {
1926         (*pos).second->SetIsActive (active_state);
1927     }
1928 }
1929 
1930 void
1931 Target::RunStopHooks ()
1932 {
1933     if (m_suppress_stop_hooks)
1934         return;
1935 
1936     if (!m_process_sp)
1937         return;
1938 
1939     // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
1940     // since in that case we do not want to run the stop-hooks
1941     if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
1942         return;
1943 
1944     if (m_stop_hooks.empty())
1945         return;
1946 
1947     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1948 
1949     // If there aren't any active stop hooks, don't bother either:
1950     bool any_active_hooks = false;
1951     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1952     {
1953         if ((*pos).second->IsActive())
1954         {
1955             any_active_hooks = true;
1956             break;
1957         }
1958     }
1959     if (!any_active_hooks)
1960         return;
1961 
1962     CommandReturnObject result;
1963 
1964     std::vector<ExecutionContext> exc_ctx_with_reasons;
1965     std::vector<SymbolContext> sym_ctx_with_reasons;
1966 
1967     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1968     size_t num_threads = cur_threadlist.GetSize();
1969     for (size_t i = 0; i < num_threads; i++)
1970     {
1971         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1972         if (cur_thread_sp->ThreadStoppedForAReason())
1973         {
1974             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1975             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1976             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1977         }
1978     }
1979 
1980     // If no threads stopped for a reason, don't run the stop-hooks.
1981     size_t num_exe_ctx = exc_ctx_with_reasons.size();
1982     if (num_exe_ctx == 0)
1983         return;
1984 
1985     result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
1986     result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
1987 
1988     bool keep_going = true;
1989     bool hooks_ran = false;
1990     bool print_hook_header;
1991     bool print_thread_header;
1992 
1993     if (num_exe_ctx == 1)
1994         print_thread_header = false;
1995     else
1996         print_thread_header = true;
1997 
1998     if (m_stop_hooks.size() == 1)
1999         print_hook_header = false;
2000     else
2001         print_hook_header = true;
2002 
2003     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
2004     {
2005         // result.Clear();
2006         StopHookSP cur_hook_sp = (*pos).second;
2007         if (!cur_hook_sp->IsActive())
2008             continue;
2009 
2010         bool any_thread_matched = false;
2011         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2012         {
2013             if ((cur_hook_sp->GetSpecifier () == NULL
2014                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2015                 && (cur_hook_sp->GetThreadSpecifier() == NULL
2016                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2017             {
2018                 if (!hooks_ran)
2019                 {
2020                     hooks_ran = true;
2021                 }
2022                 if (print_hook_header && !any_thread_matched)
2023                 {
2024                     const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2025                                        cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2026                                        NULL);
2027                     if (cmd)
2028                         result.AppendMessageWithFormat("\n- Hook %llu (%s)\n", cur_hook_sp->GetID(), cmd);
2029                     else
2030                         result.AppendMessageWithFormat("\n- Hook %llu\n", cur_hook_sp->GetID());
2031                     any_thread_matched = true;
2032                 }
2033 
2034                 if (print_thread_header)
2035                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2036 
2037                 bool stop_on_continue = true;
2038                 bool stop_on_error = true;
2039                 bool echo_commands = false;
2040                 bool print_results = true;
2041                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2042                                                                       &exc_ctx_with_reasons[i],
2043                                                                       stop_on_continue,
2044                                                                       stop_on_error,
2045                                                                       echo_commands,
2046                                                                       print_results,
2047                                                                       eLazyBoolNo,
2048                                                                       result);
2049 
2050                 // If the command started the target going again, we should bag out of
2051                 // running the stop hooks.
2052                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2053                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2054                 {
2055                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %llu set the program running.", cur_hook_sp->GetID());
2056                     keep_going = false;
2057                 }
2058             }
2059         }
2060     }
2061 
2062     result.GetImmediateOutputStream()->Flush();
2063     result.GetImmediateErrorStream()->Flush();
2064 }
2065 
2066 
2067 //--------------------------------------------------------------
2068 // class Target::StopHook
2069 //--------------------------------------------------------------
2070 
2071 
2072 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2073         UserID (uid),
2074         m_target_sp (target_sp),
2075         m_commands (),
2076         m_specifier_sp (),
2077         m_thread_spec_ap(NULL),
2078         m_active (true)
2079 {
2080 }
2081 
2082 Target::StopHook::StopHook (const StopHook &rhs) :
2083         UserID (rhs.GetID()),
2084         m_target_sp (rhs.m_target_sp),
2085         m_commands (rhs.m_commands),
2086         m_specifier_sp (rhs.m_specifier_sp),
2087         m_thread_spec_ap (NULL),
2088         m_active (rhs.m_active)
2089 {
2090     if (rhs.m_thread_spec_ap.get() != NULL)
2091         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2092 }
2093 
2094 
2095 Target::StopHook::~StopHook ()
2096 {
2097 }
2098 
2099 void
2100 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2101 {
2102     m_thread_spec_ap.reset (specifier);
2103 }
2104 
2105 
2106 void
2107 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2108 {
2109     int indent_level = s->GetIndentLevel();
2110 
2111     s->SetIndentLevel(indent_level + 2);
2112 
2113     s->Printf ("Hook: %llu\n", GetID());
2114     if (m_active)
2115         s->Indent ("State: enabled\n");
2116     else
2117         s->Indent ("State: disabled\n");
2118 
2119     if (m_specifier_sp)
2120     {
2121         s->Indent();
2122         s->PutCString ("Specifier:\n");
2123         s->SetIndentLevel (indent_level + 4);
2124         m_specifier_sp->GetDescription (s, level);
2125         s->SetIndentLevel (indent_level + 2);
2126     }
2127 
2128     if (m_thread_spec_ap.get() != NULL)
2129     {
2130         StreamString tmp;
2131         s->Indent("Thread:\n");
2132         m_thread_spec_ap->GetDescription (&tmp, level);
2133         s->SetIndentLevel (indent_level + 4);
2134         s->Indent (tmp.GetData());
2135         s->PutCString ("\n");
2136         s->SetIndentLevel (indent_level + 2);
2137     }
2138 
2139     s->Indent ("Commands: \n");
2140     s->SetIndentLevel (indent_level + 4);
2141     uint32_t num_commands = m_commands.GetSize();
2142     for (uint32_t i = 0; i < num_commands; i++)
2143     {
2144         s->Indent(m_commands.GetStringAtIndex(i));
2145         s->PutCString ("\n");
2146     }
2147     s->SetIndentLevel (indent_level);
2148 }
2149 
2150 
2151 //--------------------------------------------------------------
2152 // class Target::SettingsController
2153 //--------------------------------------------------------------
2154 
2155 Target::SettingsController::SettingsController () :
2156     UserSettingsController ("target", Debugger::GetSettingsController()),
2157     m_default_architecture ()
2158 {
2159 }
2160 
2161 Target::SettingsController::~SettingsController ()
2162 {
2163 }
2164 
2165 lldb::InstanceSettingsSP
2166 Target::SettingsController::CreateInstanceSettings (const char *instance_name)
2167 {
2168     lldb::InstanceSettingsSP new_settings_sp (new TargetInstanceSettings (GetSettingsController(),
2169                                                                           false,
2170                                                                           instance_name));
2171     return new_settings_sp;
2172 }
2173 
2174 
2175 #define TSC_DEFAULT_ARCH        "default-arch"
2176 #define TSC_EXPR_PREFIX         "expr-prefix"
2177 #define TSC_PREFER_DYNAMIC      "prefer-dynamic-value"
2178 #define TSC_ENABLE_SYNTHETIC    "enable-synthetic-value"
2179 #define TSC_SKIP_PROLOGUE       "skip-prologue"
2180 #define TSC_SOURCE_MAP          "source-map"
2181 #define TSC_EXE_SEARCH_PATHS    "exec-search-paths"
2182 #define TSC_MAX_CHILDREN        "max-children-count"
2183 #define TSC_MAX_STRLENSUMMARY   "max-string-summary-length"
2184 #define TSC_PLATFORM_AVOID      "breakpoints-use-platform-avoid-list"
2185 #define TSC_RUN_ARGS            "run-args"
2186 #define TSC_ENV_VARS            "env-vars"
2187 #define TSC_INHERIT_ENV         "inherit-env"
2188 #define TSC_STDIN_PATH          "input-path"
2189 #define TSC_STDOUT_PATH         "output-path"
2190 #define TSC_STDERR_PATH         "error-path"
2191 #define TSC_DISABLE_ASLR        "disable-aslr"
2192 #define TSC_DISABLE_STDIO       "disable-stdio"
2193 
2194 
2195 static const ConstString &
2196 GetSettingNameForDefaultArch ()
2197 {
2198     static ConstString g_const_string (TSC_DEFAULT_ARCH);
2199     return g_const_string;
2200 }
2201 
2202 static const ConstString &
2203 GetSettingNameForExpressionPrefix ()
2204 {
2205     static ConstString g_const_string (TSC_EXPR_PREFIX);
2206     return g_const_string;
2207 }
2208 
2209 static const ConstString &
2210 GetSettingNameForPreferDynamicValue ()
2211 {
2212     static ConstString g_const_string (TSC_PREFER_DYNAMIC);
2213     return g_const_string;
2214 }
2215 
2216 static const ConstString &
2217 GetSettingNameForEnableSyntheticValue ()
2218 {
2219     static ConstString g_const_string (TSC_ENABLE_SYNTHETIC);
2220     return g_const_string;
2221 }
2222 
2223 static const ConstString &
2224 GetSettingNameForSourcePathMap ()
2225 {
2226     static ConstString g_const_string (TSC_SOURCE_MAP);
2227     return g_const_string;
2228 }
2229 
2230 static const ConstString &
2231 GetSettingNameForExecutableSearchPaths ()
2232 {
2233     static ConstString g_const_string (TSC_EXE_SEARCH_PATHS);
2234     return g_const_string;
2235 }
2236 
2237 static const ConstString &
2238 GetSettingNameForSkipPrologue ()
2239 {
2240     static ConstString g_const_string (TSC_SKIP_PROLOGUE);
2241     return g_const_string;
2242 }
2243 
2244 static const ConstString &
2245 GetSettingNameForMaxChildren ()
2246 {
2247     static ConstString g_const_string (TSC_MAX_CHILDREN);
2248     return g_const_string;
2249 }
2250 
2251 static const ConstString &
2252 GetSettingNameForMaxStringSummaryLength ()
2253 {
2254     static ConstString g_const_string (TSC_MAX_STRLENSUMMARY);
2255     return g_const_string;
2256 }
2257 
2258 static const ConstString &
2259 GetSettingNameForPlatformAvoid ()
2260 {
2261     static ConstString g_const_string (TSC_PLATFORM_AVOID);
2262     return g_const_string;
2263 }
2264 
2265 const ConstString &
2266 GetSettingNameForRunArgs ()
2267 {
2268     static ConstString g_const_string (TSC_RUN_ARGS);
2269     return g_const_string;
2270 }
2271 
2272 const ConstString &
2273 GetSettingNameForEnvVars ()
2274 {
2275     static ConstString g_const_string (TSC_ENV_VARS);
2276     return g_const_string;
2277 }
2278 
2279 const ConstString &
2280 GetSettingNameForInheritHostEnv ()
2281 {
2282     static ConstString g_const_string (TSC_INHERIT_ENV);
2283     return g_const_string;
2284 }
2285 
2286 const ConstString &
2287 GetSettingNameForInputPath ()
2288 {
2289     static ConstString g_const_string (TSC_STDIN_PATH);
2290     return g_const_string;
2291 }
2292 
2293 const ConstString &
2294 GetSettingNameForOutputPath ()
2295 {
2296     static ConstString g_const_string (TSC_STDOUT_PATH);
2297     return g_const_string;
2298 }
2299 
2300 const ConstString &
2301 GetSettingNameForErrorPath ()
2302 {
2303     static ConstString g_const_string (TSC_STDERR_PATH);
2304     return g_const_string;
2305 }
2306 
2307 const ConstString &
2308 GetSettingNameForDisableASLR ()
2309 {
2310     static ConstString g_const_string (TSC_DISABLE_ASLR);
2311     return g_const_string;
2312 }
2313 
2314 const ConstString &
2315 GetSettingNameForDisableSTDIO ()
2316 {
2317     static ConstString g_const_string (TSC_DISABLE_STDIO);
2318     return g_const_string;
2319 }
2320 
2321 bool
2322 Target::SettingsController::SetGlobalVariable (const ConstString &var_name,
2323                                                const char *index_value,
2324                                                const char *value,
2325                                                const SettingEntry &entry,
2326                                                const VarSetOperationType op,
2327                                                Error&err)
2328 {
2329     if (var_name == GetSettingNameForDefaultArch())
2330     {
2331         m_default_architecture.SetTriple (value);
2332         if (!m_default_architecture.IsValid())
2333             err.SetErrorStringWithFormat ("'%s' is not a valid architecture or triple.", value);
2334     }
2335     return true;
2336 }
2337 
2338 
2339 bool
2340 Target::SettingsController::GetGlobalVariable (const ConstString &var_name,
2341                                                StringList &value,
2342                                                Error &err)
2343 {
2344     if (var_name == GetSettingNameForDefaultArch())
2345     {
2346         // If the arch is invalid (the default), don't show a string for it
2347         if (m_default_architecture.IsValid())
2348             value.AppendString (m_default_architecture.GetArchitectureName());
2349         return true;
2350     }
2351     else
2352         err.SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2353 
2354     return false;
2355 }
2356 
2357 //--------------------------------------------------------------
2358 // class TargetInstanceSettings
2359 //--------------------------------------------------------------
2360 
2361 TargetInstanceSettings::TargetInstanceSettings
2362 (
2363     const lldb::UserSettingsControllerSP &owner_sp,
2364     bool live_instance,
2365     const char *name
2366 ) :
2367     InstanceSettings (owner_sp, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
2368     m_expr_prefix_file (),
2369     m_expr_prefix_contents (),
2370     m_prefer_dynamic_value (2),
2371     m_enable_synthetic_value(true, true),
2372     m_skip_prologue (true, true),
2373     m_source_map (NULL, NULL),
2374     m_exe_search_paths (),
2375     m_max_children_display(256),
2376     m_max_strlen_length(1024),
2377     m_breakpoints_use_platform_avoid (true, true),
2378     m_run_args (),
2379     m_env_vars (),
2380     m_input_path (),
2381     m_output_path (),
2382     m_error_path (),
2383     m_disable_aslr (true),
2384     m_disable_stdio (false),
2385     m_inherit_host_env (true),
2386     m_got_host_env (false)
2387 {
2388     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2389     // until the vtables for TargetInstanceSettings are properly set up, i.e. AFTER all the initializers.
2390     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
2391     // This is true for CreateInstanceName() too.
2392 
2393     if (GetInstanceName () == InstanceSettings::InvalidName())
2394     {
2395         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2396         owner_sp->RegisterInstanceSettings (this);
2397     }
2398 
2399     if (live_instance)
2400     {
2401         const lldb::InstanceSettingsSP &pending_settings = owner_sp->FindPendingSettings (m_instance_name);
2402         CopyInstanceSettings (pending_settings,false);
2403     }
2404 }
2405 
2406 TargetInstanceSettings::TargetInstanceSettings (const TargetInstanceSettings &rhs) :
2407     InstanceSettings (Target::GetSettingsController(), CreateInstanceName().AsCString()),
2408     m_expr_prefix_file (rhs.m_expr_prefix_file),
2409     m_expr_prefix_contents (rhs.m_expr_prefix_contents),
2410     m_prefer_dynamic_value (rhs.m_prefer_dynamic_value),
2411     m_enable_synthetic_value(rhs.m_enable_synthetic_value),
2412     m_skip_prologue (rhs.m_skip_prologue),
2413     m_source_map (rhs.m_source_map),
2414     m_exe_search_paths (rhs.m_exe_search_paths),
2415     m_max_children_display (rhs.m_max_children_display),
2416     m_max_strlen_length (rhs.m_max_strlen_length),
2417     m_breakpoints_use_platform_avoid (rhs.m_breakpoints_use_platform_avoid),
2418     m_run_args (rhs.m_run_args),
2419     m_env_vars (rhs.m_env_vars),
2420     m_input_path (rhs.m_input_path),
2421     m_output_path (rhs.m_output_path),
2422     m_error_path (rhs.m_error_path),
2423     m_disable_aslr (rhs.m_disable_aslr),
2424     m_disable_stdio (rhs.m_disable_stdio),
2425     m_inherit_host_env (rhs.m_inherit_host_env)
2426 {
2427     if (m_instance_name != InstanceSettings::GetDefaultName())
2428     {
2429         UserSettingsControllerSP owner_sp (m_owner_wp.lock());
2430         if (owner_sp)
2431             CopyInstanceSettings (owner_sp->FindPendingSettings (m_instance_name),false);
2432     }
2433 }
2434 
2435 TargetInstanceSettings::~TargetInstanceSettings ()
2436 {
2437 }
2438 
2439 TargetInstanceSettings&
2440 TargetInstanceSettings::operator= (const TargetInstanceSettings &rhs)
2441 {
2442     if (this != &rhs)
2443     {
2444         m_expr_prefix_file = rhs.m_expr_prefix_file;
2445         m_expr_prefix_contents = rhs.m_expr_prefix_contents;
2446         m_prefer_dynamic_value = rhs.m_prefer_dynamic_value;
2447         m_enable_synthetic_value = rhs.m_enable_synthetic_value;
2448         m_skip_prologue = rhs.m_skip_prologue;
2449         m_source_map = rhs.m_source_map;
2450         m_exe_search_paths = rhs.m_exe_search_paths;
2451         m_max_children_display = rhs.m_max_children_display;
2452         m_max_strlen_length = rhs.m_max_strlen_length;
2453         m_breakpoints_use_platform_avoid = rhs.m_breakpoints_use_platform_avoid;
2454         m_run_args = rhs.m_run_args;
2455         m_env_vars = rhs.m_env_vars;
2456         m_input_path = rhs.m_input_path;
2457         m_output_path = rhs.m_output_path;
2458         m_error_path = rhs.m_error_path;
2459         m_disable_aslr = rhs.m_disable_aslr;
2460         m_disable_stdio = rhs.m_disable_stdio;
2461         m_inherit_host_env = rhs.m_inherit_host_env;
2462     }
2463 
2464     return *this;
2465 }
2466 
2467 void
2468 TargetInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2469                                                         const char *index_value,
2470                                                         const char *value,
2471                                                         const ConstString &instance_name,
2472                                                         const SettingEntry &entry,
2473                                                         VarSetOperationType op,
2474                                                         Error &err,
2475                                                         bool pending)
2476 {
2477     if (var_name == GetSettingNameForExpressionPrefix ())
2478     {
2479         err = UserSettingsController::UpdateFileSpecOptionValue (value, op, m_expr_prefix_file);
2480         if (err.Success())
2481         {
2482             switch (op)
2483             {
2484             default:
2485                 break;
2486             case eVarSetOperationAssign:
2487             case eVarSetOperationAppend:
2488                 {
2489                     m_expr_prefix_contents.clear();
2490 
2491                     if (!m_expr_prefix_file.GetCurrentValue().Exists())
2492                     {
2493                         err.SetErrorToGenericError ();
2494                         err.SetErrorStringWithFormat ("%s does not exist", value);
2495                         return;
2496                     }
2497 
2498                     DataBufferSP file_data_sp (m_expr_prefix_file.GetCurrentValue().ReadFileContents(0, SIZE_MAX, &err));
2499 
2500                     if (err.Success())
2501                     {
2502                         if (file_data_sp && file_data_sp->GetByteSize() > 0)
2503                         {
2504                             m_expr_prefix_contents.assign((const char*)file_data_sp->GetBytes(), file_data_sp->GetByteSize());
2505                         }
2506                         else
2507                         {
2508                             err.SetErrorStringWithFormat ("couldn't read data from '%s'", value);
2509                         }
2510                     }
2511                 }
2512                 break;
2513             case eVarSetOperationClear:
2514                 m_expr_prefix_contents.clear();
2515             }
2516         }
2517     }
2518     else if (var_name == GetSettingNameForPreferDynamicValue())
2519     {
2520         int new_value;
2521         UserSettingsController::UpdateEnumVariable (g_dynamic_value_types, &new_value, value, err);
2522         if (err.Success())
2523             m_prefer_dynamic_value = new_value;
2524     }
2525     else if (var_name == GetSettingNameForEnableSyntheticValue())
2526     {
2527         bool ok;
2528         bool new_value = Args::StringToBoolean(value, true, &ok);
2529         if (ok)
2530             m_enable_synthetic_value.SetCurrentValue(new_value);
2531     }
2532     else if (var_name == GetSettingNameForSkipPrologue())
2533     {
2534         err = UserSettingsController::UpdateBooleanOptionValue (value, op, m_skip_prologue);
2535     }
2536     else if (var_name == GetSettingNameForMaxChildren())
2537     {
2538         bool ok;
2539         uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok);
2540         if (ok)
2541             m_max_children_display = new_value;
2542     }
2543     else if (var_name == GetSettingNameForMaxStringSummaryLength())
2544     {
2545         bool ok;
2546         uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok);
2547         if (ok)
2548             m_max_strlen_length = new_value;
2549     }
2550     else if (var_name == GetSettingNameForExecutableSearchPaths())
2551     {
2552         switch (op)
2553         {
2554             case eVarSetOperationReplace:
2555             case eVarSetOperationInsertBefore:
2556             case eVarSetOperationInsertAfter:
2557             case eVarSetOperationRemove:
2558             default:
2559                 break;
2560             case eVarSetOperationAssign:
2561                 m_exe_search_paths.Clear();
2562                 // Fall through to append....
2563             case eVarSetOperationAppend:
2564             {
2565                 Args args(value);
2566                 const uint32_t argc = args.GetArgumentCount();
2567                 if (argc > 0)
2568                 {
2569                     const char *exe_search_path_dir;
2570                     for (uint32_t idx = 0; (exe_search_path_dir = args.GetArgumentAtIndex(idx)) != NULL; ++idx)
2571                     {
2572                         FileSpec file_spec;
2573                         file_spec.GetDirectory().SetCString(exe_search_path_dir);
2574                         FileSpec::FileType file_type = file_spec.GetFileType();
2575                         if (file_type == FileSpec::eFileTypeDirectory || file_type == FileSpec::eFileTypeInvalid)
2576                         {
2577                             m_exe_search_paths.Append(file_spec);
2578                         }
2579                         else
2580                         {
2581                             err.SetErrorStringWithFormat("executable search path '%s' exists, but it does not resolve to a directory", exe_search_path_dir);
2582                         }
2583                     }
2584                 }
2585             }
2586                 break;
2587 
2588             case eVarSetOperationClear:
2589                 m_exe_search_paths.Clear();
2590                 break;
2591         }
2592     }
2593     else if (var_name == GetSettingNameForSourcePathMap ())
2594     {
2595         switch (op)
2596         {
2597             case eVarSetOperationReplace:
2598             case eVarSetOperationInsertBefore:
2599             case eVarSetOperationInsertAfter:
2600             case eVarSetOperationRemove:
2601             default:
2602                 break;
2603             case eVarSetOperationAssign:
2604                 m_source_map.Clear(true);
2605                 // Fall through to append....
2606             case eVarSetOperationAppend:
2607                 {
2608                     Args args(value);
2609                     const uint32_t argc = args.GetArgumentCount();
2610                     if (argc & 1 || argc == 0)
2611                     {
2612                         err.SetErrorStringWithFormat ("an even number of paths must be supplied to to the source-map setting: %u arguments given", argc);
2613                     }
2614                     else
2615                     {
2616                         char resolved_new_path[PATH_MAX];
2617                         FileSpec file_spec;
2618                         const char *old_path;
2619                         for (uint32_t idx = 0; (old_path = args.GetArgumentAtIndex(idx)) != NULL; idx += 2)
2620                         {
2621                             const char *new_path = args.GetArgumentAtIndex(idx+1);
2622                             assert (new_path); // We have an even number of paths, this shouldn't happen!
2623 
2624                             file_spec.SetFile(new_path, true);
2625                             if (file_spec.Exists())
2626                             {
2627                                 if (file_spec.GetPath (resolved_new_path, sizeof(resolved_new_path)) >= sizeof(resolved_new_path))
2628                                 {
2629                                     err.SetErrorStringWithFormat("new path '%s' is too long", new_path);
2630                                     return;
2631                                 }
2632                             }
2633                             else
2634                             {
2635                                 err.SetErrorStringWithFormat("new path '%s' doesn't exist", new_path);
2636                                 return;
2637                             }
2638                             m_source_map.Append(ConstString (old_path), ConstString (resolved_new_path), true);
2639                         }
2640                     }
2641                 }
2642                 break;
2643 
2644             case eVarSetOperationClear:
2645                 m_source_map.Clear(true);
2646                 break;
2647         }
2648     }
2649     else if (var_name == GetSettingNameForPlatformAvoid ())
2650     {
2651         err = UserSettingsController::UpdateBooleanOptionValue (value, op, m_breakpoints_use_platform_avoid);
2652     }
2653     else if (var_name == GetSettingNameForRunArgs())
2654     {
2655         UserSettingsController::UpdateStringArrayVariable (op, index_value, m_run_args, value, err);
2656     }
2657     else if (var_name == GetSettingNameForEnvVars())
2658     {
2659         // This is nice for local debugging, but it is isn't correct for
2660         // remote debugging. We need to stop process.env-vars from being
2661         // populated with the host environment and add this as a launch option
2662         // and get the correct environment from the Target's platform.
2663         // GetHostEnvironmentIfNeeded ();
2664         UserSettingsController::UpdateDictionaryVariable (op, index_value, m_env_vars, value, err);
2665     }
2666     else if (var_name == GetSettingNameForInputPath())
2667     {
2668         UserSettingsController::UpdateStringVariable (op, m_input_path, value, err);
2669     }
2670     else if (var_name == GetSettingNameForOutputPath())
2671     {
2672         UserSettingsController::UpdateStringVariable (op, m_output_path, value, err);
2673     }
2674     else if (var_name == GetSettingNameForErrorPath())
2675     {
2676         UserSettingsController::UpdateStringVariable (op, m_error_path, value, err);
2677     }
2678     else if (var_name == GetSettingNameForDisableASLR())
2679     {
2680         UserSettingsController::UpdateBooleanVariable (op, m_disable_aslr, value, true, err);
2681     }
2682     else if (var_name == GetSettingNameForDisableSTDIO ())
2683     {
2684         UserSettingsController::UpdateBooleanVariable (op, m_disable_stdio, value, false, err);
2685     }
2686 }
2687 
2688 void
2689 TargetInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, bool pending)
2690 {
2691     TargetInstanceSettings *new_settings_ptr = static_cast <TargetInstanceSettings *> (new_settings.get());
2692 
2693     if (!new_settings_ptr)
2694         return;
2695 
2696     *this = *new_settings_ptr;
2697 }
2698 
2699 bool
2700 TargetInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2701                                                   const ConstString &var_name,
2702                                                   StringList &value,
2703                                                   Error *err)
2704 {
2705     if (var_name == GetSettingNameForExpressionPrefix ())
2706     {
2707         char path[PATH_MAX];
2708         const size_t path_len = m_expr_prefix_file.GetCurrentValue().GetPath (path, sizeof(path));
2709         if (path_len > 0)
2710             value.AppendString (path, path_len);
2711     }
2712     else if (var_name == GetSettingNameForPreferDynamicValue())
2713     {
2714         value.AppendString (g_dynamic_value_types[m_prefer_dynamic_value].string_value);
2715     }
2716     else if (var_name == GetSettingNameForEnableSyntheticValue())
2717     {
2718         if (m_skip_prologue)
2719             value.AppendString ("true");
2720         else
2721             value.AppendString ("false");
2722     }
2723     else if (var_name == GetSettingNameForSkipPrologue())
2724     {
2725         if (m_skip_prologue)
2726             value.AppendString ("true");
2727         else
2728             value.AppendString ("false");
2729     }
2730     else if (var_name == GetSettingNameForExecutableSearchPaths())
2731     {
2732         if (m_exe_search_paths.GetSize())
2733         {
2734             for (size_t i = 0, n = m_exe_search_paths.GetSize(); i < n; ++i)
2735             {
2736                 value.AppendString(m_exe_search_paths.GetFileSpecAtIndex (i).GetDirectory().AsCString());
2737             }
2738         }
2739     }
2740     else if (var_name == GetSettingNameForSourcePathMap ())
2741     {
2742         if (m_source_map.GetSize())
2743         {
2744             size_t i;
2745             for (i = 0; i < m_source_map.GetSize(); ++i) {
2746                 StreamString sstr;
2747                 m_source_map.Dump(&sstr, i);
2748                 value.AppendString(sstr.GetData());
2749             }
2750         }
2751     }
2752     else if (var_name == GetSettingNameForMaxChildren())
2753     {
2754         StreamString count_str;
2755         count_str.Printf ("%d", m_max_children_display);
2756         value.AppendString (count_str.GetData());
2757     }
2758     else if (var_name == GetSettingNameForMaxStringSummaryLength())
2759     {
2760         StreamString count_str;
2761         count_str.Printf ("%d", m_max_strlen_length);
2762         value.AppendString (count_str.GetData());
2763     }
2764     else if (var_name == GetSettingNameForPlatformAvoid())
2765     {
2766         if (m_breakpoints_use_platform_avoid)
2767             value.AppendString ("true");
2768         else
2769             value.AppendString ("false");
2770     }
2771     else if (var_name == GetSettingNameForRunArgs())
2772     {
2773         if (m_run_args.GetArgumentCount() > 0)
2774         {
2775             for (int i = 0; i < m_run_args.GetArgumentCount(); ++i)
2776                 value.AppendString (m_run_args.GetArgumentAtIndex (i));
2777         }
2778     }
2779     else if (var_name == GetSettingNameForEnvVars())
2780     {
2781         GetHostEnvironmentIfNeeded ();
2782 
2783         if (m_env_vars.size() > 0)
2784         {
2785             std::map<std::string, std::string>::iterator pos;
2786             for (pos = m_env_vars.begin(); pos != m_env_vars.end(); ++pos)
2787             {
2788                 StreamString value_str;
2789                 value_str.Printf ("%s=%s", pos->first.c_str(), pos->second.c_str());
2790                 value.AppendString (value_str.GetData());
2791             }
2792         }
2793     }
2794     else if (var_name == GetSettingNameForInputPath())
2795     {
2796         value.AppendString (m_input_path.c_str());
2797     }
2798     else if (var_name == GetSettingNameForOutputPath())
2799     {
2800         value.AppendString (m_output_path.c_str());
2801     }
2802     else if (var_name == GetSettingNameForErrorPath())
2803     {
2804         value.AppendString (m_error_path.c_str());
2805     }
2806     else if (var_name == GetSettingNameForInheritHostEnv())
2807     {
2808         if (m_inherit_host_env)
2809             value.AppendString ("true");
2810         else
2811             value.AppendString ("false");
2812     }
2813     else if (var_name == GetSettingNameForDisableASLR())
2814     {
2815         if (m_disable_aslr)
2816             value.AppendString ("true");
2817         else
2818             value.AppendString ("false");
2819     }
2820     else if (var_name == GetSettingNameForDisableSTDIO())
2821     {
2822         if (m_disable_stdio)
2823             value.AppendString ("true");
2824         else
2825             value.AppendString ("false");
2826     }
2827     else
2828     {
2829         if (err)
2830             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2831         return false;
2832     }
2833     return true;
2834 }
2835 
2836 void
2837 Target::TargetInstanceSettings::GetHostEnvironmentIfNeeded ()
2838 {
2839     if (m_inherit_host_env && !m_got_host_env)
2840     {
2841         m_got_host_env = true;
2842         StringList host_env;
2843         const size_t host_env_count = Host::GetEnvironment (host_env);
2844         for (size_t idx=0; idx<host_env_count; idx++)
2845         {
2846             const char *env_entry = host_env.GetStringAtIndex (idx);
2847             if (env_entry)
2848             {
2849                 const char *equal_pos = ::strchr(env_entry, '=');
2850                 if (equal_pos)
2851                 {
2852                     std::string key (env_entry, equal_pos - env_entry);
2853                     std::string value (equal_pos + 1);
2854                     if (m_env_vars.find (key) == m_env_vars.end())
2855                         m_env_vars[key] = value;
2856                 }
2857             }
2858         }
2859     }
2860 }
2861 
2862 
2863 size_t
2864 Target::TargetInstanceSettings::GetEnvironmentAsArgs (Args &env)
2865 {
2866     GetHostEnvironmentIfNeeded ();
2867 
2868     dictionary::const_iterator pos, end = m_env_vars.end();
2869     for (pos = m_env_vars.begin(); pos != end; ++pos)
2870     {
2871         std::string env_var_equal_value (pos->first);
2872         env_var_equal_value.append(1, '=');
2873         env_var_equal_value.append (pos->second);
2874         env.AppendArgument (env_var_equal_value.c_str());
2875     }
2876     return env.GetArgumentCount();
2877 }
2878 
2879 
2880 const ConstString
2881 TargetInstanceSettings::CreateInstanceName ()
2882 {
2883     StreamString sstr;
2884     static int instance_count = 1;
2885 
2886     sstr.Printf ("target_%d", instance_count);
2887     ++instance_count;
2888 
2889     const ConstString ret_val (sstr.GetData());
2890     return ret_val;
2891 }
2892 
2893 //--------------------------------------------------
2894 // Target::SettingsController Variable Tables
2895 //--------------------------------------------------
2896 OptionEnumValueElement
2897 TargetInstanceSettings::g_dynamic_value_types[] =
2898 {
2899 { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2900 { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2901 { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2902 { 0, NULL, NULL }
2903 };
2904 
2905 SettingEntry
2906 Target::SettingsController::global_settings_table[] =
2907 {
2908     // var-name           var-type           default      enum  init'd hidden help-text
2909     // =================  ================== ===========  ====  ====== ====== =========================================================================
2910     { TSC_DEFAULT_ARCH  , eSetVarTypeString , NULL      , NULL, false, false, "Default architecture to choose, when there's a choice." },
2911     { NULL              , eSetVarTypeNone   , NULL      , NULL, false, false, NULL }
2912 };
2913 
2914 SettingEntry
2915 Target::SettingsController::instance_settings_table[] =
2916 {
2917     // var-name             var-type            default         enum                    init'd hidden help-text
2918     // =================    ==================  =============== ======================= ====== ====== =========================================================================
2919     { TSC_EXPR_PREFIX       , eSetVarTypeString , NULL          , NULL,                  false, false, "Path to a file containing expressions to be prepended to all expressions." },
2920     { TSC_PREFER_DYNAMIC    , eSetVarTypeEnum   , NULL          , g_dynamic_value_types, false, false, "Should printed values be shown as their dynamic value." },
2921     { TSC_ENABLE_SYNTHETIC  , eSetVarTypeBoolean, "true"        , NULL,                  false, false, "Should synthetic values be used by default whenever available." },
2922     { TSC_SKIP_PROLOGUE     , eSetVarTypeBoolean, "true"        , NULL,                  false, false, "Skip function prologues when setting breakpoints by name." },
2923     { TSC_SOURCE_MAP        , eSetVarTypeArray  , NULL          , NULL,                  false, false, "Source path remappings used to track the change of location between a source file when built, and "
2924                                                                                                        "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
2925                                                                                                        "some part (starting at the root) of the path to the file when it was built, "
2926                                                                                                        "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
2927                                                                                                        "Each element of the array is checked in order and the first one that results in a match wins." },
2928     { 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." },
2929     { TSC_MAX_CHILDREN      , eSetVarTypeInt    , "256"         , NULL,                  true,  false, "Maximum number of children to expand in any level of depth." },
2930     { TSC_MAX_STRLENSUMMARY , eSetVarTypeInt    , "1024"        , NULL,                  true,  false, "Maximum number of characters to show when using %s in summary strings." },
2931     { TSC_PLATFORM_AVOID    , eSetVarTypeBoolean, "true"        , NULL,                  false, false, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2932     { TSC_RUN_ARGS          , eSetVarTypeArray  , NULL          , NULL,                  false,  false,  "A list containing all the arguments to be passed to the executable when it is run." },
2933     { 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." },
2934     { TSC_INHERIT_ENV       , eSetVarTypeBoolean, "true"        , NULL,                  false,  false,  "Inherit the environment from the process that is running LLDB." },
2935     { TSC_STDIN_PATH        , eSetVarTypeString , NULL          , NULL,                  false,  false,  "The file/path to be used by the executable program for reading its standard input." },
2936     { TSC_STDOUT_PATH       , eSetVarTypeString , NULL          , NULL,                  false,  false,  "The file/path to be used by the executable program for writing its standard output." },
2937     { TSC_STDERR_PATH       , eSetVarTypeString , NULL          , NULL,                  false,  false,  "The file/path to be used by the executable program for writing its standard error." },
2938 //    { "plugin",         eSetVarTypeEnum,        NULL,           NULL,                  false,  false,  "The plugin to be used to run the process." },
2939     { TSC_DISABLE_ASLR      , eSetVarTypeBoolean, "true"        , NULL,                  false,  false,  "Disable Address Space Layout Randomization (ASLR)" },
2940     { TSC_DISABLE_STDIO     , eSetVarTypeBoolean, "false"       , NULL,                  false,  false,  "Disable stdin/stdout for process (e.g. for a GUI application)" },
2941     { NULL                  , eSetVarTypeNone   , NULL          , NULL,                  false, false, NULL }
2942 };
2943 
2944 const ConstString &
2945 Target::TargetEventData::GetFlavorString ()
2946 {
2947     static ConstString g_flavor ("Target::TargetEventData");
2948     return g_flavor;
2949 }
2950 
2951 const ConstString &
2952 Target::TargetEventData::GetFlavor () const
2953 {
2954     return TargetEventData::GetFlavorString ();
2955 }
2956 
2957 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
2958     EventData(),
2959     m_target_sp (new_target_sp)
2960 {
2961 }
2962 
2963 Target::TargetEventData::~TargetEventData()
2964 {
2965 
2966 }
2967 
2968 void
2969 Target::TargetEventData::Dump (Stream *s) const
2970 {
2971 
2972 }
2973 
2974 const TargetSP
2975 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
2976 {
2977     TargetSP target_sp;
2978 
2979     const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
2980     if (data)
2981         target_sp = data->m_target_sp;
2982 
2983     return target_sp;
2984 }
2985 
2986 const Target::TargetEventData *
2987 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
2988 {
2989     if (event_ptr)
2990     {
2991         const EventData *event_data = event_ptr->GetData();
2992         if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
2993             return static_cast <const TargetEventData *> (event_ptr->GetData());
2994     }
2995     return NULL;
2996 }
2997 
2998