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