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         m_process_sp = GetPlatform()->DebugProcess (launch_info,
2584                                                     debugger,
2585                                                     this,
2586                                                     error);
2587     }
2588     else
2589     {
2590         if (log)
2591             log->Printf ("Target::%s the platform doesn't know how to debug a process, getting a process plugin to do this for us.", __FUNCTION__);
2592 
2593         if (state == eStateConnected)
2594         {
2595             assert(m_process_sp);
2596         }
2597         else
2598         {
2599             // Use a Process plugin to construct the process.
2600             const char *plugin_name = launch_info.GetProcessPluginName();
2601             CreateProcess (launch_info.GetListenerForProcess(debugger), plugin_name, NULL);
2602         }
2603 
2604         // Since we didn't have a platform launch the process, launch it here.
2605         if (m_process_sp)
2606             error = m_process_sp->Launch (launch_info);
2607     }
2608 
2609     if (!m_process_sp)
2610     {
2611         if (error.Success())
2612             error.SetErrorString("failed to launch or debug process");
2613         return error;
2614     }
2615 
2616     if (error.Success())
2617     {
2618         if (synchronous_execution || launch_info.GetFlags().Test(eLaunchFlagStopAtEntry) == false)
2619         {
2620             EventSP event_sp;
2621             ListenerSP hijack_listener_sp (launch_info.GetHijackListener());
2622             if (!hijack_listener_sp)
2623             {
2624                 hijack_listener_sp.reset(new Listener("lldb.Target.Launch.hijack"));
2625                 launch_info.SetHijackListener(hijack_listener_sp);
2626                 m_process_sp->HijackProcessEvents(hijack_listener_sp.get());
2627             }
2628 
2629             StateType state = m_process_sp->WaitForProcessToStop (NULL, &event_sp, false, hijack_listener_sp.get(), NULL);
2630 
2631             if (state == eStateStopped)
2632             {
2633                 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2634                 {
2635                     if (synchronous_execution)
2636                     {
2637                         error = m_process_sp->PrivateResume();
2638                         if (error.Success())
2639                         {
2640                             state = m_process_sp->WaitForProcessToStop (NULL, NULL, true, hijack_listener_sp.get(), stream);
2641                             const bool must_be_alive = false; // eStateExited is ok, so this must be false
2642                             if (!StateIsStoppedState(state, must_be_alive))
2643                             {
2644                                 error.SetErrorStringWithFormat("process isn't stopped: %s", StateAsCString(state));
2645                             }
2646                         }
2647                     }
2648                     else
2649                     {
2650                         m_process_sp->RestoreProcessEvents();
2651                         error = m_process_sp->PrivateResume();
2652                     }
2653                     if (!error.Success())
2654                     {
2655                         Error error2;
2656                         error2.SetErrorStringWithFormat("process resume at entry point failed: %s", error.AsCString());
2657                         error = error2;
2658                     }
2659                 }
2660                 else
2661                 {
2662                     assert(synchronous_execution && launch_info.GetFlags().Test(eLaunchFlagStopAtEntry));
2663 
2664                     // Target was stopped at entry as was intended. Need to notify the listeners about it.
2665                     m_process_sp->RestoreProcessEvents();
2666                     m_process_sp->HandlePrivateEvent(event_sp);
2667                 }
2668             }
2669             else if (state == eStateExited)
2670             {
2671                 bool with_shell = !!launch_info.GetShell();
2672                 const int exit_status = m_process_sp->GetExitStatus();
2673                 const char *exit_desc = m_process_sp->GetExitDescription();
2674 #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'."
2675                 if (exit_desc && exit_desc[0])
2676                 {
2677                     if (with_shell)
2678                         error.SetErrorStringWithFormat ("process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE, exit_status, exit_desc);
2679                     else
2680                         error.SetErrorStringWithFormat ("process exited with status %i (%s)", exit_status, exit_desc);
2681                 }
2682                 else
2683                 {
2684                     if (with_shell)
2685                         error.SetErrorStringWithFormat ("process exited with status %i" LAUNCH_SHELL_MESSAGE, exit_status);
2686                     else
2687                         error.SetErrorStringWithFormat ("process exited with status %i", exit_status);
2688                 }
2689             }
2690             else
2691             {
2692                 error.SetErrorStringWithFormat ("initial process state wasn't stopped: %s", StateAsCString(state));
2693             }
2694         }
2695         m_process_sp->RestoreProcessEvents ();
2696     }
2697     else
2698     {
2699         Error error2;
2700         error2.SetErrorStringWithFormat ("process launch failed: %s", error.AsCString());
2701         error = error2;
2702     }
2703     return error;
2704 }
2705 
2706 Error
2707 Target::Attach (ProcessAttachInfo &attach_info, Stream *stream)
2708 {
2709     auto state = eStateInvalid;
2710     auto process_sp = GetProcessSP ();
2711     if (process_sp)
2712     {
2713         state = process_sp->GetState ();
2714         if (process_sp->IsAlive () && state != eStateConnected)
2715         {
2716             if (state == eStateAttaching)
2717                 return Error ("process attach is in progress");
2718             return Error ("a process is already being debugged");
2719         }
2720     }
2721 
2722     ListenerSP hijack_listener_sp (new Listener ("lldb.Target.Attach.attach.hijack"));
2723     attach_info.SetHijackListener (hijack_listener_sp);
2724 
2725     const ModuleSP old_exec_module_sp = GetExecutableModule ();
2726 
2727     // If no process info was specified, then use the target executable
2728     // name as the process to attach to by default
2729     if (!attach_info.ProcessInfoSpecified ())
2730     {
2731         if (old_exec_module_sp)
2732             attach_info.GetExecutableFile ().GetFilename () = old_exec_module_sp->GetPlatformFileSpec ().GetFilename ();
2733 
2734         if (!attach_info.ProcessInfoSpecified ())
2735         {
2736             return Error ("no process specified, create a target with a file, or specify the --pid or --name");
2737         }
2738     }
2739 
2740     const auto platform_sp = GetDebugger ().GetPlatformList ().GetSelectedPlatform ();
2741 
2742     Error error;
2743     if (state != eStateConnected && platform_sp != nullptr && platform_sp->CanDebugProcess ())
2744     {
2745         SetPlatform (platform_sp);
2746         process_sp = platform_sp->Attach (attach_info, GetDebugger (), this, error);
2747     }
2748     else
2749     {
2750         if (state != eStateConnected)
2751         {
2752             const char *plugin_name = attach_info.GetProcessPluginName ();
2753             process_sp = CreateProcess (attach_info.GetListenerForProcess (GetDebugger ()), plugin_name, nullptr);
2754             if (process_sp == nullptr)
2755             {
2756                 error.SetErrorStringWithFormat ("failed to create process using plugin %s", (plugin_name) ? plugin_name : "null");
2757                 return error;
2758             }
2759         }
2760         process_sp->HijackProcessEvents (hijack_listener_sp.get ());
2761         error = process_sp->Attach (attach_info);
2762     }
2763 
2764     if (error.Success () && process_sp)
2765     {
2766         state = process_sp->WaitForProcessToStop (nullptr, nullptr, false, attach_info.GetHijackListener ().get (), stream);
2767         process_sp->RestoreProcessEvents ();
2768 
2769         if (state != eStateStopped)
2770         {
2771             const char *exit_desc = process_sp->GetExitDescription ();
2772             if (exit_desc)
2773                 error.SetErrorStringWithFormat ("attach failed: %s", exit_desc);
2774             else
2775                 error.SetErrorString ("attach failed: process did not stop (no such process or permission problem?)");
2776             process_sp->Destroy (false);
2777         }
2778     }
2779     return error;
2780 }
2781 
2782 //--------------------------------------------------------------
2783 // Target::StopHook
2784 //--------------------------------------------------------------
2785 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
2786         UserID (uid),
2787         m_target_sp (target_sp),
2788         m_commands (),
2789         m_specifier_sp (),
2790         m_thread_spec_ap(),
2791         m_active (true)
2792 {
2793 }
2794 
2795 Target::StopHook::StopHook (const StopHook &rhs) :
2796         UserID (rhs.GetID()),
2797         m_target_sp (rhs.m_target_sp),
2798         m_commands (rhs.m_commands),
2799         m_specifier_sp (rhs.m_specifier_sp),
2800         m_thread_spec_ap (),
2801         m_active (rhs.m_active)
2802 {
2803     if (rhs.m_thread_spec_ap.get() != NULL)
2804         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
2805 }
2806 
2807 
2808 Target::StopHook::~StopHook ()
2809 {
2810 }
2811 
2812 void
2813 Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier)
2814 {
2815     m_specifier_sp.reset(specifier);
2816 }
2817 
2818 void
2819 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
2820 {
2821     m_thread_spec_ap.reset (specifier);
2822 }
2823 
2824 
2825 void
2826 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
2827 {
2828     int indent_level = s->GetIndentLevel();
2829 
2830     s->SetIndentLevel(indent_level + 2);
2831 
2832     s->Printf ("Hook: %" PRIu64 "\n", GetID());
2833     if (m_active)
2834         s->Indent ("State: enabled\n");
2835     else
2836         s->Indent ("State: disabled\n");
2837 
2838     if (m_specifier_sp)
2839     {
2840         s->Indent();
2841         s->PutCString ("Specifier:\n");
2842         s->SetIndentLevel (indent_level + 4);
2843         m_specifier_sp->GetDescription (s, level);
2844         s->SetIndentLevel (indent_level + 2);
2845     }
2846 
2847     if (m_thread_spec_ap.get() != NULL)
2848     {
2849         StreamString tmp;
2850         s->Indent("Thread:\n");
2851         m_thread_spec_ap->GetDescription (&tmp, level);
2852         s->SetIndentLevel (indent_level + 4);
2853         s->Indent (tmp.GetData());
2854         s->PutCString ("\n");
2855         s->SetIndentLevel (indent_level + 2);
2856     }
2857 
2858     s->Indent ("Commands: \n");
2859     s->SetIndentLevel (indent_level + 4);
2860     uint32_t num_commands = m_commands.GetSize();
2861     for (uint32_t i = 0; i < num_commands; i++)
2862     {
2863         s->Indent(m_commands.GetStringAtIndex(i));
2864         s->PutCString ("\n");
2865     }
2866     s->SetIndentLevel (indent_level);
2867 }
2868 
2869 //--------------------------------------------------------------
2870 // class TargetProperties
2871 //--------------------------------------------------------------
2872 
2873 OptionEnumValueElement
2874 lldb_private::g_dynamic_value_types[] =
2875 {
2876     { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
2877     { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
2878     { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
2879     { 0, NULL, NULL }
2880 };
2881 
2882 static OptionEnumValueElement
2883 g_inline_breakpoint_enums[] =
2884 {
2885     { 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."},
2886     { eInlineBreakpointsHeaders, "headers",   "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
2887     { eInlineBreakpointsAlways,  "always",    "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
2888     { 0, NULL, NULL }
2889 };
2890 
2891 typedef enum x86DisassemblyFlavor
2892 {
2893     eX86DisFlavorDefault,
2894     eX86DisFlavorIntel,
2895     eX86DisFlavorATT
2896 } x86DisassemblyFlavor;
2897 
2898 static OptionEnumValueElement
2899 g_x86_dis_flavor_value_types[] =
2900 {
2901     { eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
2902     { eX86DisFlavorIntel,   "intel",   "Intel disassembler flavor."},
2903     { eX86DisFlavorATT,     "att",     "AT&T disassembler flavor."},
2904     { 0, NULL, NULL }
2905 };
2906 
2907 static OptionEnumValueElement
2908 g_hex_immediate_style_values[] =
2909 {
2910     { Disassembler::eHexStyleC,        "c",      "C-style (0xffff)."},
2911     { Disassembler::eHexStyleAsm,      "asm",    "Asm-style (0ffffh)."},
2912     { 0, NULL, NULL }
2913 };
2914 
2915 static OptionEnumValueElement
2916 g_load_script_from_sym_file_values[] =
2917 {
2918     { eLoadScriptFromSymFileTrue,    "true",    "Load debug scripts inside symbol files"},
2919     { eLoadScriptFromSymFileFalse,   "false",   "Do not load debug scripts inside symbol files."},
2920     { eLoadScriptFromSymFileWarn,    "warn",    "Warn about debug scripts inside symbol files but do not load them."},
2921     { 0, NULL, NULL }
2922 };
2923 
2924 
2925 static OptionEnumValueElement
2926 g_memory_module_load_level_values[] =
2927 {
2928     { eMemoryModuleLoadLevelMinimal,  "minimal" , "Load minimal information when loading modules from memory. Currently this setting loads sections only."},
2929     { eMemoryModuleLoadLevelPartial,  "partial" , "Load partial information when loading modules from memory. Currently this setting loads sections and function bounds."},
2930     { eMemoryModuleLoadLevelComplete, "complete", "Load complete information when loading modules from memory. Currently this setting loads sections and all symbols."},
2931     { 0, NULL, NULL }
2932 };
2933 
2934 static PropertyDefinition
2935 g_properties[] =
2936 {
2937     { "default-arch"                       , OptionValue::eTypeArch      , true , 0                         , NULL, NULL, "Default architecture to choose, when there's a choice." },
2938     { "move-to-nearest-code"               , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Move breakpoints to nearest code." },
2939     { "expr-prefix"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "Path to a file containing expressions to be prepended to all expressions." },
2940     { "prefer-dynamic-value"               , OptionValue::eTypeEnum      , false, eDynamicDontRunTarget     , NULL, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
2941     { "enable-synthetic-value"             , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Should synthetic values be used by default whenever available." },
2942     { "skip-prologue"                      , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Skip function prologues when setting breakpoints by name." },
2943     { "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 "
2944       "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
2945       "some part (starting at the root) of the path to the file when it was built, "
2946       "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
2947       "Each element of the array is checked in order and the first one that results in a match wins." },
2948     { "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." },
2949     { "debug-file-search-paths"            , OptionValue::eTypeFileSpecList, false, 0                       , NULL, NULL, "List of directories to be searched when locating debug symbol files." },
2950     { "clang-module-search-paths"          , OptionValue::eTypeFileSpecList, false, 0                       , NULL, NULL, "List of directories to be searched when locating modules for Clang." },
2951     { "auto-import-clang-modules"          , OptionValue::eTypeBoolean   , false, false                     , NULL, NULL, "Automatically load Clang modules referred to by the program." },
2952     { "max-children-count"                 , OptionValue::eTypeSInt64    , false, 256                       , NULL, NULL, "Maximum number of children to expand in any level of depth." },
2953     { "max-string-summary-length"          , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of characters to show when using %s in summary strings." },
2954     { "max-memory-read-size"               , OptionValue::eTypeSInt64    , false, 1024                      , NULL, NULL, "Maximum number of bytes that 'memory read' will fetch before --force must be specified." },
2955     { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Consult the platform module avoid list when setting non-module specific breakpoints." },
2956     { "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." },
2957     { "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." },
2958     { "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." },
2959     { "inherit-env"                        , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Inherit the environment from the process that is running LLDB." },
2960     { "input-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for reading its standard input." },
2961     { "output-path"                        , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard output." },
2962     { "error-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , NULL, NULL, "The file/path to be used by the executable program for writing its standard error." },
2963     { "detach-on-error"                    , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "debugserver will detach (rather than killing) a process if it loses connection with lldb." },
2964     { "disable-aslr"                       , OptionValue::eTypeBoolean   , false, true                      , NULL, NULL, "Disable Address Space Layout Randomization (ASLR)" },
2965     { "disable-stdio"                      , OptionValue::eTypeBoolean   , false, false                     , NULL, NULL, "Disable stdin/stdout for process (e.g. for a GUI application)" },
2966     { "inline-breakpoint-strategy"         , OptionValue::eTypeEnum      , false, eInlineBreakpointsAlways  , NULL, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
2967         "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. "
2968         "Usually this is limitted to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
2969         "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
2970         "Always checking for inlined breakpoint locations can be expensive (memory and time), so if you have a project with many headers "
2971         "and find that setting breakpoints is slow, then you can change this setting to headers. "
2972         "This setting allows you to control exactly which strategy is used when setting "
2973         "file and line breakpoints." },
2974     // 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.
2975     { "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." },
2976     { "use-hex-immediates"                 , OptionValue::eTypeBoolean   , false, true,                       NULL, NULL, "Show immediates in disassembly as hexadecimal." },
2977     { "hex-immediate-style"                , OptionValue::eTypeEnum   ,    false, Disassembler::eHexStyleC,   NULL, g_hex_immediate_style_values, "Which style to use for printing hexadecimal disassembly values." },
2978     { "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." },
2979     { "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." },
2980     { "memory-module-load-level"           , OptionValue::eTypeEnum   ,    false, eMemoryModuleLoadLevelComplete, NULL, g_memory_module_load_level_values,
2981         "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. "
2982         "This setting helps users control how much information gets loaded when loading modules from memory."
2983         "'complete' is the default value for this setting which will load all sections and symbols by reading them from memory (slowest, most accurate). "
2984         "'partial' will load sections and attempt to find function bounds without downloading the symbol table (faster, still accurate, missing symbol names). "
2985         "'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). " },
2986     { "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." },
2987     { "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." },
2988     { "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." },
2989     { "non-stop-mode"                      , OptionValue::eTypeBoolean   , false, 0,                          NULL, NULL, "Disable lock-step debugging, instead control threads independently." },
2990     { NULL                                 , OptionValue::eTypeInvalid   , false, 0                         , NULL, NULL, NULL }
2991 };
2992 
2993 enum
2994 {
2995     ePropertyDefaultArch,
2996     ePropertyMoveToNearestCode,
2997     ePropertyExprPrefix,
2998     ePropertyPreferDynamic,
2999     ePropertyEnableSynthetic,
3000     ePropertySkipPrologue,
3001     ePropertySourceMap,
3002     ePropertyExecutableSearchPaths,
3003     ePropertyDebugFileSearchPaths,
3004     ePropertyClangModuleSearchPaths,
3005     ePropertyAutoImportClangModules,
3006     ePropertyMaxChildrenCount,
3007     ePropertyMaxSummaryLength,
3008     ePropertyMaxMemReadSize,
3009     ePropertyBreakpointUseAvoidList,
3010     ePropertyArg0,
3011     ePropertyRunArgs,
3012     ePropertyEnvVars,
3013     ePropertyInheritEnv,
3014     ePropertyInputPath,
3015     ePropertyOutputPath,
3016     ePropertyErrorPath,
3017     ePropertyDetachOnError,
3018     ePropertyDisableASLR,
3019     ePropertyDisableSTDIO,
3020     ePropertyInlineStrategy,
3021     ePropertyDisassemblyFlavor,
3022     ePropertyUseHexImmediates,
3023     ePropertyHexImmediateStyle,
3024     ePropertyUseFastStepping,
3025     ePropertyLoadScriptFromSymbolFile,
3026     ePropertyMemoryModuleLoadLevel,
3027     ePropertyDisplayExpressionsInCrashlogs,
3028     ePropertyTrapHandlerNames,
3029     ePropertyDisplayRuntimeSupportValues,
3030     ePropertyNonStopModeEnabled
3031 };
3032 
3033 
3034 class TargetOptionValueProperties : public OptionValueProperties
3035 {
3036 public:
3037     TargetOptionValueProperties (const ConstString &name) :
3038         OptionValueProperties (name),
3039         m_target (NULL),
3040         m_got_host_env (false)
3041     {
3042     }
3043 
3044     // This constructor is used when creating TargetOptionValueProperties when it
3045     // is part of a new lldb_private::Target instance. It will copy all current
3046     // global property values as needed
3047     TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
3048         OptionValueProperties(*target_properties_sp->GetValueProperties()),
3049         m_target (target),
3050         m_got_host_env (false)
3051     {
3052     }
3053 
3054     virtual const Property *
3055     GetPropertyAtIndex (const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const
3056     {
3057         // When getting the value for a key from the target options, we will always
3058         // try and grab the setting from the current target if there is one. Else we just
3059         // use the one from this instance.
3060         if (idx == ePropertyEnvVars)
3061             GetHostEnvironmentIfNeeded ();
3062 
3063         if (exe_ctx)
3064         {
3065             Target *target = exe_ctx->GetTargetPtr();
3066             if (target)
3067             {
3068                 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
3069                 if (this != target_properties)
3070                     return target_properties->ProtectedGetPropertyAtIndex (idx);
3071             }
3072         }
3073         return ProtectedGetPropertyAtIndex (idx);
3074     }
3075 
3076     lldb::TargetSP
3077     GetTargetSP ()
3078     {
3079         return m_target->shared_from_this();
3080     }
3081 
3082 protected:
3083 
3084     void
3085     GetHostEnvironmentIfNeeded () const
3086     {
3087         if (!m_got_host_env)
3088         {
3089             if (m_target)
3090             {
3091                 m_got_host_env = true;
3092                 const uint32_t idx = ePropertyInheritEnv;
3093                 if (GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0))
3094                 {
3095                     PlatformSP platform_sp (m_target->GetPlatform());
3096                     if (platform_sp)
3097                     {
3098                         StringList env;
3099                         if (platform_sp->GetEnvironment(env))
3100                         {
3101                             OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary (NULL, ePropertyEnvVars);
3102                             if (env_dict)
3103                             {
3104                                 const bool can_replace = false;
3105                                 const size_t envc = env.GetSize();
3106                                 for (size_t idx=0; idx<envc; idx++)
3107                                 {
3108                                     const char *env_entry = env.GetStringAtIndex (idx);
3109                                     if (env_entry)
3110                                     {
3111                                         const char *equal_pos = ::strchr(env_entry, '=');
3112                                         ConstString key;
3113                                         // It is ok to have environment variables with no values
3114                                         const char *value = NULL;
3115                                         if (equal_pos)
3116                                         {
3117                                             key.SetCStringWithLength(env_entry, equal_pos - env_entry);
3118                                             if (equal_pos[1])
3119                                                 value = equal_pos + 1;
3120                                         }
3121                                         else
3122                                         {
3123                                             key.SetCString(env_entry);
3124                                         }
3125                                         // Don't allow existing keys to be replaced with ones we get from the platform environment
3126                                         env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
3127                                     }
3128                                 }
3129                             }
3130                         }
3131                     }
3132                 }
3133             }
3134         }
3135     }
3136     Target *m_target;
3137     mutable bool m_got_host_env;
3138 };
3139 
3140 //----------------------------------------------------------------------
3141 // TargetProperties
3142 //----------------------------------------------------------------------
3143 TargetProperties::TargetProperties (Target *target) :
3144     Properties (),
3145     m_launch_info ()
3146 {
3147     if (target)
3148     {
3149         m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
3150 
3151         // Set callbacks to update launch_info whenever "settins set" updated any of these properties
3152         m_collection_sp->SetValueChangedCallback(ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3153         m_collection_sp->SetValueChangedCallback(ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3154         m_collection_sp->SetValueChangedCallback(ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3155         m_collection_sp->SetValueChangedCallback(ePropertyInputPath, TargetProperties::InputPathValueChangedCallback, this);
3156         m_collection_sp->SetValueChangedCallback(ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback, this);
3157         m_collection_sp->SetValueChangedCallback(ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback, this);
3158         m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, TargetProperties::DetachOnErrorValueChangedCallback, this);
3159         m_collection_sp->SetValueChangedCallback(ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback, this);
3160         m_collection_sp->SetValueChangedCallback(ePropertyDisableSTDIO, TargetProperties::DisableSTDIOValueChangedCallback, this);
3161 
3162         // Update m_launch_info once it was created
3163         Arg0ValueChangedCallback(this, NULL);
3164         RunArgsValueChangedCallback(this, NULL);
3165         //EnvVarsValueChangedCallback(this, NULL); // FIXME: cause segfault in Target::GetPlatform()
3166         InputPathValueChangedCallback(this, NULL);
3167         OutputPathValueChangedCallback(this, NULL);
3168         ErrorPathValueChangedCallback(this, NULL);
3169         DetachOnErrorValueChangedCallback(this, NULL);
3170         DisableASLRValueChangedCallback(this, NULL);
3171         DisableSTDIOValueChangedCallback(this, NULL);
3172     }
3173     else
3174     {
3175         m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
3176         m_collection_sp->Initialize(g_properties);
3177         m_collection_sp->AppendProperty(ConstString("process"),
3178                                         ConstString("Settings specify to processes."),
3179                                         true,
3180                                         Process::GetGlobalProperties()->GetValueProperties());
3181     }
3182 
3183 }
3184 
3185 TargetProperties::~TargetProperties ()
3186 {
3187 }
3188 ArchSpec
3189 TargetProperties::GetDefaultArchitecture () const
3190 {
3191     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
3192     if (value)
3193         return value->GetCurrentValue();
3194     return ArchSpec();
3195 }
3196 
3197 void
3198 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
3199 {
3200     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch (NULL, ePropertyDefaultArch);
3201     if (value)
3202         return value->SetCurrentValue(arch, true);
3203 }
3204 
3205 bool
3206 TargetProperties::GetMoveToNearestCode() const
3207 {
3208     const uint32_t idx = ePropertyMoveToNearestCode;
3209     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3210 }
3211 
3212 lldb::DynamicValueType
3213 TargetProperties::GetPreferDynamicValue() const
3214 {
3215     const uint32_t idx = ePropertyPreferDynamic;
3216     return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
3217 }
3218 
3219 bool
3220 TargetProperties::SetPreferDynamicValue (lldb::DynamicValueType d)
3221 {
3222     const uint32_t idx = ePropertyPreferDynamic;
3223     return m_collection_sp->SetPropertyAtIndexAsEnumeration(NULL, idx, d);
3224 }
3225 
3226 
3227 bool
3228 TargetProperties::GetDisableASLR () const
3229 {
3230     const uint32_t idx = ePropertyDisableASLR;
3231     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3232 }
3233 
3234 void
3235 TargetProperties::SetDisableASLR (bool b)
3236 {
3237     const uint32_t idx = ePropertyDisableASLR;
3238     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3239 }
3240 
3241 bool
3242 TargetProperties::GetDetachOnError () const
3243 {
3244     const uint32_t idx = ePropertyDetachOnError;
3245     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3246 }
3247 
3248 void
3249 TargetProperties::SetDetachOnError (bool b)
3250 {
3251     const uint32_t idx = ePropertyDetachOnError;
3252     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3253 }
3254 
3255 bool
3256 TargetProperties::GetDisableSTDIO () const
3257 {
3258     const uint32_t idx = ePropertyDisableSTDIO;
3259     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3260 }
3261 
3262 void
3263 TargetProperties::SetDisableSTDIO (bool b)
3264 {
3265     const uint32_t idx = ePropertyDisableSTDIO;
3266     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3267 }
3268 
3269 const char *
3270 TargetProperties::GetDisassemblyFlavor () const
3271 {
3272     const uint32_t idx = ePropertyDisassemblyFlavor;
3273     const char *return_value;
3274 
3275     x86DisassemblyFlavor flavor_value = (x86DisassemblyFlavor) m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
3276     return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3277     return return_value;
3278 }
3279 
3280 InlineStrategy
3281 TargetProperties::GetInlineStrategy () const
3282 {
3283     const uint32_t idx = ePropertyInlineStrategy;
3284     return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration (NULL, idx, g_properties[idx].default_uint_value);
3285 }
3286 
3287 const char *
3288 TargetProperties::GetArg0 () const
3289 {
3290     const uint32_t idx = ePropertyArg0;
3291     return m_collection_sp->GetPropertyAtIndexAsString (NULL, idx, NULL);
3292 }
3293 
3294 void
3295 TargetProperties::SetArg0 (const char *arg)
3296 {
3297     const uint32_t idx = ePropertyArg0;
3298     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, arg);
3299     m_launch_info.SetArg0(arg);
3300 }
3301 
3302 bool
3303 TargetProperties::GetRunArguments (Args &args) const
3304 {
3305     const uint32_t idx = ePropertyRunArgs;
3306     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
3307 }
3308 
3309 void
3310 TargetProperties::SetRunArguments (const Args &args)
3311 {
3312     const uint32_t idx = ePropertyRunArgs;
3313     m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
3314     m_launch_info.GetArguments() = args;
3315 }
3316 
3317 size_t
3318 TargetProperties::GetEnvironmentAsArgs (Args &env) const
3319 {
3320     const uint32_t idx = ePropertyEnvVars;
3321     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, env);
3322 }
3323 
3324 void
3325 TargetProperties::SetEnvironmentFromArgs (const Args &env)
3326 {
3327     const uint32_t idx = ePropertyEnvVars;
3328     m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, env);
3329     m_launch_info.GetEnvironmentEntries() = env;
3330 }
3331 
3332 bool
3333 TargetProperties::GetSkipPrologue() const
3334 {
3335     const uint32_t idx = ePropertySkipPrologue;
3336     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3337 }
3338 
3339 PathMappingList &
3340 TargetProperties::GetSourcePathMap () const
3341 {
3342     const uint32_t idx = ePropertySourceMap;
3343     OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings (NULL, false, idx);
3344     assert(option_value);
3345     return option_value->GetCurrentValue();
3346 }
3347 
3348 FileSpecList &
3349 TargetProperties::GetExecutableSearchPaths ()
3350 {
3351     const uint32_t idx = ePropertyExecutableSearchPaths;
3352     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
3353     assert(option_value);
3354     return option_value->GetCurrentValue();
3355 }
3356 
3357 FileSpecList &
3358 TargetProperties::GetDebugFileSearchPaths ()
3359 {
3360     const uint32_t idx = ePropertyDebugFileSearchPaths;
3361     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
3362     assert(option_value);
3363     return option_value->GetCurrentValue();
3364 }
3365 
3366 FileSpecList &
3367 TargetProperties::GetClangModuleSearchPaths ()
3368 {
3369     const uint32_t idx = ePropertyClangModuleSearchPaths;
3370     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList (NULL, false, idx);
3371     assert(option_value);
3372     return option_value->GetCurrentValue();
3373 }
3374 
3375 bool
3376 TargetProperties::GetEnableAutoImportClangModules() const
3377 {
3378     const uint32_t idx = ePropertyAutoImportClangModules;
3379     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3380 }
3381 
3382 bool
3383 TargetProperties::GetEnableSyntheticValue () const
3384 {
3385     const uint32_t idx = ePropertyEnableSynthetic;
3386     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3387 }
3388 
3389 uint32_t
3390 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
3391 {
3392     const uint32_t idx = ePropertyMaxChildrenCount;
3393     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
3394 }
3395 
3396 uint32_t
3397 TargetProperties::GetMaximumSizeOfStringSummary() const
3398 {
3399     const uint32_t idx = ePropertyMaxSummaryLength;
3400     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
3401 }
3402 
3403 uint32_t
3404 TargetProperties::GetMaximumMemReadSize () const
3405 {
3406     const uint32_t idx = ePropertyMaxMemReadSize;
3407     return m_collection_sp->GetPropertyAtIndexAsSInt64 (NULL, idx, g_properties[idx].default_uint_value);
3408 }
3409 
3410 FileSpec
3411 TargetProperties::GetStandardInputPath () const
3412 {
3413     const uint32_t idx = ePropertyInputPath;
3414     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
3415 }
3416 
3417 void
3418 TargetProperties::SetStandardInputPath (const char *p)
3419 {
3420     const uint32_t idx = ePropertyInputPath;
3421     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3422 }
3423 
3424 FileSpec
3425 TargetProperties::GetStandardOutputPath () const
3426 {
3427     const uint32_t idx = ePropertyOutputPath;
3428     return m_collection_sp->GetPropertyAtIndexAsFileSpec (NULL, idx);
3429 }
3430 
3431 void
3432 TargetProperties::SetStandardOutputPath (const char *p)
3433 {
3434     const uint32_t idx = ePropertyOutputPath;
3435     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3436 }
3437 
3438 FileSpec
3439 TargetProperties::GetStandardErrorPath () const
3440 {
3441     const uint32_t idx = ePropertyErrorPath;
3442     return m_collection_sp->GetPropertyAtIndexAsFileSpec(NULL, idx);
3443 }
3444 
3445 const char *
3446 TargetProperties::GetExpressionPrefixContentsAsCString ()
3447 {
3448     const uint32_t idx = ePropertyExprPrefix;
3449     OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec (NULL, false, idx);
3450     if (file)
3451     {
3452         const bool null_terminate = true;
3453         DataBufferSP data_sp(file->GetFileContents(null_terminate));
3454         if (data_sp)
3455             return (const char *) data_sp->GetBytes();
3456     }
3457     return NULL;
3458 }
3459 
3460 void
3461 TargetProperties::SetStandardErrorPath (const char *p)
3462 {
3463     const uint32_t idx = ePropertyErrorPath;
3464     m_collection_sp->SetPropertyAtIndexAsString (NULL, idx, p);
3465 }
3466 
3467 bool
3468 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
3469 {
3470     const uint32_t idx = ePropertyBreakpointUseAvoidList;
3471     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3472 }
3473 
3474 bool
3475 TargetProperties::GetUseHexImmediates () const
3476 {
3477     const uint32_t idx = ePropertyUseHexImmediates;
3478     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3479 }
3480 
3481 bool
3482 TargetProperties::GetUseFastStepping () const
3483 {
3484     const uint32_t idx = ePropertyUseFastStepping;
3485     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3486 }
3487 
3488 bool
3489 TargetProperties::GetDisplayExpressionsInCrashlogs () const
3490 {
3491     const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3492     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, g_properties[idx].default_uint_value != 0);
3493 }
3494 
3495 LoadScriptFromSymFile
3496 TargetProperties::GetLoadScriptFromSymbolFile () const
3497 {
3498     const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3499     return (LoadScriptFromSymFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3500 }
3501 
3502 Disassembler::HexImmediateStyle
3503 TargetProperties::GetHexImmediateStyle () const
3504 {
3505     const uint32_t idx = ePropertyHexImmediateStyle;
3506     return (Disassembler::HexImmediateStyle)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3507 }
3508 
3509 MemoryModuleLoadLevel
3510 TargetProperties::GetMemoryModuleLoadLevel() const
3511 {
3512     const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3513     return (MemoryModuleLoadLevel)m_collection_sp->GetPropertyAtIndexAsEnumeration(NULL, idx, g_properties[idx].default_uint_value);
3514 }
3515 
3516 bool
3517 TargetProperties::GetUserSpecifiedTrapHandlerNames (Args &args) const
3518 {
3519     const uint32_t idx = ePropertyTrapHandlerNames;
3520     return m_collection_sp->GetPropertyAtIndexAsArgs (NULL, idx, args);
3521 }
3522 
3523 void
3524 TargetProperties::SetUserSpecifiedTrapHandlerNames (const Args &args)
3525 {
3526     const uint32_t idx = ePropertyTrapHandlerNames;
3527     m_collection_sp->SetPropertyAtIndexFromArgs (NULL, idx, args);
3528 }
3529 
3530 bool
3531 TargetProperties::GetDisplayRuntimeSupportValues () const
3532 {
3533     const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3534     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, false);
3535 }
3536 
3537 void
3538 TargetProperties::SetDisplayRuntimeSupportValues (bool b)
3539 {
3540     const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3541     m_collection_sp->SetPropertyAtIndexAsBoolean (NULL, idx, b);
3542 }
3543 
3544 bool
3545 TargetProperties::GetNonStopModeEnabled () const
3546 {
3547     const uint32_t idx = ePropertyNonStopModeEnabled;
3548     return m_collection_sp->GetPropertyAtIndexAsBoolean (NULL, idx, false);
3549 }
3550 
3551 const ProcessLaunchInfo &
3552 TargetProperties::GetProcessLaunchInfo ()
3553 {
3554     m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3555     return m_launch_info;
3556 }
3557 
3558 void
3559 TargetProperties::SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
3560 {
3561     m_launch_info = launch_info;
3562     SetArg0(launch_info.GetArg0());
3563     SetRunArguments(launch_info.GetArguments());
3564     SetEnvironmentFromArgs(launch_info.GetEnvironmentEntries());
3565     const FileAction *input_file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
3566     if (input_file_action)
3567     {
3568         const char *input_path = input_file_action->GetPath();
3569         if (input_path)
3570             SetStandardInputPath(input_path);
3571     }
3572     const FileAction *output_file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
3573     if (output_file_action)
3574     {
3575         const char *output_path = output_file_action->GetPath();
3576         if (output_path)
3577             SetStandardOutputPath(output_path);
3578     }
3579     const FileAction *error_file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
3580     if (error_file_action)
3581     {
3582         const char *error_path = error_file_action->GetPath();
3583         if (error_path)
3584             SetStandardErrorPath(error_path);
3585     }
3586     SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3587     SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3588     SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
3589 }
3590 
3591 void
3592 TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr, OptionValue *)
3593 {
3594     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3595     this_->m_launch_info.SetArg0(this_->GetArg0());
3596 }
3597 
3598 void
3599 TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr, OptionValue *)
3600 {
3601     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3602     Args args;
3603     if (this_->GetRunArguments(args))
3604         this_->m_launch_info.GetArguments() = args;
3605 }
3606 
3607 void
3608 TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr, OptionValue *)
3609 {
3610     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3611     Args args;
3612     if (this_->GetEnvironmentAsArgs(args))
3613         this_->m_launch_info.GetEnvironmentEntries() = args;
3614 }
3615 
3616 void
3617 TargetProperties::InputPathValueChangedCallback(void *target_property_ptr, OptionValue *)
3618 {
3619     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3620     this_->m_launch_info.AppendOpenFileAction(STDIN_FILENO, this_->GetStandardInputPath().GetPath().c_str(), true, false);
3621 }
3622 
3623 void
3624 TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr, OptionValue *)
3625 {
3626     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3627     this_->m_launch_info.AppendOpenFileAction(STDOUT_FILENO, this_->GetStandardOutputPath().GetPath().c_str(), false, true);
3628 }
3629 
3630 void
3631 TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr, OptionValue *)
3632 {
3633     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3634     this_->m_launch_info.AppendOpenFileAction(STDERR_FILENO, this_->GetStandardErrorPath().GetPath().c_str(), false, true);
3635 }
3636 
3637 void
3638 TargetProperties::DetachOnErrorValueChangedCallback(void *target_property_ptr, OptionValue *)
3639 {
3640     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3641     if (this_->GetDetachOnError())
3642         this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
3643     else
3644         this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
3645 }
3646 
3647 void
3648 TargetProperties::DisableASLRValueChangedCallback(void *target_property_ptr, OptionValue *)
3649 {
3650     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3651     if (this_->GetDisableASLR())
3652         this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
3653     else
3654         this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
3655 }
3656 
3657 void
3658 TargetProperties::DisableSTDIOValueChangedCallback(void *target_property_ptr, OptionValue *)
3659 {
3660     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
3661     if (this_->GetDisableSTDIO())
3662         this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
3663     else
3664         this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
3665 }
3666 
3667 //----------------------------------------------------------------------
3668 // Target::TargetEventData
3669 //----------------------------------------------------------------------
3670 
3671 Target::TargetEventData::TargetEventData (const lldb::TargetSP &target_sp) :
3672     EventData (),
3673     m_target_sp (target_sp),
3674     m_module_list ()
3675 {
3676 }
3677 
3678 Target::TargetEventData::TargetEventData (const lldb::TargetSP &target_sp, const ModuleList &module_list) :
3679     EventData (),
3680     m_target_sp (target_sp),
3681     m_module_list (module_list)
3682 {
3683 }
3684 
3685 Target::TargetEventData::~TargetEventData()
3686 {
3687 }
3688 
3689 const ConstString &
3690 Target::TargetEventData::GetFlavorString ()
3691 {
3692     static ConstString g_flavor ("Target::TargetEventData");
3693     return g_flavor;
3694 }
3695 
3696 void
3697 Target::TargetEventData::Dump (Stream *s) const
3698 {
3699 }
3700 
3701 const Target::TargetEventData *
3702 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
3703 {
3704     if (event_ptr)
3705     {
3706         const EventData *event_data = event_ptr->GetData();
3707         if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
3708             return static_cast <const TargetEventData *> (event_ptr->GetData());
3709     }
3710     return NULL;
3711 }
3712 
3713 TargetSP
3714 Target::TargetEventData::GetTargetFromEvent (const Event *event_ptr)
3715 {
3716     TargetSP target_sp;
3717     const TargetEventData *event_data = GetEventDataFromEvent (event_ptr);
3718     if (event_data)
3719         target_sp = event_data->m_target_sp;
3720     return target_sp;
3721 }
3722 
3723 ModuleList
3724 Target::TargetEventData::GetModuleListFromEvent (const Event *event_ptr)
3725 {
3726     ModuleList module_list;
3727     const TargetEventData *event_data = GetEventDataFromEvent (event_ptr);
3728     if (event_data)
3729         module_list = event_data->m_module_list;
3730     return module_list;
3731 }
3732