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