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