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