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