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