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