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