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