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