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