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