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