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