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