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