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