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