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     llvm::SmallVector<ModuleSP, 1>
1977         old_modules; // This will get filled in if we have a new version
1978                      // of the library
1979     bool did_create_module = false;
1980     FileSpecList search_paths = GetExecutableSearchPaths();
1981     // If there are image search path entries, try to use them first to acquire
1982     // a suitable image.
1983     if (m_image_search_paths.GetSize()) {
1984       ModuleSpec transformed_spec(module_spec);
1985       if (m_image_search_paths.RemapPath(
1986               module_spec.GetFileSpec().GetDirectory(),
1987               transformed_spec.GetFileSpec().GetDirectory())) {
1988         transformed_spec.GetFileSpec().GetFilename() =
1989             module_spec.GetFileSpec().GetFilename();
1990         error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1991                                             &search_paths, &old_modules,
1992                                             &did_create_module);
1993       }
1994     }
1995 
1996     if (!module_sp) {
1997       // If we have a UUID, we can check our global shared module list in case
1998       // we already have it. If we don't have a valid UUID, then we can't since
1999       // the path in "module_spec" will be a platform path, and we will need to
2000       // let the platform find that file. For example, we could be asking for
2001       // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
2002       // the local copy of "/usr/lib/dyld" since our platform could be a remote
2003       // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2004       // cache.
2005       if (module_spec.GetUUID().IsValid()) {
2006         // We have a UUID, it is OK to check the global module list...
2007         error =
2008             ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
2009                                         &old_modules, &did_create_module);
2010       }
2011 
2012       if (!module_sp) {
2013         // The platform is responsible for finding and caching an appropriate
2014         // module in the shared module cache.
2015         if (m_platform_sp) {
2016           error = m_platform_sp->GetSharedModule(
2017               module_spec, m_process_sp.get(), module_sp, &search_paths,
2018               &old_modules, &did_create_module);
2019         } else {
2020           error.SetErrorString("no platform is currently set");
2021         }
2022       }
2023     }
2024 
2025     // We found a module that wasn't in our target list.  Let's make sure that
2026     // there wasn't an equivalent module in the list already, and if there was,
2027     // let's remove it.
2028     if (module_sp) {
2029       ObjectFile *objfile = module_sp->GetObjectFile();
2030       if (objfile) {
2031         switch (objfile->GetType()) {
2032         case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2033                                         /// a program's execution state
2034         case ObjectFile::eTypeExecutable:    /// A normal executable
2035         case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2036                                              /// executable
2037         case ObjectFile::eTypeObjectFile:    /// An intermediate object file
2038         case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2039                                              /// used during execution
2040           break;
2041         case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2042                                          /// debug information
2043           if (error_ptr)
2044             error_ptr->SetErrorString("debug info files aren't valid target "
2045                                       "modules, please specify an executable");
2046           return ModuleSP();
2047         case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2048                                            /// against but not used for
2049                                            /// execution
2050           if (error_ptr)
2051             error_ptr->SetErrorString("stub libraries aren't valid target "
2052                                       "modules, please specify an executable");
2053           return ModuleSP();
2054         default:
2055           if (error_ptr)
2056             error_ptr->SetErrorString(
2057                 "unsupported file type, please specify an executable");
2058           return ModuleSP();
2059         }
2060         // GetSharedModule is not guaranteed to find the old shared module, for
2061         // instance in the common case where you pass in the UUID, it is only
2062         // going to find the one module matching the UUID.  In fact, it has no
2063         // good way to know what the "old module" relevant to this target is,
2064         // since there might be many copies of a module with this file spec in
2065         // various running debug sessions, but only one of them will belong to
2066         // this target. So let's remove the UUID from the module list, and look
2067         // in the target's module list. Only do this if there is SOMETHING else
2068         // in the module spec...
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           found_modules.ForEach([&](const ModuleSP &found_module) -> bool {
2078             old_modules.push_back(found_module);
2079             return true;
2080           });
2081         }
2082 
2083         // Preload symbols outside of any lock, so hopefully we can do this for
2084         // each library in parallel.
2085         if (GetPreloadSymbols())
2086           module_sp->PreloadSymbols();
2087 
2088         llvm::SmallVector<ModuleSP, 1> replaced_modules;
2089         for (ModuleSP &old_module_sp : old_modules) {
2090           if (m_images.GetIndexForModule(old_module_sp.get()) !=
2091               LLDB_INVALID_INDEX32) {
2092             if (replaced_modules.empty())
2093               m_images.ReplaceModule(old_module_sp, module_sp);
2094             else
2095               m_images.Remove(old_module_sp);
2096 
2097             replaced_modules.push_back(std::move(old_module_sp));
2098           }
2099         }
2100 
2101         if (replaced_modules.size() > 1) {
2102           // The same new module replaced multiple old modules
2103           // simultaneously.  It's not clear this should ever
2104           // happen (if we always replace old modules as we add
2105           // new ones, presumably we should never have more than
2106           // one old one).  If there are legitimate cases where
2107           // this happens, then the ModuleList::Notifier interface
2108           // may need to be adjusted to allow reporting this.
2109           // In the meantime, just log that this has happened; just
2110           // above we called ReplaceModule on the first one, and Remove
2111           // on the rest.
2112           if (Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET |
2113                                                   LIBLLDB_LOG_MODULES)) {
2114             StreamString message;
2115             auto dump = [&message](Module &dump_module) -> void {
2116               UUID dump_uuid = dump_module.GetUUID();
2117 
2118               message << '[';
2119               dump_module.GetDescription(message.AsRawOstream());
2120               message << " (uuid ";
2121 
2122               if (dump_uuid.IsValid())
2123                 dump_uuid.Dump(&message);
2124               else
2125                 message << "not specified";
2126 
2127               message << ")]";
2128             };
2129 
2130             message << "New module ";
2131             dump(*module_sp);
2132             message.AsRawOstream()
2133                 << llvm::formatv(" simultaneously replaced {0} old modules: ",
2134                                  replaced_modules.size());
2135             for (ModuleSP &replaced_module_sp : replaced_modules)
2136               dump(*replaced_module_sp);
2137 
2138             log->PutString(message.GetString());
2139           }
2140         }
2141 
2142         if (replaced_modules.empty())
2143           m_images.Append(module_sp, notify);
2144 
2145         for (ModuleSP &old_module_sp : replaced_modules) {
2146           Module *old_module_ptr = old_module_sp.get();
2147           old_module_sp.reset();
2148           ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2149         }
2150       } else
2151         module_sp.reset();
2152     }
2153   }
2154   if (error_ptr)
2155     *error_ptr = error;
2156   return module_sp;
2157 }
2158 
2159 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2160 
2161 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2162 
2163 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2164 
2165 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2166 
2167 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2168   exe_ctx.Clear();
2169   exe_ctx.SetTargetPtr(this);
2170 }
2171 
2172 PathMappingList &Target::GetImageSearchPathList() {
2173   return m_image_search_paths;
2174 }
2175 
2176 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2177                                      void *baton) {
2178   Target *target = (Target *)baton;
2179   ModuleSP exe_module_sp(target->GetExecutableModule());
2180   if (exe_module_sp)
2181     target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2182 }
2183 
2184 llvm::Expected<TypeSystem &>
2185 Target::GetScratchTypeSystemForLanguage(lldb::LanguageType language,
2186                                         bool create_on_demand) {
2187   if (!m_valid)
2188     return llvm::make_error<llvm::StringError>("Invalid Target",
2189                                                llvm::inconvertibleErrorCode());
2190 
2191   if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2192                                              // assembly code
2193       || language == eLanguageTypeUnknown) {
2194     LanguageSet languages_for_expressions =
2195         Language::GetLanguagesSupportingTypeSystemsForExpressions();
2196 
2197     if (languages_for_expressions[eLanguageTypeC]) {
2198       language = eLanguageTypeC; // LLDB's default.  Override by setting the
2199                                  // target language.
2200     } else {
2201       if (languages_for_expressions.Empty())
2202         return llvm::make_error<llvm::StringError>(
2203             "No expression support for any languages",
2204             llvm::inconvertibleErrorCode());
2205       language = (LanguageType)languages_for_expressions.bitvector.find_first();
2206     }
2207   }
2208 
2209   return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2210                                                             create_on_demand);
2211 }
2212 
2213 std::vector<TypeSystem *> Target::GetScratchTypeSystems(bool create_on_demand) {
2214   if (!m_valid)
2215     return {};
2216 
2217   std::vector<TypeSystem *> scratch_type_systems;
2218 
2219   LanguageSet languages_for_expressions =
2220       Language::GetLanguagesSupportingTypeSystemsForExpressions();
2221 
2222   for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2223     auto language = (LanguageType)bit;
2224     auto type_system_or_err =
2225         GetScratchTypeSystemForLanguage(language, create_on_demand);
2226     if (!type_system_or_err)
2227       LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2228                      type_system_or_err.takeError(),
2229                      "Language '{}' has expression support but no scratch type "
2230                      "system available",
2231                      Language::GetNameForLanguageType(language));
2232     else
2233       scratch_type_systems.emplace_back(&type_system_or_err.get());
2234   }
2235 
2236   return scratch_type_systems;
2237 }
2238 
2239 PersistentExpressionState *
2240 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2241   auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2242 
2243   if (auto err = type_system_or_err.takeError()) {
2244     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2245                    std::move(err),
2246                    "Unable to get persistent expression state for language {}",
2247                    Language::GetNameForLanguageType(language));
2248     return nullptr;
2249   }
2250 
2251   return type_system_or_err->GetPersistentExpressionState();
2252 }
2253 
2254 UserExpression *Target::GetUserExpressionForLanguage(
2255     llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2256     Expression::ResultType desired_type,
2257     const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2258     Status &error) {
2259   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2260   if (auto err = type_system_or_err.takeError()) {
2261     error.SetErrorStringWithFormat(
2262         "Could not find type system for language %s: %s",
2263         Language::GetNameForLanguageType(language),
2264         llvm::toString(std::move(err)).c_str());
2265     return nullptr;
2266   }
2267 
2268   auto *user_expr = type_system_or_err->GetUserExpression(
2269       expr, prefix, language, desired_type, options, ctx_obj);
2270   if (!user_expr)
2271     error.SetErrorStringWithFormat(
2272         "Could not create an expression for language %s",
2273         Language::GetNameForLanguageType(language));
2274 
2275   return user_expr;
2276 }
2277 
2278 FunctionCaller *Target::GetFunctionCallerForLanguage(
2279     lldb::LanguageType language, const CompilerType &return_type,
2280     const Address &function_address, const ValueList &arg_value_list,
2281     const char *name, Status &error) {
2282   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2283   if (auto err = type_system_or_err.takeError()) {
2284     error.SetErrorStringWithFormat(
2285         "Could not find type system for language %s: %s",
2286         Language::GetNameForLanguageType(language),
2287         llvm::toString(std::move(err)).c_str());
2288     return nullptr;
2289   }
2290 
2291   auto *persistent_fn = type_system_or_err->GetFunctionCaller(
2292       return_type, function_address, arg_value_list, name);
2293   if (!persistent_fn)
2294     error.SetErrorStringWithFormat(
2295         "Could not create an expression for language %s",
2296         Language::GetNameForLanguageType(language));
2297 
2298   return persistent_fn;
2299 }
2300 
2301 llvm::Expected<std::unique_ptr<UtilityFunction>>
2302 Target::CreateUtilityFunction(std::string expression, std::string name,
2303                               lldb::LanguageType language,
2304                               ExecutionContext &exe_ctx) {
2305   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2306   if (!type_system_or_err)
2307     return type_system_or_err.takeError();
2308 
2309   std::unique_ptr<UtilityFunction> utility_fn =
2310       type_system_or_err->CreateUtilityFunction(std::move(expression),
2311                                                 std::move(name));
2312   if (!utility_fn)
2313     return llvm::make_error<llvm::StringError>(
2314         llvm::StringRef("Could not create an expression for language") +
2315             Language::GetNameForLanguageType(language),
2316         llvm::inconvertibleErrorCode());
2317 
2318   DiagnosticManager diagnostics;
2319   if (!utility_fn->Install(diagnostics, exe_ctx))
2320     return llvm::make_error<llvm::StringError>(diagnostics.GetString(),
2321                                                llvm::inconvertibleErrorCode());
2322 
2323   return std::move(utility_fn);
2324 }
2325 
2326 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2327 
2328 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2329 
2330 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2331   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2332   if (properties_sp)
2333     return properties_sp->GetExecutableSearchPaths();
2334   return FileSpecList();
2335 }
2336 
2337 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2338   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2339   if (properties_sp)
2340     return properties_sp->GetDebugFileSearchPaths();
2341   return FileSpecList();
2342 }
2343 
2344 ArchSpec Target::GetDefaultArchitecture() {
2345   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2346   if (properties_sp)
2347     return properties_sp->GetDefaultArchitecture();
2348   return ArchSpec();
2349 }
2350 
2351 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2352   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2353   if (properties_sp) {
2354     LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET),
2355              "Target::SetDefaultArchitecture setting target's "
2356              "default architecture to  {0} ({1})",
2357              arch.GetArchitectureName(), arch.GetTriple().getTriple());
2358     return properties_sp->SetDefaultArchitecture(arch);
2359   }
2360 }
2361 
2362 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2363                                       const SymbolContext *sc_ptr) {
2364   // The target can either exist in the "process" of ExecutionContext, or in
2365   // the "target_sp" member of SymbolContext. This accessor helper function
2366   // will get the target from one of these locations.
2367 
2368   Target *target = nullptr;
2369   if (sc_ptr != nullptr)
2370     target = sc_ptr->target_sp.get();
2371   if (target == nullptr && exe_ctx_ptr)
2372     target = exe_ctx_ptr->GetTargetPtr();
2373   return target;
2374 }
2375 
2376 ExpressionResults Target::EvaluateExpression(
2377     llvm::StringRef expr, ExecutionContextScope *exe_scope,
2378     lldb::ValueObjectSP &result_valobj_sp,
2379     const EvaluateExpressionOptions &options, std::string *fixed_expression,
2380     ValueObject *ctx_obj) {
2381   result_valobj_sp.reset();
2382 
2383   ExpressionResults execution_results = eExpressionSetupError;
2384 
2385   if (expr.empty())
2386     return execution_results;
2387 
2388   // We shouldn't run stop hooks in expressions.
2389   bool old_suppress_value = m_suppress_stop_hooks;
2390   m_suppress_stop_hooks = true;
2391   auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2392     m_suppress_stop_hooks = old_suppress_value;
2393   });
2394 
2395   ExecutionContext exe_ctx;
2396 
2397   if (exe_scope) {
2398     exe_scope->CalculateExecutionContext(exe_ctx);
2399   } else if (m_process_sp) {
2400     m_process_sp->CalculateExecutionContext(exe_ctx);
2401   } else {
2402     CalculateExecutionContext(exe_ctx);
2403   }
2404 
2405   // Make sure we aren't just trying to see the value of a persistent variable
2406   // (something like "$0")
2407   // Only check for persistent variables the expression starts with a '$'
2408   lldb::ExpressionVariableSP persistent_var_sp;
2409   if (expr[0] == '$') {
2410     auto type_system_or_err =
2411             GetScratchTypeSystemForLanguage(eLanguageTypeC);
2412     if (auto err = type_system_or_err.takeError()) {
2413       LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2414                      std::move(err), "Unable to get scratch type system");
2415     } else {
2416       persistent_var_sp =
2417           type_system_or_err->GetPersistentExpressionState()->GetVariable(expr);
2418     }
2419   }
2420   if (persistent_var_sp) {
2421     result_valobj_sp = persistent_var_sp->GetValueObject();
2422     execution_results = eExpressionCompleted;
2423   } else {
2424     llvm::StringRef prefix = GetExpressionPrefixContents();
2425     Status error;
2426     execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2427                                                  result_valobj_sp, error,
2428                                                  fixed_expression, ctx_obj);
2429   }
2430 
2431   return execution_results;
2432 }
2433 
2434 lldb::ExpressionVariableSP Target::GetPersistentVariable(ConstString name) {
2435   lldb::ExpressionVariableSP variable_sp;
2436   m_scratch_type_system_map.ForEach(
2437       [name, &variable_sp](TypeSystem *type_system) -> bool {
2438         if (PersistentExpressionState *persistent_state =
2439                 type_system->GetPersistentExpressionState()) {
2440           variable_sp = persistent_state->GetVariable(name);
2441 
2442           if (variable_sp)
2443             return false; // Stop iterating the ForEach
2444         }
2445         return true; // Keep iterating the ForEach
2446       });
2447   return variable_sp;
2448 }
2449 
2450 lldb::addr_t Target::GetPersistentSymbol(ConstString name) {
2451   lldb::addr_t address = LLDB_INVALID_ADDRESS;
2452 
2453   m_scratch_type_system_map.ForEach(
2454       [name, &address](TypeSystem *type_system) -> bool {
2455         if (PersistentExpressionState *persistent_state =
2456                 type_system->GetPersistentExpressionState()) {
2457           address = persistent_state->LookupSymbol(name);
2458           if (address != LLDB_INVALID_ADDRESS)
2459             return false; // Stop iterating the ForEach
2460         }
2461         return true; // Keep iterating the ForEach
2462       });
2463   return address;
2464 }
2465 
2466 llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2467   Module *exe_module = GetExecutableModulePointer();
2468 
2469   // Try to find the entry point address in the primary executable.
2470   const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2471   if (has_primary_executable) {
2472     Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2473     if (entry_addr.IsValid())
2474       return entry_addr;
2475   }
2476 
2477   const ModuleList &modules = GetImages();
2478   const size_t num_images = modules.GetSize();
2479   for (size_t idx = 0; idx < num_images; ++idx) {
2480     ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2481     if (!module_sp || !module_sp->GetObjectFile())
2482       continue;
2483 
2484     Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2485     if (entry_addr.IsValid())
2486       return entry_addr;
2487   }
2488 
2489   // We haven't found the entry point address. Return an appropriate error.
2490   if (!has_primary_executable)
2491     return llvm::make_error<llvm::StringError>(
2492         "No primary executable found and could not find entry point address in "
2493         "any executable module",
2494         llvm::inconvertibleErrorCode());
2495 
2496   return llvm::make_error<llvm::StringError>(
2497       "Could not find entry point address for primary executable module \"" +
2498           exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"",
2499       llvm::inconvertibleErrorCode());
2500 }
2501 
2502 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2503                                             AddressClass addr_class) const {
2504   auto arch_plugin = GetArchitecturePlugin();
2505   return arch_plugin
2506              ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2507              : load_addr;
2508 }
2509 
2510 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2511                                           AddressClass addr_class) const {
2512   auto arch_plugin = GetArchitecturePlugin();
2513   return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2514                      : load_addr;
2515 }
2516 
2517 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2518   auto arch_plugin = GetArchitecturePlugin();
2519   return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2520 }
2521 
2522 SourceManager &Target::GetSourceManager() {
2523   if (!m_source_manager_up)
2524     m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2525   return *m_source_manager_up;
2526 }
2527 
2528 ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2529   static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2530                                                        // we can make it
2531                                                        // per-target
2532 
2533   {
2534     std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2535 
2536     if (!m_clang_modules_decl_vendor_up) {
2537       m_clang_modules_decl_vendor_up.reset(
2538           ClangModulesDeclVendor::Create(*this));
2539     }
2540   }
2541 
2542   return m_clang_modules_decl_vendor_up.get();
2543 }
2544 
2545 Target::StopHookSP Target::CreateStopHook(StopHook::StopHookKind kind) {
2546   lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2547   Target::StopHookSP stop_hook_sp;
2548   switch (kind) {
2549   case StopHook::StopHookKind::CommandBased:
2550     stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
2551     break;
2552   case StopHook::StopHookKind::ScriptBased:
2553     stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
2554     break;
2555   }
2556   m_stop_hooks[new_uid] = stop_hook_sp;
2557   return stop_hook_sp;
2558 }
2559 
2560 void Target::UndoCreateStopHook(lldb::user_id_t user_id) {
2561   if (!RemoveStopHookByID(user_id))
2562     return;
2563   if (user_id == m_stop_hook_next_id)
2564     m_stop_hook_next_id--;
2565 }
2566 
2567 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2568   size_t num_removed = m_stop_hooks.erase(user_id);
2569   return (num_removed != 0);
2570 }
2571 
2572 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2573 
2574 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2575   StopHookSP found_hook;
2576 
2577   StopHookCollection::iterator specified_hook_iter;
2578   specified_hook_iter = m_stop_hooks.find(user_id);
2579   if (specified_hook_iter != m_stop_hooks.end())
2580     found_hook = (*specified_hook_iter).second;
2581   return found_hook;
2582 }
2583 
2584 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2585                                         bool active_state) {
2586   StopHookCollection::iterator specified_hook_iter;
2587   specified_hook_iter = m_stop_hooks.find(user_id);
2588   if (specified_hook_iter == m_stop_hooks.end())
2589     return false;
2590 
2591   (*specified_hook_iter).second->SetIsActive(active_state);
2592   return true;
2593 }
2594 
2595 void Target::SetAllStopHooksActiveState(bool active_state) {
2596   StopHookCollection::iterator pos, end = m_stop_hooks.end();
2597   for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2598     (*pos).second->SetIsActive(active_state);
2599   }
2600 }
2601 
2602 bool Target::RunStopHooks() {
2603   if (m_suppress_stop_hooks)
2604     return false;
2605 
2606   if (!m_process_sp)
2607     return false;
2608 
2609   // Somebody might have restarted the process:
2610   // Still return false, the return value is about US restarting the target.
2611   if (m_process_sp->GetState() != eStateStopped)
2612     return false;
2613 
2614   // <rdar://problem/12027563> make sure we check that we are not stopped
2615   // because of us running a user expression since in that case we do not want
2616   // to run the stop-hooks
2617   if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2618     return false;
2619 
2620   if (m_stop_hooks.empty())
2621     return false;
2622 
2623   // If there aren't any active stop hooks, don't bother either.
2624   bool any_active_hooks = false;
2625   for (auto hook : m_stop_hooks) {
2626     if (hook.second->IsActive()) {
2627       any_active_hooks = true;
2628       break;
2629     }
2630   }
2631   if (!any_active_hooks)
2632     return false;
2633 
2634   std::vector<ExecutionContext> exc_ctx_with_reasons;
2635 
2636   ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2637   size_t num_threads = cur_threadlist.GetSize();
2638   for (size_t i = 0; i < num_threads; i++) {
2639     lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2640     if (cur_thread_sp->ThreadStoppedForAReason()) {
2641       lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2642       exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
2643                                         cur_frame_sp.get());
2644     }
2645   }
2646 
2647   // If no threads stopped for a reason, don't run the stop-hooks.
2648   size_t num_exe_ctx = exc_ctx_with_reasons.size();
2649   if (num_exe_ctx == 0)
2650     return false;
2651 
2652   StreamSP output_sp = m_debugger.GetAsyncOutputStream();
2653 
2654   bool auto_continue = false;
2655   bool hooks_ran = false;
2656   bool print_hook_header = (m_stop_hooks.size() != 1);
2657   bool print_thread_header = (num_exe_ctx != 1);
2658   bool should_stop = false;
2659   bool somebody_restarted = false;
2660 
2661   for (auto stop_entry : m_stop_hooks) {
2662     StopHookSP cur_hook_sp = stop_entry.second;
2663     if (!cur_hook_sp->IsActive())
2664       continue;
2665 
2666     bool any_thread_matched = false;
2667     for (auto exc_ctx : exc_ctx_with_reasons) {
2668       // We detect somebody restarted in the stop-hook loop, and broke out of
2669       // that loop back to here.  So break out of here too.
2670       if (somebody_restarted)
2671         break;
2672 
2673       if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
2674         continue;
2675 
2676       // We only consult the auto-continue for a stop hook if it matched the
2677       // specifier.
2678       auto_continue |= cur_hook_sp->GetAutoContinue();
2679 
2680       if (!hooks_ran)
2681         hooks_ran = true;
2682 
2683       if (print_hook_header && !any_thread_matched) {
2684         StreamString s;
2685         cur_hook_sp->GetDescription(&s, eDescriptionLevelBrief);
2686         if (s.GetSize() != 0)
2687           output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
2688                             s.GetData());
2689         else
2690           output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2691         any_thread_matched = true;
2692       }
2693 
2694       if (print_thread_header)
2695         output_sp->Printf("-- Thread %d\n",
2696                           exc_ctx.GetThreadPtr()->GetIndexID());
2697 
2698       StopHook::StopHookResult this_result =
2699           cur_hook_sp->HandleStop(exc_ctx, output_sp);
2700       bool this_should_stop = true;
2701 
2702       switch (this_result) {
2703       case StopHook::StopHookResult::KeepStopped:
2704         // If this hook is set to auto-continue that should override the
2705         // HandleStop result...
2706         if (cur_hook_sp->GetAutoContinue())
2707           this_should_stop = false;
2708         else
2709           this_should_stop = true;
2710 
2711         break;
2712       case StopHook::StopHookResult::RequestContinue:
2713         this_should_stop = false;
2714         break;
2715       case StopHook::StopHookResult::AlreadyContinued:
2716         // We don't have a good way to prohibit people from restarting the
2717         // target willy nilly in a stop hook.  If the hook did so, give a
2718         // gentle suggestion here and bag out if the hook processing.
2719         output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
2720                           " set the program running.\n"
2721                           "  Consider using '-G true' to make "
2722                           "stop hooks auto-continue.\n",
2723                           cur_hook_sp->GetID());
2724         somebody_restarted = true;
2725         break;
2726       }
2727       // If we're already restarted, stop processing stop hooks.
2728       // FIXME: if we are doing non-stop mode for real, we would have to
2729       // check that OUR thread was restarted, otherwise we should keep
2730       // processing stop hooks.
2731       if (somebody_restarted)
2732         break;
2733 
2734       // If anybody wanted to stop, we should all stop.
2735       if (!should_stop)
2736         should_stop = this_should_stop;
2737     }
2738   }
2739 
2740   output_sp->Flush();
2741 
2742   // If one of the commands in the stop hook already restarted the target,
2743   // report that fact.
2744   if (somebody_restarted)
2745     return true;
2746 
2747   // Finally, if auto-continue was requested, do it now:
2748   // We only compute should_stop against the hook results if a hook got to run
2749   // which is why we have to do this conjoint test.
2750   if ((hooks_ran && !should_stop) || auto_continue) {
2751     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2752     Status error = m_process_sp->PrivateResume();
2753     if (error.Success()) {
2754       LLDB_LOG(log, "Resuming from RunStopHooks");
2755       return true;
2756     } else {
2757       LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
2758       return false;
2759     }
2760   }
2761 
2762   return false;
2763 }
2764 
2765 const TargetPropertiesSP &Target::GetGlobalProperties() {
2766   // NOTE: intentional leak so we don't crash if global destructor chain gets
2767   // called as other threads still use the result of this function
2768   static TargetPropertiesSP *g_settings_sp_ptr =
2769       new TargetPropertiesSP(new TargetProperties(nullptr));
2770   return *g_settings_sp_ptr;
2771 }
2772 
2773 Status Target::Install(ProcessLaunchInfo *launch_info) {
2774   Status error;
2775   PlatformSP platform_sp(GetPlatform());
2776   if (platform_sp) {
2777     if (platform_sp->IsRemote()) {
2778       if (platform_sp->IsConnected()) {
2779         // Install all files that have an install path when connected to a
2780         // remote platform. If target.auto-install-main-executable is set then
2781         // also install the main executable even if it does not have an explicit
2782         // install path specified.
2783         const ModuleList &modules = GetImages();
2784         const size_t num_images = modules.GetSize();
2785         for (size_t idx = 0; idx < num_images; ++idx) {
2786           ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2787           if (module_sp) {
2788             const bool is_main_executable = module_sp == GetExecutableModule();
2789             FileSpec local_file(module_sp->GetFileSpec());
2790             if (local_file) {
2791               FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2792               if (!remote_file) {
2793                 if (is_main_executable && GetAutoInstallMainExecutable()) {
2794                   // Automatically install the main executable.
2795                   remote_file = platform_sp->GetRemoteWorkingDirectory();
2796                   remote_file.AppendPathComponent(
2797                       module_sp->GetFileSpec().GetFilename().GetCString());
2798                 }
2799               }
2800               if (remote_file) {
2801                 error = platform_sp->Install(local_file, remote_file);
2802                 if (error.Success()) {
2803                   module_sp->SetPlatformFileSpec(remote_file);
2804                   if (is_main_executable) {
2805                     platform_sp->SetFilePermissions(remote_file, 0700);
2806                     if (launch_info)
2807                       launch_info->SetExecutableFile(remote_file, false);
2808                   }
2809                 } else
2810                   break;
2811               }
2812             }
2813           }
2814         }
2815       }
2816     }
2817   }
2818   return error;
2819 }
2820 
2821 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2822                                 uint32_t stop_id) {
2823   return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2824 }
2825 
2826 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2827                                 Address &resolved_addr) {
2828   return m_images.ResolveFileAddress(file_addr, resolved_addr);
2829 }
2830 
2831 bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2832                                    addr_t new_section_load_addr,
2833                                    bool warn_multiple) {
2834   const addr_t old_section_load_addr =
2835       m_section_load_history.GetSectionLoadAddress(
2836           SectionLoadHistory::eStopIDNow, section_sp);
2837   if (old_section_load_addr != new_section_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     if (m_section_load_history.SetSectionLoadAddress(
2845             stop_id, section_sp, new_section_load_addr, warn_multiple))
2846       return true; // Return true if the section load address was changed...
2847   }
2848   return false; // Return false to indicate nothing changed
2849 }
2850 
2851 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2852   size_t section_unload_count = 0;
2853   size_t num_modules = module_list.GetSize();
2854   for (size_t i = 0; i < num_modules; ++i) {
2855     section_unload_count +=
2856         UnloadModuleSections(module_list.GetModuleAtIndex(i));
2857   }
2858   return section_unload_count;
2859 }
2860 
2861 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2862   uint32_t stop_id = 0;
2863   ProcessSP process_sp(GetProcessSP());
2864   if (process_sp)
2865     stop_id = process_sp->GetStopID();
2866   else
2867     stop_id = m_section_load_history.GetLastStopID();
2868   SectionList *sections = module_sp->GetSectionList();
2869   size_t section_unload_count = 0;
2870   if (sections) {
2871     const uint32_t num_sections = sections->GetNumSections(0);
2872     for (uint32_t i = 0; i < num_sections; ++i) {
2873       section_unload_count += m_section_load_history.SetSectionUnloaded(
2874           stop_id, sections->GetSectionAtIndex(i));
2875     }
2876   }
2877   return section_unload_count;
2878 }
2879 
2880 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2881   uint32_t stop_id = 0;
2882   ProcessSP process_sp(GetProcessSP());
2883   if (process_sp)
2884     stop_id = process_sp->GetStopID();
2885   else
2886     stop_id = m_section_load_history.GetLastStopID();
2887   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2888 }
2889 
2890 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2891                                 addr_t load_addr) {
2892   uint32_t stop_id = 0;
2893   ProcessSP process_sp(GetProcessSP());
2894   if (process_sp)
2895     stop_id = process_sp->GetStopID();
2896   else
2897     stop_id = m_section_load_history.GetLastStopID();
2898   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2899                                                    load_addr);
2900 }
2901 
2902 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2903 
2904 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2905   Status error;
2906   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2907 
2908   LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
2909             launch_info.GetExecutableFile().GetPath().c_str());
2910 
2911   StateType state = eStateInvalid;
2912 
2913   // Scope to temporarily get the process state in case someone has manually
2914   // remotely connected already to a process and we can skip the platform
2915   // launching.
2916   {
2917     ProcessSP process_sp(GetProcessSP());
2918 
2919     if (process_sp) {
2920       state = process_sp->GetState();
2921       LLDB_LOGF(log,
2922                 "Target::%s the process exists, and its current state is %s",
2923                 __FUNCTION__, StateAsCString(state));
2924     } else {
2925       LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
2926                 __FUNCTION__);
2927     }
2928   }
2929 
2930   launch_info.GetFlags().Set(eLaunchFlagDebug);
2931 
2932   // Get the value of synchronous execution here.  If you wait till after you
2933   // have started to run, then you could have hit a breakpoint, whose command
2934   // might switch the value, and then you'll pick up that incorrect value.
2935   Debugger &debugger = GetDebugger();
2936   const bool synchronous_execution =
2937       debugger.GetCommandInterpreter().GetSynchronous();
2938 
2939   PlatformSP platform_sp(GetPlatform());
2940 
2941   FinalizeFileActions(launch_info);
2942 
2943   if (state == eStateConnected) {
2944     if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2945       error.SetErrorString(
2946           "can't launch in tty when launching through a remote connection");
2947       return error;
2948     }
2949   }
2950 
2951   if (!launch_info.GetArchitecture().IsValid())
2952     launch_info.GetArchitecture() = GetArchitecture();
2953 
2954   // If we're not already connected to the process, and if we have a platform
2955   // that can launch a process for debugging, go ahead and do that here.
2956   if (state != eStateConnected && platform_sp &&
2957       platform_sp->CanDebugProcess()) {
2958     LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
2959               __FUNCTION__);
2960 
2961     // If there was a previous process, delete it before we make the new one.
2962     // One subtle point, we delete the process before we release the reference
2963     // to m_process_sp.  That way even if we are the last owner, the process
2964     // will get Finalized before it gets destroyed.
2965     DeleteCurrentProcess();
2966 
2967     m_process_sp =
2968         GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2969 
2970   } else {
2971     LLDB_LOGF(log,
2972               "Target::%s the platform doesn't know how to debug a "
2973               "process, getting a process plugin to do this for us.",
2974               __FUNCTION__);
2975 
2976     if (state == eStateConnected) {
2977       assert(m_process_sp);
2978     } else {
2979       // Use a Process plugin to construct the process.
2980       const char *plugin_name = launch_info.GetProcessPluginName();
2981       CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
2982     }
2983 
2984     // Since we didn't have a platform launch the process, launch it here.
2985     if (m_process_sp)
2986       error = m_process_sp->Launch(launch_info);
2987   }
2988 
2989   if (!m_process_sp && error.Success())
2990     error.SetErrorString("failed to launch or debug process");
2991 
2992   if (!error.Success())
2993     return error;
2994 
2995   auto at_exit =
2996       llvm::make_scope_exit([&]() { m_process_sp->RestoreProcessEvents(); });
2997 
2998   if (!synchronous_execution &&
2999       launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3000     return error;
3001 
3002   ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
3003   if (!hijack_listener_sp) {
3004     hijack_listener_sp = Listener::MakeListener("lldb.Target.Launch.hijack");
3005     launch_info.SetHijackListener(hijack_listener_sp);
3006     m_process_sp->HijackProcessEvents(hijack_listener_sp);
3007   }
3008 
3009   switch (m_process_sp->WaitForProcessToStop(llvm::None, nullptr, false,
3010                                              hijack_listener_sp, nullptr)) {
3011   case eStateStopped: {
3012     if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3013       break;
3014     if (synchronous_execution) {
3015       // Now we have handled the stop-from-attach, and we are just
3016       // switching to a synchronous resume.  So we should switch to the
3017       // SyncResume hijacker.
3018       m_process_sp->RestoreProcessEvents();
3019       m_process_sp->ResumeSynchronous(stream);
3020     } else {
3021       m_process_sp->RestoreProcessEvents();
3022       error = m_process_sp->PrivateResume();
3023     }
3024     if (!error.Success()) {
3025       Status error2;
3026       error2.SetErrorStringWithFormat(
3027           "process resume at entry point failed: %s", error.AsCString());
3028       error = error2;
3029     }
3030   } break;
3031   case eStateExited: {
3032     bool with_shell = !!launch_info.GetShell();
3033     const int exit_status = m_process_sp->GetExitStatus();
3034     const char *exit_desc = m_process_sp->GetExitDescription();
3035     std::string desc;
3036     if (exit_desc && exit_desc[0])
3037       desc = " (" + std::string(exit_desc) + ')';
3038     if (with_shell)
3039       error.SetErrorStringWithFormat(
3040           "process exited with status %i%s\n"
3041           "'r' and 'run' are aliases that default to launching through a "
3042           "shell.\n"
3043           "Try launching without going through a shell by using "
3044           "'process launch'.",
3045           exit_status, desc.c_str());
3046     else
3047       error.SetErrorStringWithFormat("process exited with status %i%s",
3048                                      exit_status, desc.c_str());
3049   } break;
3050   default:
3051     error.SetErrorStringWithFormat("initial process state wasn't stopped: %s",
3052                                    StateAsCString(state));
3053     break;
3054   }
3055   return error;
3056 }
3057 
3058 void Target::SetTrace(const TraceSP &trace_sp) { m_trace_sp = trace_sp; }
3059 
3060 const TraceSP &Target::GetTrace() { return m_trace_sp; }
3061 
3062 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
3063   auto state = eStateInvalid;
3064   auto process_sp = GetProcessSP();
3065   if (process_sp) {
3066     state = process_sp->GetState();
3067     if (process_sp->IsAlive() && state != eStateConnected) {
3068       if (state == eStateAttaching)
3069         return Status("process attach is in progress");
3070       return Status("a process is already being debugged");
3071     }
3072   }
3073 
3074   const ModuleSP old_exec_module_sp = GetExecutableModule();
3075 
3076   // If no process info was specified, then use the target executable name as
3077   // the process to attach to by default
3078   if (!attach_info.ProcessInfoSpecified()) {
3079     if (old_exec_module_sp)
3080       attach_info.GetExecutableFile().GetFilename() =
3081           old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3082 
3083     if (!attach_info.ProcessInfoSpecified()) {
3084       return Status("no process specified, create a target with a file, or "
3085                     "specify the --pid or --name");
3086     }
3087   }
3088 
3089   const auto platform_sp =
3090       GetDebugger().GetPlatformList().GetSelectedPlatform();
3091   ListenerSP hijack_listener_sp;
3092   const bool async = attach_info.GetAsync();
3093   if (!async) {
3094     hijack_listener_sp =
3095         Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3096     attach_info.SetHijackListener(hijack_listener_sp);
3097   }
3098 
3099   Status error;
3100   if (state != eStateConnected && platform_sp != nullptr &&
3101       platform_sp->CanDebugProcess()) {
3102     SetPlatform(platform_sp);
3103     process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3104   } else {
3105     if (state != eStateConnected) {
3106       const char *plugin_name = attach_info.GetProcessPluginName();
3107       process_sp =
3108           CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3109                         plugin_name, nullptr);
3110       if (process_sp == nullptr) {
3111         error.SetErrorStringWithFormat(
3112             "failed to create process using plugin %s",
3113             (plugin_name) ? plugin_name : "null");
3114         return error;
3115       }
3116     }
3117     if (hijack_listener_sp)
3118       process_sp->HijackProcessEvents(hijack_listener_sp);
3119     error = process_sp->Attach(attach_info);
3120   }
3121 
3122   if (error.Success() && process_sp) {
3123     if (async) {
3124       process_sp->RestoreProcessEvents();
3125     } else {
3126       state = process_sp->WaitForProcessToStop(
3127           llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3128       process_sp->RestoreProcessEvents();
3129 
3130       if (state != eStateStopped) {
3131         const char *exit_desc = process_sp->GetExitDescription();
3132         if (exit_desc)
3133           error.SetErrorStringWithFormat("%s", exit_desc);
3134         else
3135           error.SetErrorString(
3136               "process did not stop (no such process or permission problem?)");
3137         process_sp->Destroy(false);
3138       }
3139     }
3140   }
3141   return error;
3142 }
3143 
3144 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3145   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3146 
3147   // Finalize the file actions, and if none were given, default to opening up a
3148   // pseudo terminal
3149   PlatformSP platform_sp = GetPlatform();
3150   const bool default_to_use_pty =
3151       m_platform_sp ? m_platform_sp->IsHost() : false;
3152   LLDB_LOG(
3153       log,
3154       "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3155       bool(platform_sp),
3156       platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3157       default_to_use_pty);
3158 
3159   // If nothing for stdin or stdout or stderr was specified, then check the
3160   // process for any default settings that were set with "settings set"
3161   if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3162       info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3163       info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3164     LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3165                   "default handling");
3166 
3167     if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3168       // Do nothing, if we are launching in a remote terminal no file actions
3169       // should be done at all.
3170       return;
3171     }
3172 
3173     if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3174       LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3175                     "for stdin, stdout and stderr");
3176       info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3177       info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3178       info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3179     } else {
3180       // Check for any values that might have gotten set with any of: (lldb)
3181       // settings set target.input-path (lldb) settings set target.output-path
3182       // (lldb) settings set target.error-path
3183       FileSpec in_file_spec;
3184       FileSpec out_file_spec;
3185       FileSpec err_file_spec;
3186       // Only override with the target settings if we don't already have an
3187       // action for in, out or error
3188       if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3189         in_file_spec = GetStandardInputPath();
3190       if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3191         out_file_spec = GetStandardOutputPath();
3192       if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3193         err_file_spec = GetStandardErrorPath();
3194 
3195       LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3196                in_file_spec, out_file_spec, err_file_spec);
3197 
3198       if (in_file_spec) {
3199         info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3200         LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3201       }
3202 
3203       if (out_file_spec) {
3204         info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3205         LLDB_LOG(log, "appended stdout open file action for {0}",
3206                  out_file_spec);
3207       }
3208 
3209       if (err_file_spec) {
3210         info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3211         LLDB_LOG(log, "appended stderr open file action for {0}",
3212                  err_file_spec);
3213       }
3214 
3215       if (default_to_use_pty &&
3216           (!in_file_spec || !out_file_spec || !err_file_spec)) {
3217         llvm::Error Err = info.SetUpPtyRedirection();
3218         LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3219       }
3220     }
3221   }
3222 }
3223 
3224 // Target::StopHook
3225 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3226     : UserID(uid), m_target_sp(target_sp), m_specifier_sp(),
3227       m_thread_spec_up() {}
3228 
3229 Target::StopHook::StopHook(const StopHook &rhs)
3230     : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3231       m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(),
3232       m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) {
3233   if (rhs.m_thread_spec_up)
3234     m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3235 }
3236 
3237 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3238   m_specifier_sp.reset(specifier);
3239 }
3240 
3241 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3242   m_thread_spec_up.reset(specifier);
3243 }
3244 
3245 bool Target::StopHook::ExecutionContextPasses(const ExecutionContext &exc_ctx) {
3246   SymbolContextSpecifier *specifier = GetSpecifier();
3247   if (!specifier)
3248     return true;
3249 
3250   bool will_run = true;
3251   if (exc_ctx.GetFramePtr())
3252     will_run = GetSpecifier()->SymbolContextMatches(
3253         exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
3254   if (will_run && GetThreadSpecifier() != nullptr)
3255     will_run =
3256         GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
3257 
3258   return will_run;
3259 }
3260 
3261 void Target::StopHook::GetDescription(Stream *s,
3262                                       lldb::DescriptionLevel level) const {
3263 
3264   // For brief descriptions, only print the subclass description:
3265   if (level == eDescriptionLevelBrief) {
3266     GetSubclassDescription(s, level);
3267     return;
3268   }
3269 
3270   unsigned indent_level = s->GetIndentLevel();
3271 
3272   s->SetIndentLevel(indent_level + 2);
3273 
3274   s->Printf("Hook: %" PRIu64 "\n", GetID());
3275   if (m_active)
3276     s->Indent("State: enabled\n");
3277   else
3278     s->Indent("State: disabled\n");
3279 
3280   if (m_auto_continue)
3281     s->Indent("AutoContinue on\n");
3282 
3283   if (m_specifier_sp) {
3284     s->Indent();
3285     s->PutCString("Specifier:\n");
3286     s->SetIndentLevel(indent_level + 4);
3287     m_specifier_sp->GetDescription(s, level);
3288     s->SetIndentLevel(indent_level + 2);
3289   }
3290 
3291   if (m_thread_spec_up) {
3292     StreamString tmp;
3293     s->Indent("Thread:\n");
3294     m_thread_spec_up->GetDescription(&tmp, level);
3295     s->SetIndentLevel(indent_level + 4);
3296     s->Indent(tmp.GetString());
3297     s->PutCString("\n");
3298     s->SetIndentLevel(indent_level + 2);
3299   }
3300   GetSubclassDescription(s, level);
3301 }
3302 
3303 void Target::StopHookCommandLine::GetSubclassDescription(
3304     Stream *s, lldb::DescriptionLevel level) const {
3305   // The brief description just prints the first command.
3306   if (level == eDescriptionLevelBrief) {
3307     if (m_commands.GetSize() == 1)
3308       s->PutCString(m_commands.GetStringAtIndex(0));
3309     return;
3310   }
3311   s->Indent("Commands: \n");
3312   s->SetIndentLevel(s->GetIndentLevel() + 4);
3313   uint32_t num_commands = m_commands.GetSize();
3314   for (uint32_t i = 0; i < num_commands; i++) {
3315     s->Indent(m_commands.GetStringAtIndex(i));
3316     s->PutCString("\n");
3317   }
3318   s->SetIndentLevel(s->GetIndentLevel() - 4);
3319 }
3320 
3321 // Target::StopHookCommandLine
3322 void Target::StopHookCommandLine::SetActionFromString(const std::string &string) {
3323   GetCommands().SplitIntoLines(string);
3324 }
3325 
3326 void Target::StopHookCommandLine::SetActionFromStrings(
3327     const std::vector<std::string> &strings) {
3328   for (auto string : strings)
3329     GetCommands().AppendString(string.c_str());
3330 }
3331 
3332 Target::StopHook::StopHookResult
3333 Target::StopHookCommandLine::HandleStop(ExecutionContext &exc_ctx,
3334                                         StreamSP output_sp) {
3335   assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
3336                                    "with no target");
3337 
3338   if (!m_commands.GetSize())
3339     return StopHookResult::KeepStopped;
3340 
3341   CommandReturnObject result(false);
3342   result.SetImmediateOutputStream(output_sp);
3343   result.SetInteractive(false);
3344   Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
3345   CommandInterpreterRunOptions options;
3346   options.SetStopOnContinue(true);
3347   options.SetStopOnError(true);
3348   options.SetEchoCommands(false);
3349   options.SetPrintResults(true);
3350   options.SetPrintErrors(true);
3351   options.SetAddToHistory(false);
3352 
3353   // Force Async:
3354   bool old_async = debugger.GetAsyncExecution();
3355   debugger.SetAsyncExecution(true);
3356   debugger.GetCommandInterpreter().HandleCommands(GetCommands(), &exc_ctx,
3357                                                   options, result);
3358   debugger.SetAsyncExecution(old_async);
3359   lldb::ReturnStatus status = result.GetStatus();
3360   if (status == eReturnStatusSuccessContinuingNoResult ||
3361       status == eReturnStatusSuccessContinuingResult)
3362     return StopHookResult::AlreadyContinued;
3363   return StopHookResult::KeepStopped;
3364 }
3365 
3366 // Target::StopHookScripted
3367 Status Target::StopHookScripted::SetScriptCallback(
3368     std::string class_name, StructuredData::ObjectSP extra_args_sp) {
3369   Status error;
3370 
3371   ScriptInterpreter *script_interp =
3372       GetTarget()->GetDebugger().GetScriptInterpreter();
3373   if (!script_interp) {
3374     error.SetErrorString("No script interpreter installed.");
3375     return error;
3376   }
3377 
3378   m_class_name = class_name;
3379 
3380   m_extra_args = new StructuredDataImpl();
3381 
3382   if (extra_args_sp)
3383     m_extra_args->SetObjectSP(extra_args_sp);
3384 
3385   m_implementation_sp = script_interp->CreateScriptedStopHook(
3386       GetTarget(), m_class_name.c_str(), m_extra_args, error);
3387 
3388   return error;
3389 }
3390 
3391 Target::StopHook::StopHookResult
3392 Target::StopHookScripted::HandleStop(ExecutionContext &exc_ctx,
3393                                      StreamSP output_sp) {
3394   assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
3395                                    "with no target");
3396 
3397   ScriptInterpreter *script_interp =
3398       GetTarget()->GetDebugger().GetScriptInterpreter();
3399   if (!script_interp)
3400     return StopHookResult::KeepStopped;
3401 
3402   bool should_stop = script_interp->ScriptedStopHookHandleStop(
3403       m_implementation_sp, exc_ctx, output_sp);
3404 
3405   return should_stop ? StopHookResult::KeepStopped
3406                      : StopHookResult::RequestContinue;
3407 }
3408 
3409 void Target::StopHookScripted::GetSubclassDescription(
3410     Stream *s, lldb::DescriptionLevel level) const {
3411   if (level == eDescriptionLevelBrief) {
3412     s->PutCString(m_class_name);
3413     return;
3414   }
3415   s->Indent("Class:");
3416   s->Printf("%s\n", m_class_name.c_str());
3417 
3418   // Now print the extra args:
3419   // FIXME: We should use StructuredData.GetDescription on the m_extra_args
3420   // but that seems to rely on some printing plugin that doesn't exist.
3421   if (!m_extra_args->IsValid())
3422     return;
3423   StructuredData::ObjectSP object_sp = m_extra_args->GetObjectSP();
3424   if (!object_sp || !object_sp->IsValid())
3425     return;
3426 
3427   StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary();
3428   if (!as_dict || !as_dict->IsValid())
3429     return;
3430 
3431   uint32_t num_keys = as_dict->GetSize();
3432   if (num_keys == 0)
3433     return;
3434 
3435   s->Indent("Args:\n");
3436   s->SetIndentLevel(s->GetIndentLevel() + 4);
3437 
3438   auto print_one_element = [&s](ConstString key,
3439                                 StructuredData::Object *object) {
3440     s->Indent();
3441     s->Printf("%s : %s\n", key.GetCString(),
3442               object->GetStringValue().str().c_str());
3443     return true;
3444   };
3445 
3446   as_dict->ForEach(print_one_element);
3447 
3448   s->SetIndentLevel(s->GetIndentLevel() - 4);
3449 }
3450 
3451 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3452     {
3453         eNoDynamicValues,
3454         "no-dynamic-values",
3455         "Don't calculate the dynamic type of values",
3456     },
3457     {
3458         eDynamicCanRunTarget,
3459         "run-target",
3460         "Calculate the dynamic type of values "
3461         "even if you have to run the target.",
3462     },
3463     {
3464         eDynamicDontRunTarget,
3465         "no-run-target",
3466         "Calculate the dynamic type of values, but don't run the target.",
3467     },
3468 };
3469 
3470 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3471   return OptionEnumValues(g_dynamic_value_types);
3472 }
3473 
3474 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3475     {
3476         eInlineBreakpointsNever,
3477         "never",
3478         "Never look for inline breakpoint locations (fastest). This setting "
3479         "should only be used if you know that no inlining occurs in your"
3480         "programs.",
3481     },
3482     {
3483         eInlineBreakpointsHeaders,
3484         "headers",
3485         "Only check for inline breakpoint locations when setting breakpoints "
3486         "in header files, but not when setting breakpoint in implementation "
3487         "source files (default).",
3488     },
3489     {
3490         eInlineBreakpointsAlways,
3491         "always",
3492         "Always look for inline breakpoint locations when setting file and "
3493         "line breakpoints (slower but most accurate).",
3494     },
3495 };
3496 
3497 enum x86DisassemblyFlavor {
3498   eX86DisFlavorDefault,
3499   eX86DisFlavorIntel,
3500   eX86DisFlavorATT
3501 };
3502 
3503 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3504     {
3505         eX86DisFlavorDefault,
3506         "default",
3507         "Disassembler default (currently att).",
3508     },
3509     {
3510         eX86DisFlavorIntel,
3511         "intel",
3512         "Intel disassembler flavor.",
3513     },
3514     {
3515         eX86DisFlavorATT,
3516         "att",
3517         "AT&T disassembler flavor.",
3518     },
3519 };
3520 
3521 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3522     {
3523         Disassembler::eHexStyleC,
3524         "c",
3525         "C-style (0xffff).",
3526     },
3527     {
3528         Disassembler::eHexStyleAsm,
3529         "asm",
3530         "Asm-style (0ffffh).",
3531     },
3532 };
3533 
3534 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3535     {
3536         eLoadScriptFromSymFileTrue,
3537         "true",
3538         "Load debug scripts inside symbol files",
3539     },
3540     {
3541         eLoadScriptFromSymFileFalse,
3542         "false",
3543         "Do not load debug scripts inside symbol files.",
3544     },
3545     {
3546         eLoadScriptFromSymFileWarn,
3547         "warn",
3548         "Warn about debug scripts inside symbol files but do not load them.",
3549     },
3550 };
3551 
3552 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
3553     {
3554         eLoadCWDlldbinitTrue,
3555         "true",
3556         "Load .lldbinit files from current directory",
3557     },
3558     {
3559         eLoadCWDlldbinitFalse,
3560         "false",
3561         "Do not load .lldbinit files from current directory",
3562     },
3563     {
3564         eLoadCWDlldbinitWarn,
3565         "warn",
3566         "Warn about loading .lldbinit files from current directory",
3567     },
3568 };
3569 
3570 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3571     {
3572         eMemoryModuleLoadLevelMinimal,
3573         "minimal",
3574         "Load minimal information when loading modules from memory. Currently "
3575         "this setting loads sections only.",
3576     },
3577     {
3578         eMemoryModuleLoadLevelPartial,
3579         "partial",
3580         "Load partial information when loading modules from memory. Currently "
3581         "this setting loads sections and function bounds.",
3582     },
3583     {
3584         eMemoryModuleLoadLevelComplete,
3585         "complete",
3586         "Load complete information when loading modules from memory. Currently "
3587         "this setting loads sections and all symbols.",
3588     },
3589 };
3590 
3591 #define LLDB_PROPERTIES_target
3592 #include "TargetProperties.inc"
3593 
3594 enum {
3595 #define LLDB_PROPERTIES_target
3596 #include "TargetPropertiesEnum.inc"
3597   ePropertyExperimental,
3598 };
3599 
3600 class TargetOptionValueProperties : public OptionValueProperties {
3601 public:
3602   TargetOptionValueProperties(ConstString name) : OptionValueProperties(name) {}
3603 
3604   // This constructor is used when creating TargetOptionValueProperties when it
3605   // is part of a new lldb_private::Target instance. It will copy all current
3606   // global property values as needed
3607   TargetOptionValueProperties(const TargetPropertiesSP &target_properties_sp)
3608       : OptionValueProperties(*target_properties_sp->GetValueProperties()) {}
3609 
3610   const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3611                                      bool will_modify,
3612                                      uint32_t idx) const override {
3613     // When getting the value for a key from the target options, we will always
3614     // try and grab the setting from the current target if there is one. Else
3615     // we just use the one from this instance.
3616     if (exe_ctx) {
3617       Target *target = exe_ctx->GetTargetPtr();
3618       if (target) {
3619         TargetOptionValueProperties *target_properties =
3620             static_cast<TargetOptionValueProperties *>(
3621                 target->GetValueProperties().get());
3622         if (this != target_properties)
3623           return target_properties->ProtectedGetPropertyAtIndex(idx);
3624       }
3625     }
3626     return ProtectedGetPropertyAtIndex(idx);
3627   }
3628 };
3629 
3630 // TargetProperties
3631 #define LLDB_PROPERTIES_target_experimental
3632 #include "TargetProperties.inc"
3633 
3634 enum {
3635 #define LLDB_PROPERTIES_target_experimental
3636 #include "TargetPropertiesEnum.inc"
3637 };
3638 
3639 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3640 public:
3641   TargetExperimentalOptionValueProperties()
3642       : OptionValueProperties(
3643             ConstString(Properties::GetExperimentalSettingsName())) {}
3644 };
3645 
3646 TargetExperimentalProperties::TargetExperimentalProperties()
3647     : Properties(OptionValuePropertiesSP(
3648           new TargetExperimentalOptionValueProperties())) {
3649   m_collection_sp->Initialize(g_target_experimental_properties);
3650 }
3651 
3652 // TargetProperties
3653 TargetProperties::TargetProperties(Target *target)
3654     : Properties(), m_launch_info(), m_target(target) {
3655   if (target) {
3656     m_collection_sp = std::make_shared<TargetOptionValueProperties>(
3657         Target::GetGlobalProperties());
3658 
3659     // Set callbacks to update launch_info whenever "settins set" updated any
3660     // of these properties
3661     m_collection_sp->SetValueChangedCallback(
3662         ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
3663     m_collection_sp->SetValueChangedCallback(
3664         ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
3665     m_collection_sp->SetValueChangedCallback(
3666         ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
3667     m_collection_sp->SetValueChangedCallback(
3668         ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
3669     m_collection_sp->SetValueChangedCallback(
3670         ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
3671     m_collection_sp->SetValueChangedCallback(
3672         ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
3673     m_collection_sp->SetValueChangedCallback(
3674         ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
3675     m_collection_sp->SetValueChangedCallback(
3676         ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
3677     m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
3678       DetachOnErrorValueChangedCallback();
3679     });
3680     m_collection_sp->SetValueChangedCallback(
3681         ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
3682     m_collection_sp->SetValueChangedCallback(
3683         ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
3684     m_collection_sp->SetValueChangedCallback(
3685         ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
3686 
3687     m_experimental_properties_up =
3688         std::make_unique<TargetExperimentalProperties>();
3689     m_collection_sp->AppendProperty(
3690         ConstString(Properties::GetExperimentalSettingsName()),
3691         ConstString("Experimental settings - setting these won't produce "
3692                     "errors if the setting is not present."),
3693         true, m_experimental_properties_up->GetValueProperties());
3694   } else {
3695     m_collection_sp =
3696         std::make_shared<TargetOptionValueProperties>(ConstString("target"));
3697     m_collection_sp->Initialize(g_target_properties);
3698     m_experimental_properties_up =
3699         std::make_unique<TargetExperimentalProperties>();
3700     m_collection_sp->AppendProperty(
3701         ConstString(Properties::GetExperimentalSettingsName()),
3702         ConstString("Experimental settings - setting these won't produce "
3703                     "errors if the setting is not present."),
3704         true, m_experimental_properties_up->GetValueProperties());
3705     m_collection_sp->AppendProperty(
3706         ConstString("process"), ConstString("Settings specific to processes."),
3707         true, Process::GetGlobalProperties()->GetValueProperties());
3708   }
3709 }
3710 
3711 TargetProperties::~TargetProperties() = default;
3712 
3713 void TargetProperties::UpdateLaunchInfoFromProperties() {
3714   Arg0ValueChangedCallback();
3715   RunArgsValueChangedCallback();
3716   EnvVarsValueChangedCallback();
3717   InputPathValueChangedCallback();
3718   OutputPathValueChangedCallback();
3719   ErrorPathValueChangedCallback();
3720   DetachOnErrorValueChangedCallback();
3721   DisableASLRValueChangedCallback();
3722   InheritTCCValueChangedCallback();
3723   DisableSTDIOValueChangedCallback();
3724 }
3725 
3726 bool TargetProperties::GetInjectLocalVariables(
3727     ExecutionContext *exe_ctx) const {
3728   const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3729       exe_ctx, false, ePropertyExperimental);
3730   OptionValueProperties *exp_values =
3731       exp_property->GetValue()->GetAsProperties();
3732   if (exp_values)
3733     return exp_values->GetPropertyAtIndexAsBoolean(
3734         exe_ctx, ePropertyInjectLocalVars, true);
3735   else
3736     return true;
3737 }
3738 
3739 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3740                                                bool b) {
3741   const Property *exp_property =
3742       m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3743   OptionValueProperties *exp_values =
3744       exp_property->GetValue()->GetAsProperties();
3745   if (exp_values)
3746     exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3747                                             true);
3748 }
3749 
3750 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3751   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3752       nullptr, ePropertyDefaultArch);
3753   if (value)
3754     return value->GetCurrentValue();
3755   return ArchSpec();
3756 }
3757 
3758 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3759   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3760       nullptr, ePropertyDefaultArch);
3761   if (value)
3762     return value->SetCurrentValue(arch, true);
3763 }
3764 
3765 bool TargetProperties::GetMoveToNearestCode() const {
3766   const uint32_t idx = ePropertyMoveToNearestCode;
3767   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3768       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3769 }
3770 
3771 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3772   const uint32_t idx = ePropertyPreferDynamic;
3773   return (lldb::DynamicValueType)
3774       m_collection_sp->GetPropertyAtIndexAsEnumeration(
3775           nullptr, idx, g_target_properties[idx].default_uint_value);
3776 }
3777 
3778 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3779   const uint32_t idx = ePropertyPreferDynamic;
3780   return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3781 }
3782 
3783 bool TargetProperties::GetPreloadSymbols() const {
3784   const uint32_t idx = ePropertyPreloadSymbols;
3785   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3786       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3787 }
3788 
3789 void TargetProperties::SetPreloadSymbols(bool b) {
3790   const uint32_t idx = ePropertyPreloadSymbols;
3791   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3792 }
3793 
3794 bool TargetProperties::GetDisableASLR() const {
3795   const uint32_t idx = ePropertyDisableASLR;
3796   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3797       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3798 }
3799 
3800 void TargetProperties::SetDisableASLR(bool b) {
3801   const uint32_t idx = ePropertyDisableASLR;
3802   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3803 }
3804 
3805 bool TargetProperties::GetInheritTCC() const {
3806   const uint32_t idx = ePropertyInheritTCC;
3807   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3808       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3809 }
3810 
3811 void TargetProperties::SetInheritTCC(bool b) {
3812   const uint32_t idx = ePropertyInheritTCC;
3813   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3814 }
3815 
3816 bool TargetProperties::GetDetachOnError() const {
3817   const uint32_t idx = ePropertyDetachOnError;
3818   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3819       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3820 }
3821 
3822 void TargetProperties::SetDetachOnError(bool b) {
3823   const uint32_t idx = ePropertyDetachOnError;
3824   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3825 }
3826 
3827 bool TargetProperties::GetDisableSTDIO() const {
3828   const uint32_t idx = ePropertyDisableSTDIO;
3829   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3830       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3831 }
3832 
3833 void TargetProperties::SetDisableSTDIO(bool b) {
3834   const uint32_t idx = ePropertyDisableSTDIO;
3835   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3836 }
3837 
3838 const char *TargetProperties::GetDisassemblyFlavor() const {
3839   const uint32_t idx = ePropertyDisassemblyFlavor;
3840   const char *return_value;
3841 
3842   x86DisassemblyFlavor flavor_value =
3843       (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3844           nullptr, idx, g_target_properties[idx].default_uint_value);
3845   return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3846   return return_value;
3847 }
3848 
3849 InlineStrategy TargetProperties::GetInlineStrategy() const {
3850   const uint32_t idx = ePropertyInlineStrategy;
3851   return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3852       nullptr, idx, g_target_properties[idx].default_uint_value);
3853 }
3854 
3855 llvm::StringRef TargetProperties::GetArg0() const {
3856   const uint32_t idx = ePropertyArg0;
3857   return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx,
3858                                                      llvm::StringRef());
3859 }
3860 
3861 void TargetProperties::SetArg0(llvm::StringRef arg) {
3862   const uint32_t idx = ePropertyArg0;
3863   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3864   m_launch_info.SetArg0(arg);
3865 }
3866 
3867 bool TargetProperties::GetRunArguments(Args &args) const {
3868   const uint32_t idx = ePropertyRunArgs;
3869   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3870 }
3871 
3872 void TargetProperties::SetRunArguments(const Args &args) {
3873   const uint32_t idx = ePropertyRunArgs;
3874   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3875   m_launch_info.GetArguments() = args;
3876 }
3877 
3878 Environment TargetProperties::ComputeEnvironment() const {
3879   Environment env;
3880 
3881   if (m_target &&
3882       m_collection_sp->GetPropertyAtIndexAsBoolean(
3883           nullptr, ePropertyInheritEnv,
3884           g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
3885     if (auto platform_sp = m_target->GetPlatform()) {
3886       Environment platform_env = platform_sp->GetEnvironment();
3887       for (const auto &KV : platform_env)
3888         env[KV.first()] = KV.second;
3889     }
3890   }
3891 
3892   Args property_unset_env;
3893   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyUnsetEnvVars,
3894                                             property_unset_env);
3895   for (const auto &var : property_unset_env)
3896     env.erase(var.ref());
3897 
3898   Args property_env;
3899   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyEnvVars,
3900                                             property_env);
3901   for (const auto &KV : Environment(property_env))
3902     env[KV.first()] = KV.second;
3903 
3904   return env;
3905 }
3906 
3907 Environment TargetProperties::GetEnvironment() const {
3908   return ComputeEnvironment();
3909 }
3910 
3911 void TargetProperties::SetEnvironment(Environment env) {
3912   // TODO: Get rid of the Args intermediate step
3913   const uint32_t idx = ePropertyEnvVars;
3914   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3915 }
3916 
3917 bool TargetProperties::GetSkipPrologue() const {
3918   const uint32_t idx = ePropertySkipPrologue;
3919   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3920       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3921 }
3922 
3923 PathMappingList &TargetProperties::GetSourcePathMap() const {
3924   const uint32_t idx = ePropertySourceMap;
3925   OptionValuePathMappings *option_value =
3926       m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3927                                                                    false, idx);
3928   assert(option_value);
3929   return option_value->GetCurrentValue();
3930 }
3931 
3932 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
3933   const uint32_t idx = ePropertyExecutableSearchPaths;
3934   OptionValueFileSpecList *option_value =
3935       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3936                                                                    false, idx);
3937   assert(option_value);
3938   option_value->AppendCurrentValue(dir);
3939 }
3940 
3941 FileSpecList TargetProperties::GetExecutableSearchPaths() {
3942   const uint32_t idx = ePropertyExecutableSearchPaths;
3943   const OptionValueFileSpecList *option_value =
3944       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3945                                                                    false, idx);
3946   assert(option_value);
3947   return option_value->GetCurrentValue();
3948 }
3949 
3950 FileSpecList TargetProperties::GetDebugFileSearchPaths() {
3951   const uint32_t idx = ePropertyDebugFileSearchPaths;
3952   const OptionValueFileSpecList *option_value =
3953       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3954                                                                    false, idx);
3955   assert(option_value);
3956   return option_value->GetCurrentValue();
3957 }
3958 
3959 FileSpecList TargetProperties::GetClangModuleSearchPaths() {
3960   const uint32_t idx = ePropertyClangModuleSearchPaths;
3961   const OptionValueFileSpecList *option_value =
3962       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3963                                                                    false, idx);
3964   assert(option_value);
3965   return option_value->GetCurrentValue();
3966 }
3967 
3968 bool TargetProperties::GetEnableAutoImportClangModules() const {
3969   const uint32_t idx = ePropertyAutoImportClangModules;
3970   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3971       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3972 }
3973 
3974 bool TargetProperties::GetEnableImportStdModule() const {
3975   const uint32_t idx = ePropertyImportStdModule;
3976   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3977       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3978 }
3979 
3980 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3981   const uint32_t idx = ePropertyAutoApplyFixIts;
3982   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3983       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3984 }
3985 
3986 uint64_t TargetProperties::GetNumberOfRetriesWithFixits() const {
3987   const uint32_t idx = ePropertyRetriesWithFixIts;
3988   return m_collection_sp->GetPropertyAtIndexAsUInt64(
3989       nullptr, idx, g_target_properties[idx].default_uint_value);
3990 }
3991 
3992 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3993   const uint32_t idx = ePropertyNotifyAboutFixIts;
3994   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3995       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3996 }
3997 
3998 bool TargetProperties::GetEnableSaveObjects() const {
3999   const uint32_t idx = ePropertySaveObjects;
4000   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4001       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4002 }
4003 
4004 bool TargetProperties::GetEnableSyntheticValue() const {
4005   const uint32_t idx = ePropertyEnableSynthetic;
4006   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4007       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4008 }
4009 
4010 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
4011   const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
4012   return m_collection_sp->GetPropertyAtIndexAsUInt64(
4013       nullptr, idx, g_target_properties[idx].default_uint_value);
4014 }
4015 
4016 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
4017   const uint32_t idx = ePropertyMaxChildrenCount;
4018   return m_collection_sp->GetPropertyAtIndexAsSInt64(
4019       nullptr, idx, g_target_properties[idx].default_uint_value);
4020 }
4021 
4022 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
4023   const uint32_t idx = ePropertyMaxSummaryLength;
4024   return m_collection_sp->GetPropertyAtIndexAsSInt64(
4025       nullptr, idx, g_target_properties[idx].default_uint_value);
4026 }
4027 
4028 uint32_t TargetProperties::GetMaximumMemReadSize() const {
4029   const uint32_t idx = ePropertyMaxMemReadSize;
4030   return m_collection_sp->GetPropertyAtIndexAsSInt64(
4031       nullptr, idx, g_target_properties[idx].default_uint_value);
4032 }
4033 
4034 FileSpec TargetProperties::GetStandardInputPath() const {
4035   const uint32_t idx = ePropertyInputPath;
4036   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4037 }
4038 
4039 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4040   const uint32_t idx = ePropertyInputPath;
4041   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4042 }
4043 
4044 FileSpec TargetProperties::GetStandardOutputPath() const {
4045   const uint32_t idx = ePropertyOutputPath;
4046   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4047 }
4048 
4049 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
4050   const uint32_t idx = ePropertyOutputPath;
4051   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4052 }
4053 
4054 FileSpec TargetProperties::GetStandardErrorPath() const {
4055   const uint32_t idx = ePropertyErrorPath;
4056   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4057 }
4058 
4059 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4060   const uint32_t idx = ePropertyErrorPath;
4061   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4062 }
4063 
4064 LanguageType TargetProperties::GetLanguage() const {
4065   OptionValueLanguage *value =
4066       m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
4067           nullptr, ePropertyLanguage);
4068   if (value)
4069     return value->GetCurrentValue();
4070   return LanguageType();
4071 }
4072 
4073 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
4074   const uint32_t idx = ePropertyExprPrefix;
4075   OptionValueFileSpec *file =
4076       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
4077                                                                idx);
4078   if (file) {
4079     DataBufferSP data_sp(file->GetFileContents());
4080     if (data_sp)
4081       return llvm::StringRef(
4082           reinterpret_cast<const char *>(data_sp->GetBytes()),
4083           data_sp->GetByteSize());
4084   }
4085   return "";
4086 }
4087 
4088 uint64_t TargetProperties::GetExprErrorLimit() const {
4089   const uint32_t idx = ePropertyExprErrorLimit;
4090   return m_collection_sp->GetPropertyAtIndexAsUInt64(
4091       nullptr, idx, g_target_properties[idx].default_uint_value);
4092 }
4093 
4094 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4095   const uint32_t idx = ePropertyBreakpointUseAvoidList;
4096   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4097       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4098 }
4099 
4100 bool TargetProperties::GetUseHexImmediates() const {
4101   const uint32_t idx = ePropertyUseHexImmediates;
4102   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4103       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4104 }
4105 
4106 bool TargetProperties::GetUseFastStepping() const {
4107   const uint32_t idx = ePropertyUseFastStepping;
4108   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4109       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4110 }
4111 
4112 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4113   const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4114   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4115       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4116 }
4117 
4118 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4119   const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4120   return (LoadScriptFromSymFile)
4121       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4122           nullptr, idx, g_target_properties[idx].default_uint_value);
4123 }
4124 
4125 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4126   const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4127   return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4128       nullptr, idx, g_target_properties[idx].default_uint_value);
4129 }
4130 
4131 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4132   const uint32_t idx = ePropertyHexImmediateStyle;
4133   return (Disassembler::HexImmediateStyle)
4134       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4135           nullptr, idx, g_target_properties[idx].default_uint_value);
4136 }
4137 
4138 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4139   const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4140   return (MemoryModuleLoadLevel)
4141       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4142           nullptr, idx, g_target_properties[idx].default_uint_value);
4143 }
4144 
4145 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4146   const uint32_t idx = ePropertyTrapHandlerNames;
4147   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4148 }
4149 
4150 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4151   const uint32_t idx = ePropertyTrapHandlerNames;
4152   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4153 }
4154 
4155 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4156   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4157   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4158 }
4159 
4160 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4161   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4162   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4163 }
4164 
4165 bool TargetProperties::GetDisplayRecognizedArguments() const {
4166   const uint32_t idx = ePropertyDisplayRecognizedArguments;
4167   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4168 }
4169 
4170 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
4171   const uint32_t idx = ePropertyDisplayRecognizedArguments;
4172   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4173 }
4174 
4175 bool TargetProperties::GetNonStopModeEnabled() const {
4176   const uint32_t idx = ePropertyNonStopModeEnabled;
4177   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4178 }
4179 
4180 void TargetProperties::SetNonStopModeEnabled(bool b) {
4181   const uint32_t idx = ePropertyNonStopModeEnabled;
4182   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4183 }
4184 
4185 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
4186   m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4187   return m_launch_info;
4188 }
4189 
4190 void TargetProperties::SetProcessLaunchInfo(
4191     const ProcessLaunchInfo &launch_info) {
4192   m_launch_info = launch_info;
4193   SetArg0(launch_info.GetArg0());
4194   SetRunArguments(launch_info.GetArguments());
4195   SetEnvironment(launch_info.GetEnvironment());
4196   const FileAction *input_file_action =
4197       launch_info.GetFileActionForFD(STDIN_FILENO);
4198   if (input_file_action) {
4199     SetStandardInputPath(input_file_action->GetPath());
4200   }
4201   const FileAction *output_file_action =
4202       launch_info.GetFileActionForFD(STDOUT_FILENO);
4203   if (output_file_action) {
4204     SetStandardOutputPath(output_file_action->GetPath());
4205   }
4206   const FileAction *error_file_action =
4207       launch_info.GetFileActionForFD(STDERR_FILENO);
4208   if (error_file_action) {
4209     SetStandardErrorPath(error_file_action->GetPath());
4210   }
4211   SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4212   SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4213   SetInheritTCC(
4214       launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
4215   SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4216 }
4217 
4218 bool TargetProperties::GetRequireHardwareBreakpoints() const {
4219   const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4220   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4221       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4222 }
4223 
4224 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
4225   const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4226   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4227 }
4228 
4229 bool TargetProperties::GetAutoInstallMainExecutable() const {
4230   const uint32_t idx = ePropertyAutoInstallMainExecutable;
4231   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4232       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4233 }
4234 
4235 void TargetProperties::Arg0ValueChangedCallback() {
4236   m_launch_info.SetArg0(GetArg0());
4237 }
4238 
4239 void TargetProperties::RunArgsValueChangedCallback() {
4240   Args args;
4241   if (GetRunArguments(args))
4242     m_launch_info.GetArguments() = args;
4243 }
4244 
4245 void TargetProperties::EnvVarsValueChangedCallback() {
4246   m_launch_info.GetEnvironment() = ComputeEnvironment();
4247 }
4248 
4249 void TargetProperties::InputPathValueChangedCallback() {
4250   m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
4251                                      false);
4252 }
4253 
4254 void TargetProperties::OutputPathValueChangedCallback() {
4255   m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
4256                                      false, true);
4257 }
4258 
4259 void TargetProperties::ErrorPathValueChangedCallback() {
4260   m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
4261                                      false, true);
4262 }
4263 
4264 void TargetProperties::DetachOnErrorValueChangedCallback() {
4265   if (GetDetachOnError())
4266     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4267   else
4268     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4269 }
4270 
4271 void TargetProperties::DisableASLRValueChangedCallback() {
4272   if (GetDisableASLR())
4273     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4274   else
4275     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4276 }
4277 
4278 void TargetProperties::InheritTCCValueChangedCallback() {
4279   if (GetInheritTCC())
4280     m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
4281   else
4282     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
4283 }
4284 
4285 void TargetProperties::DisableSTDIOValueChangedCallback() {
4286   if (GetDisableSTDIO())
4287     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4288   else
4289     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4290 }
4291 
4292 // Target::TargetEventData
4293 
4294 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4295     : EventData(), m_target_sp(target_sp), m_module_list() {}
4296 
4297 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4298                                          const ModuleList &module_list)
4299     : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4300 
4301 Target::TargetEventData::~TargetEventData() = default;
4302 
4303 ConstString Target::TargetEventData::GetFlavorString() {
4304   static ConstString g_flavor("Target::TargetEventData");
4305   return g_flavor;
4306 }
4307 
4308 void Target::TargetEventData::Dump(Stream *s) const {
4309   for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4310     if (i != 0)
4311       *s << ", ";
4312     m_module_list.GetModuleAtIndex(i)->GetDescription(
4313         s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4314   }
4315 }
4316 
4317 const Target::TargetEventData *
4318 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4319   if (event_ptr) {
4320     const EventData *event_data = event_ptr->GetData();
4321     if (event_data &&
4322         event_data->GetFlavor() == TargetEventData::GetFlavorString())
4323       return static_cast<const TargetEventData *>(event_ptr->GetData());
4324   }
4325   return nullptr;
4326 }
4327 
4328 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4329   TargetSP target_sp;
4330   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4331   if (event_data)
4332     target_sp = event_data->m_target_sp;
4333   return target_sp;
4334 }
4335 
4336 ModuleList
4337 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4338   ModuleList module_list;
4339   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4340   if (event_data)
4341     module_list = event_data->m_module_list;
4342   return module_list;
4343 }
4344 
4345 std::recursive_mutex &Target::GetAPIMutex() {
4346   if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4347     return m_private_mutex;
4348   else
4349     return m_mutex;
4350 }
4351