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