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