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