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