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