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