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