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/BreakpointResolverName.h"
20 #include "lldb/Core/Event.h"
21 #include "lldb/Core/Log.h"
22 #include "lldb/Core/Timer.h"
23 #include "lldb/Core/StreamString.h"
24 #include "lldb/Host/Host.h"
25 #include "lldb/lldb-private-log.h"
26 #include "lldb/Symbol/ObjectFile.h"
27 #include "lldb/Target/Process.h"
28 #include "lldb/Core/Debugger.h"
29 
30 using namespace lldb;
31 using namespace lldb_private;
32 
33 //----------------------------------------------------------------------
34 // Target constructor
35 //----------------------------------------------------------------------
36 Target::Target(Debugger &debugger) :
37     Broadcaster("Target"),
38     TargetInstanceSettings (*(Target::GetSettingsController().get())),
39     m_debugger (debugger),
40     m_images(),
41     m_section_load_list (),
42     m_breakpoint_list (false),
43     m_internal_breakpoint_list (true),
44     m_process_sp(),
45     m_triple(),
46     m_search_filter_sp(),
47     m_image_search_paths (ImageSearchPathsChanged, this),
48     m_scratch_ast_context_ap(NULL)
49 {
50     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT);
51     if (log)
52         log->Printf ("%p Target::Target()", this);
53 }
54 
55 //----------------------------------------------------------------------
56 // Destructor
57 //----------------------------------------------------------------------
58 Target::~Target()
59 {
60     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT);
61     if (log)
62         log->Printf ("%p Target::~Target()", this);
63     DeleteCurrentProcess ();
64 }
65 
66 void
67 Target::Dump (Stream *s)
68 {
69 //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
70     s->Indent();
71     s->PutCString("Target\n");
72     s->IndentMore();
73     m_images.Dump(s);
74     m_breakpoint_list.Dump(s);
75     m_internal_breakpoint_list.Dump(s);
76 //  if (m_process_sp.get())
77 //      m_process_sp->Dump(s);
78     s->IndentLess();
79 }
80 
81 void
82 Target::DeleteCurrentProcess ()
83 {
84     if (m_process_sp.get())
85     {
86         m_section_load_list.Clear();
87         if (m_process_sp->IsAlive())
88             m_process_sp->Destroy();
89         else
90             m_process_sp->Finalize();
91 
92         // Do any cleanup of the target we need to do between process instances.
93         // NB It is better to do this before destroying the process in case the
94         // clean up needs some help from the process.
95         m_breakpoint_list.ClearAllBreakpointSites();
96         m_internal_breakpoint_list.ClearAllBreakpointSites();
97         m_process_sp.reset();
98     }
99 }
100 
101 const lldb::ProcessSP &
102 Target::CreateProcess (Listener &listener, const char *plugin_name)
103 {
104     DeleteCurrentProcess ();
105     m_process_sp.reset(Process::FindPlugin(*this, plugin_name, listener));
106     return m_process_sp;
107 }
108 
109 const lldb::ProcessSP &
110 Target::GetProcessSP () const
111 {
112     return m_process_sp;
113 }
114 
115 lldb::TargetSP
116 Target::GetSP()
117 {
118     return m_debugger.GetTargetList().GetTargetSP(this);
119 }
120 
121 BreakpointList &
122 Target::GetBreakpointList(bool internal)
123 {
124     if (internal)
125         return m_internal_breakpoint_list;
126     else
127         return m_breakpoint_list;
128 }
129 
130 const BreakpointList &
131 Target::GetBreakpointList(bool internal) const
132 {
133     if (internal)
134         return m_internal_breakpoint_list;
135     else
136         return m_breakpoint_list;
137 }
138 
139 BreakpointSP
140 Target::GetBreakpointByID (break_id_t break_id)
141 {
142     BreakpointSP bp_sp;
143 
144     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
145         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
146     else
147         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
148 
149     return bp_sp;
150 }
151 
152 BreakpointSP
153 Target::CreateBreakpoint (const FileSpec *containingModule, const FileSpec &file, uint32_t line_no, bool check_inlines, bool internal)
154 {
155     SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
156     BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL, file, line_no, check_inlines));
157     return CreateBreakpoint (filter_sp, resolver_sp, internal);
158 }
159 
160 
161 BreakpointSP
162 Target::CreateBreakpoint (lldb::addr_t addr, bool internal)
163 {
164     Address so_addr;
165     // Attempt to resolve our load address if possible, though it is ok if
166     // it doesn't resolve to section/offset.
167 
168     // Try and resolve as a load address if possible
169     m_section_load_list.ResolveLoadAddress(addr, so_addr);
170     if (!so_addr.IsValid())
171     {
172         // The address didn't resolve, so just set this as an absolute address
173         so_addr.SetOffset (addr);
174     }
175     BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal));
176     return bp_sp;
177 }
178 
179 BreakpointSP
180 Target::CreateBreakpoint (Address &addr, bool internal)
181 {
182     TargetSP target_sp = this->GetSP();
183     SearchFilterSP filter_sp(new SearchFilter (target_sp));
184     BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
185     return CreateBreakpoint (filter_sp, resolver_sp, internal);
186 }
187 
188 BreakpointSP
189 Target::CreateBreakpoint (FileSpec *containingModule, const char *func_name, uint32_t func_name_type_mask, bool internal)
190 {
191     BreakpointSP bp_sp;
192     if (func_name)
193     {
194         SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
195         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL, func_name, func_name_type_mask, Breakpoint::Exact));
196         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
197     }
198     return bp_sp;
199 }
200 
201 
202 SearchFilterSP
203 Target::GetSearchFilterForModule (const FileSpec *containingModule)
204 {
205     SearchFilterSP filter_sp;
206     lldb::TargetSP target_sp = this->GetSP();
207     if (containingModule != NULL)
208     {
209         // TODO: We should look into sharing module based search filters
210         // across many breakpoints like we do for the simple target based one
211         filter_sp.reset (new SearchFilterByModule (target_sp, *containingModule));
212     }
213     else
214     {
215         if (m_search_filter_sp.get() == NULL)
216             m_search_filter_sp.reset (new SearchFilter (target_sp));
217         filter_sp = m_search_filter_sp;
218     }
219     return filter_sp;
220 }
221 
222 BreakpointSP
223 Target::CreateBreakpoint (FileSpec *containingModule, RegularExpression &func_regex, bool internal)
224 {
225     SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
226     BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL, func_regex));
227 
228     return CreateBreakpoint (filter_sp, resolver_sp, internal);
229 }
230 
231 BreakpointSP
232 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal)
233 {
234     BreakpointSP bp_sp;
235     if (filter_sp && resolver_sp)
236     {
237         bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp));
238         resolver_sp->SetBreakpoint (bp_sp.get());
239 
240         if (internal)
241             m_internal_breakpoint_list.Add (bp_sp, false);
242         else
243             m_breakpoint_list.Add (bp_sp, true);
244 
245         Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
246         if (log)
247         {
248             StreamString s;
249             bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
250             log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
251         }
252 
253         bp_sp->ResolveBreakpoint();
254     }
255 
256     if (!internal && bp_sp)
257     {
258         m_last_created_breakpoint = bp_sp;
259     }
260 
261     return bp_sp;
262 }
263 
264 void
265 Target::RemoveAllBreakpoints (bool internal_also)
266 {
267     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
268     if (log)
269         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
270 
271     m_breakpoint_list.RemoveAll (true);
272     if (internal_also)
273         m_internal_breakpoint_list.RemoveAll (false);
274 
275     m_last_created_breakpoint.reset();
276 }
277 
278 void
279 Target::DisableAllBreakpoints (bool internal_also)
280 {
281     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
282     if (log)
283         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
284 
285     m_breakpoint_list.SetEnabledAll (false);
286     if (internal_also)
287         m_internal_breakpoint_list.SetEnabledAll (false);
288 }
289 
290 void
291 Target::EnableAllBreakpoints (bool internal_also)
292 {
293     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
294     if (log)
295         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
296 
297     m_breakpoint_list.SetEnabledAll (true);
298     if (internal_also)
299         m_internal_breakpoint_list.SetEnabledAll (true);
300 }
301 
302 bool
303 Target::RemoveBreakpointByID (break_id_t break_id)
304 {
305     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
306     if (log)
307         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
308 
309     if (DisableBreakpointByID (break_id))
310     {
311         if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
312             m_internal_breakpoint_list.Remove(break_id, false);
313         else
314         {
315             if (m_last_created_breakpoint->GetID() == break_id)
316                 m_last_created_breakpoint.reset();
317             m_breakpoint_list.Remove(break_id, true);
318         }
319         return true;
320     }
321     return false;
322 }
323 
324 bool
325 Target::DisableBreakpointByID (break_id_t break_id)
326 {
327     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
328     if (log)
329         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
330 
331     BreakpointSP bp_sp;
332 
333     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
334         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
335     else
336         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
337     if (bp_sp)
338     {
339         bp_sp->SetEnabled (false);
340         return true;
341     }
342     return false;
343 }
344 
345 bool
346 Target::EnableBreakpointByID (break_id_t break_id)
347 {
348     Log *log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS);
349     if (log)
350         log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
351                      __FUNCTION__,
352                      break_id,
353                      LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
354 
355     BreakpointSP bp_sp;
356 
357     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
358         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
359     else
360         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
361 
362     if (bp_sp)
363     {
364         bp_sp->SetEnabled (true);
365         return true;
366     }
367     return false;
368 }
369 
370 ModuleSP
371 Target::GetExecutableModule ()
372 {
373     ModuleSP executable_sp;
374     if (m_images.GetSize() > 0)
375         executable_sp = m_images.GetModuleAtIndex(0);
376     return executable_sp;
377 }
378 
379 void
380 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
381 {
382     m_images.Clear();
383     m_scratch_ast_context_ap.reset();
384 
385     if (executable_sp.get())
386     {
387         Timer scoped_timer (__PRETTY_FUNCTION__,
388                             "Target::SetExecutableModule (executable = '%s/%s')",
389                             executable_sp->GetFileSpec().GetDirectory().AsCString(),
390                             executable_sp->GetFileSpec().GetFilename().AsCString());
391 
392         m_images.Append(executable_sp); // The first image is our exectuable file
393 
394         ArchSpec exe_arch = executable_sp->GetArchitecture();
395         // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
396         if (!m_arch_spec.IsValid())
397             m_arch_spec = exe_arch;
398 
399         FileSpecList dependent_files;
400         ObjectFile * executable_objfile = executable_sp->GetObjectFile();
401         if (executable_objfile == NULL)
402         {
403 
404             FileSpec bundle_executable(executable_sp->GetFileSpec());
405             if (Host::ResolveExecutableInBundle (bundle_executable))
406             {
407                 ModuleSP bundle_exe_module_sp(GetSharedModule(bundle_executable,
408                                                               exe_arch));
409                 SetExecutableModule (bundle_exe_module_sp, get_dependent_files);
410                 if (bundle_exe_module_sp->GetObjectFile() != NULL)
411                     executable_sp = bundle_exe_module_sp;
412                 return;
413             }
414         }
415 
416         if (executable_objfile)
417         {
418             executable_objfile->GetDependentModules(dependent_files);
419             for (uint32_t i=0; i<dependent_files.GetSize(); i++)
420             {
421                 ModuleSP image_module_sp(GetSharedModule(dependent_files.GetFileSpecPointerAtIndex(i),
422                                                          exe_arch));
423                 if (image_module_sp.get())
424                 {
425                     //image_module_sp->Dump(&s);// REMOVE THIS, DEBUG ONLY
426                     ObjectFile *objfile = image_module_sp->GetObjectFile();
427                     if (objfile)
428                         objfile->GetDependentModules(dependent_files);
429                 }
430             }
431         }
432 
433         // Now see if we know the target triple, and if so, create our scratch AST context:
434         ConstString target_triple;
435         if (GetTargetTriple(target_triple))
436         {
437             m_scratch_ast_context_ap.reset (new ClangASTContext(target_triple.GetCString()));
438         }
439     }
440 
441     UpdateInstanceName();
442 }
443 
444 
445 ModuleList&
446 Target::GetImages ()
447 {
448     return m_images;
449 }
450 
451 ArchSpec
452 Target::GetArchitecture () const
453 {
454     return m_arch_spec;
455 }
456 
457 bool
458 Target::SetArchitecture (const ArchSpec &arch_spec)
459 {
460     if (m_arch_spec == arch_spec)
461     {
462         // If we're setting the architecture to our current architecture, we
463         // don't need to do anything.
464         return true;
465     }
466     else if (!m_arch_spec.IsValid())
467     {
468         // If we haven't got a valid arch spec, then we just need to set it.
469         m_arch_spec = arch_spec;
470         return true;
471     }
472     else
473     {
474         // If we have an executable file, try to reset the executable to the desired architecture
475         m_arch_spec = arch_spec;
476         ModuleSP executable_sp = GetExecutableModule ();
477         m_images.Clear();
478         m_scratch_ast_context_ap.reset();
479         m_triple.Clear();
480         // Need to do something about unsetting breakpoints.
481 
482         if (executable_sp)
483         {
484             FileSpec exec_file_spec = executable_sp->GetFileSpec();
485             Error error = ModuleList::GetSharedModule(exec_file_spec,
486                                                       arch_spec,
487                                                       NULL,
488                                                       NULL,
489                                                       0,
490                                                       executable_sp,
491                                                       NULL,
492                                                       NULL);
493 
494             if (!error.Fail() && executable_sp)
495             {
496                 SetExecutableModule (executable_sp, true);
497                 return true;
498             }
499             else
500             {
501                 return false;
502             }
503         }
504         else
505         {
506             return false;
507         }
508     }
509 }
510 
511 bool
512 Target::GetTargetTriple(ConstString &triple)
513 {
514     triple.Clear();
515 
516     if (m_triple)
517     {
518         triple = m_triple;
519     }
520     else
521     {
522         Module *exe_module = GetExecutableModule().get();
523         if (exe_module)
524         {
525             ObjectFile *objfile = exe_module->GetObjectFile();
526             if (objfile)
527             {
528                 objfile->GetTargetTriple(m_triple);
529                 triple = m_triple;
530             }
531         }
532     }
533     return !triple.IsEmpty();
534 }
535 
536 void
537 Target::ModuleAdded (ModuleSP &module_sp)
538 {
539     // A module is being added to this target for the first time
540     ModuleList module_list;
541     module_list.Append(module_sp);
542     ModulesDidLoad (module_list);
543 }
544 
545 void
546 Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp)
547 {
548     // A module is being added to this target for the first time
549     ModuleList module_list;
550     module_list.Append (old_module_sp);
551     ModulesDidUnload (module_list);
552     module_list.Clear ();
553     module_list.Append (new_module_sp);
554     ModulesDidLoad (module_list);
555 }
556 
557 void
558 Target::ModulesDidLoad (ModuleList &module_list)
559 {
560     m_breakpoint_list.UpdateBreakpoints (module_list, true);
561     // TODO: make event data that packages up the module_list
562     BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
563 }
564 
565 void
566 Target::ModulesDidUnload (ModuleList &module_list)
567 {
568     m_breakpoint_list.UpdateBreakpoints (module_list, false);
569     // TODO: make event data that packages up the module_list
570     BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
571 }
572 
573 size_t
574 Target::ReadMemory (const Address& addr, void *dst, size_t dst_len, Error &error)
575 {
576     error.Clear();
577 
578     bool process_is_valid = m_process_sp && m_process_sp->IsAlive();
579 
580     Address resolved_addr(addr);
581     if (!resolved_addr.IsSectionOffset())
582     {
583         if (process_is_valid)
584         {
585             m_section_load_list.ResolveLoadAddress (addr.GetOffset(), resolved_addr);
586         }
587         else
588         {
589             m_images.ResolveFileAddress(addr.GetOffset(), resolved_addr);
590         }
591     }
592 
593 
594     if (process_is_valid)
595     {
596         lldb::addr_t load_addr = resolved_addr.GetLoadAddress (this);
597         if (load_addr == LLDB_INVALID_ADDRESS)
598         {
599             if (resolved_addr.GetModule() && resolved_addr.GetModule()->GetFileSpec())
600                 error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded.\n",
601                                                resolved_addr.GetModule()->GetFileSpec().GetFilename().AsCString(),
602                                                resolved_addr.GetFileAddress());
603             else
604                 error.SetErrorStringWithFormat("0x%llx can't be resolved.\n", resolved_addr.GetFileAddress());
605         }
606         else
607         {
608             size_t bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
609             if (bytes_read != dst_len)
610             {
611                 if (error.Success())
612                 {
613                     if (bytes_read == 0)
614                         error.SetErrorStringWithFormat("Read memory from 0x%llx failed.\n", load_addr);
615                     else
616                         error.SetErrorStringWithFormat("Only %zu of %zu bytes were read from memory at 0x%llx.\n", bytes_read, dst_len, load_addr);
617                 }
618             }
619             if (bytes_read)
620                 return bytes_read;
621             // If the address is not section offset we have an address that
622             // doesn't resolve to any address in any currently loaded shared
623             // libaries and we failed to read memory so there isn't anything
624             // more we can do. If it is section offset, we might be able to
625             // read cached memory from the object file.
626             if (!resolved_addr.IsSectionOffset())
627                 return 0;
628         }
629     }
630 
631     const Section *section = resolved_addr.GetSection();
632     if (section && section->GetModule())
633     {
634         ObjectFile *objfile = section->GetModule()->GetObjectFile();
635         return section->ReadSectionDataFromObjectFile (objfile,
636                                                        resolved_addr.GetOffset(),
637                                                        dst,
638                                                        dst_len);
639     }
640     return 0;
641 }
642 
643 
644 ModuleSP
645 Target::GetSharedModule
646 (
647     const FileSpec& file_spec,
648     const ArchSpec& arch,
649     const UUID *uuid_ptr,
650     const ConstString *object_name,
651     off_t object_offset,
652     Error *error_ptr
653 )
654 {
655     // Don't pass in the UUID so we can tell if we have a stale value in our list
656     ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
657     bool did_create_module = false;
658     ModuleSP module_sp;
659 
660     // If there are image search path entries, try to use them first to acquire a suitable image.
661 
662     Error error;
663 
664     if (m_image_search_paths.GetSize())
665     {
666         FileSpec transformed_spec;
667         if (m_image_search_paths.RemapPath (file_spec.GetDirectory(), transformed_spec.GetDirectory()))
668         {
669             transformed_spec.GetFilename() = file_spec.GetFilename();
670             error = ModuleList::GetSharedModule (transformed_spec, arch, uuid_ptr, object_name, object_offset, module_sp, &old_module_sp, &did_create_module);
671         }
672     }
673 
674     // If a module hasn't been found yet, use the unmodified path.
675 
676     if (!module_sp)
677     {
678         error = (ModuleList::GetSharedModule (file_spec, arch, uuid_ptr, object_name, object_offset, module_sp, &old_module_sp, &did_create_module));
679     }
680 
681     if (module_sp)
682     {
683         m_images.Append (module_sp);
684         if (did_create_module)
685         {
686             if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
687                 ModuleUpdated(old_module_sp, module_sp);
688             else
689                 ModuleAdded(module_sp);
690         }
691     }
692     if (error_ptr)
693         *error_ptr = error;
694     return module_sp;
695 }
696 
697 
698 Target *
699 Target::CalculateTarget ()
700 {
701     return this;
702 }
703 
704 Process *
705 Target::CalculateProcess ()
706 {
707     return NULL;
708 }
709 
710 Thread *
711 Target::CalculateThread ()
712 {
713     return NULL;
714 }
715 
716 StackFrame *
717 Target::CalculateStackFrame ()
718 {
719     return NULL;
720 }
721 
722 void
723 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
724 {
725     exe_ctx.target = this;
726     exe_ctx.process = NULL; // Do NOT fill in process...
727     exe_ctx.thread = NULL;
728     exe_ctx.frame = NULL;
729 }
730 
731 PathMappingList &
732 Target::GetImageSearchPathList ()
733 {
734     return m_image_search_paths;
735 }
736 
737 void
738 Target::ImageSearchPathsChanged
739 (
740     const PathMappingList &path_list,
741     void *baton
742 )
743 {
744     Target *target = (Target *)baton;
745     if (target->m_images.GetSize() > 1)
746     {
747         ModuleSP exe_module_sp (target->GetExecutableModule());
748         if (exe_module_sp)
749         {
750             target->m_images.Clear();
751             target->SetExecutableModule (exe_module_sp, true);
752         }
753     }
754 }
755 
756 ClangASTContext *
757 Target::GetScratchClangASTContext()
758 {
759     return m_scratch_ast_context_ap.get();
760 }
761 
762 lldb::UserSettingsControllerSP
763 Target::GetSettingsController (bool finish)
764 {
765     static lldb::UserSettingsControllerSP g_settings_controller (new SettingsController);
766     static bool initialized = false;
767 
768     if (!initialized)
769     {
770         initialized = UserSettingsController::InitializeSettingsController (g_settings_controller,
771                                                             Target::SettingsController::global_settings_table,
772                                                             Target::SettingsController::instance_settings_table);
773     }
774 
775     if (finish)
776     {
777         UserSettingsController::FinalizeSettingsController (g_settings_controller);
778         g_settings_controller.reset();
779         initialized = false;
780     }
781 
782     return g_settings_controller;
783 }
784 
785 ArchSpec
786 Target::GetDefaultArchitecture ()
787 {
788     lldb::UserSettingsControllerSP settings_controller = Target::GetSettingsController();
789     lldb::SettableVariableType var_type;
790     Error err;
791     StringList result = settings_controller->GetVariable ("target.default-arch", var_type, "[]", err);
792 
793     const char *default_name = "";
794     if (result.GetSize() == 1 && err.Success())
795         default_name = result.GetStringAtIndex (0);
796 
797     ArchSpec default_arch (default_name);
798     return default_arch;
799 }
800 
801 void
802 Target::SetDefaultArchitecture (ArchSpec new_arch)
803 {
804     if (new_arch.IsValid())
805         Target::GetSettingsController ()->SetVariable ("target.default-arch", new_arch.AsCString(),
806                                                        lldb::eVarSetOperationAssign, false, "[]");
807 }
808 
809 Target *
810 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
811 {
812     // The target can either exist in the "process" of ExecutionContext, or in
813     // the "target_sp" member of SymbolContext. This accessor helper function
814     // will get the target from one of these locations.
815 
816     Target *target = NULL;
817     if (sc_ptr != NULL)
818         target = sc_ptr->target_sp.get();
819     if (target == NULL)
820     {
821         if (exe_ctx_ptr != NULL && exe_ctx_ptr->process != NULL)
822             target = &exe_ctx_ptr->process->GetTarget();
823     }
824     return target;
825 }
826 
827 
828 void
829 Target::UpdateInstanceName ()
830 {
831     StreamString sstr;
832 
833     ModuleSP module_sp = GetExecutableModule();
834     if (module_sp)
835     {
836         sstr.Printf ("%s_%s", module_sp->GetFileSpec().GetFilename().AsCString(),
837                      module_sp->GetArchitecture().AsCString());
838 	Target::GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
839 								 sstr.GetData());
840     }
841 }
842 
843 //--------------------------------------------------------------
844 // class Target::SettingsController
845 //--------------------------------------------------------------
846 
847 Target::SettingsController::SettingsController () :
848     UserSettingsController ("target", Debugger::GetSettingsController()),
849     m_default_architecture ()
850 {
851     m_default_settings.reset (new TargetInstanceSettings (*this, false,
852                                                           InstanceSettings::GetDefaultName().AsCString()));
853 }
854 
855 Target::SettingsController::~SettingsController ()
856 {
857 }
858 
859 lldb::InstanceSettingsSP
860 Target::SettingsController::CreateInstanceSettings (const char *instance_name)
861 {
862     TargetInstanceSettings *new_settings = new TargetInstanceSettings (*(Target::GetSettingsController().get()),
863                                                                        false, instance_name);
864     lldb::InstanceSettingsSP new_settings_sp (new_settings);
865     return new_settings_sp;
866 }
867 
868 const ConstString &
869 Target::SettingsController::DefArchVarName ()
870 {
871     static ConstString def_arch_var_name ("default-arch");
872 
873     return def_arch_var_name;
874 }
875 
876 bool
877 Target::SettingsController::SetGlobalVariable (const ConstString &var_name,
878                                                const char *index_value,
879                                                const char *value,
880                                                const SettingEntry &entry,
881                                                const lldb::VarSetOperationType op,
882                                                Error&err)
883 {
884     if (var_name == DefArchVarName())
885     {
886         ArchSpec tmp_spec (value);
887         if (tmp_spec.IsValid())
888             m_default_architecture = tmp_spec;
889         else
890           err.SetErrorStringWithFormat ("'%s' is not a valid architecture.", value);
891     }
892     return true;
893 }
894 
895 
896 bool
897 Target::SettingsController::GetGlobalVariable (const ConstString &var_name,
898                                                StringList &value,
899                                                Error &err)
900 {
901     if (var_name == DefArchVarName())
902     {
903         value.AppendString (m_default_architecture.AsCString());
904         return true;
905     }
906     else
907         err.SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
908 
909     return false;
910 }
911 
912 //--------------------------------------------------------------
913 // class TargetInstanceSettings
914 //--------------------------------------------------------------
915 
916 TargetInstanceSettings::TargetInstanceSettings (UserSettingsController &owner, bool live_instance,
917                                                 const char *name) :
918     InstanceSettings (owner, (name == NULL ? InstanceSettings::InvalidName().AsCString() : name), live_instance)
919 {
920     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
921     // until the vtables for TargetInstanceSettings are properly set up, i.e. AFTER all the initializers.
922     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
923     // This is true for CreateInstanceName() too.
924 
925     if (GetInstanceName () == InstanceSettings::InvalidName())
926     {
927         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
928         m_owner.RegisterInstanceSettings (this);
929     }
930 
931     if (live_instance)
932     {
933         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
934         CopyInstanceSettings (pending_settings,false);
935         //m_owner.RemovePendingSettings (m_instance_name);
936     }
937 }
938 
939 TargetInstanceSettings::TargetInstanceSettings (const TargetInstanceSettings &rhs) :
940     InstanceSettings (*(Target::GetSettingsController().get()), CreateInstanceName().AsCString())
941 {
942     if (m_instance_name != InstanceSettings::GetDefaultName())
943     {
944         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
945         CopyInstanceSettings (pending_settings,false);
946         //m_owner.RemovePendingSettings (m_instance_name);
947     }
948 }
949 
950 TargetInstanceSettings::~TargetInstanceSettings ()
951 {
952 }
953 
954 TargetInstanceSettings&
955 TargetInstanceSettings::operator= (const TargetInstanceSettings &rhs)
956 {
957     if (this != &rhs)
958     {
959     }
960 
961     return *this;
962 }
963 
964 
965 void
966 TargetInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
967                                                         const char *index_value,
968                                                         const char *value,
969                                                         const ConstString &instance_name,
970                                                         const SettingEntry &entry,
971                                                         lldb::VarSetOperationType op,
972                                                         Error &err,
973                                                         bool pending)
974 {
975     // Currently 'target' does not have any instance settings.
976 }
977 
978 void
979 TargetInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings,
980                                                bool pending)
981 {
982     // Currently 'target' does not have any instance settings.
983 }
984 
985 bool
986 TargetInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
987                                                   const ConstString &var_name,
988                                                   StringList &value,
989                                                   Error *err)
990 {
991     if (err)
992         err->SetErrorString ("'target' does not have any instance settings");
993     return false;
994 }
995 
996 const ConstString
997 TargetInstanceSettings::CreateInstanceName ()
998 {
999     StreamString sstr;
1000     static int instance_count = 1;
1001 
1002     sstr.Printf ("target_%d", instance_count);
1003     ++instance_count;
1004 
1005     const ConstString ret_val (sstr.GetData());
1006     return ret_val;
1007 }
1008 
1009 //--------------------------------------------------
1010 // Target::SettingsController Variable Tables
1011 //--------------------------------------------------
1012 
1013 SettingEntry
1014 Target::SettingsController::global_settings_table[] =
1015 {
1016   //{ "var-name",    var-type  ,        "default", enum-table, init'd, hidden, "help-text"},
1017     { "default-arch", eSetVarTypeString, "x86_64", NULL,       false,  false,   "Default architecture to choose, when there's a choice." },
1018     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1019 };
1020 
1021 SettingEntry
1022 Target::SettingsController::instance_settings_table[] =
1023 {
1024   //{ "var-name",    var-type,              "default",      enum-table, init'd, hidden, "help-text"},
1025     {  NULL, eSetVarTypeNone, NULL, NULL, 0, 0, NULL }
1026 };
1027