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