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