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/lldb-python.h"
11 
12 #include "lldb/Target/Target.h"
13 
14 // C Includes
15 // C++ Includes
16 // Other libraries and framework includes
17 // Project includes
18 #include "lldb/Breakpoint/BreakpointResolver.h"
19 #include "lldb/Breakpoint/BreakpointResolverAddress.h"
20 #include "lldb/Breakpoint/BreakpointResolverFileLine.h"
21 #include "lldb/Breakpoint/BreakpointResolverFileRegex.h"
22 #include "lldb/Breakpoint/BreakpointResolverName.h"
23 #include "lldb/Breakpoint/Watchpoint.h"
24 #include "lldb/Core/Debugger.h"
25 #include "lldb/Core/Event.h"
26 #include "lldb/Core/Log.h"
27 #include "lldb/Core/Module.h"
28 #include "lldb/Core/ModuleSpec.h"
29 #include "lldb/Core/Section.h"
30 #include "lldb/Core/SourceManager.h"
31 #include "lldb/Core/State.h"
32 #include "lldb/Core/StreamString.h"
33 #include "lldb/Core/Timer.h"
34 #include "lldb/Core/ValueObject.h"
35 #include "lldb/Expression/ClangASTSource.h"
36 #include "lldb/Expression/ClangUserExpression.h"
37 #include "lldb/Host/Host.h"
38 #include "lldb/Interpreter/CommandInterpreter.h"
39 #include "lldb/Interpreter/CommandReturnObject.h"
40 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
41 #include "lldb/Interpreter/OptionValues.h"
42 #include "lldb/Interpreter/Property.h"
43 #include "lldb/lldb-private-log.h"
44 #include "lldb/Symbol/ObjectFile.h"
45 #include "lldb/Target/Process.h"
46 #include "lldb/Target/SectionLoadList.h"
47 #include "lldb/Target/StackFrame.h"
48 #include "lldb/Target/SystemRuntime.h"
49 #include "lldb/Target/Thread.h"
50 #include "lldb/Target/ThreadSpec.h"
51 
52 using namespace lldb;
53 using namespace lldb_private;
54 
55 ConstString &
56 Target::GetStaticBroadcasterClass ()
57 {
58     static ConstString class_name ("lldb.target");
59     return class_name;
60 }
61 
62 //----------------------------------------------------------------------
63 // Target constructor
64 //----------------------------------------------------------------------
65 Target::Target(Debugger &debugger, const ArchSpec &target_arch, const lldb::PlatformSP &platform_sp) :
66     TargetProperties (this),
67     Broadcaster (&debugger, Target::GetStaticBroadcasterClass().AsCString()),
68     ExecutionContextScope (),
69     m_debugger (debugger),
70     m_platform_sp (platform_sp),
71     m_mutex (Mutex::eMutexTypeRecursive),
72     m_arch (target_arch),
73     m_images (this),
74     m_section_load_history (),
75     m_breakpoint_list (false),
76     m_internal_breakpoint_list (true),
77     m_watchpoint_list (),
78     m_process_sp (),
79     m_search_filter_sp (),
80     m_image_search_paths (ImageSearchPathsChanged, this),
81     m_scratch_ast_context_ap (),
82     m_scratch_ast_source_ap (),
83     m_ast_importer_ap (),
84     m_persistent_variables (),
85     m_source_manager_ap(),
86     m_stop_hooks (),
87     m_stop_hook_next_id (0),
88     m_valid (true),
89     m_suppress_stop_hooks (false)
90 {
91     SetEventName (eBroadcastBitBreakpointChanged, "breakpoint-changed");
92     SetEventName (eBroadcastBitModulesLoaded, "modules-loaded");
93     SetEventName (eBroadcastBitModulesUnloaded, "modules-unloaded");
94     SetEventName (eBroadcastBitWatchpointChanged, "watchpoint-changed");
95     SetEventName (eBroadcastBitSymbolsLoaded, "symbols-loaded");
96 
97     CheckInWithManager();
98 
99     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
100     if (log)
101         log->Printf ("%p Target::Target()", this);
102     if (m_arch.IsValid())
103     {
104         LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::Target created with architecture %s (%s)", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
105     }
106 }
107 
108 //----------------------------------------------------------------------
109 // Destructor
110 //----------------------------------------------------------------------
111 Target::~Target()
112 {
113     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
114     if (log)
115         log->Printf ("%p Target::~Target()", this);
116     DeleteCurrentProcess ();
117 }
118 
119 void
120 Target::Dump (Stream *s, lldb::DescriptionLevel description_level)
121 {
122 //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
123     if (description_level != lldb::eDescriptionLevelBrief)
124     {
125         s->Indent();
126         s->PutCString("Target\n");
127         s->IndentMore();
128             m_images.Dump(s);
129             m_breakpoint_list.Dump(s);
130             m_internal_breakpoint_list.Dump(s);
131         s->IndentLess();
132     }
133     else
134     {
135         Module *exe_module = GetExecutableModulePointer();
136         if (exe_module)
137             s->PutCString (exe_module->GetFileSpec().GetFilename().GetCString());
138         else
139             s->PutCString ("No executable module.");
140     }
141 }
142 
143 void
144 Target::CleanupProcess ()
145 {
146     // Do any cleanup of the target we need to do between process instances.
147     // NB It is better to do this before destroying the process in case the
148     // clean up needs some help from the process.
149     m_breakpoint_list.ClearAllBreakpointSites();
150     m_internal_breakpoint_list.ClearAllBreakpointSites();
151     // Disable watchpoints just on the debugger side.
152     Mutex::Locker locker;
153     this->GetWatchpointList().GetListMutex(locker);
154     DisableAllWatchpoints(false);
155     ClearAllWatchpointHitCounts();
156 }
157 
158 void
159 Target::DeleteCurrentProcess ()
160 {
161     if (m_process_sp.get())
162     {
163         m_section_load_history.Clear();
164         if (m_process_sp->IsAlive())
165             m_process_sp->Destroy();
166 
167         m_process_sp->Finalize();
168 
169         CleanupProcess ();
170 
171         m_process_sp.reset();
172     }
173 }
174 
175 const lldb::ProcessSP &
176 Target::CreateProcess (Listener &listener, const char *plugin_name, const FileSpec *crash_file)
177 {
178     DeleteCurrentProcess ();
179     m_process_sp = Process::FindPlugin(*this, plugin_name, listener, crash_file);
180     return m_process_sp;
181 }
182 
183 const lldb::ProcessSP &
184 Target::GetProcessSP () const
185 {
186     return m_process_sp;
187 }
188 
189 void
190 Target::Destroy()
191 {
192     Mutex::Locker locker (m_mutex);
193     m_valid = false;
194     DeleteCurrentProcess ();
195     m_platform_sp.reset();
196     m_arch.Clear();
197     ClearModules(true);
198     m_section_load_history.Clear();
199     const bool notify = false;
200     m_breakpoint_list.RemoveAll(notify);
201     m_internal_breakpoint_list.RemoveAll(notify);
202     m_last_created_breakpoint.reset();
203     m_last_created_watchpoint.reset();
204     m_search_filter_sp.reset();
205     m_image_search_paths.Clear(notify);
206     m_persistent_variables.Clear();
207     m_stop_hooks.clear();
208     m_stop_hook_next_id = 0;
209     m_suppress_stop_hooks = false;
210 }
211 
212 
213 BreakpointList &
214 Target::GetBreakpointList(bool internal)
215 {
216     if (internal)
217         return m_internal_breakpoint_list;
218     else
219         return m_breakpoint_list;
220 }
221 
222 const BreakpointList &
223 Target::GetBreakpointList(bool internal) const
224 {
225     if (internal)
226         return m_internal_breakpoint_list;
227     else
228         return m_breakpoint_list;
229 }
230 
231 BreakpointSP
232 Target::GetBreakpointByID (break_id_t break_id)
233 {
234     BreakpointSP bp_sp;
235 
236     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
237         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
238     else
239         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
240 
241     return bp_sp;
242 }
243 
244 BreakpointSP
245 Target::CreateSourceRegexBreakpoint (const FileSpecList *containingModules,
246                                      const FileSpecList *source_file_spec_list,
247                                      RegularExpression &source_regex,
248                                      bool internal,
249                                      bool hardware)
250 {
251     SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, source_file_spec_list));
252     BreakpointResolverSP resolver_sp(new BreakpointResolverFileRegex (NULL, source_regex));
253     return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
254 }
255 
256 
257 BreakpointSP
258 Target::CreateBreakpoint (const FileSpecList *containingModules,
259                           const FileSpec &file,
260                           uint32_t line_no,
261                           LazyBool check_inlines,
262                           LazyBool skip_prologue,
263                           bool internal,
264                           bool hardware)
265 {
266     if (check_inlines == eLazyBoolCalculate)
267     {
268         const InlineStrategy inline_strategy = GetInlineStrategy();
269         switch (inline_strategy)
270         {
271             case eInlineBreakpointsNever:
272                 check_inlines = eLazyBoolNo;
273                 break;
274 
275             case eInlineBreakpointsHeaders:
276                 if (file.IsSourceImplementationFile())
277                     check_inlines = eLazyBoolNo;
278                 else
279                     check_inlines = eLazyBoolYes;
280                 break;
281 
282             case eInlineBreakpointsAlways:
283                 check_inlines = eLazyBoolYes;
284                 break;
285         }
286     }
287     SearchFilterSP filter_sp;
288     if (check_inlines == eLazyBoolNo)
289     {
290         // Not checking for inlines, we are looking only for matching compile units
291         FileSpecList compile_unit_list;
292         compile_unit_list.Append (file);
293         filter_sp = GetSearchFilterForModuleAndCUList (containingModules, &compile_unit_list);
294     }
295     else
296     {
297         filter_sp = GetSearchFilterForModuleList (containingModules);
298     }
299     if (skip_prologue == eLazyBoolCalculate)
300         skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
301 
302     BreakpointResolverSP resolver_sp(new BreakpointResolverFileLine (NULL,
303                                                                      file,
304                                                                      line_no,
305                                                                      check_inlines,
306                                                                      skip_prologue));
307     return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
308 }
309 
310 
311 BreakpointSP
312 Target::CreateBreakpoint (lldb::addr_t addr, bool internal, bool hardware)
313 {
314     Address so_addr;
315     // Attempt to resolve our load address if possible, though it is ok if
316     // it doesn't resolve to section/offset.
317 
318     // Try and resolve as a load address if possible
319     GetSectionLoadList().ResolveLoadAddress(addr, so_addr);
320     if (!so_addr.IsValid())
321     {
322         // The address didn't resolve, so just set this as an absolute address
323         so_addr.SetOffset (addr);
324     }
325     BreakpointSP bp_sp (CreateBreakpoint(so_addr, internal, hardware));
326     return bp_sp;
327 }
328 
329 BreakpointSP
330 Target::CreateBreakpoint (Address &addr, bool internal, bool hardware)
331 {
332     SearchFilterSP filter_sp(new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
333     BreakpointResolverSP resolver_sp (new BreakpointResolverAddress (NULL, addr));
334     return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, false);
335 }
336 
337 BreakpointSP
338 Target::CreateBreakpoint (const FileSpecList *containingModules,
339                           const FileSpecList *containingSourceFiles,
340                           const char *func_name,
341                           uint32_t func_name_type_mask,
342                           LazyBool skip_prologue,
343                           bool internal,
344                           bool hardware)
345 {
346     BreakpointSP bp_sp;
347     if (func_name)
348     {
349         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
350 
351         if (skip_prologue == eLazyBoolCalculate)
352             skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
353 
354         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
355                                                                       func_name,
356                                                                       func_name_type_mask,
357                                                                       Breakpoint::Exact,
358                                                                       skip_prologue));
359         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
360     }
361     return bp_sp;
362 }
363 
364 lldb::BreakpointSP
365 Target::CreateBreakpoint (const FileSpecList *containingModules,
366                           const FileSpecList *containingSourceFiles,
367                           const std::vector<std::string> &func_names,
368                           uint32_t func_name_type_mask,
369                           LazyBool skip_prologue,
370                           bool internal,
371                           bool hardware)
372 {
373     BreakpointSP bp_sp;
374     size_t num_names = func_names.size();
375     if (num_names > 0)
376     {
377         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
378 
379         if (skip_prologue == eLazyBoolCalculate)
380             skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
381 
382         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
383                                                                       func_names,
384                                                                       func_name_type_mask,
385                                                                       skip_prologue));
386         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
387     }
388     return bp_sp;
389 }
390 
391 BreakpointSP
392 Target::CreateBreakpoint (const FileSpecList *containingModules,
393                           const FileSpecList *containingSourceFiles,
394                           const char *func_names[],
395                           size_t num_names,
396                           uint32_t func_name_type_mask,
397                           LazyBool skip_prologue,
398                           bool internal,
399                           bool hardware)
400 {
401     BreakpointSP bp_sp;
402     if (num_names > 0)
403     {
404         SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
405 
406         if (skip_prologue == eLazyBoolCalculate)
407             skip_prologue = GetSkipPrologue() ? eLazyBoolYes : eLazyBoolNo;
408 
409         BreakpointResolverSP resolver_sp (new BreakpointResolverName (NULL,
410                                                                       func_names,
411                                                                       num_names,
412                                                                       func_name_type_mask,
413                                                                       skip_prologue));
414         bp_sp = CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
415     }
416     return bp_sp;
417 }
418 
419 SearchFilterSP
420 Target::GetSearchFilterForModule (const FileSpec *containingModule)
421 {
422     SearchFilterSP filter_sp;
423     if (containingModule != NULL)
424     {
425         // TODO: We should look into sharing module based search filters
426         // across many breakpoints like we do for the simple target based one
427         filter_sp.reset (new SearchFilterByModule (shared_from_this(), *containingModule));
428     }
429     else
430     {
431         if (m_search_filter_sp.get() == NULL)
432             m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
433         filter_sp = m_search_filter_sp;
434     }
435     return filter_sp;
436 }
437 
438 SearchFilterSP
439 Target::GetSearchFilterForModuleList (const FileSpecList *containingModules)
440 {
441     SearchFilterSP filter_sp;
442     if (containingModules && containingModules->GetSize() != 0)
443     {
444         // TODO: We should look into sharing module based search filters
445         // across many breakpoints like we do for the simple target based one
446         filter_sp.reset (new SearchFilterByModuleList (shared_from_this(), *containingModules));
447     }
448     else
449     {
450         if (m_search_filter_sp.get() == NULL)
451             m_search_filter_sp.reset (new SearchFilterForNonModuleSpecificSearches (shared_from_this()));
452         filter_sp = m_search_filter_sp;
453     }
454     return filter_sp;
455 }
456 
457 SearchFilterSP
458 Target::GetSearchFilterForModuleAndCUList (const FileSpecList *containingModules,
459                                            const FileSpecList *containingSourceFiles)
460 {
461     if (containingSourceFiles == NULL || containingSourceFiles->GetSize() == 0)
462         return GetSearchFilterForModuleList(containingModules);
463 
464     SearchFilterSP filter_sp;
465     if (containingModules == NULL)
466     {
467         // We could make a special "CU List only SearchFilter".  Better yet was if these could be composable,
468         // but that will take a little reworking.
469 
470         filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), FileSpecList(), *containingSourceFiles));
471     }
472     else
473     {
474         filter_sp.reset (new SearchFilterByModuleListAndCU (shared_from_this(), *containingModules, *containingSourceFiles));
475     }
476     return filter_sp;
477 }
478 
479 BreakpointSP
480 Target::CreateFuncRegexBreakpoint (const FileSpecList *containingModules,
481                                    const FileSpecList *containingSourceFiles,
482                                    RegularExpression &func_regex,
483                                    LazyBool skip_prologue,
484                                    bool internal,
485                                    bool hardware)
486 {
487     SearchFilterSP filter_sp(GetSearchFilterForModuleAndCUList (containingModules, containingSourceFiles));
488     BreakpointResolverSP resolver_sp(new BreakpointResolverName (NULL,
489                                                                  func_regex,
490                                                                  skip_prologue == eLazyBoolCalculate ? GetSkipPrologue() : skip_prologue));
491 
492     return CreateBreakpoint (filter_sp, resolver_sp, internal, hardware, true);
493 }
494 
495 lldb::BreakpointSP
496 Target::CreateExceptionBreakpoint (enum lldb::LanguageType language, bool catch_bp, bool throw_bp, bool internal)
497 {
498     return LanguageRuntime::CreateExceptionBreakpoint (*this, language, catch_bp, throw_bp, internal);
499 }
500 
501 BreakpointSP
502 Target::CreateBreakpoint (SearchFilterSP &filter_sp, BreakpointResolverSP &resolver_sp, bool internal, bool request_hardware, bool resolve_indirect_symbols)
503 {
504     BreakpointSP bp_sp;
505     if (filter_sp && resolver_sp)
506     {
507         bp_sp.reset(new Breakpoint (*this, filter_sp, resolver_sp, request_hardware, resolve_indirect_symbols));
508         resolver_sp->SetBreakpoint (bp_sp.get());
509 
510         if (internal)
511             m_internal_breakpoint_list.Add (bp_sp, false);
512         else
513             m_breakpoint_list.Add (bp_sp, true);
514 
515         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
516         if (log)
517         {
518             StreamString s;
519             bp_sp->GetDescription(&s, lldb::eDescriptionLevelVerbose);
520             log->Printf ("Target::%s (internal = %s) => break_id = %s\n", __FUNCTION__, internal ? "yes" : "no", s.GetData());
521         }
522 
523         bp_sp->ResolveBreakpoint();
524     }
525 
526     if (!internal && bp_sp)
527     {
528         m_last_created_breakpoint = bp_sp;
529     }
530 
531     return bp_sp;
532 }
533 
534 bool
535 Target::ProcessIsValid()
536 {
537     return (m_process_sp && m_process_sp->IsAlive());
538 }
539 
540 static bool
541 CheckIfWatchpointsExhausted(Target *target, Error &error)
542 {
543     uint32_t num_supported_hardware_watchpoints;
544     Error rc = target->GetProcessSP()->GetWatchpointSupportInfo(num_supported_hardware_watchpoints);
545     if (rc.Success())
546     {
547         uint32_t num_current_watchpoints = target->GetWatchpointList().GetSize();
548         if (num_current_watchpoints >= num_supported_hardware_watchpoints)
549             error.SetErrorStringWithFormat("number of supported hardware watchpoints (%u) has been reached",
550                                            num_supported_hardware_watchpoints);
551     }
552     return false;
553 }
554 
555 // See also Watchpoint::SetWatchpointType(uint32_t type) and
556 // the OptionGroupWatchpoint::WatchType enum type.
557 WatchpointSP
558 Target::CreateWatchpoint(lldb::addr_t addr, size_t size, const ClangASTType *type, uint32_t kind, Error &error)
559 {
560     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
561     if (log)
562         log->Printf("Target::%s (addr = 0x%8.8" PRIx64 " size = %" PRIu64 " type = %u)\n",
563                     __FUNCTION__, addr, (uint64_t)size, kind);
564 
565     WatchpointSP wp_sp;
566     if (!ProcessIsValid())
567     {
568         error.SetErrorString("process is not alive");
569         return wp_sp;
570     }
571 
572     if (addr == LLDB_INVALID_ADDRESS || size == 0)
573     {
574         if (size == 0)
575             error.SetErrorString("cannot set a watchpoint with watch_size of 0");
576         else
577             error.SetErrorStringWithFormat("invalid watch address: %" PRIu64, addr);
578         return wp_sp;
579     }
580 
581     if (!LLDB_WATCH_TYPE_IS_VALID(kind))
582     {
583         error.SetErrorStringWithFormat ("invalid watchpoint type: %d", kind);
584     }
585 
586     // Currently we only support one watchpoint per address, with total number
587     // of watchpoints limited by the hardware which the inferior is running on.
588 
589     // Grab the list mutex while doing operations.
590     const bool notify = false;   // Don't notify about all the state changes we do on creating the watchpoint.
591     Mutex::Locker locker;
592     this->GetWatchpointList().GetListMutex(locker);
593     WatchpointSP matched_sp = m_watchpoint_list.FindByAddress(addr);
594     if (matched_sp)
595     {
596         size_t old_size = matched_sp->GetByteSize();
597         uint32_t old_type =
598             (matched_sp->WatchpointRead() ? LLDB_WATCH_TYPE_READ : 0) |
599             (matched_sp->WatchpointWrite() ? LLDB_WATCH_TYPE_WRITE : 0);
600         // Return the existing watchpoint if both size and type match.
601         if (size == old_size && kind == old_type)
602         {
603             wp_sp = matched_sp;
604             wp_sp->SetEnabled(false, notify);
605         }
606         else
607         {
608             // Nil the matched watchpoint; we will be creating a new one.
609             m_process_sp->DisableWatchpoint(matched_sp.get(), notify);
610             m_watchpoint_list.Remove(matched_sp->GetID(), true);
611         }
612     }
613 
614     if (!wp_sp)
615     {
616         wp_sp.reset(new Watchpoint(*this, addr, size, type));
617         wp_sp->SetWatchpointType(kind, notify);
618         m_watchpoint_list.Add (wp_sp, true);
619     }
620 
621     error = m_process_sp->EnableWatchpoint(wp_sp.get(), notify);
622     if (log)
623         log->Printf("Target::%s (creation of watchpoint %s with id = %u)\n",
624                     __FUNCTION__,
625                     error.Success() ? "succeeded" : "failed",
626                     wp_sp->GetID());
627 
628     if (error.Fail())
629     {
630         // Enabling the watchpoint on the device side failed.
631         // Remove the said watchpoint from the list maintained by the target instance.
632         m_watchpoint_list.Remove (wp_sp->GetID(), true);
633         // See if we could provide more helpful error message.
634         if (!CheckIfWatchpointsExhausted(this, error))
635         {
636             if (!OptionGroupWatchpoint::IsWatchSizeSupported(size))
637                 error.SetErrorStringWithFormat("watch size of %zu is not supported", size);
638         }
639         wp_sp.reset();
640     }
641     else
642         m_last_created_watchpoint = wp_sp;
643     return wp_sp;
644 }
645 
646 void
647 Target::RemoveAllBreakpoints (bool internal_also)
648 {
649     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
650     if (log)
651         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
652 
653     m_breakpoint_list.RemoveAll (true);
654     if (internal_also)
655         m_internal_breakpoint_list.RemoveAll (false);
656 
657     m_last_created_breakpoint.reset();
658 }
659 
660 void
661 Target::DisableAllBreakpoints (bool internal_also)
662 {
663     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
664     if (log)
665         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
666 
667     m_breakpoint_list.SetEnabledAll (false);
668     if (internal_also)
669         m_internal_breakpoint_list.SetEnabledAll (false);
670 }
671 
672 void
673 Target::EnableAllBreakpoints (bool internal_also)
674 {
675     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
676     if (log)
677         log->Printf ("Target::%s (internal_also = %s)\n", __FUNCTION__, internal_also ? "yes" : "no");
678 
679     m_breakpoint_list.SetEnabledAll (true);
680     if (internal_also)
681         m_internal_breakpoint_list.SetEnabledAll (true);
682 }
683 
684 bool
685 Target::RemoveBreakpointByID (break_id_t break_id)
686 {
687     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
688     if (log)
689         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
690 
691     if (DisableBreakpointByID (break_id))
692     {
693         if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
694             m_internal_breakpoint_list.Remove(break_id, false);
695         else
696         {
697             if (m_last_created_breakpoint)
698             {
699                 if (m_last_created_breakpoint->GetID() == break_id)
700                     m_last_created_breakpoint.reset();
701             }
702             m_breakpoint_list.Remove(break_id, true);
703         }
704         return true;
705     }
706     return false;
707 }
708 
709 bool
710 Target::DisableBreakpointByID (break_id_t break_id)
711 {
712     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
713     if (log)
714         log->Printf ("Target::%s (break_id = %i, internal = %s)\n", __FUNCTION__, break_id, LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
715 
716     BreakpointSP bp_sp;
717 
718     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
719         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
720     else
721         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
722     if (bp_sp)
723     {
724         bp_sp->SetEnabled (false);
725         return true;
726     }
727     return false;
728 }
729 
730 bool
731 Target::EnableBreakpointByID (break_id_t break_id)
732 {
733     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
734     if (log)
735         log->Printf ("Target::%s (break_id = %i, internal = %s)\n",
736                      __FUNCTION__,
737                      break_id,
738                      LLDB_BREAK_ID_IS_INTERNAL (break_id) ? "yes" : "no");
739 
740     BreakpointSP bp_sp;
741 
742     if (LLDB_BREAK_ID_IS_INTERNAL (break_id))
743         bp_sp = m_internal_breakpoint_list.FindBreakpointByID (break_id);
744     else
745         bp_sp = m_breakpoint_list.FindBreakpointByID (break_id);
746 
747     if (bp_sp)
748     {
749         bp_sp->SetEnabled (true);
750         return true;
751     }
752     return false;
753 }
754 
755 // The flag 'end_to_end', default to true, signifies that the operation is
756 // performed end to end, for both the debugger and the debuggee.
757 
758 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end
759 // to end operations.
760 bool
761 Target::RemoveAllWatchpoints (bool end_to_end)
762 {
763     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
764     if (log)
765         log->Printf ("Target::%s\n", __FUNCTION__);
766 
767     if (!end_to_end) {
768         m_watchpoint_list.RemoveAll(true);
769         return true;
770     }
771 
772     // Otherwise, it's an end to end operation.
773 
774     if (!ProcessIsValid())
775         return false;
776 
777     size_t num_watchpoints = m_watchpoint_list.GetSize();
778     for (size_t i = 0; i < num_watchpoints; ++i)
779     {
780         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
781         if (!wp_sp)
782             return false;
783 
784         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
785         if (rc.Fail())
786             return false;
787     }
788     m_watchpoint_list.RemoveAll (true);
789     m_last_created_watchpoint.reset();
790     return true; // Success!
791 }
792 
793 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
794 // end operations.
795 bool
796 Target::DisableAllWatchpoints (bool end_to_end)
797 {
798     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
799     if (log)
800         log->Printf ("Target::%s\n", __FUNCTION__);
801 
802     if (!end_to_end) {
803         m_watchpoint_list.SetEnabledAll(false);
804         return true;
805     }
806 
807     // Otherwise, it's an end to end operation.
808 
809     if (!ProcessIsValid())
810         return false;
811 
812     size_t num_watchpoints = m_watchpoint_list.GetSize();
813     for (size_t i = 0; i < num_watchpoints; ++i)
814     {
815         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
816         if (!wp_sp)
817             return false;
818 
819         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
820         if (rc.Fail())
821             return false;
822     }
823     return true; // Success!
824 }
825 
826 // Assumption: Caller holds the list mutex lock for m_watchpoint_list for end to
827 // end operations.
828 bool
829 Target::EnableAllWatchpoints (bool end_to_end)
830 {
831     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
832     if (log)
833         log->Printf ("Target::%s\n", __FUNCTION__);
834 
835     if (!end_to_end) {
836         m_watchpoint_list.SetEnabledAll(true);
837         return true;
838     }
839 
840     // Otherwise, it's an end to end operation.
841 
842     if (!ProcessIsValid())
843         return false;
844 
845     size_t num_watchpoints = m_watchpoint_list.GetSize();
846     for (size_t i = 0; i < num_watchpoints; ++i)
847     {
848         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
849         if (!wp_sp)
850             return false;
851 
852         Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
853         if (rc.Fail())
854             return false;
855     }
856     return true; // Success!
857 }
858 
859 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
860 bool
861 Target::ClearAllWatchpointHitCounts ()
862 {
863     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
864     if (log)
865         log->Printf ("Target::%s\n", __FUNCTION__);
866 
867     size_t num_watchpoints = m_watchpoint_list.GetSize();
868     for (size_t i = 0; i < num_watchpoints; ++i)
869     {
870         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
871         if (!wp_sp)
872             return false;
873 
874         wp_sp->ResetHitCount();
875     }
876     return true; // Success!
877 }
878 
879 // Assumption: Caller holds the list mutex lock for m_watchpoint_list
880 // during these operations.
881 bool
882 Target::IgnoreAllWatchpoints (uint32_t ignore_count)
883 {
884     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
885     if (log)
886         log->Printf ("Target::%s\n", __FUNCTION__);
887 
888     if (!ProcessIsValid())
889         return false;
890 
891     size_t num_watchpoints = m_watchpoint_list.GetSize();
892     for (size_t i = 0; i < num_watchpoints; ++i)
893     {
894         WatchpointSP wp_sp = m_watchpoint_list.GetByIndex(i);
895         if (!wp_sp)
896             return false;
897 
898         wp_sp->SetIgnoreCount(ignore_count);
899     }
900     return true; // Success!
901 }
902 
903 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
904 bool
905 Target::DisableWatchpointByID (lldb::watch_id_t watch_id)
906 {
907     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
908     if (log)
909         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
910 
911     if (!ProcessIsValid())
912         return false;
913 
914     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
915     if (wp_sp)
916     {
917         Error rc = m_process_sp->DisableWatchpoint(wp_sp.get());
918         if (rc.Success())
919             return true;
920 
921         // Else, fallthrough.
922     }
923     return false;
924 }
925 
926 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
927 bool
928 Target::EnableWatchpointByID (lldb::watch_id_t watch_id)
929 {
930     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
931     if (log)
932         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
933 
934     if (!ProcessIsValid())
935         return false;
936 
937     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
938     if (wp_sp)
939     {
940         Error rc = m_process_sp->EnableWatchpoint(wp_sp.get());
941         if (rc.Success())
942             return true;
943 
944         // Else, fallthrough.
945     }
946     return false;
947 }
948 
949 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
950 bool
951 Target::RemoveWatchpointByID (lldb::watch_id_t watch_id)
952 {
953     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
954     if (log)
955         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
956 
957     WatchpointSP watch_to_remove_sp = m_watchpoint_list.FindByID(watch_id);
958     if (watch_to_remove_sp == m_last_created_watchpoint)
959         m_last_created_watchpoint.reset();
960 
961     if (DisableWatchpointByID (watch_id))
962     {
963         m_watchpoint_list.Remove(watch_id, true);
964         return true;
965     }
966     return false;
967 }
968 
969 // Assumption: Caller holds the list mutex lock for m_watchpoint_list.
970 bool
971 Target::IgnoreWatchpointByID (lldb::watch_id_t watch_id, uint32_t ignore_count)
972 {
973     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_WATCHPOINTS));
974     if (log)
975         log->Printf ("Target::%s (watch_id = %i)\n", __FUNCTION__, watch_id);
976 
977     if (!ProcessIsValid())
978         return false;
979 
980     WatchpointSP wp_sp = m_watchpoint_list.FindByID (watch_id);
981     if (wp_sp)
982     {
983         wp_sp->SetIgnoreCount(ignore_count);
984         return true;
985     }
986     return false;
987 }
988 
989 ModuleSP
990 Target::GetExecutableModule ()
991 {
992     return m_images.GetModuleAtIndex(0);
993 }
994 
995 Module*
996 Target::GetExecutableModulePointer ()
997 {
998     return m_images.GetModulePointerAtIndex(0);
999 }
1000 
1001 static void
1002 LoadScriptingResourceForModule (const ModuleSP &module_sp, Target *target)
1003 {
1004     Error error;
1005     StreamString feedback_stream;
1006     if (module_sp && !module_sp->LoadScriptingResourceInTarget(target, error, &feedback_stream))
1007     {
1008         if (error.AsCString())
1009             target->GetDebugger().GetErrorStream().Printf("unable to load scripting data for module %s - error reported was %s\n",
1010                                                            module_sp->GetFileSpec().GetFileNameStrippingExtension().GetCString(),
1011                                                            error.AsCString());
1012         if (feedback_stream.GetSize())
1013             target->GetDebugger().GetOutputStream().Printf("%s\n",
1014                                                            feedback_stream.GetData());
1015     }
1016 }
1017 
1018 void
1019 Target::ClearModules(bool delete_locations)
1020 {
1021     ModulesDidUnload (m_images, delete_locations);
1022     m_section_load_history.Clear();
1023     m_images.Clear();
1024     m_scratch_ast_context_ap.reset();
1025     m_scratch_ast_source_ap.reset();
1026     m_ast_importer_ap.reset();
1027 }
1028 
1029 void
1030 Target::DidExec ()
1031 {
1032     // When a process exec's we need to know about it so we can do some cleanup.
1033     m_breakpoint_list.RemoveInvalidLocations(m_arch);
1034     m_internal_breakpoint_list.RemoveInvalidLocations(m_arch);
1035 }
1036 
1037 void
1038 Target::SetExecutableModule (ModuleSP& executable_sp, bool get_dependent_files)
1039 {
1040     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1041     ClearModules(false);
1042 
1043     if (executable_sp.get())
1044     {
1045         Timer scoped_timer (__PRETTY_FUNCTION__,
1046                             "Target::SetExecutableModule (executable = '%s')",
1047                             executable_sp->GetFileSpec().GetPath().c_str());
1048 
1049         m_images.Append(executable_sp); // The first image is our exectuable file
1050 
1051         // If we haven't set an architecture yet, reset our architecture based on what we found in the executable module.
1052         if (!m_arch.IsValid())
1053         {
1054             m_arch = executable_sp->GetArchitecture();
1055             if (log)
1056               log->Printf ("Target::SetExecutableModule setting architecture to %s (%s) based on executable file", m_arch.GetArchitectureName(), m_arch.GetTriple().getTriple().c_str());
1057         }
1058 
1059         FileSpecList dependent_files;
1060         ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1061 
1062         if (executable_objfile && get_dependent_files)
1063         {
1064             executable_objfile->GetDependentModules(dependent_files);
1065             for (uint32_t i=0; i<dependent_files.GetSize(); i++)
1066             {
1067                 FileSpec dependent_file_spec (dependent_files.GetFileSpecPointerAtIndex(i));
1068                 FileSpec platform_dependent_file_spec;
1069                 if (m_platform_sp)
1070                     m_platform_sp->GetFileWithUUID (dependent_file_spec, NULL, platform_dependent_file_spec);
1071                 else
1072                     platform_dependent_file_spec = dependent_file_spec;
1073 
1074                 ModuleSpec module_spec (platform_dependent_file_spec, m_arch);
1075                 ModuleSP image_module_sp(GetSharedModule (module_spec));
1076                 if (image_module_sp.get())
1077                 {
1078                     ObjectFile *objfile = image_module_sp->GetObjectFile();
1079                     if (objfile)
1080                         objfile->GetDependentModules(dependent_files);
1081                 }
1082             }
1083         }
1084     }
1085 }
1086 
1087 
1088 bool
1089 Target::SetArchitecture (const ArchSpec &arch_spec)
1090 {
1091     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
1092     if (m_arch.IsCompatibleMatch(arch_spec) || !m_arch.IsValid())
1093     {
1094         // If we haven't got a valid arch spec, or the architectures are
1095         // compatible, so just update the architecture. Architectures can be
1096         // equal, yet the triple OS and vendor might change, so we need to do
1097         // the assignment here just in case.
1098         m_arch = arch_spec;
1099         if (log)
1100             log->Printf ("Target::SetArchitecture setting architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1101         return true;
1102     }
1103     else
1104     {
1105         // If we have an executable file, try to reset the executable to the desired architecture
1106         if (log)
1107           log->Printf ("Target::SetArchitecture changing architecture to %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1108         m_arch = arch_spec;
1109         ModuleSP executable_sp = GetExecutableModule ();
1110 
1111         ClearModules(true);
1112         // Need to do something about unsetting breakpoints.
1113 
1114         if (executable_sp)
1115         {
1116             if (log)
1117               log->Printf("Target::SetArchitecture Trying to select executable file architecture %s (%s)", arch_spec.GetArchitectureName(), arch_spec.GetTriple().getTriple().c_str());
1118             ModuleSpec module_spec (executable_sp->GetFileSpec(), arch_spec);
1119             Error error = ModuleList::GetSharedModule (module_spec,
1120                                                        executable_sp,
1121                                                        &GetExecutableSearchPaths(),
1122                                                        NULL,
1123                                                        NULL);
1124 
1125             if (!error.Fail() && executable_sp)
1126             {
1127                 SetExecutableModule (executable_sp, true);
1128                 return true;
1129             }
1130         }
1131     }
1132     return false;
1133 }
1134 
1135 void
1136 Target::WillClearList (const ModuleList& module_list)
1137 {
1138 }
1139 
1140 void
1141 Target::ModuleAdded (const ModuleList& module_list, const ModuleSP &module_sp)
1142 {
1143     // A module is being added to this target for the first time
1144     ModuleList my_module_list;
1145     my_module_list.Append(module_sp);
1146     LoadScriptingResourceForModule(module_sp, this);
1147     ModulesDidLoad (my_module_list);
1148 }
1149 
1150 void
1151 Target::ModuleRemoved (const ModuleList& module_list, const ModuleSP &module_sp)
1152 {
1153     // A module is being added to this target for the first time
1154     ModuleList my_module_list;
1155     my_module_list.Append(module_sp);
1156     ModulesDidUnload (my_module_list, false);
1157 }
1158 
1159 void
1160 Target::ModuleUpdated (const ModuleList& module_list, const ModuleSP &old_module_sp, const ModuleSP &new_module_sp)
1161 {
1162     // A module is replacing an already added module
1163     m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp, new_module_sp);
1164 }
1165 
1166 void
1167 Target::ModulesDidLoad (ModuleList &module_list)
1168 {
1169     if (module_list.GetSize())
1170     {
1171         m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1172         if (m_process_sp)
1173         {
1174             SystemRuntime *sys_runtime = m_process_sp->GetSystemRuntime();
1175             if (sys_runtime)
1176             {
1177                 sys_runtime->ModulesDidLoad (module_list);
1178             }
1179         }
1180         // TODO: make event data that packages up the module_list
1181         BroadcastEvent (eBroadcastBitModulesLoaded, NULL);
1182     }
1183 }
1184 
1185 void
1186 Target::SymbolsDidLoad (ModuleList &module_list)
1187 {
1188     if (module_list.GetSize())
1189     {
1190         if (m_process_sp)
1191         {
1192             LanguageRuntime* runtime = m_process_sp->GetLanguageRuntime(lldb::eLanguageTypeObjC);
1193             if (runtime)
1194             {
1195                 ObjCLanguageRuntime *objc_runtime = (ObjCLanguageRuntime*)runtime;
1196                 objc_runtime->SymbolsDidLoad(module_list);
1197             }
1198         }
1199 
1200         m_breakpoint_list.UpdateBreakpoints (module_list, true, false);
1201         BroadcastEvent(eBroadcastBitSymbolsLoaded, NULL);
1202     }
1203 }
1204 
1205 void
1206 Target::ModulesDidUnload (ModuleList &module_list, bool delete_locations)
1207 {
1208     if (module_list.GetSize())
1209     {
1210         m_breakpoint_list.UpdateBreakpoints (module_list, false, delete_locations);
1211         // TODO: make event data that packages up the module_list
1212         BroadcastEvent (eBroadcastBitModulesUnloaded, NULL);
1213     }
1214 }
1215 
1216 bool
1217 Target::ModuleIsExcludedForNonModuleSpecificSearches (const FileSpec &module_file_spec)
1218 {
1219     if (GetBreakpointsConsultPlatformAvoidList())
1220     {
1221         ModuleList matchingModules;
1222         ModuleSpec module_spec (module_file_spec);
1223         size_t num_modules = GetImages().FindModules(module_spec, matchingModules);
1224 
1225         // If there is more than one module for this file spec, only return true if ALL the modules are on the
1226         // black list.
1227         if (num_modules > 0)
1228         {
1229             for (size_t i  = 0; i < num_modules; i++)
1230             {
1231                 if (!ModuleIsExcludedForNonModuleSpecificSearches (matchingModules.GetModuleAtIndex(i)))
1232                     return false;
1233             }
1234             return true;
1235         }
1236     }
1237     return false;
1238 }
1239 
1240 bool
1241 Target::ModuleIsExcludedForNonModuleSpecificSearches (const lldb::ModuleSP &module_sp)
1242 {
1243     if (GetBreakpointsConsultPlatformAvoidList())
1244     {
1245         if (m_platform_sp)
1246             return m_platform_sp->ModuleIsExcludedForNonModuleSpecificSearches (*this, module_sp);
1247     }
1248     return false;
1249 }
1250 
1251 size_t
1252 Target::ReadMemoryFromFileCache (const Address& addr, void *dst, size_t dst_len, Error &error)
1253 {
1254     SectionSP section_sp (addr.GetSection());
1255     if (section_sp)
1256     {
1257         // If the contents of this section are encrypted, the on-disk file is unusuable.  Read only from live memory.
1258         if (section_sp->IsEncrypted())
1259         {
1260             error.SetErrorString("section is encrypted");
1261             return 0;
1262         }
1263         ModuleSP module_sp (section_sp->GetModule());
1264         if (module_sp)
1265         {
1266             ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1267             if (objfile)
1268             {
1269                 size_t bytes_read = objfile->ReadSectionData (section_sp.get(),
1270                                                               addr.GetOffset(),
1271                                                               dst,
1272                                                               dst_len);
1273                 if (bytes_read > 0)
1274                     return bytes_read;
1275                 else
1276                     error.SetErrorStringWithFormat("error reading data from section %s", section_sp->GetName().GetCString());
1277             }
1278             else
1279                 error.SetErrorString("address isn't from a object file");
1280         }
1281         else
1282             error.SetErrorString("address isn't in a module");
1283     }
1284     else
1285         error.SetErrorString("address doesn't contain a section that points to a section in a object file");
1286 
1287     return 0;
1288 }
1289 
1290 size_t
1291 Target::ReadMemory (const Address& addr,
1292                     bool prefer_file_cache,
1293                     void *dst,
1294                     size_t dst_len,
1295                     Error &error,
1296                     lldb::addr_t *load_addr_ptr)
1297 {
1298     error.Clear();
1299 
1300     // if we end up reading this from process memory, we will fill this
1301     // with the actual load address
1302     if (load_addr_ptr)
1303         *load_addr_ptr = LLDB_INVALID_ADDRESS;
1304 
1305     size_t bytes_read = 0;
1306 
1307     addr_t load_addr = LLDB_INVALID_ADDRESS;
1308     addr_t file_addr = LLDB_INVALID_ADDRESS;
1309     Address resolved_addr;
1310     if (!addr.IsSectionOffset())
1311     {
1312         SectionLoadList &section_load_list = GetSectionLoadList();
1313         if (section_load_list.IsEmpty())
1314         {
1315             // No sections are loaded, so we must assume we are not running
1316             // yet and anything we are given is a file address.
1317             file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the file address
1318             m_images.ResolveFileAddress (file_addr, resolved_addr);
1319         }
1320         else
1321         {
1322             // We have at least one section loaded. This can be becuase
1323             // we have manually loaded some sections with "target modules load ..."
1324             // or because we have have a live process that has sections loaded
1325             // through the dynamic loader
1326             load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its offset is the load address
1327             section_load_list.ResolveLoadAddress (load_addr, resolved_addr);
1328         }
1329     }
1330     if (!resolved_addr.IsValid())
1331         resolved_addr = addr;
1332 
1333 
1334     if (prefer_file_cache)
1335     {
1336         bytes_read = ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1337         if (bytes_read > 0)
1338             return bytes_read;
1339     }
1340 
1341     if (ProcessIsValid())
1342     {
1343         if (load_addr == LLDB_INVALID_ADDRESS)
1344             load_addr = resolved_addr.GetLoadAddress (this);
1345 
1346         if (load_addr == LLDB_INVALID_ADDRESS)
1347         {
1348             ModuleSP addr_module_sp (resolved_addr.GetModule());
1349             if (addr_module_sp && addr_module_sp->GetFileSpec())
1350                 error.SetErrorStringWithFormat("%s[0x%" PRIx64 "] can't be resolved, %s in not currently loaded",
1351                                                addr_module_sp->GetFileSpec().GetFilename().AsCString(),
1352                                                resolved_addr.GetFileAddress(),
1353                                                addr_module_sp->GetFileSpec().GetFilename().AsCString());
1354             else
1355                 error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved", resolved_addr.GetFileAddress());
1356         }
1357         else
1358         {
1359             bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1360             if (bytes_read != dst_len)
1361             {
1362                 if (error.Success())
1363                 {
1364                     if (bytes_read == 0)
1365                         error.SetErrorStringWithFormat("read memory from 0x%" PRIx64 " failed", load_addr);
1366                     else
1367                         error.SetErrorStringWithFormat("only %" PRIu64 " of %" PRIu64 " bytes were read from memory at 0x%" PRIx64, (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1368                 }
1369             }
1370             if (bytes_read)
1371             {
1372                 if (load_addr_ptr)
1373                     *load_addr_ptr = load_addr;
1374                 return bytes_read;
1375             }
1376             // If the address is not section offset we have an address that
1377             // doesn't resolve to any address in any currently loaded shared
1378             // libaries and we failed to read memory so there isn't anything
1379             // more we can do. If it is section offset, we might be able to
1380             // read cached memory from the object file.
1381             if (!resolved_addr.IsSectionOffset())
1382                 return 0;
1383         }
1384     }
1385 
1386     if (!prefer_file_cache && resolved_addr.IsSectionOffset())
1387     {
1388         // If we didn't already try and read from the object file cache, then
1389         // try it after failing to read from the process.
1390         return ReadMemoryFromFileCache (resolved_addr, dst, dst_len, error);
1391     }
1392     return 0;
1393 }
1394 
1395 size_t
1396 Target::ReadCStringFromMemory (const Address& addr, std::string &out_str, Error &error)
1397 {
1398     char buf[256];
1399     out_str.clear();
1400     addr_t curr_addr = addr.GetLoadAddress(this);
1401     Address address(addr);
1402     while (1)
1403     {
1404         size_t length = ReadCStringFromMemory (address, buf, sizeof(buf), error);
1405         if (length == 0)
1406             break;
1407         out_str.append(buf, length);
1408         // If we got "length - 1" bytes, we didn't get the whole C string, we
1409         // need to read some more characters
1410         if (length == sizeof(buf) - 1)
1411             curr_addr += length;
1412         else
1413             break;
1414         address = Address(curr_addr);
1415     }
1416     return out_str.size();
1417 }
1418 
1419 
1420 size_t
1421 Target::ReadCStringFromMemory (const Address& addr, char *dst, size_t dst_max_len, Error &result_error)
1422 {
1423     size_t total_cstr_len = 0;
1424     if (dst && dst_max_len)
1425     {
1426         result_error.Clear();
1427         // NULL out everything just to be safe
1428         memset (dst, 0, dst_max_len);
1429         Error error;
1430         addr_t curr_addr = addr.GetLoadAddress(this);
1431         Address address(addr);
1432         const size_t cache_line_size = 512;
1433         size_t bytes_left = dst_max_len - 1;
1434         char *curr_dst = dst;
1435 
1436         while (bytes_left > 0)
1437         {
1438             addr_t cache_line_bytes_left = cache_line_size - (curr_addr % cache_line_size);
1439             addr_t bytes_to_read = std::min<addr_t>(bytes_left, cache_line_bytes_left);
1440             size_t bytes_read = ReadMemory (address, false, curr_dst, bytes_to_read, error);
1441 
1442             if (bytes_read == 0)
1443             {
1444                 result_error = error;
1445                 dst[total_cstr_len] = '\0';
1446                 break;
1447             }
1448             const size_t len = strlen(curr_dst);
1449 
1450             total_cstr_len += len;
1451 
1452             if (len < bytes_to_read)
1453                 break;
1454 
1455             curr_dst += bytes_read;
1456             curr_addr += bytes_read;
1457             bytes_left -= bytes_read;
1458             address = Address(curr_addr);
1459         }
1460     }
1461     else
1462     {
1463         if (dst == NULL)
1464             result_error.SetErrorString("invalid arguments");
1465         else
1466             result_error.Clear();
1467     }
1468     return total_cstr_len;
1469 }
1470 
1471 size_t
1472 Target::ReadScalarIntegerFromMemory (const Address& addr,
1473                                      bool prefer_file_cache,
1474                                      uint32_t byte_size,
1475                                      bool is_signed,
1476                                      Scalar &scalar,
1477                                      Error &error)
1478 {
1479     uint64_t uval;
1480 
1481     if (byte_size <= sizeof(uval))
1482     {
1483         size_t bytes_read = ReadMemory (addr, prefer_file_cache, &uval, byte_size, error);
1484         if (bytes_read == byte_size)
1485         {
1486             DataExtractor data (&uval, sizeof(uval), m_arch.GetByteOrder(), m_arch.GetAddressByteSize());
1487             lldb::offset_t offset = 0;
1488             if (byte_size <= 4)
1489                 scalar = data.GetMaxU32 (&offset, byte_size);
1490             else
1491                 scalar = data.GetMaxU64 (&offset, byte_size);
1492 
1493             if (is_signed)
1494                 scalar.SignExtend(byte_size * 8);
1495             return bytes_read;
1496         }
1497     }
1498     else
1499     {
1500         error.SetErrorStringWithFormat ("byte size of %u is too large for integer scalar type", byte_size);
1501     }
1502     return 0;
1503 }
1504 
1505 uint64_t
1506 Target::ReadUnsignedIntegerFromMemory (const Address& addr,
1507                                        bool prefer_file_cache,
1508                                        size_t integer_byte_size,
1509                                        uint64_t fail_value,
1510                                        Error &error)
1511 {
1512     Scalar scalar;
1513     if (ReadScalarIntegerFromMemory (addr,
1514                                      prefer_file_cache,
1515                                      integer_byte_size,
1516                                      false,
1517                                      scalar,
1518                                      error))
1519         return scalar.ULongLong(fail_value);
1520     return fail_value;
1521 }
1522 
1523 bool
1524 Target::ReadPointerFromMemory (const Address& addr,
1525                                bool prefer_file_cache,
1526                                Error &error,
1527                                Address &pointer_addr)
1528 {
1529     Scalar scalar;
1530     if (ReadScalarIntegerFromMemory (addr,
1531                                      prefer_file_cache,
1532                                      m_arch.GetAddressByteSize(),
1533                                      false,
1534                                      scalar,
1535                                      error))
1536     {
1537         addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1538         if (pointer_vm_addr != LLDB_INVALID_ADDRESS)
1539         {
1540             SectionLoadList &section_load_list = GetSectionLoadList();
1541             if (section_load_list.IsEmpty())
1542             {
1543                 // No sections are loaded, so we must assume we are not running
1544                 // yet and anything we are given is a file address.
1545                 m_images.ResolveFileAddress (pointer_vm_addr, pointer_addr);
1546             }
1547             else
1548             {
1549                 // We have at least one section loaded. This can be becuase
1550                 // we have manually loaded some sections with "target modules load ..."
1551                 // or because we have have a live process that has sections loaded
1552                 // through the dynamic loader
1553                 section_load_list.ResolveLoadAddress (pointer_vm_addr, pointer_addr);
1554             }
1555             // We weren't able to resolve the pointer value, so just return
1556             // an address with no section
1557             if (!pointer_addr.IsValid())
1558                 pointer_addr.SetOffset (pointer_vm_addr);
1559             return true;
1560 
1561         }
1562     }
1563     return false;
1564 }
1565 
1566 ModuleSP
1567 Target::GetSharedModule (const ModuleSpec &module_spec, Error *error_ptr)
1568 {
1569     ModuleSP module_sp;
1570 
1571     Error error;
1572 
1573     // First see if we already have this module in our module list.  If we do, then we're done, we don't need
1574     // to consult the shared modules list.  But only do this if we are passed a UUID.
1575 
1576     if (module_spec.GetUUID().IsValid())
1577         module_sp = m_images.FindFirstModule(module_spec);
1578 
1579     if (!module_sp)
1580     {
1581         ModuleSP old_module_sp; // This will get filled in if we have a new version of the library
1582         bool did_create_module = false;
1583 
1584         // If there are image search path entries, try to use them first to acquire a suitable image.
1585         if (m_image_search_paths.GetSize())
1586         {
1587             ModuleSpec transformed_spec (module_spec);
1588             if (m_image_search_paths.RemapPath (module_spec.GetFileSpec().GetDirectory(), transformed_spec.GetFileSpec().GetDirectory()))
1589             {
1590                 transformed_spec.GetFileSpec().GetFilename() = module_spec.GetFileSpec().GetFilename();
1591                 error = ModuleList::GetSharedModule (transformed_spec,
1592                                                      module_sp,
1593                                                      &GetExecutableSearchPaths(),
1594                                                      &old_module_sp,
1595                                                      &did_create_module);
1596             }
1597         }
1598 
1599         if (!module_sp)
1600         {
1601             // If we have a UUID, we can check our global shared module list in case
1602             // we already have it. If we don't have a valid UUID, then we can't since
1603             // the path in "module_spec" will be a platform path, and we will need to
1604             // let the platform find that file. For example, we could be asking for
1605             // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1606             // the local copy of "/usr/lib/dyld" since our platform could be a remote
1607             // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
1608             // cache.
1609             if (module_spec.GetUUID().IsValid())
1610             {
1611                 // We have a UUID, it is OK to check the global module list...
1612                 error = ModuleList::GetSharedModule (module_spec,
1613                                                      module_sp,
1614                                                      &GetExecutableSearchPaths(),
1615                                                      &old_module_sp,
1616                                                      &did_create_module);
1617             }
1618 
1619             if (!module_sp)
1620             {
1621                 // The platform is responsible for finding and caching an appropriate
1622                 // module in the shared module cache.
1623                 if (m_platform_sp)
1624                 {
1625                     FileSpec platform_file_spec;
1626                     error = m_platform_sp->GetSharedModule (module_spec,
1627                                                             module_sp,
1628                                                             &GetExecutableSearchPaths(),
1629                                                             &old_module_sp,
1630                                                             &did_create_module);
1631                 }
1632                 else
1633                 {
1634                     error.SetErrorString("no platform is currently set");
1635                 }
1636             }
1637         }
1638 
1639         // We found a module that wasn't in our target list.  Let's make sure that there wasn't an equivalent
1640         // module in the list already, and if there was, let's remove it.
1641         if (module_sp)
1642         {
1643             ObjectFile *objfile = module_sp->GetObjectFile();
1644             if (objfile)
1645             {
1646                 switch (objfile->GetType())
1647                 {
1648                     case ObjectFile::eTypeCoreFile:      /// A core file that has a checkpoint of a program's execution state
1649                     case ObjectFile::eTypeExecutable:    /// A normal executable
1650                     case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker executable
1651                     case ObjectFile::eTypeObjectFile:    /// An intermediate object file
1652                     case ObjectFile::eTypeSharedLibrary: /// A shared library that can be used during execution
1653                         break;
1654                     case ObjectFile::eTypeDebugInfo:     /// An object file that contains only debug information
1655                         if (error_ptr)
1656                             error_ptr->SetErrorString("debug info files aren't valid target modules, please specify an executable");
1657                         return ModuleSP();
1658                     case ObjectFile::eTypeStubLibrary:   /// A library that can be linked against but not used for execution
1659                         if (error_ptr)
1660                             error_ptr->SetErrorString("stub libraries aren't valid target modules, please specify an executable");
1661                         return ModuleSP();
1662                     default:
1663                         if (error_ptr)
1664                             error_ptr->SetErrorString("unsupported file type, please specify an executable");
1665                         return ModuleSP();
1666                 }
1667                 // GetSharedModule is not guaranteed to find the old shared module, for instance
1668                 // in the common case where you pass in the UUID, it is only going to find the one
1669                 // module matching the UUID.  In fact, it has no good way to know what the "old module"
1670                 // relevant to this target is, since there might be many copies of a module with this file spec
1671                 // in various running debug sessions, but only one of them will belong to this target.
1672                 // So let's remove the UUID from the module list, and look in the target's module list.
1673                 // Only do this if there is SOMETHING else in the module spec...
1674                 if (!old_module_sp)
1675                 {
1676                     if (module_spec.GetUUID().IsValid() && !module_spec.GetFileSpec().GetFilename().IsEmpty() && !module_spec.GetFileSpec().GetDirectory().IsEmpty())
1677                     {
1678                         ModuleSpec module_spec_copy(module_spec.GetFileSpec());
1679                         module_spec_copy.GetUUID().Clear();
1680 
1681                         ModuleList found_modules;
1682                         size_t num_found = m_images.FindModules (module_spec_copy, found_modules);
1683                         if (num_found == 1)
1684                         {
1685                             old_module_sp = found_modules.GetModuleAtIndex(0);
1686                         }
1687                     }
1688                 }
1689 
1690                 if (old_module_sp && m_images.GetIndexForModule (old_module_sp.get()) != LLDB_INVALID_INDEX32)
1691                 {
1692                     m_images.ReplaceModule(old_module_sp, module_sp);
1693                     Module *old_module_ptr = old_module_sp.get();
1694                     old_module_sp.reset();
1695                     ModuleList::RemoveSharedModuleIfOrphaned (old_module_ptr);
1696                 }
1697                 else
1698                     m_images.Append(module_sp);
1699             }
1700         }
1701     }
1702     if (error_ptr)
1703         *error_ptr = error;
1704     return module_sp;
1705 }
1706 
1707 
1708 TargetSP
1709 Target::CalculateTarget ()
1710 {
1711     return shared_from_this();
1712 }
1713 
1714 ProcessSP
1715 Target::CalculateProcess ()
1716 {
1717     return ProcessSP();
1718 }
1719 
1720 ThreadSP
1721 Target::CalculateThread ()
1722 {
1723     return ThreadSP();
1724 }
1725 
1726 StackFrameSP
1727 Target::CalculateStackFrame ()
1728 {
1729     return StackFrameSP();
1730 }
1731 
1732 void
1733 Target::CalculateExecutionContext (ExecutionContext &exe_ctx)
1734 {
1735     exe_ctx.Clear();
1736     exe_ctx.SetTargetPtr(this);
1737 }
1738 
1739 PathMappingList &
1740 Target::GetImageSearchPathList ()
1741 {
1742     return m_image_search_paths;
1743 }
1744 
1745 void
1746 Target::ImageSearchPathsChanged
1747 (
1748     const PathMappingList &path_list,
1749     void *baton
1750 )
1751 {
1752     Target *target = (Target *)baton;
1753     ModuleSP exe_module_sp (target->GetExecutableModule());
1754     if (exe_module_sp)
1755         target->SetExecutableModule (exe_module_sp, true);
1756 }
1757 
1758 ClangASTContext *
1759 Target::GetScratchClangASTContext(bool create_on_demand)
1760 {
1761     // Now see if we know the target triple, and if so, create our scratch AST context:
1762     if (m_scratch_ast_context_ap.get() == NULL && m_arch.IsValid() && create_on_demand)
1763     {
1764         m_scratch_ast_context_ap.reset (new ClangASTContext(m_arch.GetTriple().str().c_str()));
1765         m_scratch_ast_source_ap.reset (new ClangASTSource(shared_from_this()));
1766         m_scratch_ast_source_ap->InstallASTContext(m_scratch_ast_context_ap->getASTContext());
1767         llvm::OwningPtr<clang::ExternalASTSource> proxy_ast_source(m_scratch_ast_source_ap->CreateProxy());
1768         m_scratch_ast_context_ap->SetExternalSource(proxy_ast_source);
1769     }
1770     return m_scratch_ast_context_ap.get();
1771 }
1772 
1773 ClangASTImporter *
1774 Target::GetClangASTImporter()
1775 {
1776     ClangASTImporter *ast_importer = m_ast_importer_ap.get();
1777 
1778     if (!ast_importer)
1779     {
1780         ast_importer = new ClangASTImporter();
1781         m_ast_importer_ap.reset(ast_importer);
1782     }
1783 
1784     return ast_importer;
1785 }
1786 
1787 void
1788 Target::SettingsInitialize ()
1789 {
1790     Process::SettingsInitialize ();
1791 }
1792 
1793 void
1794 Target::SettingsTerminate ()
1795 {
1796     Process::SettingsTerminate ();
1797 }
1798 
1799 FileSpecList
1800 Target::GetDefaultExecutableSearchPaths ()
1801 {
1802     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1803     if (properties_sp)
1804         return properties_sp->GetExecutableSearchPaths();
1805     return FileSpecList();
1806 }
1807 
1808 FileSpecList
1809 Target::GetDefaultDebugFileSearchPaths ()
1810 {
1811     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1812     if (properties_sp)
1813         return properties_sp->GetDebugFileSearchPaths();
1814     return FileSpecList();
1815 }
1816 
1817 ArchSpec
1818 Target::GetDefaultArchitecture ()
1819 {
1820     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1821     if (properties_sp)
1822         return properties_sp->GetDefaultArchitecture();
1823     return ArchSpec();
1824 }
1825 
1826 void
1827 Target::SetDefaultArchitecture (const ArchSpec &arch)
1828 {
1829     TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
1830     if (properties_sp)
1831     {
1832         LogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET, "Target::SetDefaultArchitecture setting target's default architecture to  %s (%s)", arch.GetArchitectureName(), arch.GetTriple().getTriple().c_str());
1833         return properties_sp->SetDefaultArchitecture(arch);
1834     }
1835 }
1836 
1837 Target *
1838 Target::GetTargetFromContexts (const ExecutionContext *exe_ctx_ptr, const SymbolContext *sc_ptr)
1839 {
1840     // The target can either exist in the "process" of ExecutionContext, or in
1841     // the "target_sp" member of SymbolContext. This accessor helper function
1842     // will get the target from one of these locations.
1843 
1844     Target *target = NULL;
1845     if (sc_ptr != NULL)
1846         target = sc_ptr->target_sp.get();
1847     if (target == NULL && exe_ctx_ptr)
1848         target = exe_ctx_ptr->GetTargetPtr();
1849     return target;
1850 }
1851 
1852 ExecutionResults
1853 Target::EvaluateExpression
1854 (
1855     const char *expr_cstr,
1856     StackFrame *frame,
1857     lldb::ValueObjectSP &result_valobj_sp,
1858     const EvaluateExpressionOptions& options
1859 )
1860 {
1861     result_valobj_sp.reset();
1862 
1863     ExecutionResults execution_results = eExecutionSetupError;
1864 
1865     if (expr_cstr == NULL || expr_cstr[0] == '\0')
1866         return execution_results;
1867 
1868     // We shouldn't run stop hooks in expressions.
1869     // Be sure to reset this if you return anywhere within this function.
1870     bool old_suppress_value = m_suppress_stop_hooks;
1871     m_suppress_stop_hooks = true;
1872 
1873     ExecutionContext exe_ctx;
1874 
1875     if (frame)
1876     {
1877         frame->CalculateExecutionContext(exe_ctx);
1878     }
1879     else if (m_process_sp)
1880     {
1881         m_process_sp->CalculateExecutionContext(exe_ctx);
1882     }
1883     else
1884     {
1885         CalculateExecutionContext(exe_ctx);
1886     }
1887 
1888     // Make sure we aren't just trying to see the value of a persistent
1889     // variable (something like "$0")
1890     lldb::ClangExpressionVariableSP persistent_var_sp;
1891     // Only check for persistent variables the expression starts with a '$'
1892     if (expr_cstr[0] == '$')
1893         persistent_var_sp = m_persistent_variables.GetVariable (expr_cstr);
1894 
1895     if (persistent_var_sp)
1896     {
1897         result_valobj_sp = persistent_var_sp->GetValueObject ();
1898         execution_results = eExecutionCompleted;
1899     }
1900     else
1901     {
1902         const char *prefix = GetExpressionPrefixContentsAsCString();
1903         Error error;
1904         execution_results = ClangUserExpression::Evaluate (exe_ctx,
1905                                                            options,
1906                                                            expr_cstr,
1907                                                            prefix,
1908                                                            result_valobj_sp,
1909                                                            error);
1910     }
1911 
1912     m_suppress_stop_hooks = old_suppress_value;
1913 
1914     return execution_results;
1915 }
1916 
1917 lldb::addr_t
1918 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1919 {
1920     addr_t code_addr = load_addr;
1921     switch (m_arch.GetMachine())
1922     {
1923     case llvm::Triple::arm:
1924     case llvm::Triple::thumb:
1925         switch (addr_class)
1926         {
1927         case eAddressClassData:
1928         case eAddressClassDebug:
1929             return LLDB_INVALID_ADDRESS;
1930 
1931         case eAddressClassUnknown:
1932         case eAddressClassInvalid:
1933         case eAddressClassCode:
1934         case eAddressClassCodeAlternateISA:
1935         case eAddressClassRuntime:
1936             // Check if bit zero it no set?
1937             if ((code_addr & 1ull) == 0)
1938             {
1939                 // Bit zero isn't set, check if the address is a multiple of 2?
1940                 if (code_addr & 2ull)
1941                 {
1942                     // The address is a multiple of 2 so it must be thumb, set bit zero
1943                     code_addr |= 1ull;
1944                 }
1945                 else if (addr_class == eAddressClassCodeAlternateISA)
1946                 {
1947                     // We checked the address and the address claims to be the alternate ISA
1948                     // which means thumb, so set bit zero.
1949                     code_addr |= 1ull;
1950                 }
1951             }
1952             break;
1953         }
1954         break;
1955 
1956     default:
1957         break;
1958     }
1959     return code_addr;
1960 }
1961 
1962 lldb::addr_t
1963 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
1964 {
1965     addr_t opcode_addr = load_addr;
1966     switch (m_arch.GetMachine())
1967     {
1968     case llvm::Triple::arm:
1969     case llvm::Triple::thumb:
1970         switch (addr_class)
1971         {
1972         case eAddressClassData:
1973         case eAddressClassDebug:
1974             return LLDB_INVALID_ADDRESS;
1975 
1976         case eAddressClassInvalid:
1977         case eAddressClassUnknown:
1978         case eAddressClassCode:
1979         case eAddressClassCodeAlternateISA:
1980         case eAddressClassRuntime:
1981             opcode_addr &= ~(1ull);
1982             break;
1983         }
1984         break;
1985 
1986     default:
1987         break;
1988     }
1989     return opcode_addr;
1990 }
1991 
1992 SourceManager &
1993 Target::GetSourceManager ()
1994 {
1995     if (m_source_manager_ap.get() == NULL)
1996         m_source_manager_ap.reset (new SourceManager(shared_from_this()));
1997     return *m_source_manager_ap;
1998 }
1999 
2000 
2001 lldb::user_id_t
2002 Target::AddStopHook (Target::StopHookSP &new_hook_sp)
2003 {
2004     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2005     new_hook_sp.reset (new StopHook(shared_from_this(), new_uid));
2006     m_stop_hooks[new_uid] = new_hook_sp;
2007     return new_uid;
2008 }
2009 
2010 bool
2011 Target::RemoveStopHookByID (lldb::user_id_t user_id)
2012 {
2013     size_t num_removed;
2014     num_removed = m_stop_hooks.erase (user_id);
2015     if (num_removed == 0)
2016         return false;
2017     else
2018         return true;
2019 }
2020 
2021 void
2022 Target::RemoveAllStopHooks ()
2023 {
2024     m_stop_hooks.clear();
2025 }
2026 
2027 Target::StopHookSP
2028 Target::GetStopHookByID (lldb::user_id_t user_id)
2029 {
2030     StopHookSP found_hook;
2031 
2032     StopHookCollection::iterator specified_hook_iter;
2033     specified_hook_iter = m_stop_hooks.find (user_id);
2034     if (specified_hook_iter != m_stop_hooks.end())
2035         found_hook = (*specified_hook_iter).second;
2036     return found_hook;
2037 }
2038 
2039 bool
2040 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
2041 {
2042     StopHookCollection::iterator specified_hook_iter;
2043     specified_hook_iter = m_stop_hooks.find (user_id);
2044     if (specified_hook_iter == m_stop_hooks.end())
2045         return false;
2046 
2047     (*specified_hook_iter).second->SetIsActive (active_state);
2048     return true;
2049 }
2050 
2051 void
2052 Target::SetAllStopHooksActiveState (bool active_state)
2053 {
2054     StopHookCollection::iterator pos, end = m_stop_hooks.end();
2055     for (pos = m_stop_hooks.begin(); pos != end; pos++)
2056     {
2057         (*pos).second->SetIsActive (active_state);
2058     }
2059 }
2060 
2061 void
2062 Target::RunStopHooks ()
2063 {
2064     if (m_suppress_stop_hooks)
2065         return;
2066 
2067     if (!m_process_sp)
2068         return;
2069 
2070     // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
2071     // since in that case we do not want to run the stop-hooks
2072     if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2073         return;
2074 
2075     if (m_stop_hooks.empty())
2076         return;
2077 
2078     StopHookCollection::iterator pos, end = m_stop_hooks.end();
2079 
2080     // If there aren't any active stop hooks, don't bother either:
2081     bool any_active_hooks = false;
2082     for (pos = m_stop_hooks.begin(); pos != end; pos++)
2083     {
2084         if ((*pos).second->IsActive())
2085         {
2086             any_active_hooks = true;
2087             break;
2088         }
2089     }
2090     if (!any_active_hooks)
2091         return;
2092 
2093     CommandReturnObject result;
2094 
2095     std::vector<ExecutionContext> exc_ctx_with_reasons;
2096     std::vector<SymbolContext> sym_ctx_with_reasons;
2097 
2098     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2099     size_t num_threads = cur_threadlist.GetSize();
2100     for (size_t i = 0; i < num_threads; i++)
2101     {
2102         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
2103         if (cur_thread_sp->ThreadStoppedForAReason())
2104         {
2105             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2106             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2107             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2108         }
2109     }
2110 
2111     // If no threads stopped for a reason, don't run the stop-hooks.
2112     size_t num_exe_ctx = exc_ctx_with_reasons.size();
2113     if (num_exe_ctx == 0)
2114         return;
2115 
2116     result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
2117     result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
2118 
2119     bool keep_going = true;
2120     bool hooks_ran = false;
2121     bool print_hook_header;
2122     bool print_thread_header;
2123 
2124     if (num_exe_ctx == 1)
2125         print_thread_header = false;
2126     else
2127         print_thread_header = true;
2128 
2129     if (m_stop_hooks.size() == 1)
2130         print_hook_header = false;
2131     else
2132         print_hook_header = true;
2133 
2134     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
2135     {
2136         // result.Clear();
2137         StopHookSP cur_hook_sp = (*pos).second;
2138         if (!cur_hook_sp->IsActive())
2139             continue;
2140 
2141         bool any_thread_matched = false;
2142         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2143         {
2144             if ((cur_hook_sp->GetSpecifier () == NULL
2145                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2146                 && (cur_hook_sp->GetThreadSpecifier() == NULL
2147                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2148             {
2149                 if (!hooks_ran)
2150                 {
2151                     hooks_ran = true;
2152                 }
2153                 if (print_hook_header && !any_thread_matched)
2154                 {
2155                     const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2156                                        cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2157                                        NULL);
2158                     if (cmd)
2159                         result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(), cmd);
2160                     else
2161                         result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2162                     any_thread_matched = true;
2163                 }
2164 
2165                 if (print_thread_header)
2166                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2167 
2168                 bool stop_on_continue = true;
2169                 bool stop_on_error = true;
2170                 bool echo_commands = false;
2171                 bool print_results = true;
2172                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2173                                                                       &exc_ctx_with_reasons[i],
2174                                                                       stop_on_continue,
2175                                                                       stop_on_error,
2176                                                                       echo_commands,
2177                                                                       print_results,
2178                                                                       eLazyBoolNo,
2179                                                                       result);
2180 
2181                 // If the command started the target going again, we should bag out of
2182                 // running the stop hooks.
2183                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2184                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2185                 {
2186                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %" PRIu64 " set the program running.", cur_hook_sp->GetID());
2187                     keep_going = false;
2188                 }
2189             }
2190         }
2191     }
2192 
2193     result.GetImmediateOutputStream()->Flush();
2194     result.GetImmediateErrorStream()->Flush();
2195 }
2196 
2197 const TargetPropertiesSP &
2198 Target::GetGlobalProperties()
2199 {
2200     static TargetPropertiesSP g_settings_sp;
2201     if (!g_settings_sp)
2202     {
2203         g_settings_sp.reset (new TargetProperties (NULL));
2204     }
2205     return g_settings_sp;
2206 }
2207 
2208 Error
2209 Target::Install (ProcessLaunchInfo *launch_info)
2210 {
2211     Error error;
2212     PlatformSP platform_sp (GetPlatform());
2213     if (platform_sp)
2214     {
2215         if (platform_sp->IsRemote())
2216         {
2217             if (platform_sp->IsConnected())
2218             {
2219                 // Install all files that have an install path, and always install the
2220                 // main executable when connected to a remote platform
2221                 const ModuleList& modules = GetImages();
2222                 const size_t num_images = modules.GetSize();
2223                 for (size_t idx = 0; idx < num_images; ++idx)
2224                 {
2225                     const bool is_main_executable = idx == 0;
2226                     ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2227                     if (module_sp)
2228                     {
2229                         FileSpec local_file (module_sp->GetFileSpec());
2230                         if (local_file)
2231                         {
2232                             FileSpec remote_file (module_sp->GetRemoteInstallFileSpec());
2233                             if (!remote_file)
2234                             {
2235                                 if (is_main_executable) // TODO: add setting for always installing main executable???
2236                                 {
2237                                     // Always install the main executable
2238                                     remote_file.GetDirectory() = platform_sp->GetWorkingDirectory();
2239                                     remote_file.GetFilename() = module_sp->GetFileSpec().GetFilename();
2240                                 }
2241                             }
2242                             if (remote_file)
2243                             {
2244                                 error = platform_sp->Install(local_file, remote_file);
2245                                 if (error.Success())
2246                                 {
2247                                     module_sp->SetPlatformFileSpec(remote_file);
2248                                     if (is_main_executable)
2249                                     {
2250                                         if (launch_info)
2251                                             launch_info->SetExecutableFile(remote_file, false);
2252                                     }
2253                                 }
2254                                 else
2255                                     break;
2256                             }
2257                         }
2258                     }
2259                 }
2260             }
2261         }
2262     }
2263     return error;
2264 }
2265 
2266 bool
2267 Target::ResolveLoadAddress (addr_t load_addr, Address &so_addr, uint32_t stop_id)
2268 {
2269     return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2270 }
2271 
2272 bool
2273 Target::SetSectionLoadAddress (const SectionSP &section_sp, addr_t new_section_load_addr, bool warn_multiple)
2274 {
2275     const addr_t old_section_load_addr = m_section_load_history.GetSectionLoadAddress (SectionLoadHistory::eStopIDNow, section_sp);
2276     if (old_section_load_addr != new_section_load_addr)
2277     {
2278         uint32_t stop_id = 0;
2279         ProcessSP process_sp(GetProcessSP());
2280         if (process_sp)
2281             stop_id = process_sp->GetStopID();
2282         else
2283             stop_id = m_section_load_history.GetLastStopID();
2284         if (m_section_load_history.SetSectionLoadAddress (stop_id, section_sp, new_section_load_addr, warn_multiple))
2285             return true; // Return true if the section load address was changed...
2286     }
2287     return false; // Return false to indicate nothing changed
2288 
2289 }
2290 
2291 bool
2292 Target::SetSectionUnloaded (const lldb::SectionSP &section_sp)
2293 {
2294     uint32_t stop_id = 0;
2295     ProcessSP process_sp(GetProcessSP());
2296     if (process_sp)
2297         stop_id = process_sp->GetStopID();
2298     else
2299         stop_id = m_section_load_history.GetLastStopID();
2300     return m_section_load_history.SetSectionUnloaded (stop_id, section_sp);
2301 }
2302 
2303 bool
2304 Target::SetSectionUnloaded (const lldb::SectionSP &section_sp, addr_t load_addr)
2305 {
2306     uint32_t stop_id = 0;
2307     ProcessSP process_sp(GetProcessSP());
2308     if (process_sp)
2309         stop_id = process_sp->GetStopID();
2310     else
2311         stop_id = m_section_load_history.GetLastStopID();
2312     return m_section_load_history.SetSectionUnloaded (stop_id, section_sp, load_addr);
2313 }
2314 
2315 void
2316 Target::ClearAllLoadedSections ()
2317 {
2318     m_section_load_history.Clear();
2319 }
2320 
2321 
2322 Error
2323 Target::Launch (Listener &listener, ProcessLaunchInfo &launch_info)
2324 {
2325     Error error;
2326     Error error2;
2327 
2328     StateType state = eStateInvalid;
2329 
2330     // Scope to temporarily get the process state in case someone has manually
2331     // remotely connected already to a process and we can skip the platform
2332     // launching.
2333     {
2334         ProcessSP process_sp (GetProcessSP());
2335 
2336         if (process_sp)
2337             state = process_sp->GetState();
2338     }
2339 
2340     launch_info.GetFlags().Set (eLaunchFlagDebug);
2341 
2342     // Get the value of synchronous execution here.  If you wait till after you have started to
2343     // run, then you could have hit a breakpoint, whose command might switch the value, and
2344     // then you'll pick up that incorrect value.
2345     Debugger &debugger = GetDebugger();
2346     const bool synchronous_execution = debugger.GetCommandInterpreter().GetSynchronous ();
2347 
2348     PlatformSP platform_sp (GetPlatform());
2349 
2350     // Finalize the file actions, and if none were given, default to opening
2351     // up a pseudo terminal
2352     const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2353     launch_info.FinalizeFileActions (this, default_to_use_pty);
2354 
2355     if (state == eStateConnected)
2356     {
2357         if (launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY))
2358         {
2359             error.SetErrorString("can't launch in tty when launching through a remote connection");
2360             return error;
2361         }
2362     }
2363 
2364     if (!launch_info.GetArchitecture().IsValid())
2365         launch_info.GetArchitecture() = GetArchitecture();
2366 
2367     if (state != eStateConnected && platform_sp && platform_sp->CanDebugProcess ())
2368     {
2369         m_process_sp = GetPlatform()->DebugProcess (launch_info,
2370                                                     debugger,
2371                                                     this,
2372                                                     listener,
2373                                                     error);
2374     }
2375     else
2376     {
2377         if (state == eStateConnected)
2378         {
2379             assert(m_process_sp);
2380         }
2381         else
2382         {
2383             const char *plugin_name = launch_info.GetProcessPluginName();
2384             CreateProcess (listener, plugin_name, NULL);
2385         }
2386 
2387         if (m_process_sp)
2388             error = m_process_sp->Launch (launch_info);
2389     }
2390 
2391     if (!m_process_sp)
2392     {
2393         if (error.Success())
2394             error.SetErrorString("failed to launch or debug process");
2395         return error;
2396     }
2397 
2398     if (error.Success())
2399     {
2400         if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry) == false)
2401         {
2402             StateType state = m_process_sp->WaitForProcessToStop (NULL, NULL, false);
2403 
2404             if (state == eStateStopped)
2405             {
2406                 error = m_process_sp->Resume();
2407                 if (error.Success())
2408                 {
2409                     if (synchronous_execution)
2410                     {
2411                         state = m_process_sp->WaitForProcessToStop (NULL);
2412                         const bool must_be_alive = false; // eStateExited is ok, so this must be false
2413                         if (!StateIsStoppedState(state, must_be_alive))
2414                         {
2415                             error2.SetErrorStringWithFormat("process isn't stopped: %s", StateAsCString(state));
2416                             return error2;
2417                         }
2418                     }
2419                 }
2420                 else
2421                 {
2422                     error2.SetErrorStringWithFormat("process resume at entry point failed: %s", error.AsCString());
2423                     return error2;
2424                 }
2425             }
2426             else
2427             {
2428                 error.SetErrorStringWithFormat ("initial process state wasn't stopped: %s", StateAsCString(state));
2429             }
2430         }
2431     }
2432     else
2433     {
2434         error2.SetErrorStringWithFormat ("process launch failed: %s", error.AsCString());
2435         return error2;
2436     }
2437     return error;
2438 }
2439 //--------------------------------------------------------------
2440 // Target::StopHook
2441 //--------------------------------------------------------------
2442 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2443         UserID (uid),
2444         m_target_sp (target_sp),
2445         m_commands (),
2446         m_specifier_sp (),
2447         m_thread_spec_ap(),
2448         m_active (true)
2449 {
2450 }
2451 
2452 Target::StopHook::StopHook (const StopHook &rhs) :
2453         UserID (rhs.GetID()),
2454         m_target_sp (rhs.m_target_sp),
2455         m_commands (rhs.m_commands),
2456         m_specifier_sp (rhs.m_specifier_sp),
2457         m_thread_spec_ap (),
2458         m_active (rhs.m_active)
2459 {
2460     if (rhs.m_thread_spec_ap.get() != NULL)
2461         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2462 }
2463 
2464 
2465 Target::StopHook::~StopHook ()
2466 {
2467 }
2468 
2469 void
2470 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2471 {
2472     m_thread_spec_ap.reset (specifier);
2473 }
2474 
2475 
2476 void
2477 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2478 {
2479     int indent_level = s->GetIndentLevel();
2480 
2481     s->SetIndentLevel(indent_level + 2);
2482 
2483     s->Printf ("Hook: %" PRIu64 "\n", GetID());
2484     if (m_active)
2485         s->Indent ("State: enabled\n");
2486     else
2487         s->Indent ("State: disabled\n");
2488 
2489     if (m_specifier_sp)
2490     {
2491         s->Indent();
2492         s->PutCString ("Specifier:\n");
2493         s->SetIndentLevel (indent_level + 4);
2494         m_specifier_sp->GetDescription (s, level);
2495         s->SetIndentLevel (indent_level + 2);
2496     }
2497 
2498     if (m_thread_spec_ap.get() != NULL)
2499     {
2500         StreamString tmp;
2501         s->Indent("Thread:\n");
2502         m_thread_spec_ap->GetDescription (&tmp, level);
2503         s->SetIndentLevel (indent_level + 4);
2504         s->Indent (tmp.GetData());
2505         s->PutCString ("\n");
2506         s->SetIndentLevel (indent_level + 2);
2507     }
2508 
2509     s->Indent ("Commands: \n");
2510     s->SetIndentLevel (indent_level + 4);
2511     uint32_t num_commands = m_commands.GetSize();
2512     for (uint32_t i = 0; i < num_commands; i++)
2513     {
2514         s->Indent(m_commands.GetStringAtIndex(i));
2515         s->PutCString ("\n");
2516     }
2517     s->SetIndentLevel (indent_level);
2518 }
2519 
2520 //--------------------------------------------------------------
2521 // class TargetProperties
2522 //--------------------------------------------------------------
2523 
2524 OptionEnumValueElement
2525 lldb_private::g_dynamic_value_types[] =
2526 {
2527     { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2528     { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2529     { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2530     { 0, NULL, NULL }
2531 };
2532 
2533 static OptionEnumValueElement
2534 g_inline_breakpoint_enums[] =
2535 {
2536     { eInlineBreakpointsNever,   "never",     "Never look for inline breakpoint locations (fastest). This setting should only be used if you know that no inlining occurs in your programs."},
2537     { eInlineBreakpointsHeaders, "headers",   "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2538     { eInlineBreakpointsAlways,  "always",    "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2539     { 0, NULL, NULL }
2540 };
2541 
2542 typedef enum x86DisassemblyFlavor
2543 {
2544     eX86DisFlavorDefault,
2545     eX86DisFlavorIntel,
2546     eX86DisFlavorATT
2547 } x86DisassemblyFlavor;
2548 
2549 static OptionEnumValueElement
2550 g_x86_dis_flavor_value_types[] =
2551 {
2552     { eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
2553     { eX86DisFlavorIntel,   "intel",   "Intel disassembler flavor."},
2554     { eX86DisFlavorATT,     "att",     "AT&T disassembler flavor."},
2555     { 0, NULL, NULL }
2556 };
2557 
2558 static OptionEnumValueElement
2559 g_hex_immediate_style_values[] =
2560 {
2561     { Disassembler::eHexStyleC,        "c",      "C-style (0xffff)."},
2562     { Disassembler::eHexStyleAsm,      "asm",    "Asm-style (0ffffh)."},
2563     { 0, NULL, NULL }
2564 };
2565 
2566 static OptionEnumValueElement
2567 g_load_script_from_sym_file_values[] =
2568 {
2569     { eLoadScriptFromSymFileTrue,    "true",    "Load debug scripts inside symbol files"},
2570     { eLoadScriptFromSymFileFalse,   "false",   "Do not load debug scripts inside symbol files."},
2571     { eLoadScriptFromSymFileWarn,    "warn",    "Warn about debug scripts inside symbol files but do not load them."},
2572     { 0, NULL, NULL }
2573 };
2574 
2575 
2576 static OptionEnumValueElement
2577 g_memory_module_load_level_values[] =
2578 {
2579     { eMemoryModuleLoadLevelMinimal,  "minimal" , "Load minimal information when loading modules from memory. Currently this setting loads sections only."},
2580     { eMemoryModuleLoadLevelPartial,  "partial" , "Load partial information when loading modules from memory. Currently this setting loads sections and function bounds."},
2581     { eMemoryModuleLoadLevelComplete, "complete", "Load complete information when loading modules from memory. Currently this setting loads sections and all symbols."},
2582     { 0, NULL, NULL }
2583 };
2584 
2585 static PropertyDefinition
2586 g_properties[] =
2587 {
2588     { "default-arch"                       , OptionValue::eTypeArch      , true , 0                         , NULL, NULL, "Default architecture to choose, when there's a choice." },
2589     { "expr-prefix"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2590     { "prefer-dynamic-value"               , OptionValue::eTypeEnum      , false, eNoDynamicValues          , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2591     { "enable-synthetic-value"             , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Should synthetic values be used by default whenever available." },
2592     { "skip-prologue"                      , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2593     { "source-map"                         , OptionValue::eTypePathMap   , false, 0                         , NULL, NULL, "Source path remappings used to track the change of location between a source file when built, and "
2594       "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
2595       "some part (starting at the root) of the path to the file when it was built, "
2596       "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
2597       "Each element of the array is checked in order and the first one that results in a match wins." },
2598     { "exec-search-paths"                  , OptionValue::eTypeFileSpecList, false, 0                       , NULL, NULL, "Executable search paths to use when locating executable files whose paths don't match the local file system." },
2599     { "debug-file-search-paths"            , OptionValue::eTypeFileSpecList, false, 0                       , NULL, NULL, "List of directories to be searched when locating debug symbol files." },
2600     { "max-children-count"                 , OptionValue::eTypeSInt64    , false, 256                       , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2601     { "max-string-summary-length"          , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2602     { "max-memory-read-size"               , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of bytes that 'memory read' will fetch before --force must be specified." },
2603     { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2604     { "arg0"                               , OptionValue::eTypeString    , false, 0                         , NULL, NULL, "The first argument passed to the program in the argument array which can be different from the executable itself." },
2605     { "run-args"                           , OptionValue::eTypeArgs      , false, 0                         , NULL, NULL, "A list containing all the arguments to be passed to the executable when it is run. Note that this does NOT include the argv[0] which is in target.arg0." },
2606     { "env-vars"                           , OptionValue::eTypeDictionary, false, OptionValue::eTypeString  , NULL, NULL, "A list of all the environment variables to be passed to the executable's environment, and their values." },
2607     { "inherit-env"                        , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2608     { "input-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2609     { "output-path"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2610     { "error-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2611     { "disable-aslr"                       , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2612     { "disable-stdio"                      , OptionValue::eTypeBoolean   , false, false                     , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2613     { "inline-breakpoint-strategy"         , OptionValue::eTypeEnum      , false, eInlineBreakpointsHeaders , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2614         "Breakpoint locations can end up being inlined by the compiler, so that a compile unit 'a.c' might contain an inlined function from another source file. "
2615         "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2616         "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2617         "Always checking for inlined breakpoint locations can be expensive (memory and time), so we try to minimize the "
2618         "times we look for inlined locations. This setting allows you to control exactly which strategy is used when settings "
2619         "file and line breakpoints." },
2620     // FIXME: This is the wrong way to do per-architecture settings, but we don't have a general per architecture settings system in place yet.
2621     { "x86-disassembly-flavor"             , OptionValue::eTypeEnum      , false, eX86DisFlavorDefault,       NULL, g_x86_dis_flavor_value_types, "The default disassembly flavor to use for x86 or x86-64 targets." },
2622     { "use-hex-immediates"                 , OptionValue::eTypeBoolean   , false, true,                       NULL, NULL, "Show immediates in disassembly as hexadecimal." },
2623     { "hex-immediate-style"                , OptionValue::eTypeEnum   ,    false, Disassembler::eHexStyleC,   NULL, g_hex_immediate_style_values, "Which style to use for printing hexadecimal disassembly values." },
2624     { "use-fast-stepping"                  , OptionValue::eTypeBoolean   , false, true,                       NULL, NULL, "Use a fast stepping algorithm based on running from branch to branch rather than instruction single-stepping." },
2625     { "load-script-from-symbol-file"       , OptionValue::eTypeEnum   ,    false, eLoadScriptFromSymFileWarn, NULL, g_load_script_from_sym_file_values, "Allow LLDB to load scripting resources embedded in symbol files when available." },
2626     { "memory-module-load-level"           , OptionValue::eTypeEnum   ,    false, eMemoryModuleLoadLevelComplete, NULL, g_memory_module_load_level_values,
2627         "Loading modules from memory can be slow as reading the symbol tables and other data can take a long time depending on your connection to the debug target. "
2628         "This setting helps users control how much information gets loaded when loading modules from memory."
2629         "'complete' is the default value for this setting which will load all sections and symbols by reading them from memory (slowest, most accurate). "
2630         "'partial' will load sections and attempt to find function bounds without downloading the symbol table (faster, still accurate, missing symbol names). "
2631         "'minimal' is the fastest setting and will load section data with no symbols, but should rarely be used as stack frames in these memory regions will be inaccurate and not provide any context (fastest). " },
2632     { "display-expression-in-crashlogs"    , OptionValue::eTypeBoolean   , false, false,                      NULL, NULL, "Expressions that crash will show up in crash logs if the host system supports executable specific crash log strings and this setting is set to true." },
2633     { NULL                                 , OptionValue::eTypeInvalid   , false, 0                         , NULL, NULL, NULL }
2634 };
2635 enum
2636 {
2637     ePropertyDefaultArch,
2638     ePropertyExprPrefix,
2639     ePropertyPreferDynamic,
2640     ePropertyEnableSynthetic,
2641     ePropertySkipPrologue,
2642     ePropertySourceMap,
2643     ePropertyExecutableSearchPaths,
2644     ePropertyDebugFileSearchPaths,
2645     ePropertyMaxChildrenCount,
2646     ePropertyMaxSummaryLength,
2647     ePropertyMaxMemReadSize,
2648     ePropertyBreakpointUseAvoidList,
2649     ePropertyArg0,
2650     ePropertyRunArgs,
2651     ePropertyEnvVars,
2652     ePropertyInheritEnv,
2653     ePropertyInputPath,
2654     ePropertyOutputPath,
2655     ePropertyErrorPath,
2656     ePropertyDisableASLR,
2657     ePropertyDisableSTDIO,
2658     ePropertyInlineStrategy,
2659     ePropertyDisassemblyFlavor,
2660     ePropertyUseHexImmediates,
2661     ePropertyHexImmediateStyle,
2662     ePropertyUseFastStepping,
2663     ePropertyLoadScriptFromSymbolFile,
2664     ePropertyMemoryModuleLoadLevel,
2665     ePropertyDisplayExpressionsInCrashlogs
2666 };
2667 
2668 
2669 class TargetOptionValueProperties : public OptionValueProperties
2670 {
2671 public:
2672     TargetOptionValueProperties (const ConstString &name) :
2673         OptionValueProperties (name),
2674         m_target (NULL),
2675         m_got_host_env (false)
2676     {
2677     }
2678 
2679     // This constructor is used when creating TargetOptionValueProperties when it
2680     // is part of a new lldb_private::Target instance. It will copy all current
2681     // global property values as needed
2682     TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
2683         OptionValueProperties(*target_properties_sp->GetValueProperties()),
2684         m_target (target),
2685         m_got_host_env (false)
2686     {
2687     }
2688 
2689     virtual const Property *
2690     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
2691     {
2692         // When gettings the value for a key from the target options, we will always
2693         // try and grab the setting from the current target if there is one. Else we just
2694         // use the one from this instance.
2695         if (idx == ePropertyEnvVars)
2696             GetHostEnvironmentIfNeeded ();
2697 
2698         if (exe_ctx)
2699         {
2700             Target *target = exe_ctx->GetTargetPtr();
2701             if (target)
2702             {
2703                 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
2704                 if (this != target_properties)
2705                     return target_properties->ProtectedGetPropertyAtIndex (idx);
2706             }
2707         }
2708         return ProtectedGetPropertyAtIndex (idx);
2709     }
2710 
2711     lldb::TargetSP
2712     GetTargetSP ()
2713     {
2714         return m_target->shared_from_this();
2715     }
2716 
2717 protected:
2718 
2719     void
2720     GetHostEnvironmentIfNeeded () const
2721     {
2722         if (!m_got_host_env)
2723         {
2724             if (m_target)
2725             {
2726                 m_got_host_env = true;
2727                 const uint32_t idx = ePropertyInheritEnv;
2728                 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
2729                 {
2730                     PlatformSP platform_sp (m_target->GetPlatform());
2731                     if (platform_sp)
2732                     {
2733                         StringList env;
2734                         if (platform_sp->GetEnvironment(env))
2735                         {
2736                             OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
2737                             if (env_dict)
2738                             {
2739                                 const bool can_replace = false;
2740                                 const size_t envc = env.GetSize();
2741                                 for (size_t idx=0; idx<envc; idx++)
2742                                 {
2743                                     const char *env_entry = env.GetStringAtIndex (idx);
2744                                     if (env_entry)
2745                                     {
2746                                         const char *equal_pos = ::strchr(env_entry, '=');
2747                                         ConstString key;
2748                                         // It is ok to have environment variables with no values
2749                                         const char *value = NULL;
2750                                         if (equal_pos)
2751                                         {
2752                                             key.SetCStringWithLength(env_entry, equal_pos - env_entry);
2753                                             if (equal_pos[1])
2754                                                 value = equal_pos + 1;
2755                                         }
2756                                         else
2757                                         {
2758                                             key.SetCString(env_entry);
2759                                         }
2760                                         // Don't allow existing keys to be replaced with ones we get from the platform environment
2761                                         env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
2762                                     }
2763                                 }
2764                             }
2765                         }
2766                     }
2767                 }
2768             }
2769         }
2770     }
2771     Target *m_target;
2772     mutable bool m_got_host_env;
2773 };
2774 
2775 //----------------------------------------------------------------------
2776 // TargetProperties
2777 //----------------------------------------------------------------------
2778 TargetProperties::TargetProperties (Target *target) :
2779     Properties ()
2780 {
2781     if (target)
2782     {
2783         m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
2784     }
2785     else
2786     {
2787         m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
2788         m_collection_sp->Initialize(g_properties);
2789         m_collection_sp->AppendProperty(ConstString("process"),
2790                                         ConstString("Settings specify to processes."),
2791                                         true,
2792                                         Process::GetGlobalProperties()->GetValueProperties());
2793     }
2794 }
2795 
2796 TargetProperties::~TargetProperties ()
2797 {
2798 }
2799 ArchSpec
2800 TargetProperties::GetDefaultArchitecture () const
2801 {
2802     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2803     if (value)
2804         return value->GetCurrentValue();
2805     return ArchSpec();
2806 }
2807 
2808 void
2809 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
2810 {
2811     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
2812     if (value)
2813         return value->SetCurrentValue(arch, true);
2814 }
2815 
2816 lldb::DynamicValueType
2817 TargetProperties::GetPreferDynamicValue() const
2818 {
2819     const uint32_t idx = ePropertyPreferDynamic;
2820     return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2821 }
2822 
2823 bool
2824 TargetProperties::GetDisableASLR () const
2825 {
2826     const uint32_t idx = ePropertyDisableASLR;
2827     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2828 }
2829 
2830 void
2831 TargetProperties::SetDisableASLR (bool b)
2832 {
2833     const uint32_t idx = ePropertyDisableASLR;
2834     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2835 }
2836 
2837 bool
2838 TargetProperties::GetDisableSTDIO () const
2839 {
2840     const uint32_t idx = ePropertyDisableSTDIO;
2841     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2842 }
2843 
2844 void
2845 TargetProperties::SetDisableSTDIO (bool b)
2846 {
2847     const uint32_t idx = ePropertyDisableSTDIO;
2848     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
2849 }
2850 
2851 const char *
2852 TargetProperties::GetDisassemblyFlavor () const
2853 {
2854     const uint32_t idx = ePropertyDisassemblyFlavor;
2855     const char *return_value;
2856 
2857     x86DisassemblyFlavor flavor_value = (x86DisassemblyFlavor) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2858     return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
2859     return return_value;
2860 }
2861 
2862 InlineStrategy
2863 TargetProperties::GetInlineStrategy () const
2864 {
2865     const uint32_t idx = ePropertyInlineStrategy;
2866     return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
2867 }
2868 
2869 const char *
2870 TargetProperties::GetArg0 () const
2871 {
2872     const uint32_t idx = ePropertyArg0;
2873     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
2874 }
2875 
2876 void
2877 TargetProperties::SetArg0 (const char *arg)
2878 {
2879     const uint32_t idx = ePropertyArg0;
2880     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
2881 }
2882 
2883 bool
2884 TargetProperties::GetRunArguments (Args &args) const
2885 {
2886     const uint32_t idx = ePropertyRunArgs;
2887     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
2888 }
2889 
2890 void
2891 TargetProperties::SetRunArguments (const Args &args)
2892 {
2893     const uint32_t idx = ePropertyRunArgs;
2894     m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
2895 }
2896 
2897 size_t
2898 TargetProperties::GetEnvironmentAsArgs (Args &env) const
2899 {
2900     const uint32_t idx = ePropertyEnvVars;
2901     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
2902 }
2903 
2904 bool
2905 TargetProperties::GetSkipPrologue() const
2906 {
2907     const uint32_t idx = ePropertySkipPrologue;
2908     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2909 }
2910 
2911 PathMappingList &
2912 TargetProperties::GetSourcePathMap () const
2913 {
2914     const uint32_t idx = ePropertySourceMap;
2915     OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
2916     assert(option_value);
2917     return option_value->GetCurrentValue();
2918 }
2919 
2920 FileSpecList &
2921 TargetProperties::GetExecutableSearchPaths ()
2922 {
2923     const uint32_t idx = ePropertyExecutableSearchPaths;
2924     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2925     assert(option_value);
2926     return option_value->GetCurrentValue();
2927 }
2928 
2929 FileSpecList &
2930 TargetProperties::GetDebugFileSearchPaths ()
2931 {
2932     const uint32_t idx = ePropertyDebugFileSearchPaths;
2933     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
2934     assert(option_value);
2935     return option_value->GetCurrentValue();
2936 }
2937 
2938 bool
2939 TargetProperties::GetEnableSyntheticValue () const
2940 {
2941     const uint32_t idx = ePropertyEnableSynthetic;
2942     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
2943 }
2944 
2945 uint32_t
2946 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
2947 {
2948     const uint32_t idx = ePropertyMaxChildrenCount;
2949     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2950 }
2951 
2952 uint32_t
2953 TargetProperties::GetMaximumSizeOfStringSummary() const
2954 {
2955     const uint32_t idx = ePropertyMaxSummaryLength;
2956     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2957 }
2958 
2959 uint32_t
2960 TargetProperties::GetMaximumMemReadSize () const
2961 {
2962     const uint32_t idx = ePropertyMaxMemReadSize;
2963     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
2964 }
2965 
2966 FileSpec
2967 TargetProperties::GetStandardInputPath () const
2968 {
2969     const uint32_t idx = ePropertyInputPath;
2970     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2971 }
2972 
2973 void
2974 TargetProperties::SetStandardInputPath (const char *p)
2975 {
2976     const uint32_t idx = ePropertyInputPath;
2977     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2978 }
2979 
2980 FileSpec
2981 TargetProperties::GetStandardOutputPath () const
2982 {
2983     const uint32_t idx = ePropertyOutputPath;
2984     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
2985 }
2986 
2987 void
2988 TargetProperties::SetStandardOutputPath (const char *p)
2989 {
2990     const uint32_t idx = ePropertyOutputPath;
2991     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
2992 }
2993 
2994 FileSpec
2995 TargetProperties::GetStandardErrorPath () const
2996 {
2997     const uint32_t idx = ePropertyErrorPath;
2998     return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
2999 }
3000 
3001 const char *
3002 TargetProperties::GetExpressionPrefixContentsAsCString ()
3003 {
3004     const uint32_t idx = ePropertyExprPrefix;
3005     OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
3006     if (file)
3007     {
3008         const bool null_terminate = true;
3009         DataBufferSP data_sp(file->GetFileContents(null_terminate));
3010         if (data_sp)
3011             return (const char *) data_sp->GetBytes();
3012     }
3013     return NULL;
3014 }
3015 
3016 void
3017 TargetProperties::SetStandardErrorPath (const char *p)
3018 {
3019     const uint32_t idx = ePropertyErrorPath;
3020     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3021 }
3022 
3023 bool
3024 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
3025 {
3026     const uint32_t idx = ePropertyBreakpointUseAvoidList;
3027     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3028 }
3029 
3030 bool
3031 TargetProperties::GetUseHexImmediates () const
3032 {
3033     const uint32_t idx = ePropertyUseHexImmediates;
3034     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3035 }
3036 
3037 bool
3038 TargetProperties::GetUseFastStepping () const
3039 {
3040     const uint32_t idx = ePropertyUseFastStepping;
3041     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3042 }
3043 
3044 bool
3045 TargetProperties::GetDisplayExpressionsInCrashlogs () const
3046 {
3047     const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3048     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3049 }
3050 
3051 LoadScriptFromSymFile
3052 TargetProperties::GetLoadScriptFromSymbolFile () const
3053 {
3054     const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3055     return (LoadScriptFromSymFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3056 }
3057 
3058 Disassembler::HexImmediateStyle
3059 TargetProperties::GetHexImmediateStyle () const
3060 {
3061     const uint32_t idx = ePropertyHexImmediateStyle;
3062     return (Disassembler::HexImmediateStyle)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3063 }
3064 
3065 MemoryModuleLoadLevel
3066 TargetProperties::GetMemoryModuleLoadLevel() const
3067 {
3068     const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3069     return (MemoryModuleLoadLevel)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3070 }
3071 
3072 
3073 
3074 //----------------------------------------------------------------------
3075 // Target::TargetEventData
3076 //----------------------------------------------------------------------
3077 const ConstString &
3078 Target::TargetEventData::GetFlavorString ()
3079 {
3080     static ConstString g_flavor ("Target::TargetEventData");
3081     return g_flavor;
3082 }
3083 
3084 const ConstString &
3085 Target::TargetEventData::GetFlavor () const
3086 {
3087     return TargetEventData::GetFlavorString ();
3088 }
3089 
3090 Target::TargetEventData::TargetEventData (const lldb::TargetSP &new_target_sp) :
3091     EventData(),
3092     m_target_sp (new_target_sp)
3093 {
3094 }
3095 
3096 Target::TargetEventData::~TargetEventData()
3097 {
3098 
3099 }
3100 
3101 void
3102 Target::TargetEventData::Dump (Stream *s) const
3103 {
3104 
3105 }
3106 
3107 const TargetSP
3108 Target::TargetEventData::GetTargetFromEvent (const lldb::EventSP &event_sp)
3109 {
3110     TargetSP target_sp;
3111 
3112     const TargetEventData *data = GetEventDataFromEvent (event_sp.get());
3113     if (data)
3114         target_sp = data->m_target_sp;
3115 
3116     return target_sp;
3117 }
3118 
3119 const Target::TargetEventData *
3120 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
3121 {
3122     if (event_ptr)
3123     {
3124         const EventData *event_data = event_ptr->GetData();
3125         if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
3126             return static_cast <const TargetEventData *> (event_ptr->GetData());
3127     }
3128     return NULL;
3129 }
3130 
3131