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