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