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