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