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