1 //===-- Target.cpp ----------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Target/Target.h"
11 
12 // C Includes
13 // C++ Includes
14 // Other libraries and framework includes
15 // Project includes
16 #include "lldb/Breakpoint/BreakpointResolver.h"
17 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
18 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
19 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
20 #include "lldb/Breakpoint/BreakpointResolverName.h"
21 #include "lldb/Breakpoint/WatchpointLocation.h"
22 #include "lldb/Core/Debugger.h"
23 #include "lldb/Core/Event.h"
24 #include "lldb/Core/Log.h"
25 #include "lldb/Core/StreamAsynchronousIO.h"
26 #include "lldb/Core/StreamString.h"
27 #include "lldb/Core/Timer.h"
28 #include "lldb/Core/ValueObject.h"
29 #include "lldb/Expression/ClangUserExpression.h"
30 #include "lldb/Host/Host.h"
31 #include "lldb/Interpreter/CommandInterpreter.h"
32 #include "lldb/Interpreter/CommandReturnObject.h"
33 #include "lldb/lldb-private-log.h"
34 #include "lldb/Symbol/ObjectFile.h"
35 #include "lldb/Target/Process.h"
36 #include "lldb/Target/StackFrame.h"
37 #include "lldb/Target/Thread.h"
38 #include "lldb/Target/ThreadSpec.h"
39 
40 using namespace lldb;
41 using namespace lldb_private;
42 
43 //----------------------------------------------------------------------
44 // Target constructor
45 //----------------------------------------------------------------------
46 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
47     Broadcaster ("lldb.target"),
48     ExecutionContextScope (),
49     TargetInstanceSettings (*GetSettingsController()),
50     m_debugger (debugger),
51     m_platform_sp (platform_sp),
52     m_mutex (Mutex::eMutexTypeRecursive),
53     m_arch (target_arch),
54     m_images (),
55     m_section_load_list (),
56     m_breakpoint_list (false),
57     m_internal_breakpoint_list (true),
58     m_watchpoint_location_list (),
59     m_process_sp (),
60     m_search_filter_sp (),
61     m_image_search_paths (ImageSearchPathsChanged, this),
62     m_scratch_ast_context_ap (NULL),
63     m_persistent_variables (),
64     m_source_manager(*this),
65     m_stop_hooks (),
66     m_stop_hook_next_id (0),
67     m_suppress_stop_hooks (false)
68 {
69     SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
70     SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
71     SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
72 
73     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
74     if (log)
75         log->Printf ("%p Target::Target()", this);
76 }
77 
78 //----------------------------------------------------------------------
79 // Destructor
80 //----------------------------------------------------------------------
81 Target::~Target()
82 {
83     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
84     if (log)
85         log->Printf ("%p Target::~Target()", this);
86     DeleteCurrentProcess ();
87 }
88 
89 void
90 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
91 {
92 //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
93     if (description_level != lldb::eDescriptionLevelBrief)
94     {
95         s->Indent();
96         s->PutCString("Target\n");
97         s->IndentMore();
98             m_images.Dump(s);
99             m_breakpoint_list.Dump(s);
100             m_internal_breakpoint_list.Dump(s);
101         s->IndentLess();
102     }
103     else
104     {
105         Module *exe_module = GetExecutableModulePointer();
106         if (exe_module)
107             s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
108         else
109             s->PutCString ("No executable module.");
110     }
111 }
112 
113 void
114 Target::DeleteCurrentProcess ()
115 {
116     if (m_process_sp.get())
117     {
118         m_section_load_list.Clear();
119         if (m_process_sp->IsAlive())
120             m_process_sp->Destroy();
121 
122         m_process_sp->Finalize();
123 
124         // Do any cleanup of the target we need to do between process instances.
125         // NB It is better to do this before destroying the process in case the
126         // clean up needs some help from the process.
127         m_breakpoint_list.ClearAllBreakpointSites();
128         m_internal_breakpoint_list.ClearAllBreakpointSites();
129         // Disable watchpoint locations just on the debugger side.
130         DisableAllWatchpointLocations(false);
131         m_process_sp.reset();
132     }
133 }
134 
135 const lldb::ProcessSP &
136 Target::CreateProcess (Listener &listener, const char *plugin_name)
137 {
138     DeleteCurrentProcess ();
139     m_process_sp.reset(Process::FindPlugin(*this, plugin_name, listener));
140     return m_process_sp;
141 }
142 
143 const lldb::ProcessSP &
144 Target::GetProcessSP () const
145 {
146     return m_process_sp;
147 }
148 
149 lldb::TargetSP
150 Target::GetSP()
151 {
152     // This object contains an instrusive ref count base class so we can
153     // easily make a shared pointer to this object
154     return TargetSP(this);
155 }
156 
157 void
158 Target::Destroy()
159 {
160     Mutex::Locker locker (m_mutex);
161     DeleteCurrentProcess ();
162     m_platform_sp.reset();
163     m_arch.Clear();
164     m_images.Clear();
165     m_section_load_list.Clear();
166     const bool notify = false;
167     m_breakpoint_list.RemoveAll(notify);
168     m_internal_breakpoint_list.RemoveAll(notify);
169     m_last_created_breakpoint.reset();
170     m_last_created_watchpoint_location.reset();
171     m_search_filter_sp.reset();
172     m_image_search_paths.Clear(notify);
173     m_scratch_ast_context_ap.reset();
174     m_persistent_variables.Clear();
175     m_stop_hooks.clear();
176     m_stop_hook_next_id = 0;
177     m_suppress_stop_hooks = false;
178 }
179 
180 
181 BreakpointList &
182 Target::GetBreakpointList(bool internal)
183 {
184     if (internal)
185         return m_internal_breakpoint_list;
186     else
187         return m_breakpoint_list;
188 }
189 
190 const BreakpointList &
191 Target::GetBreakpointList(bool internal) const
192 {
193     if (internal)
194         return m_internal_breakpoint_list;
195     else
196         return m_breakpoint_list;
197 }
198 
199 BreakpointSP
200 Target::GetBreakpointByID (break_id_t break_id)
201 {
202     BreakpointSP bp_sp;
203 
204     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
205         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
206     else
207         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
208 
209     return bp_sp;
210 }
211 
212 BreakpointSP
213 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
214                   const FileSpecList *source_file_spec_list,
215                   RegularExpression &source_regex,
216                   bool internal)
217 {
218     SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list));
219     BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex (NULL, source_regex));
220     return CreateBreakpoint (filter_sp, resolver_sp, internal);
221 }
222 
223 
224 BreakpointSP
225 Target::CreateBreakpoint (const FileSpecList *containingModules, const FileSpec &file, uint32_t line_no, bool check_inlines, bool internal)
226 {
227     SearchFilterSP filter_sp(GetSearchFilterForModuleList (containingModules));
228     BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL, file, line_no, check_inlines));
229     return CreateBreakpoint (filter_sp, resolver_sp, internal);
230 }
231 
232 
233 BreakpointSP
234 Target::CreateBreakpoint (lldb::addr_t addr, bool internal)
235 {
236     Address so_addr;
237     // Attempt to resolve our load address if possible, though it is ok if
238     // it doesn't resolve to section/offset.
239 
240     // Try and resolve as a load address if possible
241     m_section_load_list.ResolveLoadAddress(addr, so_addr);
242     if (!so_addr.IsValid())
243     {
244         // The address didn't resolve, so just set this as an absolute address
245         so_addr.SetOffset (addr);
246     }
247     BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal));
248     return bp_sp;
249 }
250 
251 BreakpointSP
252 Target::CreateBreakpoint (Address &addr, bool internal)
253 {
254     TargetSP target_sp = this->GetSP();
255     SearchFilterSP filter_sp(new SearchFilter (target_sp));
256     BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
257     return CreateBreakpoint (filter_sp, resolver_sp, internal);
258 }
259 
260 BreakpointSP
261 Target::CreateBreakpoint (const FileSpecList *containingModules,
262                           const FileSpecList *containingSourceFiles,
263                           const char *func_name,
264                           uint32_t func_name_type_mask,
265                           bool internal,
266                           LazyBool skip_prologue)
267 {
268     BreakpointSP bp_sp;
269     if (func_name)
270     {
271         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
272 
273         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
274                                                                       func_name,
275                                                                       func_name_type_mask,
276                                                                       Breakpoint::Exact,
277                                                                       skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
278         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal);
279     }
280     return bp_sp;
281 }
282 
283 
284 SearchFilterSP
285 Target::GetSearchFilterForModule (const FileSpec *containingModule)
286 {
287     SearchFilterSP filter_sp;
288     lldb::TargetSP target_sp = this->GetSP();
289     if (containingModule != NULL)
290     {
291         // TODO: We should look into sharing module based search filters
292         // across many breakpoints like we do for the simple target based one
293         filter_sp.reset (new SearchFilterByModule (target_sp, *containingModule));
294     }
295     else
296     {
297         if (m_search_filter_sp.get() == NULL)
298             m_search_filter_sp.reset (new SearchFilter (target_sp));
299         filter_sp = m_search_filter_sp;
300     }
301     return filter_sp;
302 }
303 
304 SearchFilterSP
305 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules)
306 {
307     SearchFilterSP filter_sp;
308     lldb::TargetSP target_sp = this->GetSP();
309     if (containingModules && containingModules->GetSize() != 0)
310     {
311         // TODO: We should look into sharing module based search filters
312         // across many breakpoints like we do for the simple target based one
313         filter_sp.reset (new SearchFilterByModuleList (target_sp, *containingModules));
314     }
315     else
316     {
317         if (m_search_filter_sp.get() == NULL)
318             m_search_filter_sp.reset (new SearchFilter (target_sp));
319         filter_sp = m_search_filter_sp;
320     }
321     return filter_sp;
322 }
323 
324 SearchFilterSP
325 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules, const FileSpecList *containingSourceFiles)
326 {
327     if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0)
328         return GetSearchFilterForModuleList(containingModules);
329 
330     SearchFilterSP filter_sp;
331     lldb::TargetSP target_sp = this->GetSP();
332     if (containingModules == NULL)
333     {
334         // We could make a special "CU List only SearchFilter".  Better yet was if these could be composable,
335         // but that will take a little reworking.
336 
337         filter_sp.reset (new SearchFilterByModuleListAndCU (target_sp, FileSpecList(), *containingSourceFiles));
338     }
339     else
340     {
341         filter_sp.reset (new SearchFilterByModuleListAndCU (target_sp, *containingModules, *containingSourceFiles));
342     }
343     return filter_sp;
344 }
345 
346 BreakpointSP
347 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
348                           const FileSpecList *containingSourceFiles,
349                           RegularExpression &func_regex,
350                           bool internal,
351                           LazyBool skip_prologue)
352 {
353     SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
354     BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
355                                                                  func_regex,
356                                                                  skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
357 
358     return CreateBreakpoint (filter_sp, resolver_sp, internal);
359 }
360 
361 BreakpointSP
362 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal)
363 {
364     BreakpointSP bp_sp;
365     if (filter_sp && resolver_sp)
366     {
367         bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp));
368         resolver_sp->SetBreakpoint (bp_sp.get());
369 
370         if (internal)
371             m_internal_breakpoint_list.Add (bp_sp, false);
372         else
373             m_breakpoint_list.Add (bp_sp, true);
374 
375         LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
376         if (log)
377         {
378             StreamString s;
379             bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
380             log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
381         }
382 
383         bp_sp->ResolveBreakpoint();
384     }
385 
386     if (!internal && bp_sp)
387     {
388         m_last_created_breakpoint = bp_sp;
389     }
390 
391     return bp_sp;
392 }
393 
394 bool
395 Target::ProcessIsValid()
396 {
397     return (m_process_sp && m_process_sp->IsAlive());
398 }
399 
400 // See also WatchpointLocation::SetWatchpointType(uint32_t type) and
401 // the OptionGroupWatchpoint::WatchType enum type.
402 WatchpointLocationSP
403 Target::CreateWatchpointLocation(lldb::addr_t addr, size_t size, uint32_t type)
404 {
405     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
406     if (log)
407         log->Printf("Target::%s (addr = 0x%8.8llx size = %zu type = %u)\n",
408                     __FUNCTION__, addr, size, type);
409 
410     WatchpointLocationSP wp_loc_sp;
411     if (!ProcessIsValid())
412         return wp_loc_sp;
413     if (addr == LLDB_INVALID_ADDRESS || size == 0)
414         return wp_loc_sp;
415 
416     // Currently we only support one watchpoint location per address, with total
417     // number of watchpoint locations limited by the hardware which the inferior
418     // is running on.
419     WatchpointLocationSP matched_sp = m_watchpoint_location_list.FindByAddress(addr);
420     if (matched_sp)
421     {
422         size_t old_size = matched_sp->GetByteSize();
423         uint32_t old_type =
424             (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
425             (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
426         // Return the existing watchpoint location if both size and type match.
427         if (size == old_size && type == old_type) {
428             wp_loc_sp = matched_sp;
429             wp_loc_sp->SetEnabled(false);
430         } else {
431             // Nil the matched watchpoint location; we will be creating a new one.
432             m_process_sp->DisableWatchpoint(matched_sp.get());
433             m_watchpoint_location_list.Remove(matched_sp->GetID());
434         }
435     }
436 
437     if (!wp_loc_sp) {
438         WatchpointLocation *new_loc = new WatchpointLocation(addr, size);
439         if (!new_loc) {
440             printf("WatchpointLocation ctor failed, out of memory?\n");
441             return wp_loc_sp;
442         }
443         new_loc->SetWatchpointType(type);
444         new_loc->SetTarget(this);
445         wp_loc_sp.reset(new_loc);
446         m_watchpoint_location_list.Add(wp_loc_sp);
447     }
448 
449     Error rc = m_process_sp->EnableWatchpoint(wp_loc_sp.get());
450     if (log)
451             log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
452                         __FUNCTION__,
453                         rc.Success() ? "succeeded" : "failed",
454                         wp_loc_sp->GetID());
455 
456     if (rc.Fail())
457         wp_loc_sp.reset();
458     else
459         m_last_created_watchpoint_location = wp_loc_sp;
460     return wp_loc_sp;
461 }
462 
463 void
464 Target::RemoveAllBreakpoints (bool internal_also)
465 {
466     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
467     if (log)
468         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
469 
470     m_breakpoint_list.RemoveAll (true);
471     if (internal_also)
472         m_internal_breakpoint_list.RemoveAll (false);
473 
474     m_last_created_breakpoint.reset();
475 }
476 
477 void
478 Target::DisableAllBreakpoints (bool internal_also)
479 {
480     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
481     if (log)
482         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
483 
484     m_breakpoint_list.SetEnabledAll (false);
485     if (internal_also)
486         m_internal_breakpoint_list.SetEnabledAll (false);
487 }
488 
489 void
490 Target::EnableAllBreakpoints (bool internal_also)
491 {
492     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
493     if (log)
494         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
495 
496     m_breakpoint_list.SetEnabledAll (true);
497     if (internal_also)
498         m_internal_breakpoint_list.SetEnabledAll (true);
499 }
500 
501 bool
502 Target::RemoveBreakpointByID (break_id_t break_id)
503 {
504     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
505     if (log)
506         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
507 
508     if (DisableBreakpointByID (break_id))
509     {
510         if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
511             m_internal_breakpoint_list.Remove(break_id, false);
512         else
513         {
514             if (m_last_created_breakpoint)
515             {
516                 if (m_last_created_breakpoint->GetID() == break_id)
517                     m_last_created_breakpoint.reset();
518             }
519             m_breakpoint_list.Remove(break_id, true);
520         }
521         return true;
522     }
523     return false;
524 }
525 
526 bool
527 Target::DisableBreakpointByID (break_id_t break_id)
528 {
529     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
530     if (log)
531         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
532 
533     BreakpointSP bp_sp;
534 
535     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
536         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
537     else
538         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
539     if (bp_sp)
540     {
541         bp_sp->SetEnabled (false);
542         return true;
543     }
544     return false;
545 }
546 
547 bool
548 Target::EnableBreakpointByID (break_id_t break_id)
549 {
550     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
551     if (log)
552         log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
553                      __FUNCTION__,
554                      break_id,
555                      LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
556 
557     BreakpointSP bp_sp;
558 
559     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
560         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
561     else
562         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
563 
564     if (bp_sp)
565     {
566         bp_sp->SetEnabled (true);
567         return true;
568     }
569     return false;
570 }
571 
572 // The flag 'end_to_end', default to true, signifies that the operation is
573 // performed end to end, for both the debugger and the debuggee.
574 
575 // Assumption: Caller holds the list mutex lock for m_watchpoint_location_list
576 // for end to end operations.
577 bool
578 Target::RemoveAllWatchpointLocations (bool end_to_end)
579 {
580     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
581     if (log)
582         log->Printf ("Target::%s\n", __FUNCTION__);
583 
584     if (!end_to_end) {
585         m_watchpoint_location_list.RemoveAll();
586         return true;
587     }
588 
589     // Otherwise, it's an end to end operation.
590 
591     if (!ProcessIsValid())
592         return false;
593 
594     size_t num_watchpoints = m_watchpoint_location_list.GetSize();
595     for (size_t i = 0; i < num_watchpoints; ++i)
596     {
597         WatchpointLocationSP wp_loc_sp = m_watchpoint_location_list.GetByIndex(i);
598         if (!wp_loc_sp)
599             return false;
600 
601         Error rc = m_process_sp->DisableWatchpoint(wp_loc_sp.get());
602         if (rc.Fail())
603             return false;
604     }
605     m_watchpoint_location_list.RemoveAll ();
606     return true; // Success!
607 }
608 
609 // Assumption: Caller holds the list mutex lock for m_watchpoint_location_list
610 // for end to end operations.
611 bool
612 Target::DisableAllWatchpointLocations (bool end_to_end)
613 {
614     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
615     if (log)
616         log->Printf ("Target::%s\n", __FUNCTION__);
617 
618     if (!end_to_end) {
619         m_watchpoint_location_list.SetEnabledAll(false);
620         return true;
621     }
622 
623     // Otherwise, it's an end to end operation.
624 
625     if (!ProcessIsValid())
626         return false;
627 
628     size_t num_watchpoints = m_watchpoint_location_list.GetSize();
629     for (size_t i = 0; i < num_watchpoints; ++i)
630     {
631         WatchpointLocationSP wp_loc_sp = m_watchpoint_location_list.GetByIndex(i);
632         if (!wp_loc_sp)
633             return false;
634 
635         Error rc = m_process_sp->DisableWatchpoint(wp_loc_sp.get());
636         if (rc.Fail())
637             return false;
638     }
639     return true; // Success!
640 }
641 
642 // Assumption: Caller holds the list mutex lock for m_watchpoint_location_list
643 // for end to end operations.
644 bool
645 Target::EnableAllWatchpointLocations (bool end_to_end)
646 {
647     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
648     if (log)
649         log->Printf ("Target::%s\n", __FUNCTION__);
650 
651     if (!end_to_end) {
652         m_watchpoint_location_list.SetEnabledAll(true);
653         return true;
654     }
655 
656     // Otherwise, it's an end to end operation.
657 
658     if (!ProcessIsValid())
659         return false;
660 
661     size_t num_watchpoints = m_watchpoint_location_list.GetSize();
662     for (size_t i = 0; i < num_watchpoints; ++i)
663     {
664         WatchpointLocationSP wp_loc_sp = m_watchpoint_location_list.GetByIndex(i);
665         if (!wp_loc_sp)
666             return false;
667 
668         Error rc = m_process_sp->EnableWatchpoint(wp_loc_sp.get());
669         if (rc.Fail())
670             return false;
671     }
672     return true; // Success!
673 }
674 
675 // Assumption: Caller holds the list mutex lock for m_watchpoint_location_list
676 // during these operations.
677 bool
678 Target::IgnoreAllWatchpointLocations (uint32_t ignore_count)
679 {
680     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
681     if (log)
682         log->Printf ("Target::%s\n", __FUNCTION__);
683 
684     if (!ProcessIsValid())
685         return false;
686 
687     size_t num_watchpoints = m_watchpoint_location_list.GetSize();
688     for (size_t i = 0; i < num_watchpoints; ++i)
689     {
690         WatchpointLocationSP wp_loc_sp = m_watchpoint_location_list.GetByIndex(i);
691         if (!wp_loc_sp)
692             return false;
693 
694         wp_loc_sp->SetIgnoreCount(ignore_count);
695     }
696     return true; // Success!
697 }
698 
699 // Assumption: Caller holds the list mutex lock for m_watchpoint_location_list.
700 bool
701 Target::DisableWatchpointLocationByID (lldb::watch_id_t watch_id)
702 {
703     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
704     if (log)
705         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
706 
707     if (!ProcessIsValid())
708         return false;
709 
710     WatchpointLocationSP wp_loc_sp = m_watchpoint_location_list.FindByID (watch_id);
711     if (wp_loc_sp)
712     {
713         Error rc = m_process_sp->DisableWatchpoint(wp_loc_sp.get());
714         if (rc.Success())
715             return true;
716 
717         // Else, fallthrough.
718     }
719     return false;
720 }
721 
722 // Assumption: Caller holds the list mutex lock for m_watchpoint_location_list.
723 bool
724 Target::EnableWatchpointLocationByID (lldb::watch_id_t watch_id)
725 {
726     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
727     if (log)
728         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
729 
730     if (!ProcessIsValid())
731         return false;
732 
733     WatchpointLocationSP wp_loc_sp = m_watchpoint_location_list.FindByID (watch_id);
734     if (wp_loc_sp)
735     {
736         Error rc = m_process_sp->EnableWatchpoint(wp_loc_sp.get());
737         if (rc.Success())
738             return true;
739 
740         // Else, fallthrough.
741     }
742     return false;
743 }
744 
745 // Assumption: Caller holds the list mutex lock for m_watchpoint_location_list.
746 bool
747 Target::RemoveWatchpointLocationByID (lldb::watch_id_t watch_id)
748 {
749     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
750     if (log)
751         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
752 
753     if (DisableWatchpointLocationByID (watch_id))
754     {
755         m_watchpoint_location_list.Remove(watch_id);
756         return true;
757     }
758     return false;
759 }
760 
761 // Assumption: Caller holds the list mutex lock for m_watchpoint_location_list.
762 bool
763 Target::IgnoreWatchpointLocationByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
764 {
765     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
766     if (log)
767         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
768 
769     if (!ProcessIsValid())
770         return false;
771 
772     WatchpointLocationSP wp_loc_sp = m_watchpoint_location_list.FindByID (watch_id);
773     if (wp_loc_sp)
774     {
775         wp_loc_sp->SetIgnoreCount(ignore_count);
776         return true;
777     }
778     return false;
779 }
780 
781 ModuleSP
782 Target::GetExecutableModule ()
783 {
784     return m_images.GetModuleAtIndex(0);
785 }
786 
787 Module*
788 Target::GetExecutableModulePointer ()
789 {
790     return m_images.GetModulePointerAtIndex(0);
791 }
792 
793 void
794 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
795 {
796     m_images.Clear();
797     m_scratch_ast_context_ap.reset();
798 
799     if (executable_sp.get())
800     {
801         Timer scoped_timer (__PRETTY_FUNCTION__,
802                             "Target::SetExecutableModule (executable = '%s/%s')",
803                             executable_sp->GetFileSpec().GetDirectory().AsCString(),
804                             executable_sp->GetFileSpec().GetFilename().AsCString());
805 
806         m_images.Append(executable_sp); // The first image is our exectuable file
807 
808         // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
809         if (!m_arch.IsValid())
810             m_arch = executable_sp->GetArchitecture();
811 
812         FileSpecList dependent_files;
813         ObjectFile *executable_objfile = executable_sp->GetObjectFile();
814 
815         if (executable_objfile && get_dependent_files)
816         {
817             executable_objfile->GetDependentModules(dependent_files);
818             for (uint32_t i=0; i<dependent_files.GetSize(); i++)
819             {
820                 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
821                 FileSpec platform_dependent_file_spec;
822                 if (m_platform_sp)
823                     m_platform_sp->GetFile (dependent_file_spec, NULL, platform_dependent_file_spec);
824                 else
825                     platform_dependent_file_spec = dependent_file_spec;
826 
827                 ModuleSP image_module_sp(GetSharedModule (platform_dependent_file_spec,
828                                                           m_arch));
829                 if (image_module_sp.get())
830                 {
831                     ObjectFile *objfile = image_module_sp->GetObjectFile();
832                     if (objfile)
833                         objfile->GetDependentModules(dependent_files);
834                 }
835             }
836         }
837 
838     }
839 
840     UpdateInstanceName();
841 }
842 
843 
844 bool
845 Target::SetArchitecture (const ArchSpec &arch_spec)
846 {
847     if (m_arch == arch_spec)
848     {
849         // If we're setting the architecture to our current architecture, we
850         // don't need to do anything.
851         return true;
852     }
853     else if (!m_arch.IsValid())
854     {
855         // If we haven't got a valid arch spec, then we just need to set it.
856         m_arch = arch_spec;
857         return true;
858     }
859     else
860     {
861         // If we have an executable file, try to reset the executable to the desired architecture
862         m_arch = arch_spec;
863         ModuleSP executable_sp = GetExecutableModule ();
864         m_images.Clear();
865         m_scratch_ast_context_ap.reset();
866         // Need to do something about unsetting breakpoints.
867 
868         if (executable_sp)
869         {
870             FileSpec exec_file_spec = executable_sp->GetFileSpec();
871             Error error = ModuleList::GetSharedModule(exec_file_spec,
872                                                       arch_spec,
873                                                       NULL,
874                                                       NULL,
875                                                       0,
876                                                       executable_sp,
877                                                       NULL,
878                                                       NULL);
879 
880             if (!error.Fail() && executable_sp)
881             {
882                 SetExecutableModule (executable_sp, true);
883                 return true;
884             }
885             else
886             {
887                 return false;
888             }
889         }
890         else
891         {
892             return false;
893         }
894     }
895 }
896 
897 void
898 Target::ModuleAdded (ModuleSP &module_sp)
899 {
900     // A module is being added to this target for the first time
901     ModuleList module_list;
902     module_list.Append(module_sp);
903     ModulesDidLoad (module_list);
904 }
905 
906 void
907 Target::ModuleUpdated (ModuleSP &old_module_sp, ModuleSP &new_module_sp)
908 {
909     // A module is replacing an already added module
910     ModuleList module_list;
911     module_list.Append (old_module_sp);
912     ModulesDidUnload (module_list);
913     module_list.Clear ();
914     module_list.Append (new_module_sp);
915     ModulesDidLoad (module_list);
916 }
917 
918 void
919 Target::ModulesDidLoad (ModuleList &module_list)
920 {
921     m_breakpoint_list.UpdateBreakpoints (module_list, true);
922     // TODO: make event data that packages up the module_list
923     BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
924 }
925 
926 void
927 Target::ModulesDidUnload (ModuleList &module_list)
928 {
929     m_breakpoint_list.UpdateBreakpoints (module_list, false);
930 
931     // Remove the images from the target image list
932     m_images.Remove(module_list);
933 
934     // TODO: make event data that packages up the module_list
935     BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
936 }
937 
938 size_t
939 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
940 {
941     const Section *section = addr.GetSection();
942     if (section && section->GetModule())
943     {
944         ObjectFile *objfile = section->GetModule()->GetObjectFile();
945         if (objfile)
946         {
947             size_t bytes_read = section->ReadSectionDataFromObjectFile (objfile,
948                                                                         addr.GetOffset(),
949                                                                         dst,
950                                                                         dst_len);
951             if (bytes_read > 0)
952                 return bytes_read;
953             else
954                 error.SetErrorStringWithFormat("error reading data from section %s", section->GetName().GetCString());
955         }
956         else
957         {
958             error.SetErrorString("address isn't from a object file");
959         }
960     }
961     else
962     {
963         error.SetErrorString("address doesn't contain a section that points to a section in a object file");
964     }
965     return 0;
966 }
967 
968 size_t
969 Target::ReadMemory (const Address& addr,
970                     bool prefer_file_cache,
971                     void *dst,
972                     size_t dst_len,
973                     Error &error,
974                     lldb::addr_t *load_addr_ptr)
975 {
976     error.Clear();
977 
978     // if we end up reading this from process memory, we will fill this
979     // with the actual load address
980     if (load_addr_ptr)
981         *load_addr_ptr = LLDB_INVALID_ADDRESS;
982 
983     size_t bytes_read = 0;
984 
985     addr_t load_addr = LLDB_INVALID_ADDRESS;
986     addr_t file_addr = LLDB_INVALID_ADDRESS;
987     Address resolved_addr;
988     if (!addr.IsSectionOffset())
989     {
990         if (m_section_load_list.IsEmpty())
991         {
992             // No sections are loaded, so we must assume we are not running
993             // yet and anything we are given is a file address.
994             file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
995             m_images.ResolveFileAddress (file_addr, resolved_addr);
996         }
997         else
998         {
999             // We have at least one section loaded. This can be becuase
1000             // we have manually loaded some sections with "target modules load ..."
1001             // or because we have have a live process that has sections loaded
1002             // through the dynamic loader
1003             load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1004             m_section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1005         }
1006     }
1007     if (!resolved_addr.IsValid())
1008         resolved_addr = addr;
1009 
1010 
1011     if (prefer_file_cache)
1012     {
1013         bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1014         if (bytes_read > 0)
1015             return bytes_read;
1016     }
1017 
1018     if (ProcessIsValid())
1019     {
1020         if (load_addr == LLDB_INVALID_ADDRESS)
1021             load_addr = resolved_addr.GetLoadAddress (this);
1022 
1023         if (load_addr == LLDB_INVALID_ADDRESS)
1024         {
1025             if (resolved_addr.GetModule() && resolved_addr.GetModule()->GetFileSpec())
1026                 error.SetErrorStringWithFormat("%s[0x%llx] can't be resolved, %s in not currently loaded.\n",
1027                                                resolved_addr.GetModule()->GetFileSpec().GetFilename().AsCString(),
1028                                                resolved_addr.GetFileAddress(),
1029                                                resolved_addr.GetModule()->GetFileSpec().GetFilename().AsCString());
1030             else
1031                 error.SetErrorStringWithFormat("0x%llx can't be resolved.\n", resolved_addr.GetFileAddress());
1032         }
1033         else
1034         {
1035             bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1036             if (bytes_read != dst_len)
1037             {
1038                 if (error.Success())
1039                 {
1040                     if (bytes_read == 0)
1041                         error.SetErrorStringWithFormat("Read memory from 0x%llx failed.\n", load_addr);
1042                     else
1043                         error.SetErrorStringWithFormat("Only %zu of %zu bytes were read from memory at 0x%llx.\n", bytes_read, dst_len, load_addr);
1044                 }
1045             }
1046             if (bytes_read)
1047             {
1048                 if (load_addr_ptr)
1049                     *load_addr_ptr = load_addr;
1050                 return bytes_read;
1051             }
1052             // If the address is not section offset we have an address that
1053             // doesn't resolve to any address in any currently loaded shared
1054             // libaries and we failed to read memory so there isn't anything
1055             // more we can do. If it is section offset, we might be able to
1056             // read cached memory from the object file.
1057             if (!resolved_addr.IsSectionOffset())
1058                 return 0;
1059         }
1060     }
1061 
1062     if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1063     {
1064         // If we didn't already try and read from the object file cache, then
1065         // try it after failing to read from the process.
1066         return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1067     }
1068     return 0;
1069 }
1070 
1071 size_t
1072 Target::ReadScalarIntegerFromMemory (const Address& addr,
1073                                      bool prefer_file_cache,
1074                                      uint32_t byte_size,
1075                                      bool is_signed,
1076                                      Scalar &scalar,
1077                                      Error &error)
1078 {
1079     uint64_t uval;
1080 
1081     if (byte_size <= sizeof(uval))
1082     {
1083         size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1084         if (bytes_read == byte_size)
1085         {
1086             DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1087             uint32_t offset = 0;
1088             if (byte_size <= 4)
1089                 scalar = data.GetMaxU32 (&offset, byte_size);
1090             else
1091                 scalar = data.GetMaxU64 (&offset, byte_size);
1092 
1093             if (is_signed)
1094                 scalar.SignExtend(byte_size * 8);
1095             return bytes_read;
1096         }
1097     }
1098     else
1099     {
1100         error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1101     }
1102     return 0;
1103 }
1104 
1105 uint64_t
1106 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1107                                        bool prefer_file_cache,
1108                                        size_t integer_byte_size,
1109                                        uint64_t fail_value,
1110                                        Error &error)
1111 {
1112     Scalar scalar;
1113     if (ReadScalarIntegerFromMemory (addr,
1114                                      prefer_file_cache,
1115                                      integer_byte_size,
1116                                      false,
1117                                      scalar,
1118                                      error))
1119         return scalar.ULongLong(fail_value);
1120     return fail_value;
1121 }
1122 
1123 bool
1124 Target::ReadPointerFromMemory (const Address& addr,
1125                                bool prefer_file_cache,
1126                                Error &error,
1127                                Address &pointer_addr)
1128 {
1129     Scalar scalar;
1130     if (ReadScalarIntegerFromMemory (addr,
1131                                      prefer_file_cache,
1132                                      m_arch.GetAddressByteSize(),
1133                                      false,
1134                                      scalar,
1135                                      error))
1136     {
1137         addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1138         if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1139         {
1140             if (m_section_load_list.IsEmpty())
1141             {
1142                 // No sections are loaded, so we must assume we are not running
1143                 // yet and anything we are given is a file address.
1144                 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1145             }
1146             else
1147             {
1148                 // We have at least one section loaded. This can be becuase
1149                 // we have manually loaded some sections with "target modules load ..."
1150                 // or because we have have a live process that has sections loaded
1151                 // through the dynamic loader
1152                 m_section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1153             }
1154             // We weren't able to resolve the pointer value, so just return
1155             // an address with no section
1156             if (!pointer_addr.IsValid())
1157                 pointer_addr.SetOffset (pointer_vm_addr);
1158             return true;
1159 
1160         }
1161     }
1162     return false;
1163 }
1164 
1165 ModuleSP
1166 Target::GetSharedModule
1167 (
1168     const FileSpec& file_spec,
1169     const ArchSpec& arch,
1170     const lldb_private::UUID *uuid_ptr,
1171     const ConstString *object_name,
1172     off_t object_offset,
1173     Error *error_ptr
1174 )
1175 {
1176     // Don't pass in the UUID so we can tell if we have a stale value in our list
1177     ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1178     bool did_create_module = false;
1179     ModuleSP module_sp;
1180 
1181     Error error;
1182 
1183     // If there are image search path entries, try to use them first to acquire a suitable image.
1184     if (m_image_search_paths.GetSize())
1185     {
1186         FileSpec transformed_spec;
1187         if (m_image_search_paths.RemapPath (file_spec.GetDirectory(), transformed_spec.GetDirectory()))
1188         {
1189             transformed_spec.GetFilename() = file_spec.GetFilename();
1190             error = ModuleList::GetSharedModule (transformed_spec, arch, uuid_ptr, object_name, object_offset, module_sp, &old_module_sp, &did_create_module);
1191         }
1192     }
1193 
1194     // The platform is responsible for finding and caching an appropriate
1195     // module in the shared module cache.
1196     if (m_platform_sp)
1197     {
1198         FileSpec platform_file_spec;
1199         error = m_platform_sp->GetSharedModule (file_spec,
1200                                                 arch,
1201                                                 uuid_ptr,
1202                                                 object_name,
1203                                                 object_offset,
1204                                                 module_sp,
1205                                                 &old_module_sp,
1206                                                 &did_create_module);
1207     }
1208     else
1209     {
1210         error.SetErrorString("no platform is currently set");
1211     }
1212 
1213     // If a module hasn't been found yet, use the unmodified path.
1214     if (module_sp)
1215     {
1216         m_images.Append (module_sp);
1217         if (did_create_module)
1218         {
1219             if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1220                 ModuleUpdated(old_module_sp, module_sp);
1221             else
1222                 ModuleAdded(module_sp);
1223         }
1224     }
1225     if (error_ptr)
1226         *error_ptr = error;
1227     return module_sp;
1228 }
1229 
1230 
1231 Target *
1232 Target::CalculateTarget ()
1233 {
1234     return this;
1235 }
1236 
1237 Process *
1238 Target::CalculateProcess ()
1239 {
1240     return NULL;
1241 }
1242 
1243 Thread *
1244 Target::CalculateThread ()
1245 {
1246     return NULL;
1247 }
1248 
1249 StackFrame *
1250 Target::CalculateStackFrame ()
1251 {
1252     return NULL;
1253 }
1254 
1255 void
1256 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1257 {
1258     exe_ctx.Clear();
1259     exe_ctx.SetTargetPtr(this);
1260 }
1261 
1262 PathMappingList &
1263 Target::GetImageSearchPathList ()
1264 {
1265     return m_image_search_paths;
1266 }
1267 
1268 void
1269 Target::ImageSearchPathsChanged
1270 (
1271     const PathMappingList &path_list,
1272     void *baton
1273 )
1274 {
1275     Target *target = (Target *)baton;
1276     ModuleSP exe_module_sp (target->GetExecutableModule());
1277     if (exe_module_sp)
1278     {
1279         target->m_images.Clear();
1280         target->SetExecutableModule (exe_module_sp, true);
1281     }
1282 }
1283 
1284 ClangASTContext *
1285 Target::GetScratchClangASTContext()
1286 {
1287     // Now see if we know the target triple, and if so, create our scratch AST context:
1288     if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid())
1289         m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1290     return m_scratch_ast_context_ap.get();
1291 }
1292 
1293 void
1294 Target::SettingsInitialize ()
1295 {
1296     UserSettingsControllerSP &usc = GetSettingsController();
1297     usc.reset (new SettingsController);
1298     UserSettingsController::InitializeSettingsController (usc,
1299                                                           SettingsController::global_settings_table,
1300                                                           SettingsController::instance_settings_table);
1301 
1302     // Now call SettingsInitialize() on each 'child' setting of Target
1303     Process::SettingsInitialize ();
1304 }
1305 
1306 void
1307 Target::SettingsTerminate ()
1308 {
1309 
1310     // Must call SettingsTerminate() on each settings 'child' of Target, before terminating Target's Settings.
1311 
1312     Process::SettingsTerminate ();
1313 
1314     // Now terminate Target Settings.
1315 
1316     UserSettingsControllerSP &usc = GetSettingsController();
1317     UserSettingsController::FinalizeSettingsController (usc);
1318     usc.reset();
1319 }
1320 
1321 UserSettingsControllerSP &
1322 Target::GetSettingsController ()
1323 {
1324     static UserSettingsControllerSP g_settings_controller;
1325     return g_settings_controller;
1326 }
1327 
1328 ArchSpec
1329 Target::GetDefaultArchitecture ()
1330 {
1331     lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController());
1332 
1333     if (settings_controller_sp)
1334         return static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture ();
1335     return ArchSpec();
1336 }
1337 
1338 void
1339 Target::SetDefaultArchitecture (const ArchSpec& arch)
1340 {
1341     lldb::UserSettingsControllerSP settings_controller_sp (GetSettingsController());
1342 
1343     if (settings_controller_sp)
1344         static_cast<Target::SettingsController *>(settings_controller_sp.get())->GetArchitecture () = arch;
1345 }
1346 
1347 Target *
1348 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1349 {
1350     // The target can either exist in the "process" of ExecutionContext, or in
1351     // the "target_sp" member of SymbolContext. This accessor helper function
1352     // will get the target from one of these locations.
1353 
1354     Target *target = NULL;
1355     if (sc_ptr != NULL)
1356         target = sc_ptr->target_sp.get();
1357     if (target == NULL && exe_ctx_ptr)
1358         target = exe_ctx_ptr->GetTargetPtr();
1359     return target;
1360 }
1361 
1362 
1363 void
1364 Target::UpdateInstanceName ()
1365 {
1366     StreamString sstr;
1367 
1368     Module *exe_module = GetExecutableModulePointer();
1369     if (exe_module)
1370     {
1371         sstr.Printf ("%s_%s",
1372                      exe_module->GetFileSpec().GetFilename().AsCString(),
1373                      exe_module->GetArchitecture().GetArchitectureName());
1374         GetSettingsController()->RenameInstanceSettings (GetInstanceName().AsCString(), sstr.GetData());
1375     }
1376 }
1377 
1378 const char *
1379 Target::GetExpressionPrefixContentsAsCString ()
1380 {
1381     if (m_expr_prefix_contents_sp)
1382         return (const char *)m_expr_prefix_contents_sp->GetBytes();
1383     return NULL;
1384 }
1385 
1386 ExecutionResults
1387 Target::EvaluateExpression
1388 (
1389     const char *expr_cstr,
1390     StackFrame *frame,
1391     lldb_private::ExecutionPolicy execution_policy,
1392     bool unwind_on_error,
1393     bool keep_in_memory,
1394     lldb::DynamicValueType use_dynamic,
1395     lldb::ValueObjectSP &result_valobj_sp
1396 )
1397 {
1398     ExecutionResults execution_results = eExecutionSetupError;
1399 
1400     result_valobj_sp.reset();
1401 
1402     // We shouldn't run stop hooks in expressions.
1403     // Be sure to reset this if you return anywhere within this function.
1404     bool old_suppress_value = m_suppress_stop_hooks;
1405     m_suppress_stop_hooks = true;
1406 
1407     ExecutionContext exe_ctx;
1408     if (frame)
1409     {
1410         frame->CalculateExecutionContext(exe_ctx);
1411         Error error;
1412         const uint32_t expr_path_options = StackFrame::eExpressionPathOptionCheckPtrVsMember |
1413                                            StackFrame::eExpressionPathOptionsNoFragileObjcIvar |
1414                                            StackFrame::eExpressionPathOptionsNoSyntheticChildren;
1415         lldb::VariableSP var_sp;
1416         result_valobj_sp = frame->GetValueForVariableExpressionPath (expr_cstr,
1417                                                                      use_dynamic,
1418                                                                      expr_path_options,
1419                                                                      var_sp,
1420                                                                      error);
1421     }
1422     else if (m_process_sp)
1423     {
1424         m_process_sp->CalculateExecutionContext(exe_ctx);
1425     }
1426     else
1427     {
1428         CalculateExecutionContext(exe_ctx);
1429     }
1430 
1431     if (result_valobj_sp)
1432     {
1433         execution_results = eExecutionCompleted;
1434         // We got a result from the frame variable expression path above...
1435         ConstString persistent_variable_name (m_persistent_variables.GetNextPersistentVariableName());
1436 
1437         lldb::ValueObjectSP const_valobj_sp;
1438 
1439         // Check in case our value is already a constant value
1440         if (result_valobj_sp->GetIsConstant())
1441         {
1442             const_valobj_sp = result_valobj_sp;
1443             const_valobj_sp->SetName (persistent_variable_name);
1444         }
1445         else
1446         {
1447             if (use_dynamic != lldb::eNoDynamicValues)
1448             {
1449                 ValueObjectSP dynamic_sp = result_valobj_sp->GetDynamicValue(use_dynamic);
1450                 if (dynamic_sp)
1451                     result_valobj_sp = dynamic_sp;
1452             }
1453 
1454             const_valobj_sp = result_valobj_sp->CreateConstantValue (persistent_variable_name);
1455         }
1456 
1457         lldb::ValueObjectSP live_valobj_sp = result_valobj_sp;
1458 
1459         result_valobj_sp = const_valobj_sp;
1460 
1461         ClangExpressionVariableSP clang_expr_variable_sp(m_persistent_variables.CreatePersistentVariable(result_valobj_sp));
1462         assert (clang_expr_variable_sp.get());
1463 
1464         // Set flags and live data as appropriate
1465 
1466         const Value &result_value = live_valobj_sp->GetValue();
1467 
1468         switch (result_value.GetValueType())
1469         {
1470         case Value::eValueTypeHostAddress:
1471         case Value::eValueTypeFileAddress:
1472             // we don't do anything with these for now
1473             break;
1474         case Value::eValueTypeScalar:
1475             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsLLDBAllocated;
1476             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVNeedsAllocation;
1477             break;
1478         case Value::eValueTypeLoadAddress:
1479             clang_expr_variable_sp->m_live_sp = live_valobj_sp;
1480             clang_expr_variable_sp->m_flags |= ClangExpressionVariable::EVIsProgramReference;
1481             break;
1482         }
1483     }
1484     else
1485     {
1486         // Make sure we aren't just trying to see the value of a persistent
1487         // variable (something like "$0")
1488         lldb::ClangExpressionVariableSP persistent_var_sp;
1489         // Only check for persistent variables the expression starts with a '$'
1490         if (expr_cstr[0] == '$')
1491             persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1492 
1493         if (persistent_var_sp)
1494         {
1495             result_valobj_sp = persistent_var_sp->GetValueObject ();
1496             execution_results = eExecutionCompleted;
1497         }
1498         else
1499         {
1500             const char *prefix = GetExpressionPrefixContentsAsCString();
1501 
1502             execution_results = ClangUserExpression::Evaluate (exe_ctx,
1503                                                                execution_policy,
1504                                                                unwind_on_error,
1505                                                                expr_cstr,
1506                                                                prefix,
1507                                                                result_valobj_sp);
1508         }
1509     }
1510 
1511     m_suppress_stop_hooks = old_suppress_value;
1512 
1513     return execution_results;
1514 }
1515 
1516 lldb::addr_t
1517 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1518 {
1519     addr_t code_addr = load_addr;
1520     switch (m_arch.GetMachine())
1521     {
1522     case llvm::Triple::arm:
1523     case llvm::Triple::thumb:
1524         switch (addr_class)
1525         {
1526         case eAddressClassData:
1527         case eAddressClassDebug:
1528             return LLDB_INVALID_ADDRESS;
1529 
1530         case eAddressClassUnknown:
1531         case eAddressClassInvalid:
1532         case eAddressClassCode:
1533         case eAddressClassCodeAlternateISA:
1534         case eAddressClassRuntime:
1535             // Check if bit zero it no set?
1536             if ((code_addr & 1ull) == 0)
1537             {
1538                 // Bit zero isn't set, check if the address is a multiple of 2?
1539                 if (code_addr & 2ull)
1540                 {
1541                     // The address is a multiple of 2 so it must be thumb, set bit zero
1542                     code_addr |= 1ull;
1543                 }
1544                 else if (addr_class == eAddressClassCodeAlternateISA)
1545                 {
1546                     // We checked the address and the address claims to be the alternate ISA
1547                     // which means thumb, so set bit zero.
1548                     code_addr |= 1ull;
1549                 }
1550             }
1551             break;
1552         }
1553         break;
1554 
1555     default:
1556         break;
1557     }
1558     return code_addr;
1559 }
1560 
1561 lldb::addr_t
1562 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1563 {
1564     addr_t opcode_addr = load_addr;
1565     switch (m_arch.GetMachine())
1566     {
1567     case llvm::Triple::arm:
1568     case llvm::Triple::thumb:
1569         switch (addr_class)
1570         {
1571         case eAddressClassData:
1572         case eAddressClassDebug:
1573             return LLDB_INVALID_ADDRESS;
1574 
1575         case eAddressClassInvalid:
1576         case eAddressClassUnknown:
1577         case eAddressClassCode:
1578         case eAddressClassCodeAlternateISA:
1579         case eAddressClassRuntime:
1580             opcode_addr &= ~(1ull);
1581             break;
1582         }
1583         break;
1584 
1585     default:
1586         break;
1587     }
1588     return opcode_addr;
1589 }
1590 
1591 lldb::user_id_t
1592 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
1593 {
1594     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
1595     new_hook_sp.reset (new StopHook(GetSP(), new_uid));
1596     m_stop_hooks[new_uid] = new_hook_sp;
1597     return new_uid;
1598 }
1599 
1600 bool
1601 Target::RemoveStopHookByID (lldb::user_id_t user_id)
1602 {
1603     size_t num_removed;
1604     num_removed = m_stop_hooks.erase (user_id);
1605     if (num_removed == 0)
1606         return false;
1607     else
1608         return true;
1609 }
1610 
1611 void
1612 Target::RemoveAllStopHooks ()
1613 {
1614     m_stop_hooks.clear();
1615 }
1616 
1617 Target::StopHookSP
1618 Target::GetStopHookByID (lldb::user_id_t user_id)
1619 {
1620     StopHookSP found_hook;
1621 
1622     StopHookCollection::iterator specified_hook_iter;
1623     specified_hook_iter = m_stop_hooks.find (user_id);
1624     if (specified_hook_iter != m_stop_hooks.end())
1625         found_hook = (*specified_hook_iter).second;
1626     return found_hook;
1627 }
1628 
1629 bool
1630 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
1631 {
1632     StopHookCollection::iterator specified_hook_iter;
1633     specified_hook_iter = m_stop_hooks.find (user_id);
1634     if (specified_hook_iter == m_stop_hooks.end())
1635         return false;
1636 
1637     (*specified_hook_iter).second->SetIsActive (active_state);
1638     return true;
1639 }
1640 
1641 void
1642 Target::SetAllStopHooksActiveState (bool active_state)
1643 {
1644     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1645     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1646     {
1647         (*pos).second->SetIsActive (active_state);
1648     }
1649 }
1650 
1651 void
1652 Target::RunStopHooks ()
1653 {
1654     if (m_suppress_stop_hooks)
1655         return;
1656 
1657     if (!m_process_sp)
1658         return;
1659 
1660     if (m_stop_hooks.empty())
1661         return;
1662 
1663     StopHookCollection::iterator pos, end = m_stop_hooks.end();
1664 
1665     // If there aren't any active stop hooks, don't bother either:
1666     bool any_active_hooks = false;
1667     for (pos = m_stop_hooks.begin(); pos != end; pos++)
1668     {
1669         if ((*pos).second->IsActive())
1670         {
1671             any_active_hooks = true;
1672             break;
1673         }
1674     }
1675     if (!any_active_hooks)
1676         return;
1677 
1678     CommandReturnObject result;
1679 
1680     std::vector<ExecutionContext> exc_ctx_with_reasons;
1681     std::vector<SymbolContext> sym_ctx_with_reasons;
1682 
1683     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
1684     size_t num_threads = cur_threadlist.GetSize();
1685     for (size_t i = 0; i < num_threads; i++)
1686     {
1687         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
1688         if (cur_thread_sp->ThreadStoppedForAReason())
1689         {
1690             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
1691             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
1692             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
1693         }
1694     }
1695 
1696     // If no threads stopped for a reason, don't run the stop-hooks.
1697     size_t num_exe_ctx = exc_ctx_with_reasons.size();
1698     if (num_exe_ctx == 0)
1699         return;
1700 
1701     result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
1702     result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
1703 
1704     bool keep_going = true;
1705     bool hooks_ran = false;
1706     bool print_hook_header;
1707     bool print_thread_header;
1708 
1709     if (num_exe_ctx == 1)
1710         print_thread_header = false;
1711     else
1712         print_thread_header = true;
1713 
1714     if (m_stop_hooks.size() == 1)
1715         print_hook_header = false;
1716     else
1717         print_hook_header = true;
1718 
1719     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
1720     {
1721         // result.Clear();
1722         StopHookSP cur_hook_sp = (*pos).second;
1723         if (!cur_hook_sp->IsActive())
1724             continue;
1725 
1726         bool any_thread_matched = false;
1727         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
1728         {
1729             if ((cur_hook_sp->GetSpecifier () == NULL
1730                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
1731                 && (cur_hook_sp->GetThreadSpecifier() == NULL
1732                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadPtr())))
1733             {
1734                 if (!hooks_ran)
1735                 {
1736                     hooks_ran = true;
1737                 }
1738                 if (print_hook_header && !any_thread_matched)
1739                 {
1740                     result.AppendMessageWithFormat("\n- Hook %d\n", cur_hook_sp->GetID());
1741                     any_thread_matched = true;
1742                 }
1743 
1744                 if (print_thread_header)
1745                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
1746 
1747                 bool stop_on_continue = true;
1748                 bool stop_on_error = true;
1749                 bool echo_commands = false;
1750                 bool print_results = true;
1751                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
1752                                                                       &exc_ctx_with_reasons[i],
1753                                                                       stop_on_continue,
1754                                                                       stop_on_error,
1755                                                                       echo_commands,
1756                                                                       print_results,
1757                                                                       result);
1758 
1759                 // If the command started the target going again, we should bag out of
1760                 // running the stop hooks.
1761                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
1762                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
1763                 {
1764                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %d set the program running.", cur_hook_sp->GetID());
1765                     keep_going = false;
1766                 }
1767             }
1768         }
1769     }
1770 
1771     result.GetImmediateOutputStream()->Flush();
1772     result.GetImmediateErrorStream()->Flush();
1773 }
1774 
1775 bool
1776 Target::LoadModuleWithSlide (Module *module, lldb::addr_t slide)
1777 {
1778     bool changed = false;
1779     if (module)
1780     {
1781         ObjectFile *object_file = module->GetObjectFile();
1782         if (object_file)
1783         {
1784             SectionList *section_list = object_file->GetSectionList ();
1785             if (section_list)
1786             {
1787                 // All sections listed in the dyld image info structure will all
1788                 // either be fixed up already, or they will all be off by a single
1789                 // slide amount that is determined by finding the first segment
1790                 // that is at file offset zero which also has bytes (a file size
1791                 // that is greater than zero) in the object file.
1792 
1793                 // Determine the slide amount (if any)
1794                 const size_t num_sections = section_list->GetSize();
1795                 size_t sect_idx = 0;
1796                 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx)
1797                 {
1798                     // Iterate through the object file sections to find the
1799                     // first section that starts of file offset zero and that
1800                     // has bytes in the file...
1801                     Section *section = section_list->GetSectionAtIndex (sect_idx).get();
1802                     if (section)
1803                     {
1804                         if (m_section_load_list.SetSectionLoadAddress (section, section->GetFileAddress() + slide))
1805                             changed = true;
1806                     }
1807                 }
1808             }
1809         }
1810     }
1811     return changed;
1812 }
1813 
1814 
1815 //--------------------------------------------------------------
1816 // class Target::StopHook
1817 //--------------------------------------------------------------
1818 
1819 
1820 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
1821         UserID (uid),
1822         m_target_sp (target_sp),
1823         m_commands (),
1824         m_specifier_sp (),
1825         m_thread_spec_ap(NULL),
1826         m_active (true)
1827 {
1828 }
1829 
1830 Target::StopHook::StopHook (const StopHook &rhs) :
1831         UserID (rhs.GetID()),
1832         m_target_sp (rhs.m_target_sp),
1833         m_commands (rhs.m_commands),
1834         m_specifier_sp (rhs.m_specifier_sp),
1835         m_thread_spec_ap (NULL),
1836         m_active (rhs.m_active)
1837 {
1838     if (rhs.m_thread_spec_ap.get() != NULL)
1839         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
1840 }
1841 
1842 
1843 Target::StopHook::~StopHook ()
1844 {
1845 }
1846 
1847 void
1848 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
1849 {
1850     m_thread_spec_ap.reset (specifier);
1851 }
1852 
1853 
1854 void
1855 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
1856 {
1857     int indent_level = s->GetIndentLevel();
1858 
1859     s->SetIndentLevel(indent_level + 2);
1860 
1861     s->Printf ("Hook: %d\n", GetID());
1862     if (m_active)
1863         s->Indent ("State: enabled\n");
1864     else
1865         s->Indent ("State: disabled\n");
1866 
1867     if (m_specifier_sp)
1868     {
1869         s->Indent();
1870         s->PutCString ("Specifier:\n");
1871         s->SetIndentLevel (indent_level + 4);
1872         m_specifier_sp->GetDescription (s, level);
1873         s->SetIndentLevel (indent_level + 2);
1874     }
1875 
1876     if (m_thread_spec_ap.get() != NULL)
1877     {
1878         StreamString tmp;
1879         s->Indent("Thread:\n");
1880         m_thread_spec_ap->GetDescription (&tmp, level);
1881         s->SetIndentLevel (indent_level + 4);
1882         s->Indent (tmp.GetData());
1883         s->PutCString ("\n");
1884         s->SetIndentLevel (indent_level + 2);
1885     }
1886 
1887     s->Indent ("Commands: \n");
1888     s->SetIndentLevel (indent_level + 4);
1889     uint32_t num_commands = m_commands.GetSize();
1890     for (uint32_t i = 0; i < num_commands; i++)
1891     {
1892         s->Indent(m_commands.GetStringAtIndex(i));
1893         s->PutCString ("\n");
1894     }
1895     s->SetIndentLevel (indent_level);
1896 }
1897 
1898 
1899 //--------------------------------------------------------------
1900 // class Target::SettingsController
1901 //--------------------------------------------------------------
1902 
1903 Target::SettingsController::SettingsController () :
1904     UserSettingsController ("target", Debugger::GetSettingsController()),
1905     m_default_architecture ()
1906 {
1907     m_default_settings.reset (new TargetInstanceSettings (*this, false,
1908                                                           InstanceSettings::GetDefaultName().AsCString()));
1909 }
1910 
1911 Target::SettingsController::~SettingsController ()
1912 {
1913 }
1914 
1915 lldb::InstanceSettingsSP
1916 Target::SettingsController::CreateInstanceSettings (const char *instance_name)
1917 {
1918     TargetInstanceSettings *new_settings = new TargetInstanceSettings (*GetSettingsController(),
1919                                                                        false,
1920                                                                        instance_name);
1921     lldb::InstanceSettingsSP new_settings_sp (new_settings);
1922     return new_settings_sp;
1923 }
1924 
1925 
1926 #define TSC_DEFAULT_ARCH      "default-arch"
1927 #define TSC_EXPR_PREFIX       "expr-prefix"
1928 #define TSC_PREFER_DYNAMIC    "prefer-dynamic-value"
1929 #define TSC_SKIP_PROLOGUE     "skip-prologue"
1930 #define TSC_SOURCE_MAP        "source-map"
1931 #define TSC_MAX_CHILDREN      "max-children-count"
1932 #define TSC_MAX_STRLENSUMMARY "max-string-summary-length"
1933 
1934 
1935 static const ConstString &
1936 GetSettingNameForDefaultArch ()
1937 {
1938     static ConstString g_const_string (TSC_DEFAULT_ARCH);
1939     return g_const_string;
1940 }
1941 
1942 static const ConstString &
1943 GetSettingNameForExpressionPrefix ()
1944 {
1945     static ConstString g_const_string (TSC_EXPR_PREFIX);
1946     return g_const_string;
1947 }
1948 
1949 static const ConstString &
1950 GetSettingNameForPreferDynamicValue ()
1951 {
1952     static ConstString g_const_string (TSC_PREFER_DYNAMIC);
1953     return g_const_string;
1954 }
1955 
1956 static const ConstString &
1957 GetSettingNameForSourcePathMap ()
1958 {
1959     static ConstString g_const_string (TSC_SOURCE_MAP);
1960     return g_const_string;
1961 }
1962 
1963 static const ConstString &
1964 GetSettingNameForSkipPrologue ()
1965 {
1966     static ConstString g_const_string (TSC_SKIP_PROLOGUE);
1967     return g_const_string;
1968 }
1969 
1970 static const ConstString &
1971 GetSettingNameForMaxChildren ()
1972 {
1973     static ConstString g_const_string (TSC_MAX_CHILDREN);
1974     return g_const_string;
1975 }
1976 
1977 static const ConstString &
1978 GetSettingNameForMaxStringSummaryLength ()
1979 {
1980     static ConstString g_const_string (TSC_MAX_STRLENSUMMARY);
1981     return g_const_string;
1982 }
1983 
1984 bool
1985 Target::SettingsController::SetGlobalVariable (const ConstString &var_name,
1986                                                const char *index_value,
1987                                                const char *value,
1988                                                const SettingEntry &entry,
1989                                                const VarSetOperationType op,
1990                                                Error&err)
1991 {
1992     if (var_name == GetSettingNameForDefaultArch())
1993     {
1994         m_default_architecture.SetTriple (value, NULL);
1995         if (!m_default_architecture.IsValid())
1996             err.SetErrorStringWithFormat ("'%s' is not a valid architecture or triple.", value);
1997     }
1998     return true;
1999 }
2000 
2001 
2002 bool
2003 Target::SettingsController::GetGlobalVariable (const ConstString &var_name,
2004                                                StringList &value,
2005                                                Error &err)
2006 {
2007     if (var_name == GetSettingNameForDefaultArch())
2008     {
2009         // If the arch is invalid (the default), don't show a string for it
2010         if (m_default_architecture.IsValid())
2011             value.AppendString (m_default_architecture.GetArchitectureName());
2012         return true;
2013     }
2014     else
2015         err.SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2016 
2017     return false;
2018 }
2019 
2020 //--------------------------------------------------------------
2021 // class TargetInstanceSettings
2022 //--------------------------------------------------------------
2023 
2024 TargetInstanceSettings::TargetInstanceSettings
2025 (
2026     UserSettingsController &owner,
2027     bool live_instance,
2028     const char *name
2029 ) :
2030     InstanceSettings (owner, name ? name : InstanceSettings::InvalidName().AsCString(), live_instance),
2031     m_expr_prefix_file (),
2032     m_expr_prefix_contents_sp (),
2033     m_prefer_dynamic_value (2),
2034     m_skip_prologue (true, true),
2035     m_source_map (NULL, NULL),
2036     m_max_children_display(256),
2037     m_max_strlen_length(1024)
2038 {
2039     // CopyInstanceSettings is a pure virtual function in InstanceSettings; it therefore cannot be called
2040     // until the vtables for TargetInstanceSettings are properly set up, i.e. AFTER all the initializers.
2041     // For this reason it has to be called here, rather than in the initializer or in the parent constructor.
2042     // This is true for CreateInstanceName() too.
2043 
2044     if (GetInstanceName () == InstanceSettings::InvalidName())
2045     {
2046         ChangeInstanceName (std::string (CreateInstanceName().AsCString()));
2047         m_owner.RegisterInstanceSettings (this);
2048     }
2049 
2050     if (live_instance)
2051     {
2052         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2053         CopyInstanceSettings (pending_settings,false);
2054     }
2055 }
2056 
2057 TargetInstanceSettings::TargetInstanceSettings (const TargetInstanceSettings &rhs) :
2058     InstanceSettings (*Target::GetSettingsController(), CreateInstanceName().AsCString()),
2059     m_expr_prefix_file (rhs.m_expr_prefix_file),
2060     m_expr_prefix_contents_sp (rhs.m_expr_prefix_contents_sp),
2061     m_prefer_dynamic_value (rhs.m_prefer_dynamic_value),
2062     m_skip_prologue (rhs.m_skip_prologue),
2063     m_source_map (rhs.m_source_map),
2064     m_max_children_display(rhs.m_max_children_display),
2065     m_max_strlen_length(rhs.m_max_strlen_length)
2066 {
2067     if (m_instance_name != InstanceSettings::GetDefaultName())
2068     {
2069         const lldb::InstanceSettingsSP &pending_settings = m_owner.FindPendingSettings (m_instance_name);
2070         CopyInstanceSettings (pending_settings,false);
2071     }
2072 }
2073 
2074 TargetInstanceSettings::~TargetInstanceSettings ()
2075 {
2076 }
2077 
2078 TargetInstanceSettings&
2079 TargetInstanceSettings::operator= (const TargetInstanceSettings &rhs)
2080 {
2081     if (this != &rhs)
2082     {
2083     }
2084 
2085     return *this;
2086 }
2087 
2088 void
2089 TargetInstanceSettings::UpdateInstanceSettingsVariable (const ConstString &var_name,
2090                                                         const char *index_value,
2091                                                         const char *value,
2092                                                         const ConstString &instance_name,
2093                                                         const SettingEntry &entry,
2094                                                         VarSetOperationType op,
2095                                                         Error &err,
2096                                                         bool pending)
2097 {
2098     if (var_name == GetSettingNameForExpressionPrefix ())
2099     {
2100         err = UserSettingsController::UpdateFileSpecOptionValue (value, op, m_expr_prefix_file);
2101         if (err.Success())
2102         {
2103             switch (op)
2104             {
2105             default:
2106                 break;
2107             case eVarSetOperationAssign:
2108             case eVarSetOperationAppend:
2109                 {
2110                     if (!m_expr_prefix_file.GetCurrentValue().Exists())
2111                     {
2112                         err.SetErrorToGenericError ();
2113                         err.SetErrorStringWithFormat ("%s does not exist.\n", value);
2114                         return;
2115                     }
2116 
2117                     m_expr_prefix_contents_sp = m_expr_prefix_file.GetCurrentValue().ReadFileContents();
2118 
2119                     if (!m_expr_prefix_contents_sp && m_expr_prefix_contents_sp->GetByteSize() == 0)
2120                     {
2121                         err.SetErrorStringWithFormat ("Couldn't read data from '%s'\n", value);
2122                         m_expr_prefix_contents_sp.reset();
2123                     }
2124                 }
2125                 break;
2126             case eVarSetOperationClear:
2127                 m_expr_prefix_contents_sp.reset();
2128             }
2129         }
2130     }
2131     else if (var_name == GetSettingNameForPreferDynamicValue())
2132     {
2133         int new_value;
2134         UserSettingsController::UpdateEnumVariable (g_dynamic_value_types, &new_value, value, err);
2135         if (err.Success())
2136             m_prefer_dynamic_value = new_value;
2137     }
2138     else if (var_name == GetSettingNameForSkipPrologue())
2139     {
2140         err = UserSettingsController::UpdateBooleanOptionValue (value, op, m_skip_prologue);
2141     }
2142     else if (var_name == GetSettingNameForMaxChildren())
2143     {
2144         bool ok;
2145         uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok);
2146         if (ok)
2147             m_max_children_display = new_value;
2148     }
2149     else if (var_name == GetSettingNameForMaxStringSummaryLength())
2150     {
2151         bool ok;
2152         uint32_t new_value = Args::StringToUInt32(value, 0, 10, &ok);
2153         if (ok)
2154             m_max_strlen_length = new_value;
2155     }
2156     else if (var_name == GetSettingNameForSourcePathMap ())
2157     {
2158         switch (op)
2159         {
2160             case eVarSetOperationReplace:
2161             case eVarSetOperationInsertBefore:
2162             case eVarSetOperationInsertAfter:
2163             case eVarSetOperationRemove:
2164             default:
2165                 break;
2166             case eVarSetOperationAssign:
2167                 m_source_map.Clear(true);
2168                 // Fall through to append....
2169             case eVarSetOperationAppend:
2170                 {
2171                     Args args(value);
2172                     const uint32_t argc = args.GetArgumentCount();
2173                     if (argc & 1 || argc == 0)
2174                     {
2175                         err.SetErrorStringWithFormat ("an even number of paths must be supplied to to the source-map setting: %u arguments given", argc);
2176                     }
2177                     else
2178                     {
2179                         char resolved_new_path[PATH_MAX];
2180                         FileSpec file_spec;
2181                         const char *old_path;
2182                         for (uint32_t idx = 0; (old_path = args.GetArgumentAtIndex(idx)) != NULL; idx += 2)
2183                         {
2184                             const char *new_path = args.GetArgumentAtIndex(idx+1);
2185                             assert (new_path); // We have an even number of paths, this shouldn't happen!
2186 
2187                             file_spec.SetFile(new_path, true);
2188                             if (file_spec.Exists())
2189                             {
2190                                 if (file_spec.GetPath (resolved_new_path, sizeof(resolved_new_path)) >= sizeof(resolved_new_path))
2191                                 {
2192                                     err.SetErrorStringWithFormat("new path '%s' is too long", new_path);
2193                                     return;
2194                                 }
2195                             }
2196                             else
2197                             {
2198                                 err.SetErrorStringWithFormat("new path '%s' doesn't exist", new_path);
2199                                 return;
2200                             }
2201                             m_source_map.Append(ConstString (old_path), ConstString (resolved_new_path), true);
2202                         }
2203                     }
2204                 }
2205                 break;
2206 
2207             case eVarSetOperationClear:
2208                 m_source_map.Clear(true);
2209                 break;
2210         }
2211     }
2212 }
2213 
2214 void
2215 TargetInstanceSettings::CopyInstanceSettings (const lldb::InstanceSettingsSP &new_settings, bool pending)
2216 {
2217     TargetInstanceSettings *new_settings_ptr = static_cast <TargetInstanceSettings *> (new_settings.get());
2218 
2219     if (!new_settings_ptr)
2220         return;
2221 
2222     m_expr_prefix_file          = new_settings_ptr->m_expr_prefix_file;
2223     m_expr_prefix_contents_sp   = new_settings_ptr->m_expr_prefix_contents_sp;
2224     m_prefer_dynamic_value      = new_settings_ptr->m_prefer_dynamic_value;
2225     m_skip_prologue             = new_settings_ptr->m_skip_prologue;
2226     m_max_children_display      = new_settings_ptr->m_max_children_display;
2227     m_max_strlen_length         = new_settings_ptr->m_max_strlen_length;
2228 }
2229 
2230 bool
2231 TargetInstanceSettings::GetInstanceSettingsValue (const SettingEntry &entry,
2232                                                   const ConstString &var_name,
2233                                                   StringList &value,
2234                                                   Error *err)
2235 {
2236     if (var_name == GetSettingNameForExpressionPrefix ())
2237     {
2238         char path[PATH_MAX];
2239         const size_t path_len = m_expr_prefix_file.GetCurrentValue().GetPath (path, sizeof(path));
2240         if (path_len > 0)
2241             value.AppendString (path, path_len);
2242     }
2243     else if (var_name == GetSettingNameForPreferDynamicValue())
2244     {
2245         value.AppendString (g_dynamic_value_types[m_prefer_dynamic_value].string_value);
2246     }
2247     else if (var_name == GetSettingNameForSkipPrologue())
2248     {
2249         if (m_skip_prologue)
2250             value.AppendString ("true");
2251         else
2252             value.AppendString ("false");
2253     }
2254     else if (var_name == GetSettingNameForSourcePathMap ())
2255     {
2256     }
2257     else if (var_name == GetSettingNameForMaxChildren())
2258     {
2259         StreamString count_str;
2260         count_str.Printf ("%d", m_max_children_display);
2261         value.AppendString (count_str.GetData());
2262     }
2263     else if (var_name == GetSettingNameForMaxStringSummaryLength())
2264     {
2265         StreamString count_str;
2266         count_str.Printf ("%d", m_max_strlen_length);
2267         value.AppendString (count_str.GetData());
2268     }
2269     else
2270     {
2271         if (err)
2272             err->SetErrorStringWithFormat ("unrecognized variable name '%s'", var_name.AsCString());
2273         return false;
2274     }
2275 
2276     return true;
2277 }
2278 
2279 const ConstString
2280 TargetInstanceSettings::CreateInstanceName ()
2281 {
2282     StreamString sstr;
2283     static int instance_count = 1;
2284 
2285     sstr.Printf ("target_%d", instance_count);
2286     ++instance_count;
2287 
2288     const ConstString ret_val (sstr.GetData());
2289     return ret_val;
2290 }
2291 
2292 //--------------------------------------------------
2293 // Target::SettingsController Variable Tables
2294 //--------------------------------------------------
2295 OptionEnumValueElement
2296 TargetInstanceSettings::g_dynamic_value_types[] =
2297 {
2298 { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2299 { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2300 { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2301 { 0, NULL, NULL }
2302 };
2303 
2304 SettingEntry
2305 Target::SettingsController::global_settings_table[] =
2306 {
2307     // var-name           var-type           default      enum  init'd hidden help-text
2308     // =================  ================== ===========  ====  ====== ====== =========================================================================
2309     { TSC_DEFAULT_ARCH  , eSetVarTypeString , NULL      , NULL, false, false, "Default architecture to choose, when there's a choice." },
2310     { NULL              , eSetVarTypeNone   , NULL      , NULL, false, false, NULL }
2311 };
2312 
2313 SettingEntry
2314 Target::SettingsController::instance_settings_table[] =
2315 {
2316     // var-name             var-type            default         enum                    init'd hidden help-text
2317     // =================    ==================  =============== ======================= ====== ====== =========================================================================
2318     { TSC_EXPR_PREFIX       , eSetVarTypeString , NULL          , NULL,                  false, false, "Path to a file containing expressions to be prepended to all expressions." },
2319     { TSC_PREFER_DYNAMIC    , eSetVarTypeEnum   , NULL          , g_dynamic_value_types, false, false, "Should printed values be shown as their dynamic value." },
2320     { TSC_SKIP_PROLOGUE     , eSetVarTypeBoolean, "true"        , NULL,                  false, false, "Skip function prologues when setting breakpoints by name." },
2321     { TSC_SOURCE_MAP        , eSetVarTypeArray  , NULL          , NULL,                  false, false, "Source path remappings to use when locating source files from debug information." },
2322     { TSC_MAX_CHILDREN      , eSetVarTypeInt    , "256"         , NULL,                  true,  false, "Maximum number of children to expand in any level of depth." },
2323     { TSC_MAX_STRLENSUMMARY , eSetVarTypeInt    , "1024"        , NULL,                  true,  false, "Maximum number of characters to show when using %s in summary strings." },
2324     { NULL                  , eSetVarTypeNone   , NULL          , NULL,                  false, false, NULL }
2325 };
2326