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