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