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