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