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