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