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