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