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