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