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   // If we read from the file cache but can't get as many bytes as requested,
1762   // we keep the result around in this buffer, in case this result is the
1763   // best we can do.
1764   std::unique_ptr<uint8_t[]> file_cache_read_buffer;
1765   size_t file_cache_bytes_read = 0;
1766 
1767   // Read from file cache if read-only section.
1768   if (!force_live_memory && resolved_addr.IsSectionOffset()) {
1769     SectionSP section_sp(resolved_addr.GetSection());
1770     if (section_sp) {
1771       auto permissions = Flags(section_sp->GetPermissions());
1772       bool is_readonly = !permissions.Test(ePermissionsWritable) &&
1773                          permissions.Test(ePermissionsReadable);
1774       if (is_readonly) {
1775         file_cache_bytes_read =
1776             ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1777         if (file_cache_bytes_read == dst_len)
1778           return file_cache_bytes_read;
1779         else if (file_cache_bytes_read > 0) {
1780           file_cache_read_buffer =
1781               std::make_unique<uint8_t[]>(file_cache_bytes_read);
1782           std::memcpy(file_cache_read_buffer.get(), dst, file_cache_bytes_read);
1783         }
1784       }
1785     }
1786   }
1787 
1788   if (ProcessIsValid()) {
1789     if (load_addr == LLDB_INVALID_ADDRESS)
1790       load_addr = resolved_addr.GetLoadAddress(this);
1791 
1792     if (load_addr == LLDB_INVALID_ADDRESS) {
1793       ModuleSP addr_module_sp(resolved_addr.GetModule());
1794       if (addr_module_sp && addr_module_sp->GetFileSpec())
1795         error.SetErrorStringWithFormatv(
1796             "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1797             addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1798       else
1799         error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1800                                        resolved_addr.GetFileAddress());
1801     } else {
1802       bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1803       if (bytes_read != dst_len) {
1804         if (error.Success()) {
1805           if (bytes_read == 0)
1806             error.SetErrorStringWithFormat(
1807                 "read memory from 0x%" PRIx64 " failed", load_addr);
1808           else
1809             error.SetErrorStringWithFormat(
1810                 "only %" PRIu64 " of %" PRIu64
1811                 " bytes were read from memory at 0x%" PRIx64,
1812                 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1813         }
1814       }
1815       if (bytes_read) {
1816         if (load_addr_ptr)
1817           *load_addr_ptr = load_addr;
1818         return bytes_read;
1819       }
1820     }
1821   }
1822 
1823   if (file_cache_read_buffer && file_cache_bytes_read > 0) {
1824     // Reading from the process failed. If we've previously succeeded in reading
1825     // something from the file cache, then copy that over and return that.
1826     std::memcpy(dst, file_cache_read_buffer.get(), file_cache_bytes_read);
1827     return file_cache_bytes_read;
1828   }
1829 
1830   if (!file_cache_read_buffer && resolved_addr.IsSectionOffset()) {
1831     // If we didn't already try and read from the object file cache, then try
1832     // it after failing to read from the process.
1833     return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1834   }
1835   return 0;
1836 }
1837 
1838 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1839                                      Status &error) {
1840   char buf[256];
1841   out_str.clear();
1842   addr_t curr_addr = addr.GetLoadAddress(this);
1843   Address address(addr);
1844   while (true) {
1845     size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1846     if (length == 0)
1847       break;
1848     out_str.append(buf, length);
1849     // If we got "length - 1" bytes, we didn't get the whole C string, we need
1850     // to read some more characters
1851     if (length == sizeof(buf) - 1)
1852       curr_addr += length;
1853     else
1854       break;
1855     address = Address(curr_addr);
1856   }
1857   return out_str.size();
1858 }
1859 
1860 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1861                                      size_t dst_max_len, Status &result_error) {
1862   size_t total_cstr_len = 0;
1863   if (dst && dst_max_len) {
1864     result_error.Clear();
1865     // NULL out everything just to be safe
1866     memset(dst, 0, dst_max_len);
1867     Status error;
1868     addr_t curr_addr = addr.GetLoadAddress(this);
1869     Address address(addr);
1870 
1871     // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1872     // this really needs to be tied to the memory cache subsystem's cache line
1873     // size, so leave this as a fixed constant.
1874     const size_t cache_line_size = 512;
1875 
1876     size_t bytes_left = dst_max_len - 1;
1877     char *curr_dst = dst;
1878 
1879     while (bytes_left > 0) {
1880       addr_t cache_line_bytes_left =
1881           cache_line_size - (curr_addr % cache_line_size);
1882       addr_t bytes_to_read =
1883           std::min<addr_t>(bytes_left, cache_line_bytes_left);
1884       size_t bytes_read =
1885           ReadMemory(address, curr_dst, bytes_to_read, error, true);
1886 
1887       if (bytes_read == 0) {
1888         result_error = error;
1889         dst[total_cstr_len] = '\0';
1890         break;
1891       }
1892       const size_t len = strlen(curr_dst);
1893 
1894       total_cstr_len += len;
1895 
1896       if (len < bytes_to_read)
1897         break;
1898 
1899       curr_dst += bytes_read;
1900       curr_addr += bytes_read;
1901       bytes_left -= bytes_read;
1902       address = Address(curr_addr);
1903     }
1904   } else {
1905     if (dst == nullptr)
1906       result_error.SetErrorString("invalid arguments");
1907     else
1908       result_error.Clear();
1909   }
1910   return total_cstr_len;
1911 }
1912 
1913 size_t Target::ReadScalarIntegerFromMemory(const Address &addr, uint32_t byte_size,
1914                                            bool is_signed, Scalar &scalar,
1915                                            Status &error,
1916                                            bool force_live_memory) {
1917   uint64_t uval;
1918 
1919   if (byte_size <= sizeof(uval)) {
1920     size_t bytes_read =
1921         ReadMemory(addr, &uval, byte_size, error, force_live_memory);
1922     if (bytes_read == byte_size) {
1923       DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1924                          m_arch.GetSpec().GetAddressByteSize());
1925       lldb::offset_t offset = 0;
1926       if (byte_size <= 4)
1927         scalar = data.GetMaxU32(&offset, byte_size);
1928       else
1929         scalar = data.GetMaxU64(&offset, byte_size);
1930 
1931       if (is_signed)
1932         scalar.SignExtend(byte_size * 8);
1933       return bytes_read;
1934     }
1935   } else {
1936     error.SetErrorStringWithFormat(
1937         "byte size of %u is too large for integer scalar type", byte_size);
1938   }
1939   return 0;
1940 }
1941 
1942 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1943                                                size_t integer_byte_size,
1944                                                uint64_t fail_value, Status &error,
1945                                                bool force_live_memory) {
1946   Scalar scalar;
1947   if (ReadScalarIntegerFromMemory(addr, integer_byte_size, false, scalar, error,
1948                                   force_live_memory))
1949     return scalar.ULongLong(fail_value);
1950   return fail_value;
1951 }
1952 
1953 bool Target::ReadPointerFromMemory(const Address &addr, Status &error,
1954                                    Address &pointer_addr,
1955                                    bool force_live_memory) {
1956   Scalar scalar;
1957   if (ReadScalarIntegerFromMemory(addr, m_arch.GetSpec().GetAddressByteSize(),
1958                                   false, scalar, error, force_live_memory)) {
1959     addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1960     if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1961       SectionLoadList &section_load_list = GetSectionLoadList();
1962       if (section_load_list.IsEmpty()) {
1963         // No sections are loaded, so we must assume we are not running yet and
1964         // anything we are given is a file address.
1965         m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1966       } else {
1967         // We have at least one section loaded. This can be because we have
1968         // manually loaded some sections with "target modules load ..." or
1969         // because we have have a live process that has sections loaded through
1970         // the dynamic loader
1971         section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1972       }
1973       // We weren't able to resolve the pointer value, so just return an
1974       // address with no section
1975       if (!pointer_addr.IsValid())
1976         pointer_addr.SetOffset(pointer_vm_addr);
1977       return true;
1978     }
1979   }
1980   return false;
1981 }
1982 
1983 ModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
1984                                    Status *error_ptr) {
1985   ModuleSP module_sp;
1986 
1987   Status error;
1988 
1989   // First see if we already have this module in our module list.  If we do,
1990   // then we're done, we don't need to consult the shared modules list.  But
1991   // only do this if we are passed a UUID.
1992 
1993   if (module_spec.GetUUID().IsValid())
1994     module_sp = m_images.FindFirstModule(module_spec);
1995 
1996   if (!module_sp) {
1997     llvm::SmallVector<ModuleSP, 1>
1998         old_modules; // This will get filled in if we have a new version
1999                      // of the library
2000     bool did_create_module = false;
2001     FileSpecList search_paths = GetExecutableSearchPaths();
2002     // If there are image search path entries, try to use them first to acquire
2003     // a suitable image.
2004     if (m_image_search_paths.GetSize()) {
2005       ModuleSpec transformed_spec(module_spec);
2006       if (m_image_search_paths.RemapPath(
2007               module_spec.GetFileSpec().GetDirectory(),
2008               transformed_spec.GetFileSpec().GetDirectory())) {
2009         transformed_spec.GetFileSpec().GetFilename() =
2010             module_spec.GetFileSpec().GetFilename();
2011         error = ModuleList::GetSharedModule(transformed_spec, module_sp,
2012                                             &search_paths, &old_modules,
2013                                             &did_create_module);
2014       }
2015     }
2016 
2017     if (!module_sp) {
2018       // If we have a UUID, we can check our global shared module list in case
2019       // we already have it. If we don't have a valid UUID, then we can't since
2020       // the path in "module_spec" will be a platform path, and we will need to
2021       // let the platform find that file. For example, we could be asking for
2022       // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2023       // the local copy of "/usr/lib/dyld" since our platform could be a remote
2024       // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2025       // cache.
2026       if (module_spec.GetUUID().IsValid()) {
2027         // We have a UUID, it is OK to check the global module list...
2028         error =
2029             ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
2030                                         &old_modules, &did_create_module);
2031       }
2032 
2033       if (!module_sp) {
2034         // The platform is responsible for finding and caching an appropriate
2035         // module in the shared module cache.
2036         if (m_platform_sp) {
2037           error = m_platform_sp->GetSharedModule(
2038               module_spec, m_process_sp.get(), module_sp, &search_paths,
2039               &old_modules, &did_create_module);
2040         } else {
2041           error.SetErrorString("no platform is currently set");
2042         }
2043       }
2044     }
2045 
2046     // We found a module that wasn't in our target list.  Let's make sure that
2047     // there wasn't an equivalent module in the list already, and if there was,
2048     // let's remove it.
2049     if (module_sp) {
2050       ObjectFile *objfile = module_sp->GetObjectFile();
2051       if (objfile) {
2052         switch (objfile->GetType()) {
2053         case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2054                                         /// a program's execution state
2055         case ObjectFile::eTypeExecutable:    /// A normal executable
2056         case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2057                                              /// executable
2058         case ObjectFile::eTypeObjectFile:    /// An intermediate object file
2059         case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2060                                              /// used during execution
2061           break;
2062         case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2063                                          /// debug information
2064           if (error_ptr)
2065             error_ptr->SetErrorString("debug info files aren't valid target "
2066                                       "modules, please specify an executable");
2067           return ModuleSP();
2068         case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2069                                            /// against but not used for
2070                                            /// execution
2071           if (error_ptr)
2072             error_ptr->SetErrorString("stub libraries aren't valid target "
2073                                       "modules, please specify an executable");
2074           return ModuleSP();
2075         default:
2076           if (error_ptr)
2077             error_ptr->SetErrorString(
2078                 "unsupported file type, please specify an executable");
2079           return ModuleSP();
2080         }
2081         // GetSharedModule is not guaranteed to find the old shared module, for
2082         // instance in the common case where you pass in the UUID, it is only
2083         // going to find the one module matching the UUID.  In fact, it has no
2084         // good way to know what the "old module" relevant to this target is,
2085         // since there might be many copies of a module with this file spec in
2086         // various running debug sessions, but only one of them will belong to
2087         // this target. So let's remove the UUID from the module list, and look
2088         // in the target's module list. Only do this if there is SOMETHING else
2089         // in the module spec...
2090         if (module_spec.GetUUID().IsValid() &&
2091             !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2092             !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2093           ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2094           module_spec_copy.GetUUID().Clear();
2095 
2096           ModuleList found_modules;
2097           m_images.FindModules(module_spec_copy, found_modules);
2098           found_modules.ForEach([&](const ModuleSP &found_module) -> bool {
2099             old_modules.push_back(found_module);
2100             return true;
2101           });
2102         }
2103 
2104         // Preload symbols outside of any lock, so hopefully we can do this for
2105         // each library in parallel.
2106         if (GetPreloadSymbols())
2107           module_sp->PreloadSymbols();
2108 
2109         llvm::SmallVector<ModuleSP, 1> replaced_modules;
2110         for (ModuleSP &old_module_sp : old_modules) {
2111           if (m_images.GetIndexForModule(old_module_sp.get()) !=
2112               LLDB_INVALID_INDEX32) {
2113             if (replaced_modules.empty())
2114               m_images.ReplaceModule(old_module_sp, module_sp);
2115             else
2116               m_images.Remove(old_module_sp);
2117 
2118             replaced_modules.push_back(std::move(old_module_sp));
2119           }
2120         }
2121 
2122         if (replaced_modules.size() > 1) {
2123           // The same new module replaced multiple old modules
2124           // simultaneously.  It's not clear this should ever
2125           // happen (if we always replace old modules as we add
2126           // new ones, presumably we should never have more than
2127           // one old one).  If there are legitimate cases where
2128           // this happens, then the ModuleList::Notifier interface
2129           // may need to be adjusted to allow reporting this.
2130           // In the meantime, just log that this has happened; just
2131           // above we called ReplaceModule on the first one, and Remove
2132           // on the rest.
2133           if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET |
2134                                                   LIBLLDB_LOG_MODULES)) {
2135             StreamString message;
2136             auto dump = [&message](Module &dump_module) -> void {
2137               UUID dump_uuid = dump_module.GetUUID();
2138 
2139               message << '[';
2140               dump_module.GetDescription(message.AsRawOstream());
2141               message << " (uuid ";
2142 
2143               if (dump_uuid.IsValid())
2144                 dump_uuid.Dump(&message);
2145               else
2146                 message << "not specified";
2147 
2148               message << ")]";
2149             };
2150 
2151             message << "New module ";
2152             dump(*module_sp);
2153             message.AsRawOstream()
2154                 << llvm::formatv(" simultaneously replaced {0} old modules: ",
2155                                  replaced_modules.size());
2156             for (ModuleSP &replaced_module_sp : replaced_modules)
2157               dump(*replaced_module_sp);
2158 
2159             log->PutString(message.GetString());
2160           }
2161         }
2162 
2163         if (replaced_modules.empty())
2164           m_images.Append(module_sp, notify);
2165 
2166         for (ModuleSP &old_module_sp : replaced_modules) {
2167           Module *old_module_ptr = old_module_sp.get();
2168           old_module_sp.reset();
2169           ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2170         }
2171       } else
2172         module_sp.reset();
2173     }
2174   }
2175   if (error_ptr)
2176     *error_ptr = error;
2177   return module_sp;
2178 }
2179 
2180 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2181 
2182 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2183 
2184 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2185 
2186 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2187 
2188 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2189   exe_ctx.Clear();
2190   exe_ctx.SetTargetPtr(this);
2191 }
2192 
2193 PathMappingList &Target::GetImageSearchPathList() {
2194   return m_image_search_paths;
2195 }
2196 
2197 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2198                                      void *baton) {
2199   Target *target = (Target *)baton;
2200   ModuleSP exe_module_sp(target->GetExecutableModule());
2201   if (exe_module_sp)
2202     target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2203 }
2204 
2205 llvm::Expected<TypeSystem &>
2206 Target::GetScratchTypeSystemForLanguage(lldb::LanguageType language,
2207                                         bool create_on_demand) {
2208   if (!m_valid)
2209     return llvm::make_error<llvm::StringError>("Invalid Target",
2210                                                llvm::inconvertibleErrorCode());
2211 
2212   if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2213                                              // assembly code
2214       || language == eLanguageTypeUnknown) {
2215     LanguageSet languages_for_expressions =
2216         Language::GetLanguagesSupportingTypeSystemsForExpressions();
2217 
2218     if (languages_for_expressions[eLanguageTypeC]) {
2219       language = eLanguageTypeC; // LLDB's default.  Override by setting the
2220                                  // target language.
2221     } else {
2222       if (languages_for_expressions.Empty())
2223         return llvm::make_error<llvm::StringError>(
2224             "No expression support for any languages",
2225             llvm::inconvertibleErrorCode());
2226       language = (LanguageType)languages_for_expressions.bitvector.find_first();
2227     }
2228   }
2229 
2230   return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2231                                                             create_on_demand);
2232 }
2233 
2234 std::vector<TypeSystem *> Target::GetScratchTypeSystems(bool create_on_demand) {
2235   if (!m_valid)
2236     return {};
2237 
2238   std::vector<TypeSystem *> scratch_type_systems;
2239 
2240   LanguageSet languages_for_expressions =
2241       Language::GetLanguagesSupportingTypeSystemsForExpressions();
2242 
2243   for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2244     auto language = (LanguageType)bit;
2245     auto type_system_or_err =
2246         GetScratchTypeSystemForLanguage(language, create_on_demand);
2247     if (!type_system_or_err)
2248       LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2249                      type_system_or_err.takeError(),
2250                      "Language '{}' has expression support but no scratch type "
2251                      "system available",
2252                      Language::GetNameForLanguageType(language));
2253     else
2254       scratch_type_systems.emplace_back(&type_system_or_err.get());
2255   }
2256 
2257   return scratch_type_systems;
2258 }
2259 
2260 PersistentExpressionState *
2261 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2262   auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2263 
2264   if (auto err = type_system_or_err.takeError()) {
2265     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2266                    std::move(err),
2267                    "Unable to get persistent expression state for language {}",
2268                    Language::GetNameForLanguageType(language));
2269     return nullptr;
2270   }
2271 
2272   return type_system_or_err->GetPersistentExpressionState();
2273 }
2274 
2275 UserExpression *Target::GetUserExpressionForLanguage(
2276     llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2277     Expression::ResultType desired_type,
2278     const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2279     Status &error) {
2280   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2281   if (auto err = type_system_or_err.takeError()) {
2282     error.SetErrorStringWithFormat(
2283         "Could not find type system for language %s: %s",
2284         Language::GetNameForLanguageType(language),
2285         llvm::toString(std::move(err)).c_str());
2286     return nullptr;
2287   }
2288 
2289   auto *user_expr = type_system_or_err->GetUserExpression(
2290       expr, prefix, language, desired_type, options, ctx_obj);
2291   if (!user_expr)
2292     error.SetErrorStringWithFormat(
2293         "Could not create an expression for language %s",
2294         Language::GetNameForLanguageType(language));
2295 
2296   return user_expr;
2297 }
2298 
2299 FunctionCaller *Target::GetFunctionCallerForLanguage(
2300     lldb::LanguageType language, const CompilerType &return_type,
2301     const Address &function_address, const ValueList &arg_value_list,
2302     const char *name, Status &error) {
2303   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2304   if (auto err = type_system_or_err.takeError()) {
2305     error.SetErrorStringWithFormat(
2306         "Could not find type system for language %s: %s",
2307         Language::GetNameForLanguageType(language),
2308         llvm::toString(std::move(err)).c_str());
2309     return nullptr;
2310   }
2311 
2312   auto *persistent_fn = type_system_or_err->GetFunctionCaller(
2313       return_type, function_address, arg_value_list, name);
2314   if (!persistent_fn)
2315     error.SetErrorStringWithFormat(
2316         "Could not create an expression for language %s",
2317         Language::GetNameForLanguageType(language));
2318 
2319   return persistent_fn;
2320 }
2321 
2322 llvm::Expected<std::unique_ptr<UtilityFunction>>
2323 Target::CreateUtilityFunction(std::string expression, std::string name,
2324                               lldb::LanguageType language,
2325                               ExecutionContext &exe_ctx) {
2326   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2327   if (!type_system_or_err)
2328     return type_system_or_err.takeError();
2329 
2330   std::unique_ptr<UtilityFunction> utility_fn =
2331       type_system_or_err->CreateUtilityFunction(std::move(expression),
2332                                                 std::move(name));
2333   if (!utility_fn)
2334     return llvm::make_error<llvm::StringError>(
2335         llvm::StringRef("Could not create an expression for language") +
2336             Language::GetNameForLanguageType(language),
2337         llvm::inconvertibleErrorCode());
2338 
2339   DiagnosticManager diagnostics;
2340   if (!utility_fn->Install(diagnostics, exe_ctx))
2341     return llvm::make_error<llvm::StringError>(diagnostics.GetString(),
2342                                                llvm::inconvertibleErrorCode());
2343 
2344   return std::move(utility_fn);
2345 }
2346 
2347 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2348 
2349 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2350 
2351 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2352   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2353   if (properties_sp)
2354     return properties_sp->GetExecutableSearchPaths();
2355   return FileSpecList();
2356 }
2357 
2358 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2359   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2360   if (properties_sp)
2361     return properties_sp->GetDebugFileSearchPaths();
2362   return FileSpecList();
2363 }
2364 
2365 ArchSpec Target::GetDefaultArchitecture() {
2366   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2367   if (properties_sp)
2368     return properties_sp->GetDefaultArchitecture();
2369   return ArchSpec();
2370 }
2371 
2372 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2373   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2374   if (properties_sp) {
2375     LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET),
2376              "Target::SetDefaultArchitecture setting target's "
2377              "default architecture to  {0} ({1})",
2378              arch.GetArchitectureName(), arch.GetTriple().getTriple());
2379     return properties_sp->SetDefaultArchitecture(arch);
2380   }
2381 }
2382 
2383 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2384                                       const SymbolContext *sc_ptr) {
2385   // The target can either exist in the "process" of ExecutionContext, or in
2386   // the "target_sp" member of SymbolContext. This accessor helper function
2387   // will get the target from one of these locations.
2388 
2389   Target *target = nullptr;
2390   if (sc_ptr != nullptr)
2391     target = sc_ptr->target_sp.get();
2392   if (target == nullptr && exe_ctx_ptr)
2393     target = exe_ctx_ptr->GetTargetPtr();
2394   return target;
2395 }
2396 
2397 ExpressionResults Target::EvaluateExpression(
2398     llvm::StringRef expr, ExecutionContextScope *exe_scope,
2399     lldb::ValueObjectSP &result_valobj_sp,
2400     const EvaluateExpressionOptions &options, std::string *fixed_expression,
2401     ValueObject *ctx_obj) {
2402   result_valobj_sp.reset();
2403 
2404   ExpressionResults execution_results = eExpressionSetupError;
2405 
2406   if (expr.empty())
2407     return execution_results;
2408 
2409   // We shouldn't run stop hooks in expressions.
2410   bool old_suppress_value = m_suppress_stop_hooks;
2411   m_suppress_stop_hooks = true;
2412   auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2413     m_suppress_stop_hooks = old_suppress_value;
2414   });
2415 
2416   ExecutionContext exe_ctx;
2417 
2418   if (exe_scope) {
2419     exe_scope->CalculateExecutionContext(exe_ctx);
2420   } else if (m_process_sp) {
2421     m_process_sp->CalculateExecutionContext(exe_ctx);
2422   } else {
2423     CalculateExecutionContext(exe_ctx);
2424   }
2425 
2426   // Make sure we aren't just trying to see the value of a persistent variable
2427   // (something like "$0")
2428   // Only check for persistent variables the expression starts with a '$'
2429   lldb::ExpressionVariableSP persistent_var_sp;
2430   if (expr[0] == '$') {
2431     auto type_system_or_err =
2432             GetScratchTypeSystemForLanguage(eLanguageTypeC);
2433     if (auto err = type_system_or_err.takeError()) {
2434       LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2435                      std::move(err), "Unable to get scratch type system");
2436     } else {
2437       persistent_var_sp =
2438           type_system_or_err->GetPersistentExpressionState()->GetVariable(expr);
2439     }
2440   }
2441   if (persistent_var_sp) {
2442     result_valobj_sp = persistent_var_sp->GetValueObject();
2443     execution_results = eExpressionCompleted;
2444   } else {
2445     llvm::StringRef prefix = GetExpressionPrefixContents();
2446     Status error;
2447     execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2448                                                  result_valobj_sp, error,
2449                                                  fixed_expression, ctx_obj);
2450   }
2451 
2452   return execution_results;
2453 }
2454 
2455 lldb::ExpressionVariableSP Target::GetPersistentVariable(ConstString name) {
2456   lldb::ExpressionVariableSP variable_sp;
2457   m_scratch_type_system_map.ForEach(
2458       [name, &variable_sp](TypeSystem *type_system) -> bool {
2459         if (PersistentExpressionState *persistent_state =
2460                 type_system->GetPersistentExpressionState()) {
2461           variable_sp = persistent_state->GetVariable(name);
2462 
2463           if (variable_sp)
2464             return false; // Stop iterating the ForEach
2465         }
2466         return true; // Keep iterating the ForEach
2467       });
2468   return variable_sp;
2469 }
2470 
2471 lldb::addr_t Target::GetPersistentSymbol(ConstString name) {
2472   lldb::addr_t address = LLDB_INVALID_ADDRESS;
2473 
2474   m_scratch_type_system_map.ForEach(
2475       [name, &address](TypeSystem *type_system) -> bool {
2476         if (PersistentExpressionState *persistent_state =
2477                 type_system->GetPersistentExpressionState()) {
2478           address = persistent_state->LookupSymbol(name);
2479           if (address != LLDB_INVALID_ADDRESS)
2480             return false; // Stop iterating the ForEach
2481         }
2482         return true; // Keep iterating the ForEach
2483       });
2484   return address;
2485 }
2486 
2487 llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2488   Module *exe_module = GetExecutableModulePointer();
2489 
2490   // Try to find the entry point address in the primary executable.
2491   const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2492   if (has_primary_executable) {
2493     Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2494     if (entry_addr.IsValid())
2495       return entry_addr;
2496   }
2497 
2498   const ModuleList &modules = GetImages();
2499   const size_t num_images = modules.GetSize();
2500   for (size_t idx = 0; idx < num_images; ++idx) {
2501     ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2502     if (!module_sp || !module_sp->GetObjectFile())
2503       continue;
2504 
2505     Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2506     if (entry_addr.IsValid())
2507       return entry_addr;
2508   }
2509 
2510   // We haven't found the entry point address. Return an appropriate error.
2511   if (!has_primary_executable)
2512     return llvm::make_error<llvm::StringError>(
2513         "No primary executable found and could not find entry point address in "
2514         "any executable module",
2515         llvm::inconvertibleErrorCode());
2516 
2517   return llvm::make_error<llvm::StringError>(
2518       "Could not find entry point address for primary executable module \"" +
2519           exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"",
2520       llvm::inconvertibleErrorCode());
2521 }
2522 
2523 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2524                                             AddressClass addr_class) const {
2525   auto arch_plugin = GetArchitecturePlugin();
2526   return arch_plugin
2527              ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2528              : load_addr;
2529 }
2530 
2531 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2532                                           AddressClass addr_class) const {
2533   auto arch_plugin = GetArchitecturePlugin();
2534   return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2535                      : load_addr;
2536 }
2537 
2538 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2539   auto arch_plugin = GetArchitecturePlugin();
2540   return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2541 }
2542 
2543 SourceManager &Target::GetSourceManager() {
2544   if (!m_source_manager_up)
2545     m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2546   return *m_source_manager_up;
2547 }
2548 
2549 Target::StopHookSP Target::CreateStopHook(StopHook::StopHookKind kind) {
2550   lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2551   Target::StopHookSP stop_hook_sp;
2552   switch (kind) {
2553   case StopHook::StopHookKind::CommandBased:
2554     stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
2555     break;
2556   case StopHook::StopHookKind::ScriptBased:
2557     stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
2558     break;
2559   }
2560   m_stop_hooks[new_uid] = stop_hook_sp;
2561   return stop_hook_sp;
2562 }
2563 
2564 void Target::UndoCreateStopHook(lldb::user_id_t user_id) {
2565   if (!RemoveStopHookByID(user_id))
2566     return;
2567   if (user_id == m_stop_hook_next_id)
2568     m_stop_hook_next_id--;
2569 }
2570 
2571 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2572   size_t num_removed = m_stop_hooks.erase(user_id);
2573   return (num_removed != 0);
2574 }
2575 
2576 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2577 
2578 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2579   StopHookSP found_hook;
2580 
2581   StopHookCollection::iterator specified_hook_iter;
2582   specified_hook_iter = m_stop_hooks.find(user_id);
2583   if (specified_hook_iter != m_stop_hooks.end())
2584     found_hook = (*specified_hook_iter).second;
2585   return found_hook;
2586 }
2587 
2588 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2589                                         bool active_state) {
2590   StopHookCollection::iterator specified_hook_iter;
2591   specified_hook_iter = m_stop_hooks.find(user_id);
2592   if (specified_hook_iter == m_stop_hooks.end())
2593     return false;
2594 
2595   (*specified_hook_iter).second->SetIsActive(active_state);
2596   return true;
2597 }
2598 
2599 void Target::SetAllStopHooksActiveState(bool active_state) {
2600   StopHookCollection::iterator pos, end = m_stop_hooks.end();
2601   for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2602     (*pos).second->SetIsActive(active_state);
2603   }
2604 }
2605 
2606 bool Target::RunStopHooks() {
2607   if (m_suppress_stop_hooks)
2608     return false;
2609 
2610   if (!m_process_sp)
2611     return false;
2612 
2613   // Somebody might have restarted the process:
2614   // Still return false, the return value is about US restarting the target.
2615   if (m_process_sp->GetState() != eStateStopped)
2616     return false;
2617 
2618   // <rdar://problem/12027563> make sure we check that we are not stopped
2619   // because of us running a user expression since in that case we do not want
2620   // to run the stop-hooks
2621   if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2622     return false;
2623 
2624   if (m_stop_hooks.empty())
2625     return false;
2626 
2627   // If there aren't any active stop hooks, don't bother either.
2628   bool any_active_hooks = false;
2629   for (auto hook : m_stop_hooks) {
2630     if (hook.second->IsActive()) {
2631       any_active_hooks = true;
2632       break;
2633     }
2634   }
2635   if (!any_active_hooks)
2636     return false;
2637 
2638   std::vector<ExecutionContext> exc_ctx_with_reasons;
2639 
2640   ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2641   size_t num_threads = cur_threadlist.GetSize();
2642   for (size_t i = 0; i < num_threads; i++) {
2643     lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2644     if (cur_thread_sp->ThreadStoppedForAReason()) {
2645       lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2646       exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
2647                                         cur_frame_sp.get());
2648     }
2649   }
2650 
2651   // If no threads stopped for a reason, don't run the stop-hooks.
2652   size_t num_exe_ctx = exc_ctx_with_reasons.size();
2653   if (num_exe_ctx == 0)
2654     return false;
2655 
2656   StreamSP output_sp = m_debugger.GetAsyncOutputStream();
2657 
2658   bool auto_continue = false;
2659   bool hooks_ran = false;
2660   bool print_hook_header = (m_stop_hooks.size() != 1);
2661   bool print_thread_header = (num_exe_ctx != 1);
2662   bool should_stop = false;
2663   bool somebody_restarted = false;
2664 
2665   for (auto stop_entry : m_stop_hooks) {
2666     StopHookSP cur_hook_sp = stop_entry.second;
2667     if (!cur_hook_sp->IsActive())
2668       continue;
2669 
2670     bool any_thread_matched = false;
2671     for (auto exc_ctx : exc_ctx_with_reasons) {
2672       // We detect somebody restarted in the stop-hook loop, and broke out of
2673       // that loop back to here.  So break out of here too.
2674       if (somebody_restarted)
2675         break;
2676 
2677       if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
2678         continue;
2679 
2680       // We only consult the auto-continue for a stop hook if it matched the
2681       // specifier.
2682       auto_continue |= cur_hook_sp->GetAutoContinue();
2683 
2684       if (!hooks_ran)
2685         hooks_ran = true;
2686 
2687       if (print_hook_header && !any_thread_matched) {
2688         StreamString s;
2689         cur_hook_sp->GetDescription(&s, eDescriptionLevelBrief);
2690         if (s.GetSize() != 0)
2691           output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
2692                             s.GetData());
2693         else
2694           output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2695         any_thread_matched = true;
2696       }
2697 
2698       if (print_thread_header)
2699         output_sp->Printf("-- Thread %d\n",
2700                           exc_ctx.GetThreadPtr()->GetIndexID());
2701 
2702       StopHook::StopHookResult this_result =
2703           cur_hook_sp->HandleStop(exc_ctx, output_sp);
2704       bool this_should_stop = true;
2705 
2706       switch (this_result) {
2707       case StopHook::StopHookResult::KeepStopped:
2708         // If this hook is set to auto-continue that should override the
2709         // HandleStop result...
2710         if (cur_hook_sp->GetAutoContinue())
2711           this_should_stop = false;
2712         else
2713           this_should_stop = true;
2714 
2715         break;
2716       case StopHook::StopHookResult::RequestContinue:
2717         this_should_stop = false;
2718         break;
2719       case StopHook::StopHookResult::AlreadyContinued:
2720         // We don't have a good way to prohibit people from restarting the
2721         // target willy nilly in a stop hook.  If the hook did so, give a
2722         // gentle suggestion here and bag out if the hook processing.
2723         output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
2724                           " set the program running.\n"
2725                           "  Consider using '-G true' to make "
2726                           "stop hooks auto-continue.\n",
2727                           cur_hook_sp->GetID());
2728         somebody_restarted = true;
2729         break;
2730       }
2731       // If we're already restarted, stop processing stop hooks.
2732       // FIXME: if we are doing non-stop mode for real, we would have to
2733       // check that OUR thread was restarted, otherwise we should keep
2734       // processing stop hooks.
2735       if (somebody_restarted)
2736         break;
2737 
2738       // If anybody wanted to stop, we should all stop.
2739       if (!should_stop)
2740         should_stop = this_should_stop;
2741     }
2742   }
2743 
2744   output_sp->Flush();
2745 
2746   // If one of the commands in the stop hook already restarted the target,
2747   // report that fact.
2748   if (somebody_restarted)
2749     return true;
2750 
2751   // Finally, if auto-continue was requested, do it now:
2752   // We only compute should_stop against the hook results if a hook got to run
2753   // which is why we have to do this conjoint test.
2754   if ((hooks_ran && !should_stop) || auto_continue) {
2755     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2756     Status error = m_process_sp->PrivateResume();
2757     if (error.Success()) {
2758       LLDB_LOG(log, "Resuming from RunStopHooks");
2759       return true;
2760     } else {
2761       LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
2762       return false;
2763     }
2764   }
2765 
2766   return false;
2767 }
2768 
2769 const TargetPropertiesSP &Target::GetGlobalProperties() {
2770   // NOTE: intentional leak so we don't crash if global destructor chain gets
2771   // called as other threads still use the result of this function
2772   static TargetPropertiesSP *g_settings_sp_ptr =
2773       new TargetPropertiesSP(new TargetProperties(nullptr));
2774   return *g_settings_sp_ptr;
2775 }
2776 
2777 Status Target::Install(ProcessLaunchInfo *launch_info) {
2778   Status error;
2779   PlatformSP platform_sp(GetPlatform());
2780   if (platform_sp) {
2781     if (platform_sp->IsRemote()) {
2782       if (platform_sp->IsConnected()) {
2783         // Install all files that have an install path when connected to a
2784         // remote platform. If target.auto-install-main-executable is set then
2785         // also install the main executable even if it does not have an explicit
2786         // install path specified.
2787         const ModuleList &modules = GetImages();
2788         const size_t num_images = modules.GetSize();
2789         for (size_t idx = 0; idx < num_images; ++idx) {
2790           ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2791           if (module_sp) {
2792             const bool is_main_executable = module_sp == GetExecutableModule();
2793             FileSpec local_file(module_sp->GetFileSpec());
2794             if (local_file) {
2795               FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2796               if (!remote_file) {
2797                 if (is_main_executable && GetAutoInstallMainExecutable()) {
2798                   // Automatically install the main executable.
2799                   remote_file = platform_sp->GetRemoteWorkingDirectory();
2800                   remote_file.AppendPathComponent(
2801                       module_sp->GetFileSpec().GetFilename().GetCString());
2802                 }
2803               }
2804               if (remote_file) {
2805                 error = platform_sp->Install(local_file, remote_file);
2806                 if (error.Success()) {
2807                   module_sp->SetPlatformFileSpec(remote_file);
2808                   if (is_main_executable) {
2809                     platform_sp->SetFilePermissions(remote_file, 0700);
2810                     if (launch_info)
2811                       launch_info->SetExecutableFile(remote_file, false);
2812                   }
2813                 } else
2814                   break;
2815               }
2816             }
2817           }
2818         }
2819       }
2820     }
2821   }
2822   return error;
2823 }
2824 
2825 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2826                                 uint32_t stop_id) {
2827   return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2828 }
2829 
2830 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2831                                 Address &resolved_addr) {
2832   return m_images.ResolveFileAddress(file_addr, resolved_addr);
2833 }
2834 
2835 bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2836                                    addr_t new_section_load_addr,
2837                                    bool warn_multiple) {
2838   const addr_t old_section_load_addr =
2839       m_section_load_history.GetSectionLoadAddress(
2840           SectionLoadHistory::eStopIDNow, section_sp);
2841   if (old_section_load_addr != new_section_load_addr) {
2842     uint32_t stop_id = 0;
2843     ProcessSP process_sp(GetProcessSP());
2844     if (process_sp)
2845       stop_id = process_sp->GetStopID();
2846     else
2847       stop_id = m_section_load_history.GetLastStopID();
2848     if (m_section_load_history.SetSectionLoadAddress(
2849             stop_id, section_sp, new_section_load_addr, warn_multiple))
2850       return true; // Return true if the section load address was changed...
2851   }
2852   return false; // Return false to indicate nothing changed
2853 }
2854 
2855 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2856   size_t section_unload_count = 0;
2857   size_t num_modules = module_list.GetSize();
2858   for (size_t i = 0; i < num_modules; ++i) {
2859     section_unload_count +=
2860         UnloadModuleSections(module_list.GetModuleAtIndex(i));
2861   }
2862   return section_unload_count;
2863 }
2864 
2865 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2866   uint32_t stop_id = 0;
2867   ProcessSP process_sp(GetProcessSP());
2868   if (process_sp)
2869     stop_id = process_sp->GetStopID();
2870   else
2871     stop_id = m_section_load_history.GetLastStopID();
2872   SectionList *sections = module_sp->GetSectionList();
2873   size_t section_unload_count = 0;
2874   if (sections) {
2875     const uint32_t num_sections = sections->GetNumSections(0);
2876     for (uint32_t i = 0; i < num_sections; ++i) {
2877       section_unload_count += m_section_load_history.SetSectionUnloaded(
2878           stop_id, sections->GetSectionAtIndex(i));
2879     }
2880   }
2881   return section_unload_count;
2882 }
2883 
2884 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2885   uint32_t stop_id = 0;
2886   ProcessSP process_sp(GetProcessSP());
2887   if (process_sp)
2888     stop_id = process_sp->GetStopID();
2889   else
2890     stop_id = m_section_load_history.GetLastStopID();
2891   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2892 }
2893 
2894 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2895                                 addr_t load_addr) {
2896   uint32_t stop_id = 0;
2897   ProcessSP process_sp(GetProcessSP());
2898   if (process_sp)
2899     stop_id = process_sp->GetStopID();
2900   else
2901     stop_id = m_section_load_history.GetLastStopID();
2902   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2903                                                    load_addr);
2904 }
2905 
2906 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2907 
2908 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2909   Status error;
2910   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2911 
2912   LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
2913             launch_info.GetExecutableFile().GetPath().c_str());
2914 
2915   StateType state = eStateInvalid;
2916 
2917   // Scope to temporarily get the process state in case someone has manually
2918   // remotely connected already to a process and we can skip the platform
2919   // launching.
2920   {
2921     ProcessSP process_sp(GetProcessSP());
2922 
2923     if (process_sp) {
2924       state = process_sp->GetState();
2925       LLDB_LOGF(log,
2926                 "Target::%s the process exists, and its current state is %s",
2927                 __FUNCTION__, StateAsCString(state));
2928     } else {
2929       LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
2930                 __FUNCTION__);
2931     }
2932   }
2933 
2934   launch_info.GetFlags().Set(eLaunchFlagDebug);
2935 
2936   if (launch_info.IsScriptedProcess()) {
2937     TargetPropertiesSP properties_sp = GetGlobalProperties();
2938 
2939     if (!properties_sp) {
2940       LLDB_LOGF(log, "Target::%s Couldn't fetch target global properties.",
2941                 __FUNCTION__);
2942       return error;
2943     }
2944 
2945     // Only copy scripted process launch options.
2946     ProcessLaunchInfo &default_launch_info =
2947         const_cast<ProcessLaunchInfo &>(properties_sp->GetProcessLaunchInfo());
2948 
2949     default_launch_info.SetProcessPluginName("ScriptedProcess");
2950     default_launch_info.SetScriptedProcessClassName(
2951         launch_info.GetScriptedProcessClassName());
2952     default_launch_info.SetScriptedProcessDictionarySP(
2953         launch_info.GetScriptedProcessDictionarySP());
2954 
2955     SetProcessLaunchInfo(launch_info);
2956   }
2957 
2958   // Get the value of synchronous execution here.  If you wait till after you
2959   // have started to run, then you could have hit a breakpoint, whose command
2960   // might switch the value, and then you'll pick up that incorrect value.
2961   Debugger &debugger = GetDebugger();
2962   const bool synchronous_execution =
2963       debugger.GetCommandInterpreter().GetSynchronous();
2964 
2965   PlatformSP platform_sp(GetPlatform());
2966 
2967   FinalizeFileActions(launch_info);
2968 
2969   if (state == eStateConnected) {
2970     if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2971       error.SetErrorString(
2972           "can't launch in tty when launching through a remote connection");
2973       return error;
2974     }
2975   }
2976 
2977   if (!launch_info.GetArchitecture().IsValid())
2978     launch_info.GetArchitecture() = GetArchitecture();
2979 
2980   // If we're not already connected to the process, and if we have a platform
2981   // that can launch a process for debugging, go ahead and do that here.
2982   if (state != eStateConnected && platform_sp &&
2983       platform_sp->CanDebugProcess()) {
2984     LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
2985               __FUNCTION__);
2986 
2987     // If there was a previous process, delete it before we make the new one.
2988     // One subtle point, we delete the process before we release the reference
2989     // to m_process_sp.  That way even if we are the last owner, the process
2990     // will get Finalized before it gets destroyed.
2991     DeleteCurrentProcess();
2992 
2993     m_process_sp =
2994         GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2995 
2996   } else {
2997     LLDB_LOGF(log,
2998               "Target::%s the platform doesn't know how to debug a "
2999               "process, getting a process plugin to do this for us.",
3000               __FUNCTION__);
3001 
3002     if (state == eStateConnected) {
3003       assert(m_process_sp);
3004     } else {
3005       // Use a Process plugin to construct the process.
3006       const char *plugin_name = launch_info.GetProcessPluginName();
3007       CreateProcess(launch_info.GetListener(), plugin_name, nullptr, false);
3008     }
3009 
3010     // Since we didn't have a platform launch the process, launch it here.
3011     if (m_process_sp)
3012       error = m_process_sp->Launch(launch_info);
3013   }
3014 
3015   if (!m_process_sp && error.Success())
3016     error.SetErrorString("failed to launch or debug process");
3017 
3018   if (!error.Success())
3019     return error;
3020 
3021   auto at_exit =
3022       llvm::make_scope_exit([&]() { m_process_sp->RestoreProcessEvents(); });
3023 
3024   if (!synchronous_execution &&
3025       launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3026     return error;
3027 
3028   ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
3029   if (!hijack_listener_sp) {
3030     hijack_listener_sp = Listener::MakeListener("lldb.Target.Launch.hijack");
3031     launch_info.SetHijackListener(hijack_listener_sp);
3032     m_process_sp->HijackProcessEvents(hijack_listener_sp);
3033   }
3034 
3035   switch (m_process_sp->WaitForProcessToStop(llvm::None, nullptr, false,
3036                                              hijack_listener_sp, nullptr)) {
3037   case eStateStopped: {
3038     if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3039       break;
3040     if (synchronous_execution) {
3041       // Now we have handled the stop-from-attach, and we are just
3042       // switching to a synchronous resume.  So we should switch to the
3043       // SyncResume hijacker.
3044       m_process_sp->RestoreProcessEvents();
3045       m_process_sp->ResumeSynchronous(stream);
3046     } else {
3047       m_process_sp->RestoreProcessEvents();
3048       error = m_process_sp->PrivateResume();
3049     }
3050     if (!error.Success()) {
3051       Status error2;
3052       error2.SetErrorStringWithFormat(
3053           "process resume at entry point failed: %s", error.AsCString());
3054       error = error2;
3055     }
3056   } break;
3057   case eStateExited: {
3058     bool with_shell = !!launch_info.GetShell();
3059     const int exit_status = m_process_sp->GetExitStatus();
3060     const char *exit_desc = m_process_sp->GetExitDescription();
3061     std::string desc;
3062     if (exit_desc && exit_desc[0])
3063       desc = " (" + std::string(exit_desc) + ')';
3064     if (with_shell)
3065       error.SetErrorStringWithFormat(
3066           "process exited with status %i%s\n"
3067           "'r' and 'run' are aliases that default to launching through a "
3068           "shell.\n"
3069           "Try launching without going through a shell by using "
3070           "'process launch'.",
3071           exit_status, desc.c_str());
3072     else
3073       error.SetErrorStringWithFormat("process exited with status %i%s",
3074                                      exit_status, desc.c_str());
3075   } break;
3076   default:
3077     error.SetErrorStringWithFormat("initial process state wasn't stopped: %s",
3078                                    StateAsCString(state));
3079     break;
3080   }
3081   return error;
3082 }
3083 
3084 void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3085 
3086 TraceSP &Target::GetTrace() { return m_trace_sp; }
3087 
3088 llvm::Expected<TraceSP &> Target::GetTraceOrCreate() {
3089   if (!m_trace_sp && m_process_sp) {
3090     llvm::Expected<TraceSupportedResponse> trace_type =
3091         m_process_sp->TraceSupported();
3092     if (!trace_type)
3093       return llvm::createStringError(
3094           llvm::inconvertibleErrorCode(), "Tracing is not supported. %s",
3095           llvm::toString(trace_type.takeError()).c_str());
3096     if (llvm::Expected<TraceSP> trace_sp =
3097             Trace::FindPluginForLiveProcess(trace_type->name, *m_process_sp))
3098       m_trace_sp = *trace_sp;
3099     else
3100       return llvm::createStringError(
3101           llvm::inconvertibleErrorCode(),
3102           "Couldn't start tracing the process. %s",
3103           llvm::toString(trace_sp.takeError()).c_str());
3104   }
3105   return m_trace_sp;
3106 }
3107 
3108 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
3109   auto state = eStateInvalid;
3110   auto process_sp = GetProcessSP();
3111   if (process_sp) {
3112     state = process_sp->GetState();
3113     if (process_sp->IsAlive() && state != eStateConnected) {
3114       if (state == eStateAttaching)
3115         return Status("process attach is in progress");
3116       return Status("a process is already being debugged");
3117     }
3118   }
3119 
3120   const ModuleSP old_exec_module_sp = GetExecutableModule();
3121 
3122   // If no process info was specified, then use the target executable name as
3123   // the process to attach to by default
3124   if (!attach_info.ProcessInfoSpecified()) {
3125     if (old_exec_module_sp)
3126       attach_info.GetExecutableFile().GetFilename() =
3127           old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3128 
3129     if (!attach_info.ProcessInfoSpecified()) {
3130       return Status("no process specified, create a target with a file, or "
3131                     "specify the --pid or --name");
3132     }
3133   }
3134 
3135   const auto platform_sp =
3136       GetDebugger().GetPlatformList().GetSelectedPlatform();
3137   ListenerSP hijack_listener_sp;
3138   const bool async = attach_info.GetAsync();
3139   if (!async) {
3140     hijack_listener_sp =
3141         Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3142     attach_info.SetHijackListener(hijack_listener_sp);
3143   }
3144 
3145   Status error;
3146   if (state != eStateConnected && platform_sp != nullptr &&
3147       platform_sp->CanDebugProcess()) {
3148     SetPlatform(platform_sp);
3149     process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3150   } else {
3151     if (state != eStateConnected) {
3152       const char *plugin_name = attach_info.GetProcessPluginName();
3153       process_sp =
3154           CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3155                         plugin_name, nullptr, false);
3156       if (process_sp == nullptr) {
3157         error.SetErrorStringWithFormat(
3158             "failed to create process using plugin %s",
3159             (plugin_name) ? plugin_name : "null");
3160         return error;
3161       }
3162     }
3163     if (hijack_listener_sp)
3164       process_sp->HijackProcessEvents(hijack_listener_sp);
3165     error = process_sp->Attach(attach_info);
3166   }
3167 
3168   if (error.Success() && process_sp) {
3169     if (async) {
3170       process_sp->RestoreProcessEvents();
3171     } else {
3172       state = process_sp->WaitForProcessToStop(
3173           llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3174       process_sp->RestoreProcessEvents();
3175 
3176       if (state != eStateStopped) {
3177         const char *exit_desc = process_sp->GetExitDescription();
3178         if (exit_desc)
3179           error.SetErrorStringWithFormat("%s", exit_desc);
3180         else
3181           error.SetErrorString(
3182               "process did not stop (no such process or permission problem?)");
3183         process_sp->Destroy(false);
3184       }
3185     }
3186   }
3187   return error;
3188 }
3189 
3190 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3191   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3192 
3193   // Finalize the file actions, and if none were given, default to opening up a
3194   // pseudo terminal
3195   PlatformSP platform_sp = GetPlatform();
3196   const bool default_to_use_pty =
3197       m_platform_sp ? m_platform_sp->IsHost() : false;
3198   LLDB_LOG(
3199       log,
3200       "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3201       bool(platform_sp),
3202       platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3203       default_to_use_pty);
3204 
3205   // If nothing for stdin or stdout or stderr was specified, then check the
3206   // process for any default settings that were set with "settings set"
3207   if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3208       info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3209       info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3210     LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3211                   "default handling");
3212 
3213     if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3214       // Do nothing, if we are launching in a remote terminal no file actions
3215       // should be done at all.
3216       return;
3217     }
3218 
3219     if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3220       LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3221                     "for stdin, stdout and stderr");
3222       info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3223       info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3224       info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3225     } else {
3226       // Check for any values that might have gotten set with any of: (lldb)
3227       // settings set target.input-path (lldb) settings set target.output-path
3228       // (lldb) settings set target.error-path
3229       FileSpec in_file_spec;
3230       FileSpec out_file_spec;
3231       FileSpec err_file_spec;
3232       // Only override with the target settings if we don't already have an
3233       // action for in, out or error
3234       if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3235         in_file_spec = GetStandardInputPath();
3236       if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3237         out_file_spec = GetStandardOutputPath();
3238       if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3239         err_file_spec = GetStandardErrorPath();
3240 
3241       LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3242                in_file_spec, out_file_spec, err_file_spec);
3243 
3244       if (in_file_spec) {
3245         info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3246         LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3247       }
3248 
3249       if (out_file_spec) {
3250         info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3251         LLDB_LOG(log, "appended stdout open file action for {0}",
3252                  out_file_spec);
3253       }
3254 
3255       if (err_file_spec) {
3256         info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3257         LLDB_LOG(log, "appended stderr open file action for {0}",
3258                  err_file_spec);
3259       }
3260 
3261       if (default_to_use_pty &&
3262           (!in_file_spec || !out_file_spec || !err_file_spec)) {
3263         llvm::Error Err = info.SetUpPtyRedirection();
3264         LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3265       }
3266     }
3267   }
3268 }
3269 
3270 // Target::StopHook
3271 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3272     : UserID(uid), m_target_sp(target_sp), m_specifier_sp(),
3273       m_thread_spec_up() {}
3274 
3275 Target::StopHook::StopHook(const StopHook &rhs)
3276     : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3277       m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(),
3278       m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) {
3279   if (rhs.m_thread_spec_up)
3280     m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3281 }
3282 
3283 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3284   m_specifier_sp.reset(specifier);
3285 }
3286 
3287 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3288   m_thread_spec_up.reset(specifier);
3289 }
3290 
3291 bool Target::StopHook::ExecutionContextPasses(const ExecutionContext &exc_ctx) {
3292   SymbolContextSpecifier *specifier = GetSpecifier();
3293   if (!specifier)
3294     return true;
3295 
3296   bool will_run = true;
3297   if (exc_ctx.GetFramePtr())
3298     will_run = GetSpecifier()->SymbolContextMatches(
3299         exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
3300   if (will_run && GetThreadSpecifier() != nullptr)
3301     will_run =
3302         GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
3303 
3304   return will_run;
3305 }
3306 
3307 void Target::StopHook::GetDescription(Stream *s,
3308                                       lldb::DescriptionLevel level) const {
3309 
3310   // For brief descriptions, only print the subclass description:
3311   if (level == eDescriptionLevelBrief) {
3312     GetSubclassDescription(s, level);
3313     return;
3314   }
3315 
3316   unsigned indent_level = s->GetIndentLevel();
3317 
3318   s->SetIndentLevel(indent_level + 2);
3319 
3320   s->Printf("Hook: %" PRIu64 "\n", GetID());
3321   if (m_active)
3322     s->Indent("State: enabled\n");
3323   else
3324     s->Indent("State: disabled\n");
3325 
3326   if (m_auto_continue)
3327     s->Indent("AutoContinue on\n");
3328 
3329   if (m_specifier_sp) {
3330     s->Indent();
3331     s->PutCString("Specifier:\n");
3332     s->SetIndentLevel(indent_level + 4);
3333     m_specifier_sp->GetDescription(s, level);
3334     s->SetIndentLevel(indent_level + 2);
3335   }
3336 
3337   if (m_thread_spec_up) {
3338     StreamString tmp;
3339     s->Indent("Thread:\n");
3340     m_thread_spec_up->GetDescription(&tmp, level);
3341     s->SetIndentLevel(indent_level + 4);
3342     s->Indent(tmp.GetString());
3343     s->PutCString("\n");
3344     s->SetIndentLevel(indent_level + 2);
3345   }
3346   GetSubclassDescription(s, level);
3347 }
3348 
3349 void Target::StopHookCommandLine::GetSubclassDescription(
3350     Stream *s, lldb::DescriptionLevel level) const {
3351   // The brief description just prints the first command.
3352   if (level == eDescriptionLevelBrief) {
3353     if (m_commands.GetSize() == 1)
3354       s->PutCString(m_commands.GetStringAtIndex(0));
3355     return;
3356   }
3357   s->Indent("Commands: \n");
3358   s->SetIndentLevel(s->GetIndentLevel() + 4);
3359   uint32_t num_commands = m_commands.GetSize();
3360   for (uint32_t i = 0; i < num_commands; i++) {
3361     s->Indent(m_commands.GetStringAtIndex(i));
3362     s->PutCString("\n");
3363   }
3364   s->SetIndentLevel(s->GetIndentLevel() - 4);
3365 }
3366 
3367 // Target::StopHookCommandLine
3368 void Target::StopHookCommandLine::SetActionFromString(const std::string &string) {
3369   GetCommands().SplitIntoLines(string);
3370 }
3371 
3372 void Target::StopHookCommandLine::SetActionFromStrings(
3373     const std::vector<std::string> &strings) {
3374   for (auto string : strings)
3375     GetCommands().AppendString(string.c_str());
3376 }
3377 
3378 Target::StopHook::StopHookResult
3379 Target::StopHookCommandLine::HandleStop(ExecutionContext &exc_ctx,
3380                                         StreamSP output_sp) {
3381   assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
3382                                    "with no target");
3383 
3384   if (!m_commands.GetSize())
3385     return StopHookResult::KeepStopped;
3386 
3387   CommandReturnObject result(false);
3388   result.SetImmediateOutputStream(output_sp);
3389   result.SetInteractive(false);
3390   Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
3391   CommandInterpreterRunOptions options;
3392   options.SetStopOnContinue(true);
3393   options.SetStopOnError(true);
3394   options.SetEchoCommands(false);
3395   options.SetPrintResults(true);
3396   options.SetPrintErrors(true);
3397   options.SetAddToHistory(false);
3398 
3399   // Force Async:
3400   bool old_async = debugger.GetAsyncExecution();
3401   debugger.SetAsyncExecution(true);
3402   debugger.GetCommandInterpreter().HandleCommands(GetCommands(), exc_ctx,
3403                                                   options, result);
3404   debugger.SetAsyncExecution(old_async);
3405   lldb::ReturnStatus status = result.GetStatus();
3406   if (status == eReturnStatusSuccessContinuingNoResult ||
3407       status == eReturnStatusSuccessContinuingResult)
3408     return StopHookResult::AlreadyContinued;
3409   return StopHookResult::KeepStopped;
3410 }
3411 
3412 // Target::StopHookScripted
3413 Status Target::StopHookScripted::SetScriptCallback(
3414     std::string class_name, StructuredData::ObjectSP extra_args_sp) {
3415   Status error;
3416 
3417   ScriptInterpreter *script_interp =
3418       GetTarget()->GetDebugger().GetScriptInterpreter();
3419   if (!script_interp) {
3420     error.SetErrorString("No script interpreter installed.");
3421     return error;
3422   }
3423 
3424   m_class_name = class_name;
3425 
3426   m_extra_args = new StructuredDataImpl();
3427 
3428   if (extra_args_sp)
3429     m_extra_args->SetObjectSP(extra_args_sp);
3430 
3431   m_implementation_sp = script_interp->CreateScriptedStopHook(
3432       GetTarget(), m_class_name.c_str(), m_extra_args, error);
3433 
3434   return error;
3435 }
3436 
3437 Target::StopHook::StopHookResult
3438 Target::StopHookScripted::HandleStop(ExecutionContext &exc_ctx,
3439                                      StreamSP output_sp) {
3440   assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
3441                                    "with no target");
3442 
3443   ScriptInterpreter *script_interp =
3444       GetTarget()->GetDebugger().GetScriptInterpreter();
3445   if (!script_interp)
3446     return StopHookResult::KeepStopped;
3447 
3448   bool should_stop = script_interp->ScriptedStopHookHandleStop(
3449       m_implementation_sp, exc_ctx, output_sp);
3450 
3451   return should_stop ? StopHookResult::KeepStopped
3452                      : StopHookResult::RequestContinue;
3453 }
3454 
3455 void Target::StopHookScripted::GetSubclassDescription(
3456     Stream *s, lldb::DescriptionLevel level) const {
3457   if (level == eDescriptionLevelBrief) {
3458     s->PutCString(m_class_name);
3459     return;
3460   }
3461   s->Indent("Class:");
3462   s->Printf("%s\n", m_class_name.c_str());
3463 
3464   // Now print the extra args:
3465   // FIXME: We should use StructuredData.GetDescription on the m_extra_args
3466   // but that seems to rely on some printing plugin that doesn't exist.
3467   if (!m_extra_args->IsValid())
3468     return;
3469   StructuredData::ObjectSP object_sp = m_extra_args->GetObjectSP();
3470   if (!object_sp || !object_sp->IsValid())
3471     return;
3472 
3473   StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary();
3474   if (!as_dict || !as_dict->IsValid())
3475     return;
3476 
3477   uint32_t num_keys = as_dict->GetSize();
3478   if (num_keys == 0)
3479     return;
3480 
3481   s->Indent("Args:\n");
3482   s->SetIndentLevel(s->GetIndentLevel() + 4);
3483 
3484   auto print_one_element = [&s](ConstString key,
3485                                 StructuredData::Object *object) {
3486     s->Indent();
3487     s->Printf("%s : %s\n", key.GetCString(),
3488               object->GetStringValue().str().c_str());
3489     return true;
3490   };
3491 
3492   as_dict->ForEach(print_one_element);
3493 
3494   s->SetIndentLevel(s->GetIndentLevel() - 4);
3495 }
3496 
3497 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3498     {
3499         eNoDynamicValues,
3500         "no-dynamic-values",
3501         "Don't calculate the dynamic type of values",
3502     },
3503     {
3504         eDynamicCanRunTarget,
3505         "run-target",
3506         "Calculate the dynamic type of values "
3507         "even if you have to run the target.",
3508     },
3509     {
3510         eDynamicDontRunTarget,
3511         "no-run-target",
3512         "Calculate the dynamic type of values, but don't run the target.",
3513     },
3514 };
3515 
3516 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3517   return OptionEnumValues(g_dynamic_value_types);
3518 }
3519 
3520 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3521     {
3522         eInlineBreakpointsNever,
3523         "never",
3524         "Never look for inline breakpoint locations (fastest). This setting "
3525         "should only be used if you know that no inlining occurs in your"
3526         "programs.",
3527     },
3528     {
3529         eInlineBreakpointsHeaders,
3530         "headers",
3531         "Only check for inline breakpoint locations when setting breakpoints "
3532         "in header files, but not when setting breakpoint in implementation "
3533         "source files (default).",
3534     },
3535     {
3536         eInlineBreakpointsAlways,
3537         "always",
3538         "Always look for inline breakpoint locations when setting file and "
3539         "line breakpoints (slower but most accurate).",
3540     },
3541 };
3542 
3543 enum x86DisassemblyFlavor {
3544   eX86DisFlavorDefault,
3545   eX86DisFlavorIntel,
3546   eX86DisFlavorATT
3547 };
3548 
3549 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3550     {
3551         eX86DisFlavorDefault,
3552         "default",
3553         "Disassembler default (currently att).",
3554     },
3555     {
3556         eX86DisFlavorIntel,
3557         "intel",
3558         "Intel disassembler flavor.",
3559     },
3560     {
3561         eX86DisFlavorATT,
3562         "att",
3563         "AT&T disassembler flavor.",
3564     },
3565 };
3566 
3567 static constexpr OptionEnumValueElement g_import_std_module_value_types[] = {
3568     {
3569         eImportStdModuleFalse,
3570         "false",
3571         "Never import the 'std' C++ module in the expression parser.",
3572     },
3573     {
3574         eImportStdModuleFallback,
3575         "fallback",
3576         "Retry evaluating expressions with an imported 'std' C++ module if they"
3577         " failed to parse without the module. This allows evaluating more "
3578         "complex expressions involving C++ standard library types."
3579     },
3580     {
3581         eImportStdModuleTrue,
3582         "true",
3583         "Always import the 'std' C++ module. This allows evaluating more "
3584         "complex expressions involving C++ standard library types. This feature"
3585         " is experimental."
3586     },
3587 };
3588 
3589 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3590     {
3591         Disassembler::eHexStyleC,
3592         "c",
3593         "C-style (0xffff).",
3594     },
3595     {
3596         Disassembler::eHexStyleAsm,
3597         "asm",
3598         "Asm-style (0ffffh).",
3599     },
3600 };
3601 
3602 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3603     {
3604         eLoadScriptFromSymFileTrue,
3605         "true",
3606         "Load debug scripts inside symbol files",
3607     },
3608     {
3609         eLoadScriptFromSymFileFalse,
3610         "false",
3611         "Do not load debug scripts inside symbol files.",
3612     },
3613     {
3614         eLoadScriptFromSymFileWarn,
3615         "warn",
3616         "Warn about debug scripts inside symbol files but do not load them.",
3617     },
3618 };
3619 
3620 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
3621     {
3622         eLoadCWDlldbinitTrue,
3623         "true",
3624         "Load .lldbinit files from current directory",
3625     },
3626     {
3627         eLoadCWDlldbinitFalse,
3628         "false",
3629         "Do not load .lldbinit files from current directory",
3630     },
3631     {
3632         eLoadCWDlldbinitWarn,
3633         "warn",
3634         "Warn about loading .lldbinit files from current directory",
3635     },
3636 };
3637 
3638 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3639     {
3640         eMemoryModuleLoadLevelMinimal,
3641         "minimal",
3642         "Load minimal information when loading modules from memory. Currently "
3643         "this setting loads sections only.",
3644     },
3645     {
3646         eMemoryModuleLoadLevelPartial,
3647         "partial",
3648         "Load partial information when loading modules from memory. Currently "
3649         "this setting loads sections and function bounds.",
3650     },
3651     {
3652         eMemoryModuleLoadLevelComplete,
3653         "complete",
3654         "Load complete information when loading modules from memory. Currently "
3655         "this setting loads sections and all symbols.",
3656     },
3657 };
3658 
3659 #define LLDB_PROPERTIES_target
3660 #include "TargetProperties.inc"
3661 
3662 enum {
3663 #define LLDB_PROPERTIES_target
3664 #include "TargetPropertiesEnum.inc"
3665   ePropertyExperimental,
3666 };
3667 
3668 class TargetOptionValueProperties
3669     : public Cloneable<TargetOptionValueProperties, OptionValueProperties> {
3670 public:
3671   TargetOptionValueProperties(ConstString name) : Cloneable(name) {}
3672 
3673   const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3674                                      bool will_modify,
3675                                      uint32_t idx) const override {
3676     // When getting the value for a key from the target options, we will always
3677     // try and grab the setting from the current target if there is one. Else
3678     // we just use the one from this instance.
3679     if (exe_ctx) {
3680       Target *target = exe_ctx->GetTargetPtr();
3681       if (target) {
3682         TargetOptionValueProperties *target_properties =
3683             static_cast<TargetOptionValueProperties *>(
3684                 target->GetValueProperties().get());
3685         if (this != target_properties)
3686           return target_properties->ProtectedGetPropertyAtIndex(idx);
3687       }
3688     }
3689     return ProtectedGetPropertyAtIndex(idx);
3690   }
3691 };
3692 
3693 // TargetProperties
3694 #define LLDB_PROPERTIES_target_experimental
3695 #include "TargetProperties.inc"
3696 
3697 enum {
3698 #define LLDB_PROPERTIES_target_experimental
3699 #include "TargetPropertiesEnum.inc"
3700 };
3701 
3702 class TargetExperimentalOptionValueProperties
3703     : public Cloneable<TargetExperimentalOptionValueProperties,
3704                        OptionValueProperties> {
3705 public:
3706   TargetExperimentalOptionValueProperties()
3707       : Cloneable(ConstString(Properties::GetExperimentalSettingsName())) {}
3708 };
3709 
3710 TargetExperimentalProperties::TargetExperimentalProperties()
3711     : Properties(OptionValuePropertiesSP(
3712           new TargetExperimentalOptionValueProperties())) {
3713   m_collection_sp->Initialize(g_target_experimental_properties);
3714 }
3715 
3716 // TargetProperties
3717 TargetProperties::TargetProperties(Target *target)
3718     : Properties(), m_launch_info(), m_target(target) {
3719   if (target) {
3720     m_collection_sp =
3721         OptionValueProperties::CreateLocalCopy(*Target::GetGlobalProperties());
3722 
3723     // Set callbacks to update launch_info whenever "settins set" updated any
3724     // of these properties
3725     m_collection_sp->SetValueChangedCallback(
3726         ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
3727     m_collection_sp->SetValueChangedCallback(
3728         ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
3729     m_collection_sp->SetValueChangedCallback(
3730         ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
3731     m_collection_sp->SetValueChangedCallback(
3732         ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
3733     m_collection_sp->SetValueChangedCallback(
3734         ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
3735     m_collection_sp->SetValueChangedCallback(
3736         ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
3737     m_collection_sp->SetValueChangedCallback(
3738         ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
3739     m_collection_sp->SetValueChangedCallback(
3740         ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
3741     m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
3742       DetachOnErrorValueChangedCallback();
3743     });
3744     m_collection_sp->SetValueChangedCallback(
3745         ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
3746     m_collection_sp->SetValueChangedCallback(
3747         ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
3748     m_collection_sp->SetValueChangedCallback(
3749         ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
3750 
3751     m_experimental_properties_up =
3752         std::make_unique<TargetExperimentalProperties>();
3753     m_collection_sp->AppendProperty(
3754         ConstString(Properties::GetExperimentalSettingsName()),
3755         ConstString("Experimental settings - setting these won't produce "
3756                     "errors if the setting is not present."),
3757         true, m_experimental_properties_up->GetValueProperties());
3758   } else {
3759     m_collection_sp =
3760         std::make_shared<TargetOptionValueProperties>(ConstString("target"));
3761     m_collection_sp->Initialize(g_target_properties);
3762     m_experimental_properties_up =
3763         std::make_unique<TargetExperimentalProperties>();
3764     m_collection_sp->AppendProperty(
3765         ConstString(Properties::GetExperimentalSettingsName()),
3766         ConstString("Experimental settings - setting these won't produce "
3767                     "errors if the setting is not present."),
3768         true, m_experimental_properties_up->GetValueProperties());
3769     m_collection_sp->AppendProperty(
3770         ConstString("process"), ConstString("Settings specific to processes."),
3771         true, Process::GetGlobalProperties()->GetValueProperties());
3772   }
3773 }
3774 
3775 TargetProperties::~TargetProperties() = default;
3776 
3777 void TargetProperties::UpdateLaunchInfoFromProperties() {
3778   Arg0ValueChangedCallback();
3779   RunArgsValueChangedCallback();
3780   EnvVarsValueChangedCallback();
3781   InputPathValueChangedCallback();
3782   OutputPathValueChangedCallback();
3783   ErrorPathValueChangedCallback();
3784   DetachOnErrorValueChangedCallback();
3785   DisableASLRValueChangedCallback();
3786   InheritTCCValueChangedCallback();
3787   DisableSTDIOValueChangedCallback();
3788 }
3789 
3790 bool TargetProperties::GetInjectLocalVariables(
3791     ExecutionContext *exe_ctx) const {
3792   const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3793       exe_ctx, false, ePropertyExperimental);
3794   OptionValueProperties *exp_values =
3795       exp_property->GetValue()->GetAsProperties();
3796   if (exp_values)
3797     return exp_values->GetPropertyAtIndexAsBoolean(
3798         exe_ctx, ePropertyInjectLocalVars, true);
3799   else
3800     return true;
3801 }
3802 
3803 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3804                                                bool b) {
3805   const Property *exp_property =
3806       m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3807   OptionValueProperties *exp_values =
3808       exp_property->GetValue()->GetAsProperties();
3809   if (exp_values)
3810     exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3811                                             true);
3812 }
3813 
3814 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3815   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3816       nullptr, ePropertyDefaultArch);
3817   if (value)
3818     return value->GetCurrentValue();
3819   return ArchSpec();
3820 }
3821 
3822 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3823   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3824       nullptr, ePropertyDefaultArch);
3825   if (value)
3826     return value->SetCurrentValue(arch, true);
3827 }
3828 
3829 bool TargetProperties::GetMoveToNearestCode() const {
3830   const uint32_t idx = ePropertyMoveToNearestCode;
3831   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3832       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3833 }
3834 
3835 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3836   const uint32_t idx = ePropertyPreferDynamic;
3837   return (lldb::DynamicValueType)
3838       m_collection_sp->GetPropertyAtIndexAsEnumeration(
3839           nullptr, idx, g_target_properties[idx].default_uint_value);
3840 }
3841 
3842 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3843   const uint32_t idx = ePropertyPreferDynamic;
3844   return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3845 }
3846 
3847 bool TargetProperties::GetPreloadSymbols() const {
3848   const uint32_t idx = ePropertyPreloadSymbols;
3849   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3850       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3851 }
3852 
3853 void TargetProperties::SetPreloadSymbols(bool b) {
3854   const uint32_t idx = ePropertyPreloadSymbols;
3855   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3856 }
3857 
3858 bool TargetProperties::GetDisableASLR() const {
3859   const uint32_t idx = ePropertyDisableASLR;
3860   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3861       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3862 }
3863 
3864 void TargetProperties::SetDisableASLR(bool b) {
3865   const uint32_t idx = ePropertyDisableASLR;
3866   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3867 }
3868 
3869 bool TargetProperties::GetInheritTCC() const {
3870   const uint32_t idx = ePropertyInheritTCC;
3871   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3872       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3873 }
3874 
3875 void TargetProperties::SetInheritTCC(bool b) {
3876   const uint32_t idx = ePropertyInheritTCC;
3877   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3878 }
3879 
3880 bool TargetProperties::GetDetachOnError() const {
3881   const uint32_t idx = ePropertyDetachOnError;
3882   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3883       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3884 }
3885 
3886 void TargetProperties::SetDetachOnError(bool b) {
3887   const uint32_t idx = ePropertyDetachOnError;
3888   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3889 }
3890 
3891 bool TargetProperties::GetDisableSTDIO() const {
3892   const uint32_t idx = ePropertyDisableSTDIO;
3893   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3894       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3895 }
3896 
3897 void TargetProperties::SetDisableSTDIO(bool b) {
3898   const uint32_t idx = ePropertyDisableSTDIO;
3899   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3900 }
3901 
3902 const char *TargetProperties::GetDisassemblyFlavor() const {
3903   const uint32_t idx = ePropertyDisassemblyFlavor;
3904   const char *return_value;
3905 
3906   x86DisassemblyFlavor flavor_value =
3907       (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3908           nullptr, idx, g_target_properties[idx].default_uint_value);
3909   return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3910   return return_value;
3911 }
3912 
3913 InlineStrategy TargetProperties::GetInlineStrategy() const {
3914   const uint32_t idx = ePropertyInlineStrategy;
3915   return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3916       nullptr, idx, g_target_properties[idx].default_uint_value);
3917 }
3918 
3919 llvm::StringRef TargetProperties::GetArg0() const {
3920   const uint32_t idx = ePropertyArg0;
3921   return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx,
3922                                                      llvm::StringRef());
3923 }
3924 
3925 void TargetProperties::SetArg0(llvm::StringRef arg) {
3926   const uint32_t idx = ePropertyArg0;
3927   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3928   m_launch_info.SetArg0(arg);
3929 }
3930 
3931 bool TargetProperties::GetRunArguments(Args &args) const {
3932   const uint32_t idx = ePropertyRunArgs;
3933   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3934 }
3935 
3936 void TargetProperties::SetRunArguments(const Args &args) {
3937   const uint32_t idx = ePropertyRunArgs;
3938   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3939   m_launch_info.GetArguments() = args;
3940 }
3941 
3942 Environment TargetProperties::ComputeEnvironment() const {
3943   Environment env;
3944 
3945   if (m_target &&
3946       m_collection_sp->GetPropertyAtIndexAsBoolean(
3947           nullptr, ePropertyInheritEnv,
3948           g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
3949     if (auto platform_sp = m_target->GetPlatform()) {
3950       Environment platform_env = platform_sp->GetEnvironment();
3951       for (const auto &KV : platform_env)
3952         env[KV.first()] = KV.second;
3953     }
3954   }
3955 
3956   Args property_unset_env;
3957   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyUnsetEnvVars,
3958                                             property_unset_env);
3959   for (const auto &var : property_unset_env)
3960     env.erase(var.ref());
3961 
3962   Args property_env;
3963   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyEnvVars,
3964                                             property_env);
3965   for (const auto &KV : Environment(property_env))
3966     env[KV.first()] = KV.second;
3967 
3968   return env;
3969 }
3970 
3971 Environment TargetProperties::GetEnvironment() const {
3972   return ComputeEnvironment();
3973 }
3974 
3975 void TargetProperties::SetEnvironment(Environment env) {
3976   // TODO: Get rid of the Args intermediate step
3977   const uint32_t idx = ePropertyEnvVars;
3978   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3979 }
3980 
3981 bool TargetProperties::GetSkipPrologue() const {
3982   const uint32_t idx = ePropertySkipPrologue;
3983   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3984       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3985 }
3986 
3987 PathMappingList &TargetProperties::GetSourcePathMap() const {
3988   const uint32_t idx = ePropertySourceMap;
3989   OptionValuePathMappings *option_value =
3990       m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3991                                                                    false, idx);
3992   assert(option_value);
3993   return option_value->GetCurrentValue();
3994 }
3995 
3996 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
3997   const uint32_t idx = ePropertyExecutableSearchPaths;
3998   OptionValueFileSpecList *option_value =
3999       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
4000                                                                    false, idx);
4001   assert(option_value);
4002   option_value->AppendCurrentValue(dir);
4003 }
4004 
4005 FileSpecList TargetProperties::GetExecutableSearchPaths() {
4006   const uint32_t idx = ePropertyExecutableSearchPaths;
4007   const OptionValueFileSpecList *option_value =
4008       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
4009                                                                    false, idx);
4010   assert(option_value);
4011   return option_value->GetCurrentValue();
4012 }
4013 
4014 FileSpecList TargetProperties::GetDebugFileSearchPaths() {
4015   const uint32_t idx = ePropertyDebugFileSearchPaths;
4016   const OptionValueFileSpecList *option_value =
4017       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
4018                                                                    false, idx);
4019   assert(option_value);
4020   return option_value->GetCurrentValue();
4021 }
4022 
4023 FileSpecList TargetProperties::GetClangModuleSearchPaths() {
4024   const uint32_t idx = ePropertyClangModuleSearchPaths;
4025   const OptionValueFileSpecList *option_value =
4026       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
4027                                                                    false, idx);
4028   assert(option_value);
4029   return option_value->GetCurrentValue();
4030 }
4031 
4032 bool TargetProperties::GetEnableAutoImportClangModules() const {
4033   const uint32_t idx = ePropertyAutoImportClangModules;
4034   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4035       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4036 }
4037 
4038 ImportStdModule TargetProperties::GetImportStdModule() const {
4039   const uint32_t idx = ePropertyImportStdModule;
4040   return (ImportStdModule)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4041       nullptr, idx, g_target_properties[idx].default_uint_value);
4042 }
4043 
4044 bool TargetProperties::GetEnableAutoApplyFixIts() const {
4045   const uint32_t idx = ePropertyAutoApplyFixIts;
4046   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4047       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4048 }
4049 
4050 uint64_t TargetProperties::GetNumberOfRetriesWithFixits() const {
4051   const uint32_t idx = ePropertyRetriesWithFixIts;
4052   return m_collection_sp->GetPropertyAtIndexAsUInt64(
4053       nullptr, idx, g_target_properties[idx].default_uint_value);
4054 }
4055 
4056 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
4057   const uint32_t idx = ePropertyNotifyAboutFixIts;
4058   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4059       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4060 }
4061 
4062 bool TargetProperties::GetEnableSaveObjects() const {
4063   const uint32_t idx = ePropertySaveObjects;
4064   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4065       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4066 }
4067 
4068 bool TargetProperties::GetEnableSyntheticValue() const {
4069   const uint32_t idx = ePropertyEnableSynthetic;
4070   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4071       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4072 }
4073 
4074 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
4075   const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
4076   return m_collection_sp->GetPropertyAtIndexAsUInt64(
4077       nullptr, idx, g_target_properties[idx].default_uint_value);
4078 }
4079 
4080 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
4081   const uint32_t idx = ePropertyMaxChildrenCount;
4082   return m_collection_sp->GetPropertyAtIndexAsSInt64(
4083       nullptr, idx, g_target_properties[idx].default_uint_value);
4084 }
4085 
4086 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
4087   const uint32_t idx = ePropertyMaxSummaryLength;
4088   return m_collection_sp->GetPropertyAtIndexAsSInt64(
4089       nullptr, idx, g_target_properties[idx].default_uint_value);
4090 }
4091 
4092 uint32_t TargetProperties::GetMaximumMemReadSize() const {
4093   const uint32_t idx = ePropertyMaxMemReadSize;
4094   return m_collection_sp->GetPropertyAtIndexAsSInt64(
4095       nullptr, idx, g_target_properties[idx].default_uint_value);
4096 }
4097 
4098 FileSpec TargetProperties::GetStandardInputPath() const {
4099   const uint32_t idx = ePropertyInputPath;
4100   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4101 }
4102 
4103 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4104   const uint32_t idx = ePropertyInputPath;
4105   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4106 }
4107 
4108 FileSpec TargetProperties::GetStandardOutputPath() const {
4109   const uint32_t idx = ePropertyOutputPath;
4110   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4111 }
4112 
4113 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
4114   const uint32_t idx = ePropertyOutputPath;
4115   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4116 }
4117 
4118 FileSpec TargetProperties::GetStandardErrorPath() const {
4119   const uint32_t idx = ePropertyErrorPath;
4120   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4121 }
4122 
4123 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4124   const uint32_t idx = ePropertyErrorPath;
4125   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4126 }
4127 
4128 LanguageType TargetProperties::GetLanguage() const {
4129   OptionValueLanguage *value =
4130       m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
4131           nullptr, ePropertyLanguage);
4132   if (value)
4133     return value->GetCurrentValue();
4134   return LanguageType();
4135 }
4136 
4137 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
4138   const uint32_t idx = ePropertyExprPrefix;
4139   OptionValueFileSpec *file =
4140       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
4141                                                                idx);
4142   if (file) {
4143     DataBufferSP data_sp(file->GetFileContents());
4144     if (data_sp)
4145       return llvm::StringRef(
4146           reinterpret_cast<const char *>(data_sp->GetBytes()),
4147           data_sp->GetByteSize());
4148   }
4149   return "";
4150 }
4151 
4152 uint64_t TargetProperties::GetExprErrorLimit() const {
4153   const uint32_t idx = ePropertyExprErrorLimit;
4154   return m_collection_sp->GetPropertyAtIndexAsUInt64(
4155       nullptr, idx, g_target_properties[idx].default_uint_value);
4156 }
4157 
4158 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4159   const uint32_t idx = ePropertyBreakpointUseAvoidList;
4160   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4161       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4162 }
4163 
4164 bool TargetProperties::GetUseHexImmediates() const {
4165   const uint32_t idx = ePropertyUseHexImmediates;
4166   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4167       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4168 }
4169 
4170 bool TargetProperties::GetUseFastStepping() const {
4171   const uint32_t idx = ePropertyUseFastStepping;
4172   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4173       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4174 }
4175 
4176 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4177   const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4178   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4179       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4180 }
4181 
4182 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4183   const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4184   return (LoadScriptFromSymFile)
4185       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4186           nullptr, idx, g_target_properties[idx].default_uint_value);
4187 }
4188 
4189 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4190   const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4191   return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4192       nullptr, idx, g_target_properties[idx].default_uint_value);
4193 }
4194 
4195 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4196   const uint32_t idx = ePropertyHexImmediateStyle;
4197   return (Disassembler::HexImmediateStyle)
4198       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4199           nullptr, idx, g_target_properties[idx].default_uint_value);
4200 }
4201 
4202 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4203   const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4204   return (MemoryModuleLoadLevel)
4205       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4206           nullptr, idx, g_target_properties[idx].default_uint_value);
4207 }
4208 
4209 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4210   const uint32_t idx = ePropertyTrapHandlerNames;
4211   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4212 }
4213 
4214 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4215   const uint32_t idx = ePropertyTrapHandlerNames;
4216   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4217 }
4218 
4219 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4220   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4221   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4222 }
4223 
4224 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4225   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4226   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4227 }
4228 
4229 bool TargetProperties::GetDisplayRecognizedArguments() const {
4230   const uint32_t idx = ePropertyDisplayRecognizedArguments;
4231   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4232 }
4233 
4234 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
4235   const uint32_t idx = ePropertyDisplayRecognizedArguments;
4236   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4237 }
4238 
4239 bool TargetProperties::GetNonStopModeEnabled() const {
4240   const uint32_t idx = ePropertyNonStopModeEnabled;
4241   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4242 }
4243 
4244 void TargetProperties::SetNonStopModeEnabled(bool b) {
4245   const uint32_t idx = ePropertyNonStopModeEnabled;
4246   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4247 }
4248 
4249 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() const {
4250   return m_launch_info;
4251 }
4252 
4253 void TargetProperties::SetProcessLaunchInfo(
4254     const ProcessLaunchInfo &launch_info) {
4255   m_launch_info = launch_info;
4256   SetArg0(launch_info.GetArg0());
4257   SetRunArguments(launch_info.GetArguments());
4258   SetEnvironment(launch_info.GetEnvironment());
4259   const FileAction *input_file_action =
4260       launch_info.GetFileActionForFD(STDIN_FILENO);
4261   if (input_file_action) {
4262     SetStandardInputPath(input_file_action->GetPath());
4263   }
4264   const FileAction *output_file_action =
4265       launch_info.GetFileActionForFD(STDOUT_FILENO);
4266   if (output_file_action) {
4267     SetStandardOutputPath(output_file_action->GetPath());
4268   }
4269   const FileAction *error_file_action =
4270       launch_info.GetFileActionForFD(STDERR_FILENO);
4271   if (error_file_action) {
4272     SetStandardErrorPath(error_file_action->GetPath());
4273   }
4274   SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4275   SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4276   SetInheritTCC(
4277       launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
4278   SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4279 }
4280 
4281 bool TargetProperties::GetRequireHardwareBreakpoints() const {
4282   const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4283   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4284       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4285 }
4286 
4287 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
4288   const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4289   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4290 }
4291 
4292 bool TargetProperties::GetAutoInstallMainExecutable() const {
4293   const uint32_t idx = ePropertyAutoInstallMainExecutable;
4294   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4295       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4296 }
4297 
4298 void TargetProperties::Arg0ValueChangedCallback() {
4299   m_launch_info.SetArg0(GetArg0());
4300 }
4301 
4302 void TargetProperties::RunArgsValueChangedCallback() {
4303   Args args;
4304   if (GetRunArguments(args))
4305     m_launch_info.GetArguments() = args;
4306 }
4307 
4308 void TargetProperties::EnvVarsValueChangedCallback() {
4309   m_launch_info.GetEnvironment() = ComputeEnvironment();
4310 }
4311 
4312 void TargetProperties::InputPathValueChangedCallback() {
4313   m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
4314                                      false);
4315 }
4316 
4317 void TargetProperties::OutputPathValueChangedCallback() {
4318   m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
4319                                      false, true);
4320 }
4321 
4322 void TargetProperties::ErrorPathValueChangedCallback() {
4323   m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
4324                                      false, true);
4325 }
4326 
4327 void TargetProperties::DetachOnErrorValueChangedCallback() {
4328   if (GetDetachOnError())
4329     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4330   else
4331     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4332 }
4333 
4334 void TargetProperties::DisableASLRValueChangedCallback() {
4335   if (GetDisableASLR())
4336     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4337   else
4338     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4339 }
4340 
4341 void TargetProperties::InheritTCCValueChangedCallback() {
4342   if (GetInheritTCC())
4343     m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
4344   else
4345     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
4346 }
4347 
4348 void TargetProperties::DisableSTDIOValueChangedCallback() {
4349   if (GetDisableSTDIO())
4350     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4351   else
4352     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4353 }
4354 
4355 bool TargetProperties::GetDebugUtilityExpression() const {
4356   const uint32_t idx = ePropertyDebugUtilityExpression;
4357   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4358       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4359 }
4360 
4361 void TargetProperties::SetDebugUtilityExpression(bool debug) {
4362   const uint32_t idx = ePropertyDebugUtilityExpression;
4363   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, debug);
4364 }
4365 
4366 // Target::TargetEventData
4367 
4368 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4369     : EventData(), m_target_sp(target_sp), m_module_list() {}
4370 
4371 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4372                                          const ModuleList &module_list)
4373     : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4374 
4375 Target::TargetEventData::~TargetEventData() = default;
4376 
4377 ConstString Target::TargetEventData::GetFlavorString() {
4378   static ConstString g_flavor("Target::TargetEventData");
4379   return g_flavor;
4380 }
4381 
4382 void Target::TargetEventData::Dump(Stream *s) const {
4383   for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4384     if (i != 0)
4385       *s << ", ";
4386     m_module_list.GetModuleAtIndex(i)->GetDescription(
4387         s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4388   }
4389 }
4390 
4391 const Target::TargetEventData *
4392 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4393   if (event_ptr) {
4394     const EventData *event_data = event_ptr->GetData();
4395     if (event_data &&
4396         event_data->GetFlavor() == TargetEventData::GetFlavorString())
4397       return static_cast<const TargetEventData *>(event_ptr->GetData());
4398   }
4399   return nullptr;
4400 }
4401 
4402 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4403   TargetSP target_sp;
4404   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4405   if (event_data)
4406     target_sp = event_data->m_target_sp;
4407   return target_sp;
4408 }
4409 
4410 ModuleList
4411 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4412   ModuleList module_list;
4413   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4414   if (event_data)
4415     module_list = event_data->m_module_list;
4416   return module_list;
4417 }
4418 
4419 std::recursive_mutex &Target::GetAPIMutex() {
4420   if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4421     return m_private_mutex;
4422   else
4423     return m_mutex;
4424 }
4425