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