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