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