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/Debugger.h"
21 #include "lldb/Core/Event.h"
22 #include "lldb/Core/Log.h"
23 #include "lldb/Core/StreamAsynchronousIO.h"
24 #include "lldb/Core/StreamString.h"
25 #include "lldb/Core/Timer.h"
26 #include "lldb/Core/ValueObject.h"
27 #include "lldb/Expression/ClangUserExpression.h"
28 #include "lldb/Host/Host.h"
29 #include "lldb/Interpreter/CommandInterpreter.h"
30 #include "lldb/Interpreter/CommandReturnObject.h"
31 #include "lldb/lldb-private-log.h"
32 #include "lldb/Symbol/ObjectFile.h"
33 #include "lldb/Target/Process.h"
34 #include "lldb/Target/StackFrame.h"
35 #include "lldb/Target/Thread.h"
36 #include "lldb/Target/ThreadSpec.h"
37 
38 using namespace lldb;
39 using namespace lldb_private;
40 
41 //----------------------------------------------------------------------
42 // Target constructor
43 //----------------------------------------------------------------------
44 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
45     Broadcaster ("lldb.target"),
46     ExecutionContextScope (),
47     TargetInstanceSettings (*GetSettingsController()),
48     m_debugger (debugger),
49     m_platform_sp (platform_sp),
50     m_mutex (Mutex::eMutexTypeRecursive),
51     m_arch (target_arch),
52     m_images (),
53     m_section_load_list (),
54     m_breakpoint_list (false),
55     m_internal_breakpoint_list (true),
56     m_process_sp (),
57     m_search_filter_sp (),
58     m_image_search_paths (ImageSearchPathsChanged, this),
59     m_scratch_ast_context_ap (NULL),
60     m_persistent_variables (),
61     m_stop_hooks (),
62     m_stop_hook_next_id (0)
63 {
64     SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
65     SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
66     SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
67 
68     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
69     if (log)
70         log->Printf ("%p Target::Target()", this);
71 }
72 
73 //----------------------------------------------------------------------
74 // Destructor
75 //----------------------------------------------------------------------
76 Target::~Target()
77 {
78     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
79     if (log)
80         log->Printf ("%p Target::~Target()", this);
81     DeleteCurrentProcess ();
82 }
83 
84 void
85 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
86 {
87 //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
88     if (description_level != lldb::eDescriptionLevelBrief)
89     {
90         s->Indent();
91         s->PutCString("Target\n");
92         s->IndentMore();
93             m_images.Dump(s);
94             m_breakpoint_list.Dump(s);
95             m_internal_breakpoint_list.Dump(s);
96         s->IndentLess();
97     }
98     else
99     {
100         s->PutCString (GetExecutableModule()->GetFileSpec().GetFilename().GetCString());
101     }
102 }
103 
104 void
105 Target::DeleteCurrentProcess ()
106 {
107     if (m_process_sp.get())
108     {
109         m_section_load_list.Clear();
110         if (m_process_sp->IsAlive())
111             m_process_sp->Destroy();
112 
113         m_process_sp->Finalize();
114 
115         // Do any cleanup of the target we need to do between process instances.
116         // NB It is better to do this before destroying the process in case the
117         // clean up needs some help from the process.
118         m_breakpoint_list.ClearAllBreakpointSites();
119         m_internal_breakpoint_list.ClearAllBreakpointSites();
120         m_process_sp.reset();
121     }
122 }
123 
124 const lldb::ProcessSP &
125 Target::CreateProcess (Listener &listener, const char *plugin_name)
126 {
127     DeleteCurrentProcess ();
128     m_process_sp.reset(Process::FindPlugin(*this, plugin_name, listener));
129     return m_process_sp;
130 }
131 
132 const lldb::ProcessSP &
133 Target::GetProcessSP () const
134 {
135     return m_process_sp;
136 }
137 
138 lldb::TargetSP
139 Target::GetSP()
140 {
141     return m_debugger.GetTargetList().GetTargetSP(this);
142 }
143 
144 BreakpointList &
145 Target::GetBreakpointList(bool internal)
146 {
147     if (internal)
148         return m_internal_breakpoint_list;
149     else
150         return m_breakpoint_list;
151 }
152 
153 const BreakpointList &
154 Target::GetBreakpointList(bool internal) const
155 {
156     if (internal)
157         return m_internal_breakpoint_list;
158     else
159         return m_breakpoint_list;
160 }
161 
162 BreakpointSP
163 Target::GetBreakpointByID (break_id_t break_id)
164 {
165     BreakpointSP bp_sp;
166 
167     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
168         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
169     else
170         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
171 
172     return bp_sp;
173 }
174 
175 BreakpointSP
176 Target::CreateBreakpoint (const FileSpec *containingModule, const FileSpec &file, uint32_t line_no, bool check_inlines, bool internal)
177 {
178     SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
179     BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL, file, line_no, check_inlines));
180     return CreateBreakpoint (filter_sp, resolver_sp, internal);
181 }
182 
183 
184 BreakpointSP
185 Target::CreateBreakpoint (lldb::addr_t addr, bool internal)
186 {
187     Address so_addr;
188     // Attempt to resolve our load address if possible, though it is ok if
189     // it doesn't resolve to section/offset.
190 
191     // Try and resolve as a load address if possible
192     m_section_load_list.ResolveLoadAddress(addr, so_addr);
193     if (!so_addr.IsValid())
194     {
195         // The address didn't resolve, so just set this as an absolute address
196         so_addr.SetOffset (addr);
197     }
198     BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal));
199     return bp_sp;
200 }
201 
202 BreakpointSP
203 Target::CreateBreakpoint (Address &addr, bool internal)
204 {
205     TargetSP target_sp = this->GetSP();
206     SearchFilterSP filter_sp(new SearchFilter (target_sp));
207     BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
208     return CreateBreakpoint (filter_sp, resolver_sp, internal);
209 }
210 
211 BreakpointSP
212 Target::CreateBreakpoint (FileSpec *containingModule, const char *func_name, uint32_t func_name_type_mask, bool internal)
213 {
214     BreakpointSP bp_sp;
215     if (func_name)
216     {
217         SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
218         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL, func_name, func_name_type_mask, Breakpoint::Exact));
219         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
220     }
221     return bp_sp;
222 }
223 
224 
225 SearchFilterSP
226 Target::GetSearchFilterForModule (const FileSpec *containingModule)
227 {
228     SearchFilterSP filter_sp;
229     lldb::TargetSP target_sp = this->GetSP();
230     if (containingModule != NULL)
231     {
232         // TODO: We should look into sharing module based search filters
233         // across many breakpoints like we do for the simple target based one
234         filter_sp.reset (new SearchFilterByModule (target_sp, *containingModule));
235     }
236     else
237     {
238         if (m_search_filter_sp.get() == NULL)
239             m_search_filter_sp.reset (new SearchFilter (target_sp));
240         filter_sp = m_search_filter_sp;
241     }
242     return filter_sp;
243 }
244 
245 BreakpointSP
246 Target::CreateBreakpoint (FileSpec *containingModule, RegularExpression &func_regex, bool internal)
247 {
248     SearchFilterSP filter_sp(GetSearchFilterForModule (containingModule));
249     BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL, func_regex));
250 
251     return CreateBreakpoint (filter_sp, resolver_sp, internal);
252 }
253 
254 BreakpointSP
255 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal)
256 {
257     BreakpointSP bp_sp;
258     if (filter_sp && resolver_sp)
259     {
260         bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp));
261         resolver_sp->SetBreakpoint (bp_sp.get());
262 
263         if (internal)
264             m_internal_breakpoint_list.Add (bp_sp, false);
265         else
266             m_breakpoint_list.Add (bp_sp, true);
267 
268         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
269         if (log)
270         {
271             StreamString s;
272             bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
273             log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
274         }
275 
276         bp_sp->ResolveBreakpoint();
277     }
278 
279     if (!internal && bp_sp)
280     {
281         m_last_created_breakpoint = bp_sp;
282     }
283 
284     return bp_sp;
285 }
286 
287 void
288 Target::RemoveAllBreakpoints (bool internal_also)
289 {
290     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
291     if (log)
292         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
293 
294     m_breakpoint_list.RemoveAll (true);
295     if (internal_also)
296         m_internal_breakpoint_list.RemoveAll (false);
297 
298     m_last_created_breakpoint.reset();
299 }
300 
301 void
302 Target::DisableAllBreakpoints (bool internal_also)
303 {
304     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
305     if (log)
306         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
307 
308     m_breakpoint_list.SetEnabledAll (false);
309     if (internal_also)
310         m_internal_breakpoint_list.SetEnabledAll (false);
311 }
312 
313 void
314 Target::EnableAllBreakpoints (bool internal_also)
315 {
316     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
317     if (log)
318         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
319 
320     m_breakpoint_list.SetEnabledAll (true);
321     if (internal_also)
322         m_internal_breakpoint_list.SetEnabledAll (true);
323 }
324 
325 bool
326 Target::RemoveBreakpointByID (break_id_t break_id)
327 {
328     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
329     if (log)
330         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
331 
332     if (DisableBreakpointByID (break_id))
333     {
334         if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
335             m_internal_breakpoint_list.Remove(break_id, false);
336         else
337         {
338             if (m_last_created_breakpoint)
339             {
340                 if (m_last_created_breakpoint->GetID() == break_id)
341                     m_last_created_breakpoint.reset();
342             }
343             m_breakpoint_list.Remove(break_id, true);
344         }
345         return true;
346     }
347     return false;
348 }
349 
350 bool
351 Target::DisableBreakpointByID (break_id_t break_id)
352 {
353     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
354     if (log)
355         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
356 
357     BreakpointSP bp_sp;
358 
359     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
360         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
361     else
362         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
363     if (bp_sp)
364     {
365         bp_sp->SetEnabled (false);
366         return true;
367     }
368     return false;
369 }
370 
371 bool
372 Target::EnableBreakpointByID (break_id_t break_id)
373 {
374     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
375     if (log)
376         log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
377                      __FUNCTION__,
378                      break_id,
379                      LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
380 
381     BreakpointSP bp_sp;
382 
383     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
384         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
385     else
386         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
387 
388     if (bp_sp)
389     {
390         bp_sp->SetEnabled (true);
391         return true;
392     }
393     return false;
394 }
395 
396 ModuleSP
397 Target::GetExecutableModule ()
398 {
399     ModuleSP executable_sp;
400     if (m_images.GetSize() > 0)
401         executable_sp = m_images.GetModuleAtIndex(0);
402     return executable_sp;
403 }
404 
405 void
406 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
407 {
408     m_images.Clear();
409     m_scratch_ast_context_ap.reset();
410 
411     if (executable_sp.get())
412     {
413         Timer scoped_timer (__PRETTY_FUNCTION__,
414                             "Target::SetExecutableModule (executable = '%s/%s')",
415                             executable_sp->GetFileSpec().GetDirectory().AsCString(),
416                             executable_sp->GetFileSpec().GetFilename().AsCString());
417 
418         m_images.Append(executable_sp); // The first image is our exectuable file
419 
420         // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
421         if (!m_arch.IsValid())
422             m_arch = executable_sp->GetArchitecture();
423 
424         FileSpecList dependent_files;
425         ObjectFile *executable_objfile = executable_sp->GetObjectFile();
426 
427         if (executable_objfile)
428         {
429             executable_objfile->GetDependentModules(dependent_files);
430             for (uint32_t i=0; i<dependent_files.GetSize(); i++)
431             {
432                 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
433                 FileSpec platform_dependent_file_spec;
434                 if (m_platform_sp)
435                     m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec);
436                 else
437                     platform_dependent_file_spec = dependent_file_spec;
438 
439                 ModuleSP image_module_sp(GetSharedModule (platform_dependent_file_spec,
440                                                           m_arch));
441                 if (image_module_sp.get())
442                 {
443                     //image_module_sp->Dump(&s);// REMOVE THIS, DEBUG ONLY
444                     ObjectFile *objfile = image_module_sp->GetObjectFile();
445                     if (objfile)
446                         objfile->GetDependentModules(dependent_files);
447                 }
448             }
449         }
450 
451         // Now see if we know the target triple, and if so, create our scratch AST context:
452         if (m_arch.IsValid())
453         {
454             m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
455         }
456     }
457 
458     UpdateInstanceName();
459 }
460 
461 
462 bool
463 Target::SetArchitecture (const ArchSpec &arch_spec)
464 {
465     if (m_arch == arch_spec)
466     {
467         // If we're setting the architecture to our current architecture, we
468         // don't need to do anything.
469         return true;
470     }
471     else if (!m_arch.IsValid())
472     {
473         // If we haven't got a valid arch spec, then we just need to set it.
474         m_arch = arch_spec;
475         return true;
476     }
477     else
478     {
479         // If we have an executable file, try to reset the executable to the desired architecture
480         m_arch = arch_spec;
481         ModuleSP executable_sp = GetExecutableModule ();
482         m_images.Clear();
483         m_scratch_ast_context_ap.reset();
484         // Need to do something about unsetting breakpoints.
485 
486         if (executable_sp)
487         {
488             FileSpec exec_file_spec = executable_sp->GetFileSpec();
489             Error error = ModuleList::GetSharedModule(exec_file_spec,
490                                                       arch_spec,
491                                                       NULL,
492                                                       NULL,
493                                                       0,
494                                                       executable_sp,
495                                                       NULL,
496                                                       NULL);
497 
498             if (!error.Fail() && executable_sp)
499             {
500                 SetExecutableModule (executable_sp, true);
501                 return true;
502             }
503             else
504             {
505                 return false;
506             }
507         }
508         else
509         {
510             return false;
511         }
512     }
513 }
514 
515 void
516 Target::ModuleAdded (ModuleSP &module_sp)
517 {
518     // A module is being added to this target for the first time
519     ModuleList module_list;
520     module_list.Append(module_sp);
521     ModulesDidLoad (module_list);
522 }
523 
524 void
525 Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp)
526 {
527     // A module is being added to this target for the first time
528     ModuleList module_list;
529     module_list.Append (old_module_sp);
530     ModulesDidUnload (module_list);
531     module_list.Clear ();
532     module_list.Append (new_module_sp);
533     ModulesDidLoad (module_list);
534 }
535 
536 void
537 Target::ModulesDidLoad (ModuleList &module_list)
538 {
539     m_breakpoint_list.UpdateBreakpoints (module_list, true);
540     // TODO: make event data that packages up the module_list
541     BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
542 }
543 
544 void
545 Target::ModulesDidUnload (ModuleList &module_list)
546 {
547     m_breakpoint_list.UpdateBreakpoints (module_list, false);
548 
549     // Remove the images from the target image list
550     m_images.Remove(module_list);
551 
552     // TODO: make event data that packages up the module_list
553     BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
554 }
555 
556 size_t
557 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
558 {
559     const Section *section = addr.GetSection();
560     if (section && section->GetModule())
561     {
562         ObjectFile *objfile = section->GetModule()->GetObjectFile();
563         if (objfile)
564         {
565             size_t bytes_read = section->ReadSectionDataFromObjectFile (objfile,
566                                                                         addr.GetOffset(),
567                                                                         dst,
568                                                                         dst_len);
569             if (bytes_read > 0)
570                 return bytes_read;
571             else
572                 error.SetErrorStringWithFormat("error reading data from section %s", section->GetName().GetCString());
573         }
574         else
575         {
576             error.SetErrorString("address isn't from a object file");
577         }
578     }
579     else
580     {
581         error.SetErrorString("address doesn't contain a section that points to a section in a object file");
582     }
583     return 0;
584 }
585 
586 size_t
587 Target::ReadMemory (const Address& addr, bool prefer_file_cache, void *dst, size_t dst_len, Error &error)
588 {
589     error.Clear();
590 
591     bool process_is_valid = m_process_sp && m_process_sp->IsAlive();
592 
593     size_t bytes_read = 0;
594     Address resolved_addr;
595     if (!addr.IsSectionOffset())
596     {
597         if (process_is_valid)
598             m_section_load_list.ResolveLoadAddress (addr.GetOffset(), resolved_addr);
599         else
600             m_images.ResolveFileAddress(addr.GetOffset(), resolved_addr);
601     }
602     if (!resolved_addr.IsValid())
603         resolved_addr = addr;
604 
605     if (prefer_file_cache)
606     {
607         bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
608         if (bytes_read > 0)
609             return bytes_read;
610     }
611 
612     if (process_is_valid)
613     {
614         lldb::addr_t load_addr = resolved_addr.GetLoadAddress (this);
615         if (load_addr == LLDB_INVALID_ADDRESS)
616         {
617             if (resolved_addr.GetModule() && resolved_addr.GetModule()->GetFileSpec())
618                 error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded.\n",
619                                                resolved_addr.GetModule()->GetFileSpec().GetFilename().AsCString(),
620                                                resolved_addr.GetFileAddress());
621             else
622                 error.SetErrorStringWithFormat("0x%llx can't be resolved.\n", resolved_addr.GetFileAddress());
623         }
624         else
625         {
626             bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
627             if (bytes_read != dst_len)
628             {
629                 if (error.Success())
630                 {
631                     if (bytes_read == 0)
632                         error.SetErrorStringWithFormat("Read memory from 0x%llx failed.\n", load_addr);
633                     else
634                         error.SetErrorStringWithFormat("Only %zu of %zu bytes were read from memory at 0x%llx.\n", bytes_read, dst_len, load_addr);
635                 }
636             }
637             if (bytes_read)
638                 return bytes_read;
639             // If the address is not section offset we have an address that
640             // doesn't resolve to any address in any currently loaded shared
641             // libaries and we failed to read memory so there isn't anything
642             // more we can do. If it is section offset, we might be able to
643             // read cached memory from the object file.
644             if (!resolved_addr.IsSectionOffset())
645                 return 0;
646         }
647     }
648 
649     if (!prefer_file_cache)
650     {
651         // If we didn't already try and read from the object file cache, then
652         // try it after failing to read from the process.
653         return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
654     }
655     return 0;
656 }
657 
658 
659 ModuleSP
660 Target::GetSharedModule
661 (
662     const FileSpec& file_spec,
663     const ArchSpec& arch,
664     const lldb_private::UUID *uuid_ptr,
665     const ConstString *object_name,
666     off_t object_offset,
667     Error *error_ptr
668 )
669 {
670     // Don't pass in the UUID so we can tell if we have a stale value in our list
671     ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
672     bool did_create_module = false;
673     ModuleSP module_sp;
674 
675     Error error;
676 
677     // If there are image search path entries, try to use them first to acquire a suitable image.
678     if (m_image_search_paths.GetSize())
679     {
680         FileSpec transformed_spec;
681         if (m_image_search_paths.RemapPath (file_spec.GetDirectory(), transformed_spec.GetDirectory()))
682         {
683             transformed_spec.GetFilename() = file_spec.GetFilename();
684             error = ModuleList::GetSharedModule (transformed_spec, arch, uuid_ptr, object_name, object_offset, module_sp, &old_module_sp, &did_create_module);
685         }
686     }
687 
688     // The platform is responsible for finding and caching an appropriate
689     // module in the shared module cache.
690     if (m_platform_sp)
691     {
692         FileSpec platform_file_spec;
693         error = m_platform_sp->GetSharedModule (file_spec,
694                                                 arch,
695                                                 uuid_ptr,
696                                                 object_name,
697                                                 object_offset,
698                                                 module_sp,
699                                                 &old_module_sp,
700                                                 &did_create_module);
701     }
702     else
703     {
704         error.SetErrorString("no platform is currently set");
705     }
706 
707     // If a module hasn't been found yet, use the unmodified path.
708     if (module_sp)
709     {
710         m_images.Append (module_sp);
711         if (did_create_module)
712         {
713             if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
714                 ModuleUpdated(old_module_sp, module_sp);
715             else
716                 ModuleAdded(module_sp);
717         }
718     }
719     if (error_ptr)
720         *error_ptr = error;
721     return module_sp;
722 }
723 
724 
725 Target *
726 Target::CalculateTarget ()
727 {
728     return this;
729 }
730 
731 Process *
732 Target::CalculateProcess ()
733 {
734     return NULL;
735 }
736 
737 Thread *
738 Target::CalculateThread ()
739 {
740     return NULL;
741 }
742 
743 StackFrame *
744 Target::CalculateStackFrame ()
745 {
746     return NULL;
747 }
748 
749 void
750 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
751 {
752     exe_ctx.target = this;
753     exe_ctx.process = NULL; // Do NOT fill in process...
754     exe_ctx.thread = NULL;
755     exe_ctx.frame = NULL;
756 }
757 
758 PathMappingList &
759 Target::GetImageSearchPathList ()
760 {
761     return m_image_search_paths;
762 }
763 
764 void
765 Target::ImageSearchPathsChanged
766 (
767     const PathMappingList &path_list,
768     void *baton
769 )
770 {
771     Target *target = (Target *)baton;
772     if (target->m_images.GetSize() > 1)
773     {
774         ModuleSP exe_module_sp (target->GetExecutableModule());
775         if (exe_module_sp)
776         {
777             target->m_images.Clear();
778             target->SetExecutableModule (exe_module_sp, true);
779         }
780     }
781 }
782 
783 ClangASTContext *
784 Target::GetScratchClangASTContext()
785 {
786     return m_scratch_ast_context_ap.get();
787 }
788 
789 void
790 Target::SettingsInitialize ()
791 {
792     UserSettingsControllerSP &usc = GetSettingsController();
793     usc.reset (new SettingsController);
794     UserSettingsController::InitializeSettingsController (usc,
795                                                           SettingsController::global_settings_table,
796                                                           SettingsController::instance_settings_table);
797 
798     // Now call SettingsInitialize() on each 'child' setting of Target
799     Process::SettingsInitialize ();
800 }
801 
802 void
803 Target::SettingsTerminate ()
804 {
805 
806     // Must call SettingsTerminate() on each settings 'child' of Target, before terminating Target's Settings.
807 
808     Process::SettingsTerminate ();
809 
810     // Now terminate Target Settings.
811 
812     UserSettingsControllerSP &usc = GetSettingsController();
813     UserSettingsController::FinalizeSettingsController (usc);
814     usc.reset();
815 }
816 
817 UserSettingsControllerSP &
818 Target::GetSettingsController ()
819 {
820     static UserSettingsControllerSP g_settings_controller;
821     return g_settings_controller;
822 }
823 
824 ArchSpec
825 Target::GetDefaultArchitecture ()
826 {
827     lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController());
828 
829     if (settings_controller_sp)
830         return static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture ();
831     return ArchSpec();
832 }
833 
834 void
835 Target::SetDefaultArchitecture (const ArchSpec& arch)
836 {
837     lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController());
838 
839     if (settings_controller_sp)
840         static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture () = arch;
841 }
842 
843 Target *
844 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
845 {
846     // The target can either exist in the "process" of ExecutionContext, or in
847     // the "target_sp" member of SymbolContext. This accessor helper function
848     // will get the target from one of these locations.
849 
850     Target *target = NULL;
851     if (sc_ptr != NULL)
852         target = sc_ptr->target_sp.get();
853     if (target == NULL)
854     {
855         if (exe_ctx_ptr != NULL && exe_ctx_ptr->process != NULL)
856             target = &exe_ctx_ptr->process->GetTarget();
857     }
858     return target;
859 }
860 
861 
862 void
863 Target::UpdateInstanceName ()
864 {
865     StreamString sstr;
866 
867     ModuleSP module_sp = GetExecutableModule();
868     if (module_sp)
869     {
870         sstr.Printf ("%s_%s",
871                      module_sp->GetFileSpec().GetFilename().AsCString(),
872                      module_sp->GetArchitecture().GetArchitectureName());
873         GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(),
874                                                          sstr.GetData());
875     }
876 }
877 
878 const char *
879 Target::GetExpressionPrefixContentsAsCString ()
880 {
881     if (m_expr_prefix_contents_sp)
882         return (const char *)m_expr_prefix_contents_sp->GetBytes();
883     return NULL;
884 }
885 
886 ExecutionResults
887 Target::EvaluateExpression
888 (
889     const char *expr_cstr,
890     StackFrame *frame,
891     bool unwind_on_error,
892     bool keep_in_memory,
893     lldb::DynamicValueType use_dynamic,
894     lldb::ValueObjectSP &result_valobj_sp
895 )
896 {
897     ExecutionResults execution_results = eExecutionSetupError;
898 
899     result_valobj_sp.reset();
900 
901     ExecutionContext exe_ctx;
902     if (frame)
903     {
904         frame->CalculateExecutionContext(exe_ctx);
905         Error error;
906         const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember |
907                                            StackFrame::eExpressionPathOptionsNoFragileObjcIvar;
908         lldb::VariableSP var_sp;
909         result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr,
910                                                                      use_dynamic,
911                                                                      expr_path_options,
912                                                                      var_sp,
913                                                                      error);
914     }
915     else if (m_process_sp)
916     {
917         m_process_sp->CalculateExecutionContext(exe_ctx);
918     }
919     else
920     {
921         CalculateExecutionContext(exe_ctx);
922     }
923 
924     if (result_valobj_sp)
925     {
926         execution_results = eExecutionCompleted;
927         // We got a result from the frame variable expression path above...
928         ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName());
929 
930         lldb::ValueObjectSP const_valobj_sp;
931 
932         // Check in case our value is already a constant value
933         if (result_valobj_sp->GetIsConstant())
934         {
935             const_valobj_sp = result_valobj_sp;
936             const_valobj_sp->SetName (persistent_variable_name);
937         }
938         else
939         {
940             if (use_dynamic != lldb::eNoDynamicValues)
941             {
942                 ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(use_dynamic);
943                 if (dynamic_sp)
944                     result_valobj_sp = dynamic_sp;
945             }
946 
947             const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name);
948         }
949 
950         lldb::ValueObjectSP live_valobj_sp = result_valobj_sp;
951 
952         result_valobj_sp = const_valobj_sp;
953 
954         ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp));
955         assert (clang_expr_variable_sp.get());
956 
957         // Set flags and live data as appropriate
958 
959         const Value &result_value = live_valobj_sp->GetValue();
960 
961         switch (result_value.GetValueType())
962         {
963         case Value::eValueTypeHostAddress:
964         case Value::eValueTypeFileAddress:
965             // we don't do anything with these for now
966             break;
967         case Value::eValueTypeScalar:
968             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
969             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
970             break;
971         case Value::eValueTypeLoadAddress:
972             clang_expr_variable_sp->m_live_sp = live_valobj_sp;
973             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
974             break;
975         }
976     }
977     else
978     {
979         // Make sure we aren't just trying to see the value of a persistent
980         // variable (something like "$0")
981         lldb::ClangExpressionVariableSP persistent_var_sp;
982         // Only check for persistent variables the expression starts with a '$'
983         if (expr_cstr[0] == '$')
984             persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
985 
986         if (persistent_var_sp)
987         {
988             result_valobj_sp = persistent_var_sp->GetValueObject ();
989             execution_results = eExecutionCompleted;
990         }
991         else
992         {
993             const char *prefix = GetExpressionPrefixContentsAsCString();
994 
995             execution_results = ClangUserExpression::Evaluate (exe_ctx,
996                                                                unwind_on_error,
997                                                                keep_in_memory,
998                                                                expr_cstr,
999                                                                prefix,
1000                                                                result_valobj_sp);
1001         }
1002     }
1003     return execution_results;
1004 }
1005 
1006 lldb::user_id_t
1007 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1008 {
1009     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1010     new_hook_sp.reset (new StopHook(GetSP(), new_uid));
1011     m_stop_hooks[new_uid] = new_hook_sp;
1012     return new_uid;
1013 }
1014 
1015 bool
1016 Target::RemoveStopHookByID (lldb::user_id_t user_id)
1017 {
1018     size_t num_removed;
1019     num_removed = m_stop_hooks.erase (user_id);
1020     if (num_removed == 0)
1021         return false;
1022     else
1023         return true;
1024 }
1025 
1026 void
1027 Target::RemoveAllStopHooks ()
1028 {
1029     m_stop_hooks.clear();
1030 }
1031 
1032 Target::StopHookSP
1033 Target::GetStopHookByID (lldb::user_id_t user_id)
1034 {
1035     StopHookSP found_hook;
1036 
1037     StopHookCollection::iterator specified_hook_iter;
1038     specified_hook_iter = m_stop_hooks.find (user_id);
1039     if (specified_hook_iter != m_stop_hooks.end())
1040         found_hook = (*specified_hook_iter).second;
1041     return found_hook;
1042 }
1043 
1044 bool
1045 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1046 {
1047     StopHookCollection::iterator specified_hook_iter;
1048     specified_hook_iter = m_stop_hooks.find (user_id);
1049     if (specified_hook_iter == m_stop_hooks.end())
1050         return false;
1051 
1052     (*specified_hook_iter).second->SetIsActive (active_state);
1053     return true;
1054 }
1055 
1056 void
1057 Target::SetAllStopHooksActiveState (bool active_state)
1058 {
1059     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1060     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1061     {
1062         (*pos).second->SetIsActive (active_state);
1063     }
1064 }
1065 
1066 void
1067 Target::RunStopHooks ()
1068 {
1069     if (!m_process_sp)
1070         return;
1071 
1072     if (m_stop_hooks.empty())
1073         return;
1074 
1075     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1076 
1077     // If there aren't any active stop hooks, don't bother either:
1078     bool any_active_hooks = false;
1079     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1080     {
1081         if ((*pos).second->IsActive())
1082         {
1083             any_active_hooks = true;
1084             break;
1085         }
1086     }
1087     if (!any_active_hooks)
1088         return;
1089 
1090     CommandReturnObject result;
1091 
1092     std::vector<ExecutionContext> exc_ctx_with_reasons;
1093     std::vector<SymbolContext> sym_ctx_with_reasons;
1094 
1095     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1096     size_t num_threads = cur_threadlist.GetSize();
1097     for (size_t i = 0; i < num_threads; i++)
1098     {
1099         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1100         if (cur_thread_sp->ThreadStoppedForAReason())
1101         {
1102             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1103             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1104             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1105         }
1106     }
1107 
1108     // If no threads stopped for a reason, don't run the stop-hooks.
1109     size_t num_exe_ctx = exc_ctx_with_reasons.size();
1110     if (num_exe_ctx == 0)
1111         return;
1112 
1113     StreamSP output_stream (new StreamAsynchronousIO (m_debugger.GetCommandInterpreter(),
1114                                                       CommandInterpreter::eBroadcastBitAsynchronousOutputData));
1115     StreamSP error_stream (new StreamAsynchronousIO (m_debugger.GetCommandInterpreter(),
1116                                                      CommandInterpreter::eBroadcastBitAsynchronousErrorData));
1117     result.SetImmediateOutputStream (output_stream);
1118     result.SetImmediateErrorStream (error_stream);
1119 
1120     bool keep_going = true;
1121     bool hooks_ran = false;
1122     bool print_hook_header;
1123     bool print_thread_header;
1124 
1125     if (num_exe_ctx == 1)
1126         print_thread_header = false;
1127     else
1128         print_thread_header = true;
1129 
1130     if (m_stop_hooks.size() == 1)
1131         print_hook_header = false;
1132     else
1133         print_hook_header = true;
1134 
1135     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
1136     {
1137         // result.Clear();
1138         StopHookSP cur_hook_sp = (*pos).second;
1139         if (!cur_hook_sp->IsActive())
1140             continue;
1141 
1142         bool any_thread_matched = false;
1143         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
1144         {
1145             if ((cur_hook_sp->GetSpecifier () == NULL
1146                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
1147                 && (cur_hook_sp->GetThreadSpecifier() == NULL
1148                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].thread)))
1149             {
1150                 if (!hooks_ran)
1151                 {
1152                     result.AppendMessage("\n** Stop Hooks **");
1153                     hooks_ran = true;
1154                 }
1155                 if (print_hook_header && !any_thread_matched)
1156                 {
1157                     result.AppendMessageWithFormat("\n- Hook %d\n", cur_hook_sp->GetID());
1158                     any_thread_matched = true;
1159                 }
1160 
1161                 if (print_thread_header)
1162                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].thread->GetIndexID());
1163 
1164                 bool stop_on_continue = true;
1165                 bool stop_on_error = true;
1166                 bool echo_commands = false;
1167                 bool print_results = true;
1168                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
1169                                                                       &exc_ctx_with_reasons[i],
1170                                                                       stop_on_continue,
1171                                                                       stop_on_error,
1172                                                                       echo_commands,
1173                                                                       print_results,
1174                                                                       result);
1175 
1176                 // If the command started the target going again, we should bag out of
1177                 // running the stop hooks.
1178                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
1179                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
1180                 {
1181                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %d set the program running.", cur_hook_sp->GetID());
1182                     keep_going = false;
1183                 }
1184             }
1185         }
1186     }
1187     if (hooks_ran)
1188         result.AppendMessage ("\n** End Stop Hooks **\n");
1189 
1190     result.GetImmediateOutputStream()->Flush();
1191     result.GetImmediateErrorStream()->Flush();
1192 }
1193 
1194 //--------------------------------------------------------------
1195 // class Target::StopHook
1196 //--------------------------------------------------------------
1197 
1198 
1199 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
1200         UserID (uid),
1201         m_target_sp (target_sp),
1202         m_commands (),
1203         m_specifier_sp (),
1204         m_thread_spec_ap(NULL),
1205         m_active (true)
1206 {
1207 }
1208 
1209 Target::StopHook::StopHook (const StopHook &rhs) :
1210         UserID (rhs.GetID()),
1211         m_target_sp (rhs.m_target_sp),
1212         m_commands (rhs.m_commands),
1213         m_specifier_sp (rhs.m_specifier_sp),
1214         m_thread_spec_ap (NULL),
1215         m_active (rhs.m_active)
1216 {
1217     if (rhs.m_thread_spec_ap.get() != NULL)
1218         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
1219 }
1220 
1221 
1222 Target::StopHook::~StopHook ()
1223 {
1224 }
1225 
1226 void
1227 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
1228 {
1229     m_thread_spec_ap.reset (specifier);
1230 }
1231 
1232 
1233 void
1234 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
1235 {
1236     int indent_level = s->GetIndentLevel();
1237 
1238     s->SetIndentLevel(indent_level + 2);
1239 
1240     s->Printf ("Hook: %d\n", GetID());
1241     if (m_active)
1242         s->Indent ("State: enabled\n");
1243     else
1244         s->Indent ("State: disabled\n");
1245 
1246     if (m_specifier_sp)
1247     {
1248         s->Indent();
1249         s->PutCString ("Specifier:\n");
1250         s->SetIndentLevel (indent_level + 4);
1251         m_specifier_sp->GetDescription (s, level);
1252         s->SetIndentLevel (indent_level + 2);
1253     }
1254 
1255     if (m_thread_spec_ap.get() != NULL)
1256     {
1257         StreamString tmp;
1258         s->Indent("Thread:\n");
1259         m_thread_spec_ap->GetDescription (&tmp, level);
1260         s->SetIndentLevel (indent_level + 4);
1261         s->Indent (tmp.GetData());
1262         s->PutCString ("\n");
1263         s->SetIndentLevel (indent_level + 2);
1264     }
1265 
1266     s->Indent ("Commands: \n");
1267     s->SetIndentLevel (indent_level + 4);
1268     uint32_t num_commands = m_commands.GetSize();
1269     for (uint32_t i = 0; i < num_commands; i++)
1270     {
1271         s->Indent(m_commands.GetStringAtIndex(i));
1272         s->PutCString ("\n");
1273     }
1274     s->SetIndentLevel (indent_level);
1275 }
1276 
1277 
1278 //--------------------------------------------------------------
1279 // class Target::SettingsController
1280 //--------------------------------------------------------------
1281 
1282 Target::SettingsController::SettingsController () :
1283     UserSettingsController ("target", Debugger::GetSettingsController()),
1284     m_default_architecture ()
1285 {
1286     m_default_settings.reset (new TargetInstanceSettings (*this, false,
1287                                                           InstanceSettings::GetDefaultName().AsCString()));
1288 }
1289 
1290 Target::SettingsController::~SettingsController ()
1291 {
1292 }
1293 
1294 lldb::InstanceSettingsSP
1295 Target::SettingsController::CreateInstanceSettings (const char *instance_name)
1296 {
1297     TargetInstanceSettings *new_settings = new TargetInstanceSettings (*GetSettingsController(),
1298                                                                        false,
1299                                                                        instance_name);
1300     lldb::InstanceSettingsSP new_settings_sp (new_settings);
1301     return new_settings_sp;
1302 }
1303 
1304 
1305 #define TSC_DEFAULT_ARCH      "default-arch"
1306 #define TSC_EXPR_PREFIX       "expr-prefix"
1307 #define TSC_PREFER_DYNAMIC    "prefer-dynamic-value"
1308 #define TSC_SKIP_PROLOGUE     "skip-prologue"
1309 #define TSC_SOURCE_MAP        "source-map"
1310 
1311 
1312 static const ConstString &
1313 GetSettingNameForDefaultArch ()
1314 {
1315     static ConstString g_const_string (TSC_DEFAULT_ARCH);
1316     return g_const_string;
1317 }
1318 
1319 static const ConstString &
1320 GetSettingNameForExpressionPrefix ()
1321 {
1322     static ConstString g_const_string (TSC_EXPR_PREFIX);
1323     return g_const_string;
1324 }
1325 
1326 static const ConstString &
1327 GetSettingNameForPreferDynamicValue ()
1328 {
1329     static ConstString g_const_string (TSC_PREFER_DYNAMIC);
1330     return g_const_string;
1331 }
1332 
1333 static const ConstString &
1334 GetSettingNameForSourcePathMap ()
1335 {
1336     static ConstString g_const_string (TSC_SOURCE_MAP);
1337     return g_const_string;
1338 }
1339 
1340 static const ConstString &
1341 GetSettingNameForSkipPrologue ()
1342 {
1343     static ConstString g_const_string (TSC_SKIP_PROLOGUE);
1344     return g_const_string;
1345 }
1346 
1347 
1348 
1349 bool
1350 Target::SettingsController::SetGlobalVariable (const ConstString &var_name,
1351                                                const char *index_value,
1352                                                const char *value,
1353                                                const SettingEntry &entry,
1354                                                const VarSetOperationType op,
1355                                                Error&err)
1356 {
1357     if (var_name == GetSettingNameForDefaultArch())
1358     {
1359         m_default_architecture.SetTriple (value, NULL);
1360         if (!m_default_architecture.IsValid())
1361             err.SetErrorStringWithFormat ("'%s' is not a valid architecture or triple.", value);
1362     }
1363     return true;
1364 }
1365 
1366 
1367 bool
1368 Target::SettingsController::GetGlobalVariable (const ConstString &var_name,
1369                                                StringList &value,
1370                                                Error &err)
1371 {
1372     if (var_name == GetSettingNameForDefaultArch())
1373     {
1374         // If the arch is invalid (the default), don't show a string for it
1375         if (m_default_architecture.IsValid())
1376             value.AppendString (m_default_architecture.GetArchitectureName());
1377         return true;
1378     }
1379     else
1380         err.SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
1381 
1382     return false;
1383 }
1384 
1385 //--------------------------------------------------------------
1386 // class TargetInstanceSettings
1387 //--------------------------------------------------------------
1388 
1389 TargetInstanceSettings::TargetInstanceSettings
1390 (
1391     UserSettingsController &owner,
1392     bool live_instance,
1393     const char *name
1394 ) :
1395     InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
1396     m_expr_prefix_file (),
1397     m_expr_prefix_contents_sp (),
1398     m_prefer_dynamic_value (2),
1399     m_skip_prologue (true, true),
1400     m_source_map (NULL, NULL)
1401 {
1402     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
1403     // until the vtables for TargetInstanceSettings are properly set up, i.e. AFTER all the initializers.
1404     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
1405     // This is true for CreateInstanceName() too.
1406 
1407     if (GetInstanceName () == InstanceSettings::InvalidName())
1408     {
1409         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
1410         m_owner.RegisterInstanceSettings (this);
1411     }
1412 
1413     if (live_instance)
1414     {
1415         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1416         CopyInstanceSettings (pending_settings,false);
1417     }
1418 }
1419 
1420 TargetInstanceSettings::TargetInstanceSettings (const TargetInstanceSettings &rhs) :
1421     InstanceSettings (*Target::GetSettingsController(), CreateInstanceName().AsCString()),
1422     m_expr_prefix_file (rhs.m_expr_prefix_file),
1423     m_expr_prefix_contents_sp (rhs.m_expr_prefix_contents_sp),
1424     m_prefer_dynamic_value (rhs.m_prefer_dynamic_value),
1425     m_skip_prologue (rhs.m_skip_prologue),
1426     m_source_map (rhs.m_source_map)
1427 {
1428     if (m_instance_name != InstanceSettings::GetDefaultName())
1429     {
1430         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
1431         CopyInstanceSettings (pending_settings,false);
1432     }
1433 }
1434 
1435 TargetInstanceSettings::~TargetInstanceSettings ()
1436 {
1437 }
1438 
1439 TargetInstanceSettings&
1440 TargetInstanceSettings::operator= (const TargetInstanceSettings &rhs)
1441 {
1442     if (this != &rhs)
1443     {
1444     }
1445 
1446     return *this;
1447 }
1448 
1449 void
1450 TargetInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
1451                                                         const char *index_value,
1452                                                         const char *value,
1453                                                         const ConstString &instance_name,
1454                                                         const SettingEntry &entry,
1455                                                         VarSetOperationType op,
1456                                                         Error &err,
1457                                                         bool pending)
1458 {
1459     if (var_name == GetSettingNameForExpressionPrefix ())
1460     {
1461         err = UserSettingsController::UpdateFileSpecOptionValue (value, op, m_expr_prefix_file);
1462         if (err.Success())
1463         {
1464             switch (op)
1465             {
1466             default:
1467                 break;
1468             case eVarSetOperationAssign:
1469             case eVarSetOperationAppend:
1470                 {
1471                     if (!m_expr_prefix_file.GetCurrentValue().Exists())
1472                     {
1473                         err.SetErrorToGenericError ();
1474                         err.SetErrorStringWithFormat ("%s does not exist.\n", value);
1475                         return;
1476                     }
1477 
1478                     m_expr_prefix_contents_sp = m_expr_prefix_file.GetCurrentValue().ReadFileContents();
1479 
1480                     if (!m_expr_prefix_contents_sp && m_expr_prefix_contents_sp->GetByteSize() == 0)
1481                     {
1482                         err.SetErrorStringWithFormat ("Couldn't read data from '%s'\n", value);
1483                         m_expr_prefix_contents_sp.reset();
1484                     }
1485                 }
1486                 break;
1487             case eVarSetOperationClear:
1488                 m_expr_prefix_contents_sp.reset();
1489             }
1490         }
1491     }
1492     else if (var_name == GetSettingNameForPreferDynamicValue())
1493     {
1494         int new_value;
1495         UserSettingsController::UpdateEnumVariable (g_dynamic_value_types, &new_value, value, err);
1496         if (err.Success())
1497             m_prefer_dynamic_value = new_value;
1498     }
1499     else if (var_name == GetSettingNameForSkipPrologue())
1500     {
1501         err = UserSettingsController::UpdateBooleanOptionValue (value, op, m_skip_prologue);
1502     }
1503     else if (var_name == GetSettingNameForSourcePathMap ())
1504     {
1505         switch (op)
1506         {
1507             case eVarSetOperationReplace:
1508             case eVarSetOperationInsertBefore:
1509             case eVarSetOperationInsertAfter:
1510             case eVarSetOperationRemove:
1511             default:
1512                 break;
1513             case eVarSetOperationAssign:
1514                 m_source_map.Clear(true);
1515                 // Fall through to append....
1516             case eVarSetOperationAppend:
1517                 {
1518                     Args args(value);
1519                     const uint32_t argc = args.GetArgumentCount();
1520                     if (argc & 1 || argc == 0)
1521                     {
1522                         err.SetErrorStringWithFormat ("an even number of paths must be supplied to to the source-map setting: %u arguments given", argc);
1523                     }
1524                     else
1525                     {
1526                         char resolved_new_path[PATH_MAX];
1527                         FileSpec file_spec;
1528                         const char *old_path;
1529                         for (uint32_t idx = 0; (old_path = args.GetArgumentAtIndex(idx)) != NULL; idx += 2)
1530                         {
1531                             const char *new_path = args.GetArgumentAtIndex(idx+1);
1532                             assert (new_path); // We have an even number of paths, this shouldn't happen!
1533 
1534                             file_spec.SetFile(new_path, true);
1535                             if (file_spec.Exists())
1536                             {
1537                                 if (file_spec.GetPath (resolved_new_path, sizeof(resolved_new_path)) >= sizeof(resolved_new_path))
1538                                 {
1539                                     err.SetErrorStringWithFormat("new path '%s' is too long", new_path);
1540                                     return;
1541                                 }
1542                             }
1543                             else
1544                             {
1545                                 err.SetErrorStringWithFormat("new path '%s' doesn't exist", new_path);
1546                                 return;
1547                             }
1548                             m_source_map.Append(ConstString (old_path), ConstString (resolved_new_path), true);
1549                         }
1550                     }
1551                 }
1552                 break;
1553 
1554             case eVarSetOperationClear:
1555                 m_source_map.Clear(true);
1556                 break;
1557         }
1558     }
1559 }
1560 
1561 void
1562 TargetInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, bool pending)
1563 {
1564     TargetInstanceSettings *new_settings_ptr = static_cast <TargetInstanceSettings *> (new_settings.get());
1565 
1566     if (!new_settings_ptr)
1567         return;
1568 
1569     m_expr_prefix_file          = new_settings_ptr->m_expr_prefix_file;
1570     m_expr_prefix_contents_sp   = new_settings_ptr->m_expr_prefix_contents_sp;
1571     m_prefer_dynamic_value      = new_settings_ptr->m_prefer_dynamic_value;
1572     m_skip_prologue             = new_settings_ptr->m_skip_prologue;
1573 }
1574 
1575 bool
1576 TargetInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
1577                                                   const ConstString &var_name,
1578                                                   StringList &value,
1579                                                   Error *err)
1580 {
1581     if (var_name == GetSettingNameForExpressionPrefix ())
1582     {
1583         char path[PATH_MAX];
1584         const size_t path_len = m_expr_prefix_file.GetCurrentValue().GetPath (path, sizeof(path));
1585         if (path_len > 0)
1586             value.AppendString (path, path_len);
1587     }
1588     else if (var_name == GetSettingNameForPreferDynamicValue())
1589     {
1590         value.AppendString (g_dynamic_value_types[m_prefer_dynamic_value].string_value);
1591     }
1592     else if (var_name == GetSettingNameForSkipPrologue())
1593     {
1594         if (m_skip_prologue)
1595             value.AppendString ("true");
1596         else
1597             value.AppendString ("false");
1598     }
1599     else if (var_name == GetSettingNameForSourcePathMap ())
1600     {
1601     }
1602     else
1603     {
1604         if (err)
1605             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
1606         return false;
1607     }
1608 
1609     return true;
1610 }
1611 
1612 const ConstString
1613 TargetInstanceSettings::CreateInstanceName ()
1614 {
1615     StreamString sstr;
1616     static int instance_count = 1;
1617 
1618     sstr.Printf ("target_%d", instance_count);
1619     ++instance_count;
1620 
1621     const ConstString ret_val (sstr.GetData());
1622     return ret_val;
1623 }
1624 
1625 //--------------------------------------------------
1626 // Target::SettingsController Variable Tables
1627 //--------------------------------------------------
1628 OptionEnumValueElement
1629 TargetInstanceSettings::g_dynamic_value_types[] =
1630 {
1631 { eNoDynamicValues,     "no-dynamic-values",  "Don't calculate the dynamic type of values"},
1632 { eDynamicCanRunTarget,        "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
1633 { eDynamicDontRunTarget,       "no-run-target",    "Calculate the dynamic type of values, but don't run the target."},
1634 { 0, NULL, NULL }
1635 };
1636 
1637 SettingEntry
1638 Target::SettingsController::global_settings_table[] =
1639 {
1640     // var-name           var-type           default      enum  init'd hidden help-text
1641     // =================  ================== ===========  ====  ====== ====== =========================================================================
1642     { TSC_DEFAULT_ARCH  , eSetVarTypeString , NULL      , NULL, false, false, "Default architecture to choose, when there's a choice." },
1643     { NULL              , eSetVarTypeNone   , NULL      , NULL, false, false, NULL }
1644 };
1645 
1646 SettingEntry
1647 Target::SettingsController::instance_settings_table[] =
1648 {
1649     // var-name           var-type           default         enum                    init'd hidden help-text
1650     // =================  ================== =============== ======================= ====== ====== =========================================================================
1651     { TSC_EXPR_PREFIX   , eSetVarTypeString , NULL          , NULL,                  false, false, "Path to a file containing expressions to be prepended to all expressions." },
1652     { TSC_PREFER_DYNAMIC, eSetVarTypeEnum ,  "no-run-target", g_dynamic_value_types, false, false, "Should printed values be shown as their dynamic value." },
1653     { TSC_SKIP_PROLOGUE , eSetVarTypeBoolean ,"true"        , NULL,                  false, false, "Skip function prologues when setting breakpoints by name." },
1654     { TSC_SOURCE_MAP    , eSetVarTypeArray   ,NULL          , NULL,                  false, false, "Source path remappings to use when locating source files from debug information." },
1655     { NULL              , eSetVarTypeNone   , NULL          , NULL,                  false, false, NULL }
1656 };
1657