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