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