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