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