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