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/ExpressionVariable.h"
31 #include "lldb/Expression/REPL.h"
32 #include "lldb/Expression/UserExpression.h"
33 #include "lldb/Host/Host.h"
34 #include "lldb/Host/PosixApi.h"
35 #include "lldb/Interpreter/CommandInterpreter.h"
36 #include "lldb/Interpreter/CommandReturnObject.h"
37 #include "lldb/Interpreter/OptionGroupWatchpoint.h"
38 #include "lldb/Interpreter/OptionValues.h"
39 #include "lldb/Interpreter/Property.h"
40 #include "lldb/Symbol/Function.h"
41 #include "lldb/Symbol/ObjectFile.h"
42 #include "lldb/Symbol/Symbol.h"
43 #include "lldb/Target/Language.h"
44 #include "lldb/Target/LanguageRuntime.h"
45 #include "lldb/Target/Process.h"
46 #include "lldb/Target/SectionLoadList.h"
47 #include "lldb/Target/StackFrame.h"
48 #include "lldb/Target/StackFrameRecognizer.h"
49 #include "lldb/Target/SystemRuntime.h"
50 #include "lldb/Target/Thread.h"
51 #include "lldb/Target/ThreadSpec.h"
52 #include "lldb/Utility/Event.h"
53 #include "lldb/Utility/FileSpec.h"
54 #include "lldb/Utility/LLDBAssert.h"
55 #include "lldb/Utility/Log.h"
56 #include "lldb/Utility/State.h"
57 #include "lldb/Utility/StreamString.h"
58 #include "lldb/Utility/Timer.h"
59 
60 #include "llvm/ADT/ScopeExit.h"
61 
62 #include <memory>
63 #include <mutex>
64 
65 using namespace lldb;
66 using namespace lldb_private;
67 
68 constexpr std::chrono::milliseconds EvaluateExpressionOptions::default_timeout;
69 
70 Target::Arch::Arch(const ArchSpec &spec)
71     : m_spec(spec),
72       m_plugin_up(PluginManager::CreateArchitectureInstance(spec)) {}
73 
74 const Target::Arch &Target::Arch::operator=(const ArchSpec &spec) {
75   m_spec = spec;
76   m_plugin_up = PluginManager::CreateArchitectureInstance(spec);
77   return *this;
78 }
79 
80 ConstString &Target::GetStaticBroadcasterClass() {
81   static ConstString class_name("lldb.target");
82   return class_name;
83 }
84 
85 Target::Target(Debugger &debugger, const ArchSpec &target_arch,
86                const lldb::PlatformSP &platform_sp, bool is_dummy_target)
87     : TargetProperties(this),
88       Broadcaster(debugger.GetBroadcasterManager(),
89                   Target::GetStaticBroadcasterClass().AsCString()),
90       ExecutionContextScope(), m_debugger(debugger), m_platform_sp(platform_sp),
91       m_mutex(), m_arch(target_arch), m_images(this), m_section_load_history(),
92       m_breakpoint_list(false), m_internal_breakpoint_list(true),
93       m_watchpoint_list(), m_process_sp(), m_search_filter_sp(),
94       m_image_search_paths(ImageSearchPathsChanged, this),
95       m_source_manager_up(), m_stop_hooks(), m_stop_hook_next_id(0),
96       m_valid(true), m_suppress_stop_hooks(false),
97       m_is_dummy_target(is_dummy_target),
98       m_frame_recognizer_manager_up(
99           std::make_unique<StackFrameRecognizerManager>()),
100       m_stats_storage(static_cast<int>(StatisticKind::StatisticMax))
101 
102 {
103   SetEventName(eBroadcastBitBreakpointChanged, "breakpoint-changed");
104   SetEventName(eBroadcastBitModulesLoaded, "modules-loaded");
105   SetEventName(eBroadcastBitModulesUnloaded, "modules-unloaded");
106   SetEventName(eBroadcastBitWatchpointChanged, "watchpoint-changed");
107   SetEventName(eBroadcastBitSymbolsLoaded, "symbols-loaded");
108 
109   CheckInWithManager();
110 
111   LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT),
112            "{0} Target::Target()", static_cast<void *>(this));
113   if (target_arch.IsValid()) {
114     LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET),
115              "Target::Target created with architecture {0} ({1})",
116              target_arch.GetArchitectureName(),
117              target_arch.GetTriple().getTriple().c_str());
118   }
119 
120   UpdateLaunchInfoFromProperties();
121 }
122 
123 Target::~Target() {
124   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
125   LLDB_LOG(log, "{0} Target::~Target()", static_cast<void *>(this));
126   DeleteCurrentProcess();
127 }
128 
129 void Target::PrimeFromDummyTarget(Target *target) {
130   if (!target)
131     return;
132 
133   m_stop_hooks = target->m_stop_hooks;
134 
135   for (const auto &breakpoint_sp : target->m_breakpoint_list.Breakpoints()) {
136     if (breakpoint_sp->IsInternal())
137       continue;
138 
139     BreakpointSP new_bp(
140         Breakpoint::CopyFromBreakpoint(shared_from_this(), *breakpoint_sp));
141     AddBreakpoint(std::move(new_bp), false);
142   }
143 
144   for (auto bp_name_entry : target->m_breakpoint_names) {
145 
146     BreakpointName *new_bp_name = new BreakpointName(*bp_name_entry.second);
147     AddBreakpointName(new_bp_name);
148   }
149 
150   m_frame_recognizer_manager_up = std::make_unique<StackFrameRecognizerManager>(
151       *target->m_frame_recognizer_manager_up);
152 }
153 
154 void Target::Dump(Stream *s, lldb::DescriptionLevel description_level) {
155   //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
156   if (description_level != lldb::eDescriptionLevelBrief) {
157     s->Indent();
158     s->PutCString("Target\n");
159     s->IndentMore();
160     m_images.Dump(s);
161     m_breakpoint_list.Dump(s);
162     m_internal_breakpoint_list.Dump(s);
163     s->IndentLess();
164   } else {
165     Module *exe_module = GetExecutableModulePointer();
166     if (exe_module)
167       s->PutCString(exe_module->GetFileSpec().GetFilename().GetCString());
168     else
169       s->PutCString("No executable module.");
170   }
171 }
172 
173 void Target::CleanupProcess() {
174   // Do any cleanup of the target we need to do between process instances.
175   // NB It is better to do this before destroying the process in case the
176   // clean up needs some help from the process.
177   m_breakpoint_list.ClearAllBreakpointSites();
178   m_internal_breakpoint_list.ClearAllBreakpointSites();
179   // Disable watchpoints just on the debugger side.
180   std::unique_lock<std::recursive_mutex> lock;
181   this->GetWatchpointList().GetListMutex(lock);
182   DisableAllWatchpoints(false);
183   ClearAllWatchpointHitCounts();
184   ClearAllWatchpointHistoricValues();
185 }
186 
187 void Target::DeleteCurrentProcess() {
188   if (m_process_sp) {
189     m_section_load_history.Clear();
190     if (m_process_sp->IsAlive())
191       m_process_sp->Destroy(false);
192 
193     m_process_sp->Finalize();
194 
195     CleanupProcess();
196 
197     m_process_sp.reset();
198   }
199 }
200 
201 const lldb::ProcessSP &Target::CreateProcess(ListenerSP listener_sp,
202                                              llvm::StringRef plugin_name,
203                                              const FileSpec *crash_file) {
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);
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     static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1404     Timer scoped_timer(func_cat,
1405                        "Target::SetExecutableModule (executable = '%s')",
1406                        executable_sp->GetFileSpec().GetPath().c_str());
1407 
1408     const bool notify = true;
1409     m_images.Append(executable_sp,
1410                     notify); // The first image is our executable file
1411 
1412     // If we haven't set an architecture yet, reset our architecture based on
1413     // what we found in the executable module.
1414     if (!m_arch.GetSpec().IsValid()) {
1415       m_arch = executable_sp->GetArchitecture();
1416       LLDB_LOG(log,
1417                "setting architecture to {0} ({1}) based on executable file",
1418                m_arch.GetSpec().GetArchitectureName(),
1419                m_arch.GetSpec().GetTriple().getTriple());
1420     }
1421 
1422     FileSpecList dependent_files;
1423     ObjectFile *executable_objfile = executable_sp->GetObjectFile();
1424     bool load_dependents = true;
1425     switch (load_dependent_files) {
1426     case eLoadDependentsDefault:
1427       load_dependents = executable_sp->IsExecutable();
1428       break;
1429     case eLoadDependentsYes:
1430       load_dependents = true;
1431       break;
1432     case eLoadDependentsNo:
1433       load_dependents = false;
1434       break;
1435     }
1436 
1437     if (executable_objfile && load_dependents) {
1438       ModuleList added_modules;
1439       executable_objfile->GetDependentModules(dependent_files);
1440       for (uint32_t i = 0; i < dependent_files.GetSize(); i++) {
1441         FileSpec dependent_file_spec(dependent_files.GetFileSpecAtIndex(i));
1442         FileSpec platform_dependent_file_spec;
1443         if (m_platform_sp)
1444           m_platform_sp->GetFileWithUUID(dependent_file_spec, nullptr,
1445                                          platform_dependent_file_spec);
1446         else
1447           platform_dependent_file_spec = dependent_file_spec;
1448 
1449         ModuleSpec module_spec(platform_dependent_file_spec, m_arch.GetSpec());
1450         ModuleSP image_module_sp(
1451             GetOrCreateModule(module_spec, false /* notify */));
1452         if (image_module_sp) {
1453           added_modules.AppendIfNeeded(image_module_sp, false);
1454           ObjectFile *objfile = image_module_sp->GetObjectFile();
1455           if (objfile)
1456             objfile->GetDependentModules(dependent_files);
1457         }
1458       }
1459       ModulesDidLoad(added_modules);
1460     }
1461   }
1462 }
1463 
1464 bool Target::SetArchitecture(const ArchSpec &arch_spec, bool set_platform) {
1465   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1466   bool missing_local_arch = !m_arch.GetSpec().IsValid();
1467   bool replace_local_arch = true;
1468   bool compatible_local_arch = false;
1469   ArchSpec other(arch_spec);
1470 
1471   // Changing the architecture might mean that the currently selected platform
1472   // isn't compatible. Set the platform correctly if we are asked to do so,
1473   // otherwise assume the user will set the platform manually.
1474   if (set_platform) {
1475     if (other.IsValid()) {
1476       auto platform_sp = GetPlatform();
1477       if (!platform_sp ||
1478           !platform_sp->IsCompatibleArchitecture(other, false, nullptr)) {
1479         ArchSpec platform_arch;
1480         auto arch_platform_sp =
1481             Platform::GetPlatformForArchitecture(other, &platform_arch);
1482         if (arch_platform_sp) {
1483           SetPlatform(arch_platform_sp);
1484           if (platform_arch.IsValid())
1485             other = platform_arch;
1486         }
1487       }
1488     }
1489   }
1490 
1491   if (!missing_local_arch) {
1492     if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1493       other.MergeFrom(m_arch.GetSpec());
1494 
1495       if (m_arch.GetSpec().IsCompatibleMatch(other)) {
1496         compatible_local_arch = true;
1497         bool arch_changed, vendor_changed, os_changed, os_ver_changed,
1498             env_changed;
1499 
1500         m_arch.GetSpec().PiecewiseTripleCompare(other, arch_changed,
1501                                                 vendor_changed, os_changed,
1502                                                 os_ver_changed, env_changed);
1503 
1504         if (!arch_changed && !vendor_changed && !os_changed && !env_changed)
1505           replace_local_arch = false;
1506       }
1507     }
1508   }
1509 
1510   if (compatible_local_arch || missing_local_arch) {
1511     // If we haven't got a valid arch spec, or the architectures are compatible
1512     // update the architecture, unless the one we already have is more
1513     // specified
1514     if (replace_local_arch)
1515       m_arch = other;
1516     LLDB_LOG(log, "set architecture to {0} ({1})",
1517              m_arch.GetSpec().GetArchitectureName(),
1518              m_arch.GetSpec().GetTriple().getTriple());
1519     return true;
1520   }
1521 
1522   // If we have an executable file, try to reset the executable to the desired
1523   // architecture
1524   LLDB_LOGF(log, "Target::SetArchitecture changing architecture to %s (%s)",
1525             arch_spec.GetArchitectureName(),
1526             arch_spec.GetTriple().getTriple().c_str());
1527   m_arch = other;
1528   ModuleSP executable_sp = GetExecutableModule();
1529 
1530   ClearModules(true);
1531   // Need to do something about unsetting breakpoints.
1532 
1533   if (executable_sp) {
1534     LLDB_LOGF(log,
1535               "Target::SetArchitecture Trying to select executable file "
1536               "architecture %s (%s)",
1537               arch_spec.GetArchitectureName(),
1538               arch_spec.GetTriple().getTriple().c_str());
1539     ModuleSpec module_spec(executable_sp->GetFileSpec(), other);
1540     FileSpecList search_paths = GetExecutableSearchPaths();
1541     Status error = ModuleList::GetSharedModule(module_spec, executable_sp,
1542                                                &search_paths, nullptr, nullptr);
1543 
1544     if (!error.Fail() && executable_sp) {
1545       SetExecutableModule(executable_sp, eLoadDependentsYes);
1546       return true;
1547     }
1548   }
1549   return false;
1550 }
1551 
1552 bool Target::MergeArchitecture(const ArchSpec &arch_spec) {
1553   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
1554   if (arch_spec.IsValid()) {
1555     if (m_arch.GetSpec().IsCompatibleMatch(arch_spec)) {
1556       // The current target arch is compatible with "arch_spec", see if we can
1557       // improve our current architecture using bits from "arch_spec"
1558 
1559       LLDB_LOGF(log,
1560                 "Target::MergeArchitecture target has arch %s, merging with "
1561                 "arch %s",
1562                 m_arch.GetSpec().GetTriple().getTriple().c_str(),
1563                 arch_spec.GetTriple().getTriple().c_str());
1564 
1565       // Merge bits from arch_spec into "merged_arch" and set our architecture
1566       ArchSpec merged_arch(m_arch.GetSpec());
1567       merged_arch.MergeFrom(arch_spec);
1568       return SetArchitecture(merged_arch);
1569     } else {
1570       // The new architecture is different, we just need to replace it
1571       return SetArchitecture(arch_spec);
1572     }
1573   }
1574   return false;
1575 }
1576 
1577 void Target::NotifyWillClearList(const ModuleList &module_list) {}
1578 
1579 void Target::NotifyModuleAdded(const ModuleList &module_list,
1580                                const ModuleSP &module_sp) {
1581   // A module is being added to this target for the first time
1582   if (m_valid) {
1583     ModuleList my_module_list;
1584     my_module_list.Append(module_sp);
1585     ModulesDidLoad(my_module_list);
1586   }
1587 }
1588 
1589 void Target::NotifyModuleRemoved(const ModuleList &module_list,
1590                                  const ModuleSP &module_sp) {
1591   // A module is being removed from this target.
1592   if (m_valid) {
1593     ModuleList my_module_list;
1594     my_module_list.Append(module_sp);
1595     ModulesDidUnload(my_module_list, false);
1596   }
1597 }
1598 
1599 void Target::NotifyModuleUpdated(const ModuleList &module_list,
1600                                  const ModuleSP &old_module_sp,
1601                                  const ModuleSP &new_module_sp) {
1602   // A module is replacing an already added module
1603   if (m_valid) {
1604     m_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(old_module_sp,
1605                                                             new_module_sp);
1606     m_internal_breakpoint_list.UpdateBreakpointsWhenModuleIsReplaced(
1607         old_module_sp, new_module_sp);
1608   }
1609 }
1610 
1611 void Target::NotifyModulesRemoved(lldb_private::ModuleList &module_list) {
1612   ModulesDidUnload(module_list, false);
1613 }
1614 
1615 void Target::ModulesDidLoad(ModuleList &module_list) {
1616   const size_t num_images = module_list.GetSize();
1617   if (m_valid && num_images) {
1618     for (size_t idx = 0; idx < num_images; ++idx) {
1619       ModuleSP module_sp(module_list.GetModuleAtIndex(idx));
1620       LoadScriptingResourceForModule(module_sp, this);
1621     }
1622     m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1623     m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1624     if (m_process_sp) {
1625       m_process_sp->ModulesDidLoad(module_list);
1626     }
1627     BroadcastEvent(eBroadcastBitModulesLoaded,
1628                    new TargetEventData(this->shared_from_this(), module_list));
1629   }
1630 }
1631 
1632 void Target::SymbolsDidLoad(ModuleList &module_list) {
1633   if (m_valid && module_list.GetSize()) {
1634     if (m_process_sp) {
1635       for (LanguageRuntime *runtime : m_process_sp->GetLanguageRuntimes()) {
1636         runtime->SymbolsDidLoad(module_list);
1637       }
1638     }
1639 
1640     m_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1641     m_internal_breakpoint_list.UpdateBreakpoints(module_list, true, false);
1642     BroadcastEvent(eBroadcastBitSymbolsLoaded,
1643                    new TargetEventData(this->shared_from_this(), module_list));
1644   }
1645 }
1646 
1647 void Target::ModulesDidUnload(ModuleList &module_list, bool delete_locations) {
1648   if (m_valid && module_list.GetSize()) {
1649     UnloadModuleSections(module_list);
1650     m_breakpoint_list.UpdateBreakpoints(module_list, false, delete_locations);
1651     m_internal_breakpoint_list.UpdateBreakpoints(module_list, false,
1652                                                  delete_locations);
1653     BroadcastEvent(eBroadcastBitModulesUnloaded,
1654                    new TargetEventData(this->shared_from_this(), module_list));
1655   }
1656 }
1657 
1658 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1659     const FileSpec &module_file_spec) {
1660   if (GetBreakpointsConsultPlatformAvoidList()) {
1661     ModuleList matchingModules;
1662     ModuleSpec module_spec(module_file_spec);
1663     GetImages().FindModules(module_spec, matchingModules);
1664     size_t num_modules = matchingModules.GetSize();
1665 
1666     // If there is more than one module for this file spec, only
1667     // return true if ALL the modules are on the black list.
1668     if (num_modules > 0) {
1669       for (size_t i = 0; i < num_modules; i++) {
1670         if (!ModuleIsExcludedForUnconstrainedSearches(
1671                 matchingModules.GetModuleAtIndex(i)))
1672           return false;
1673       }
1674       return true;
1675     }
1676   }
1677   return false;
1678 }
1679 
1680 bool Target::ModuleIsExcludedForUnconstrainedSearches(
1681     const lldb::ModuleSP &module_sp) {
1682   if (GetBreakpointsConsultPlatformAvoidList()) {
1683     if (m_platform_sp)
1684       return m_platform_sp->ModuleIsExcludedForUnconstrainedSearches(*this,
1685                                                                      module_sp);
1686   }
1687   return false;
1688 }
1689 
1690 size_t Target::ReadMemoryFromFileCache(const Address &addr, void *dst,
1691                                        size_t dst_len, Status &error) {
1692   SectionSP section_sp(addr.GetSection());
1693   if (section_sp) {
1694     // If the contents of this section are encrypted, the on-disk file is
1695     // unusable.  Read only from live memory.
1696     if (section_sp->IsEncrypted()) {
1697       error.SetErrorString("section is encrypted");
1698       return 0;
1699     }
1700     ModuleSP module_sp(section_sp->GetModule());
1701     if (module_sp) {
1702       ObjectFile *objfile = section_sp->GetModule()->GetObjectFile();
1703       if (objfile) {
1704         size_t bytes_read = objfile->ReadSectionData(
1705             section_sp.get(), addr.GetOffset(), dst, dst_len);
1706         if (bytes_read > 0)
1707           return bytes_read;
1708         else
1709           error.SetErrorStringWithFormat("error reading data from section %s",
1710                                          section_sp->GetName().GetCString());
1711       } else
1712         error.SetErrorString("address isn't from a object file");
1713     } else
1714       error.SetErrorString("address isn't in a module");
1715   } else
1716     error.SetErrorString("address doesn't contain a section that points to a "
1717                          "section in a object file");
1718 
1719   return 0;
1720 }
1721 
1722 size_t Target::ReadMemory(const Address &addr, bool prefer_file_cache,
1723                           void *dst, size_t dst_len, Status &error,
1724                           lldb::addr_t *load_addr_ptr) {
1725   error.Clear();
1726 
1727   // if we end up reading this from process memory, we will fill this with the
1728   // actual load address
1729   if (load_addr_ptr)
1730     *load_addr_ptr = LLDB_INVALID_ADDRESS;
1731 
1732   size_t bytes_read = 0;
1733 
1734   addr_t load_addr = LLDB_INVALID_ADDRESS;
1735   addr_t file_addr = LLDB_INVALID_ADDRESS;
1736   Address resolved_addr;
1737   if (!addr.IsSectionOffset()) {
1738     SectionLoadList &section_load_list = GetSectionLoadList();
1739     if (section_load_list.IsEmpty()) {
1740       // No sections are loaded, so we must assume we are not running yet and
1741       // anything we are given is a file address.
1742       file_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1743                                     // offset is the file address
1744       m_images.ResolveFileAddress(file_addr, resolved_addr);
1745     } else {
1746       // We have at least one section loaded. This can be because we have
1747       // manually loaded some sections with "target modules load ..." or
1748       // because we have have a live process that has sections loaded through
1749       // the dynamic loader
1750       load_addr = addr.GetOffset(); // "addr" doesn't have a section, so its
1751                                     // offset is the load address
1752       section_load_list.ResolveLoadAddress(load_addr, resolved_addr);
1753     }
1754   }
1755   if (!resolved_addr.IsValid())
1756     resolved_addr = addr;
1757 
1758   if (prefer_file_cache) {
1759     bytes_read = ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1760     if (bytes_read > 0)
1761       return bytes_read;
1762   }
1763 
1764   if (ProcessIsValid()) {
1765     if (load_addr == LLDB_INVALID_ADDRESS)
1766       load_addr = resolved_addr.GetLoadAddress(this);
1767 
1768     if (load_addr == LLDB_INVALID_ADDRESS) {
1769       ModuleSP addr_module_sp(resolved_addr.GetModule());
1770       if (addr_module_sp && addr_module_sp->GetFileSpec())
1771         error.SetErrorStringWithFormatv(
1772             "{0:F}[{1:x+}] can't be resolved, {0:F} is not currently loaded",
1773             addr_module_sp->GetFileSpec(), resolved_addr.GetFileAddress());
1774       else
1775         error.SetErrorStringWithFormat("0x%" PRIx64 " can't be resolved",
1776                                        resolved_addr.GetFileAddress());
1777     } else {
1778       bytes_read = m_process_sp->ReadMemory(load_addr, dst, dst_len, error);
1779       if (bytes_read != dst_len) {
1780         if (error.Success()) {
1781           if (bytes_read == 0)
1782             error.SetErrorStringWithFormat(
1783                 "read memory from 0x%" PRIx64 " failed", load_addr);
1784           else
1785             error.SetErrorStringWithFormat(
1786                 "only %" PRIu64 " of %" PRIu64
1787                 " bytes were read from memory at 0x%" PRIx64,
1788                 (uint64_t)bytes_read, (uint64_t)dst_len, load_addr);
1789         }
1790       }
1791       if (bytes_read) {
1792         if (load_addr_ptr)
1793           *load_addr_ptr = load_addr;
1794         return bytes_read;
1795       }
1796       // If the address is not section offset we have an address that doesn't
1797       // resolve to any address in any currently loaded shared libraries and we
1798       // failed to read memory so there isn't anything more we can do. If it is
1799       // section offset, we might be able to read cached memory from the object
1800       // file.
1801       if (!resolved_addr.IsSectionOffset())
1802         return 0;
1803     }
1804   }
1805 
1806   if (!prefer_file_cache && resolved_addr.IsSectionOffset()) {
1807     // If we didn't already try and read from the object file cache, then try
1808     // it after failing to read from the process.
1809     return ReadMemoryFromFileCache(resolved_addr, dst, dst_len, error);
1810   }
1811   return 0;
1812 }
1813 
1814 size_t Target::ReadCStringFromMemory(const Address &addr, std::string &out_str,
1815                                      Status &error) {
1816   char buf[256];
1817   out_str.clear();
1818   addr_t curr_addr = addr.GetLoadAddress(this);
1819   Address address(addr);
1820   while (true) {
1821     size_t length = ReadCStringFromMemory(address, buf, sizeof(buf), error);
1822     if (length == 0)
1823       break;
1824     out_str.append(buf, length);
1825     // If we got "length - 1" bytes, we didn't get the whole C string, we need
1826     // to read some more characters
1827     if (length == sizeof(buf) - 1)
1828       curr_addr += length;
1829     else
1830       break;
1831     address = Address(curr_addr);
1832   }
1833   return out_str.size();
1834 }
1835 
1836 size_t Target::ReadCStringFromMemory(const Address &addr, char *dst,
1837                                      size_t dst_max_len, Status &result_error) {
1838   size_t total_cstr_len = 0;
1839   if (dst && dst_max_len) {
1840     result_error.Clear();
1841     // NULL out everything just to be safe
1842     memset(dst, 0, dst_max_len);
1843     Status error;
1844     addr_t curr_addr = addr.GetLoadAddress(this);
1845     Address address(addr);
1846 
1847     // We could call m_process_sp->GetMemoryCacheLineSize() but I don't think
1848     // this really needs to be tied to the memory cache subsystem's cache line
1849     // size, so leave this as a fixed constant.
1850     const size_t cache_line_size = 512;
1851 
1852     size_t bytes_left = dst_max_len - 1;
1853     char *curr_dst = dst;
1854 
1855     while (bytes_left > 0) {
1856       addr_t cache_line_bytes_left =
1857           cache_line_size - (curr_addr % cache_line_size);
1858       addr_t bytes_to_read =
1859           std::min<addr_t>(bytes_left, cache_line_bytes_left);
1860       size_t bytes_read =
1861           ReadMemory(address, false, curr_dst, bytes_to_read, error);
1862 
1863       if (bytes_read == 0) {
1864         result_error = error;
1865         dst[total_cstr_len] = '\0';
1866         break;
1867       }
1868       const size_t len = strlen(curr_dst);
1869 
1870       total_cstr_len += len;
1871 
1872       if (len < bytes_to_read)
1873         break;
1874 
1875       curr_dst += bytes_read;
1876       curr_addr += bytes_read;
1877       bytes_left -= bytes_read;
1878       address = Address(curr_addr);
1879     }
1880   } else {
1881     if (dst == nullptr)
1882       result_error.SetErrorString("invalid arguments");
1883     else
1884       result_error.Clear();
1885   }
1886   return total_cstr_len;
1887 }
1888 
1889 size_t Target::ReadScalarIntegerFromMemory(const Address &addr,
1890                                            bool prefer_file_cache,
1891                                            uint32_t byte_size, bool is_signed,
1892                                            Scalar &scalar, Status &error) {
1893   uint64_t uval;
1894 
1895   if (byte_size <= sizeof(uval)) {
1896     size_t bytes_read =
1897         ReadMemory(addr, prefer_file_cache, &uval, byte_size, error);
1898     if (bytes_read == byte_size) {
1899       DataExtractor data(&uval, sizeof(uval), m_arch.GetSpec().GetByteOrder(),
1900                          m_arch.GetSpec().GetAddressByteSize());
1901       lldb::offset_t offset = 0;
1902       if (byte_size <= 4)
1903         scalar = data.GetMaxU32(&offset, byte_size);
1904       else
1905         scalar = data.GetMaxU64(&offset, byte_size);
1906 
1907       if (is_signed)
1908         scalar.SignExtend(byte_size * 8);
1909       return bytes_read;
1910     }
1911   } else {
1912     error.SetErrorStringWithFormat(
1913         "byte size of %u is too large for integer scalar type", byte_size);
1914   }
1915   return 0;
1916 }
1917 
1918 uint64_t Target::ReadUnsignedIntegerFromMemory(const Address &addr,
1919                                                bool prefer_file_cache,
1920                                                size_t integer_byte_size,
1921                                                uint64_t fail_value,
1922                                                Status &error) {
1923   Scalar scalar;
1924   if (ReadScalarIntegerFromMemory(addr, prefer_file_cache, integer_byte_size,
1925                                   false, scalar, error))
1926     return scalar.ULongLong(fail_value);
1927   return fail_value;
1928 }
1929 
1930 bool Target::ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1931                                    Status &error, Address &pointer_addr) {
1932   Scalar scalar;
1933   if (ReadScalarIntegerFromMemory(addr, prefer_file_cache,
1934                                   m_arch.GetSpec().GetAddressByteSize(), false,
1935                                   scalar, error)) {
1936     addr_t pointer_vm_addr = scalar.ULongLong(LLDB_INVALID_ADDRESS);
1937     if (pointer_vm_addr != LLDB_INVALID_ADDRESS) {
1938       SectionLoadList &section_load_list = GetSectionLoadList();
1939       if (section_load_list.IsEmpty()) {
1940         // No sections are loaded, so we must assume we are not running yet and
1941         // anything we are given is a file address.
1942         m_images.ResolveFileAddress(pointer_vm_addr, pointer_addr);
1943       } else {
1944         // We have at least one section loaded. This can be because we have
1945         // manually loaded some sections with "target modules load ..." or
1946         // because we have have a live process that has sections loaded through
1947         // the dynamic loader
1948         section_load_list.ResolveLoadAddress(pointer_vm_addr, pointer_addr);
1949       }
1950       // We weren't able to resolve the pointer value, so just return an
1951       // address with no section
1952       if (!pointer_addr.IsValid())
1953         pointer_addr.SetOffset(pointer_vm_addr);
1954       return true;
1955     }
1956   }
1957   return false;
1958 }
1959 
1960 ModuleSP Target::GetOrCreateModule(const ModuleSpec &module_spec, bool notify,
1961                                    Status *error_ptr) {
1962   ModuleSP module_sp;
1963 
1964   Status error;
1965 
1966   // First see if we already have this module in our module list.  If we do,
1967   // then we're done, we don't need to consult the shared modules list.  But
1968   // only do this if we are passed a UUID.
1969 
1970   if (module_spec.GetUUID().IsValid())
1971     module_sp = m_images.FindFirstModule(module_spec);
1972 
1973   if (!module_sp) {
1974     ModuleSP old_module_sp; // This will get filled in if we have a new version
1975                             // of the library
1976     bool did_create_module = false;
1977     FileSpecList search_paths = GetExecutableSearchPaths();
1978     // If there are image search path entries, try to use them first to acquire
1979     // a suitable image.
1980     if (m_image_search_paths.GetSize()) {
1981       ModuleSpec transformed_spec(module_spec);
1982       if (m_image_search_paths.RemapPath(
1983               module_spec.GetFileSpec().GetDirectory(),
1984               transformed_spec.GetFileSpec().GetDirectory())) {
1985         transformed_spec.GetFileSpec().GetFilename() =
1986             module_spec.GetFileSpec().GetFilename();
1987         error = ModuleList::GetSharedModule(transformed_spec, module_sp,
1988                                             &search_paths, &old_module_sp,
1989                                             &did_create_module);
1990       }
1991     }
1992 
1993     if (!module_sp) {
1994       // If we have a UUID, we can check our global shared module list in case
1995       // we already have it. If we don't have a valid UUID, then we can't since
1996       // the path in "module_spec" will be a platform path, and we will need to
1997       // let the platform find that file. For example, we could be asking for
1998       // "/usr/lib/dyld" and if we do not have a UUID, we don't want to pick
1999       // the local copy of "/usr/lib/dyld" since our platform could be a remote
2000       // platform that has its own "/usr/lib/dyld" in an SDK or in a local file
2001       // cache.
2002       if (module_spec.GetUUID().IsValid()) {
2003         // We have a UUID, it is OK to check the global module list...
2004         error =
2005             ModuleList::GetSharedModule(module_spec, module_sp, &search_paths,
2006                                         &old_module_sp, &did_create_module);
2007       }
2008 
2009       if (!module_sp) {
2010         // The platform is responsible for finding and caching an appropriate
2011         // module in the shared module cache.
2012         if (m_platform_sp) {
2013           error = m_platform_sp->GetSharedModule(
2014               module_spec, m_process_sp.get(), module_sp, &search_paths,
2015               &old_module_sp, &did_create_module);
2016         } else {
2017           error.SetErrorString("no platform is currently set");
2018         }
2019       }
2020     }
2021 
2022     // We found a module that wasn't in our target list.  Let's make sure that
2023     // there wasn't an equivalent module in the list already, and if there was,
2024     // let's remove it.
2025     if (module_sp) {
2026       ObjectFile *objfile = module_sp->GetObjectFile();
2027       if (objfile) {
2028         switch (objfile->GetType()) {
2029         case ObjectFile::eTypeCoreFile: /// A core file that has a checkpoint of
2030                                         /// a program's execution state
2031         case ObjectFile::eTypeExecutable:    /// A normal executable
2032         case ObjectFile::eTypeDynamicLinker: /// The platform's dynamic linker
2033                                              /// executable
2034         case ObjectFile::eTypeObjectFile:    /// An intermediate object file
2035         case ObjectFile::eTypeSharedLibrary: /// A shared library that can be
2036                                              /// used during execution
2037           break;
2038         case ObjectFile::eTypeDebugInfo: /// An object file that contains only
2039                                          /// debug information
2040           if (error_ptr)
2041             error_ptr->SetErrorString("debug info files aren't valid target "
2042                                       "modules, please specify an executable");
2043           return ModuleSP();
2044         case ObjectFile::eTypeStubLibrary: /// A library that can be linked
2045                                            /// against but not used for
2046                                            /// execution
2047           if (error_ptr)
2048             error_ptr->SetErrorString("stub libraries aren't valid target "
2049                                       "modules, please specify an executable");
2050           return ModuleSP();
2051         default:
2052           if (error_ptr)
2053             error_ptr->SetErrorString(
2054                 "unsupported file type, please specify an executable");
2055           return ModuleSP();
2056         }
2057         // GetSharedModule is not guaranteed to find the old shared module, for
2058         // instance in the common case where you pass in the UUID, it is only
2059         // going to find the one module matching the UUID.  In fact, it has no
2060         // good way to know what the "old module" relevant to this target is,
2061         // since there might be many copies of a module with this file spec in
2062         // various running debug sessions, but only one of them will belong to
2063         // this target. So let's remove the UUID from the module list, and look
2064         // in the target's module list. Only do this if there is SOMETHING else
2065         // in the module spec...
2066         if (!old_module_sp) {
2067           if (module_spec.GetUUID().IsValid() &&
2068               !module_spec.GetFileSpec().GetFilename().IsEmpty() &&
2069               !module_spec.GetFileSpec().GetDirectory().IsEmpty()) {
2070             ModuleSpec module_spec_copy(module_spec.GetFileSpec());
2071             module_spec_copy.GetUUID().Clear();
2072 
2073             ModuleList found_modules;
2074             m_images.FindModules(module_spec_copy, found_modules);
2075             if (found_modules.GetSize() == 1)
2076               old_module_sp = found_modules.GetModuleAtIndex(0);
2077           }
2078         }
2079 
2080         // Preload symbols outside of any lock, so hopefully we can do this for
2081         // each library in parallel.
2082         if (GetPreloadSymbols())
2083           module_sp->PreloadSymbols();
2084 
2085         if (old_module_sp && m_images.GetIndexForModule(old_module_sp.get()) !=
2086                                  LLDB_INVALID_INDEX32) {
2087           m_images.ReplaceModule(old_module_sp, module_sp);
2088           Module *old_module_ptr = old_module_sp.get();
2089           old_module_sp.reset();
2090           ModuleList::RemoveSharedModuleIfOrphaned(old_module_ptr);
2091         } else {
2092           m_images.Append(module_sp, notify);
2093         }
2094       } else
2095         module_sp.reset();
2096     }
2097   }
2098   if (error_ptr)
2099     *error_ptr = error;
2100   return module_sp;
2101 }
2102 
2103 TargetSP Target::CalculateTarget() { return shared_from_this(); }
2104 
2105 ProcessSP Target::CalculateProcess() { return m_process_sp; }
2106 
2107 ThreadSP Target::CalculateThread() { return ThreadSP(); }
2108 
2109 StackFrameSP Target::CalculateStackFrame() { return StackFrameSP(); }
2110 
2111 void Target::CalculateExecutionContext(ExecutionContext &exe_ctx) {
2112   exe_ctx.Clear();
2113   exe_ctx.SetTargetPtr(this);
2114 }
2115 
2116 PathMappingList &Target::GetImageSearchPathList() {
2117   return m_image_search_paths;
2118 }
2119 
2120 void Target::ImageSearchPathsChanged(const PathMappingList &path_list,
2121                                      void *baton) {
2122   Target *target = (Target *)baton;
2123   ModuleSP exe_module_sp(target->GetExecutableModule());
2124   if (exe_module_sp)
2125     target->SetExecutableModule(exe_module_sp, eLoadDependentsYes);
2126 }
2127 
2128 llvm::Expected<TypeSystem &>
2129 Target::GetScratchTypeSystemForLanguage(lldb::LanguageType language,
2130                                         bool create_on_demand) {
2131   if (!m_valid)
2132     return llvm::make_error<llvm::StringError>("Invalid Target",
2133                                                llvm::inconvertibleErrorCode());
2134 
2135   if (language == eLanguageTypeMipsAssembler // GNU AS and LLVM use it for all
2136                                              // assembly code
2137       || language == eLanguageTypeUnknown) {
2138     LanguageSet languages_for_expressions =
2139         Language::GetLanguagesSupportingTypeSystemsForExpressions();
2140 
2141     if (languages_for_expressions[eLanguageTypeC]) {
2142       language = eLanguageTypeC; // LLDB's default.  Override by setting the
2143                                  // target language.
2144     } else {
2145       if (languages_for_expressions.Empty())
2146         return llvm::make_error<llvm::StringError>(
2147             "No expression support for any languages",
2148             llvm::inconvertibleErrorCode());
2149       language = (LanguageType)languages_for_expressions.bitvector.find_first();
2150     }
2151   }
2152 
2153   return m_scratch_type_system_map.GetTypeSystemForLanguage(language, this,
2154                                                             create_on_demand);
2155 }
2156 
2157 std::vector<TypeSystem *> Target::GetScratchTypeSystems(bool create_on_demand) {
2158   if (!m_valid)
2159     return {};
2160 
2161   std::vector<TypeSystem *> scratch_type_systems;
2162 
2163   LanguageSet languages_for_expressions =
2164       Language::GetLanguagesSupportingTypeSystemsForExpressions();
2165 
2166   for (auto bit : languages_for_expressions.bitvector.set_bits()) {
2167     auto language = (LanguageType)bit;
2168     auto type_system_or_err =
2169         GetScratchTypeSystemForLanguage(language, create_on_demand);
2170     if (!type_system_or_err)
2171       LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2172                      type_system_or_err.takeError(),
2173                      "Language '{}' has expression support but no scratch type "
2174                      "system available",
2175                      Language::GetNameForLanguageType(language));
2176     else
2177       scratch_type_systems.emplace_back(&type_system_or_err.get());
2178   }
2179 
2180   return scratch_type_systems;
2181 }
2182 
2183 PersistentExpressionState *
2184 Target::GetPersistentExpressionStateForLanguage(lldb::LanguageType language) {
2185   auto type_system_or_err = GetScratchTypeSystemForLanguage(language, true);
2186 
2187   if (auto err = type_system_or_err.takeError()) {
2188     LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2189                    std::move(err),
2190                    "Unable to get persistent expression state for language {}",
2191                    Language::GetNameForLanguageType(language));
2192     return nullptr;
2193   }
2194 
2195   return type_system_or_err->GetPersistentExpressionState();
2196 }
2197 
2198 UserExpression *Target::GetUserExpressionForLanguage(
2199     llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
2200     Expression::ResultType desired_type,
2201     const EvaluateExpressionOptions &options, ValueObject *ctx_obj,
2202     Status &error) {
2203   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2204   if (auto err = type_system_or_err.takeError()) {
2205     error.SetErrorStringWithFormat(
2206         "Could not find type system for language %s: %s",
2207         Language::GetNameForLanguageType(language),
2208         llvm::toString(std::move(err)).c_str());
2209     return nullptr;
2210   }
2211 
2212   auto *user_expr = type_system_or_err->GetUserExpression(
2213       expr, prefix, language, desired_type, options, ctx_obj);
2214   if (!user_expr)
2215     error.SetErrorStringWithFormat(
2216         "Could not create an expression for language %s",
2217         Language::GetNameForLanguageType(language));
2218 
2219   return user_expr;
2220 }
2221 
2222 FunctionCaller *Target::GetFunctionCallerForLanguage(
2223     lldb::LanguageType language, const CompilerType &return_type,
2224     const Address &function_address, const ValueList &arg_value_list,
2225     const char *name, Status &error) {
2226   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2227   if (auto err = type_system_or_err.takeError()) {
2228     error.SetErrorStringWithFormat(
2229         "Could not find type system for language %s: %s",
2230         Language::GetNameForLanguageType(language),
2231         llvm::toString(std::move(err)).c_str());
2232     return nullptr;
2233   }
2234 
2235   auto *persistent_fn = type_system_or_err->GetFunctionCaller(
2236       return_type, function_address, arg_value_list, name);
2237   if (!persistent_fn)
2238     error.SetErrorStringWithFormat(
2239         "Could not create an expression for language %s",
2240         Language::GetNameForLanguageType(language));
2241 
2242   return persistent_fn;
2243 }
2244 
2245 UtilityFunction *
2246 Target::GetUtilityFunctionForLanguage(const char *text,
2247                                       lldb::LanguageType language,
2248                                       const char *name, Status &error) {
2249   auto type_system_or_err = GetScratchTypeSystemForLanguage(language);
2250 
2251   if (auto err = type_system_or_err.takeError()) {
2252     error.SetErrorStringWithFormat(
2253         "Could not find type system for language %s: %s",
2254         Language::GetNameForLanguageType(language),
2255         llvm::toString(std::move(err)).c_str());
2256     return nullptr;
2257   }
2258 
2259   auto *utility_fn = type_system_or_err->GetUtilityFunction(text, name);
2260   if (!utility_fn)
2261     error.SetErrorStringWithFormat(
2262         "Could not create an expression for language %s",
2263         Language::GetNameForLanguageType(language));
2264 
2265   return utility_fn;
2266 }
2267 
2268 void Target::SettingsInitialize() { Process::SettingsInitialize(); }
2269 
2270 void Target::SettingsTerminate() { Process::SettingsTerminate(); }
2271 
2272 FileSpecList Target::GetDefaultExecutableSearchPaths() {
2273   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2274   if (properties_sp)
2275     return properties_sp->GetExecutableSearchPaths();
2276   return FileSpecList();
2277 }
2278 
2279 FileSpecList Target::GetDefaultDebugFileSearchPaths() {
2280   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2281   if (properties_sp)
2282     return properties_sp->GetDebugFileSearchPaths();
2283   return FileSpecList();
2284 }
2285 
2286 ArchSpec Target::GetDefaultArchitecture() {
2287   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2288   if (properties_sp)
2289     return properties_sp->GetDefaultArchitecture();
2290   return ArchSpec();
2291 }
2292 
2293 void Target::SetDefaultArchitecture(const ArchSpec &arch) {
2294   TargetPropertiesSP properties_sp(Target::GetGlobalProperties());
2295   if (properties_sp) {
2296     LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET),
2297              "Target::SetDefaultArchitecture setting target's "
2298              "default architecture to  {0} ({1})",
2299              arch.GetArchitectureName(), arch.GetTriple().getTriple());
2300     return properties_sp->SetDefaultArchitecture(arch);
2301   }
2302 }
2303 
2304 Target *Target::GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
2305                                       const SymbolContext *sc_ptr) {
2306   // The target can either exist in the "process" of ExecutionContext, or in
2307   // the "target_sp" member of SymbolContext. This accessor helper function
2308   // will get the target from one of these locations.
2309 
2310   Target *target = nullptr;
2311   if (sc_ptr != nullptr)
2312     target = sc_ptr->target_sp.get();
2313   if (target == nullptr && exe_ctx_ptr)
2314     target = exe_ctx_ptr->GetTargetPtr();
2315   return target;
2316 }
2317 
2318 ExpressionResults Target::EvaluateExpression(
2319     llvm::StringRef expr, ExecutionContextScope *exe_scope,
2320     lldb::ValueObjectSP &result_valobj_sp,
2321     const EvaluateExpressionOptions &options, std::string *fixed_expression,
2322     ValueObject *ctx_obj) {
2323   result_valobj_sp.reset();
2324 
2325   ExpressionResults execution_results = eExpressionSetupError;
2326 
2327   if (expr.empty())
2328     return execution_results;
2329 
2330   // We shouldn't run stop hooks in expressions.
2331   bool old_suppress_value = m_suppress_stop_hooks;
2332   m_suppress_stop_hooks = true;
2333   auto on_exit = llvm::make_scope_exit([this, old_suppress_value]() {
2334     m_suppress_stop_hooks = old_suppress_value;
2335   });
2336 
2337   ExecutionContext exe_ctx;
2338 
2339   if (exe_scope) {
2340     exe_scope->CalculateExecutionContext(exe_ctx);
2341   } else if (m_process_sp) {
2342     m_process_sp->CalculateExecutionContext(exe_ctx);
2343   } else {
2344     CalculateExecutionContext(exe_ctx);
2345   }
2346 
2347   // Make sure we aren't just trying to see the value of a persistent variable
2348   // (something like "$0")
2349   // Only check for persistent variables the expression starts with a '$'
2350   lldb::ExpressionVariableSP persistent_var_sp;
2351   if (expr[0] == '$') {
2352     auto type_system_or_err =
2353             GetScratchTypeSystemForLanguage(eLanguageTypeC);
2354     if (auto err = type_system_or_err.takeError()) {
2355       LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET),
2356                      std::move(err), "Unable to get scratch type system");
2357     } else {
2358       persistent_var_sp =
2359           type_system_or_err->GetPersistentExpressionState()->GetVariable(expr);
2360     }
2361   }
2362   if (persistent_var_sp) {
2363     result_valobj_sp = persistent_var_sp->GetValueObject();
2364     execution_results = eExpressionCompleted;
2365   } else {
2366     llvm::StringRef prefix = GetExpressionPrefixContents();
2367     Status error;
2368     execution_results = UserExpression::Evaluate(exe_ctx, options, expr, prefix,
2369                                                  result_valobj_sp, error,
2370                                                  fixed_expression, ctx_obj);
2371   }
2372 
2373   return execution_results;
2374 }
2375 
2376 lldb::ExpressionVariableSP Target::GetPersistentVariable(ConstString name) {
2377   lldb::ExpressionVariableSP variable_sp;
2378   m_scratch_type_system_map.ForEach(
2379       [name, &variable_sp](TypeSystem *type_system) -> bool {
2380         if (PersistentExpressionState *persistent_state =
2381                 type_system->GetPersistentExpressionState()) {
2382           variable_sp = persistent_state->GetVariable(name);
2383 
2384           if (variable_sp)
2385             return false; // Stop iterating the ForEach
2386         }
2387         return true; // Keep iterating the ForEach
2388       });
2389   return variable_sp;
2390 }
2391 
2392 lldb::addr_t Target::GetPersistentSymbol(ConstString name) {
2393   lldb::addr_t address = LLDB_INVALID_ADDRESS;
2394 
2395   m_scratch_type_system_map.ForEach(
2396       [name, &address](TypeSystem *type_system) -> bool {
2397         if (PersistentExpressionState *persistent_state =
2398                 type_system->GetPersistentExpressionState()) {
2399           address = persistent_state->LookupSymbol(name);
2400           if (address != LLDB_INVALID_ADDRESS)
2401             return false; // Stop iterating the ForEach
2402         }
2403         return true; // Keep iterating the ForEach
2404       });
2405   return address;
2406 }
2407 
2408 llvm::Expected<lldb_private::Address> Target::GetEntryPointAddress() {
2409   Module *exe_module = GetExecutableModulePointer();
2410 
2411   // Try to find the entry point address in the primary executable.
2412   const bool has_primary_executable = exe_module && exe_module->GetObjectFile();
2413   if (has_primary_executable) {
2414     Address entry_addr = exe_module->GetObjectFile()->GetEntryPointAddress();
2415     if (entry_addr.IsValid())
2416       return entry_addr;
2417   }
2418 
2419   const ModuleList &modules = GetImages();
2420   const size_t num_images = modules.GetSize();
2421   for (size_t idx = 0; idx < num_images; ++idx) {
2422     ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2423     if (!module_sp || !module_sp->GetObjectFile())
2424       continue;
2425 
2426     Address entry_addr = module_sp->GetObjectFile()->GetEntryPointAddress();
2427     if (entry_addr.IsValid())
2428       return entry_addr;
2429   }
2430 
2431   // We haven't found the entry point address. Return an appropriate error.
2432   if (!has_primary_executable)
2433     return llvm::make_error<llvm::StringError>(
2434         "No primary executable found and could not find entry point address in "
2435         "any executable module",
2436         llvm::inconvertibleErrorCode());
2437 
2438   return llvm::make_error<llvm::StringError>(
2439       "Could not find entry point address for primary executable module \"" +
2440           exe_module->GetFileSpec().GetFilename().GetStringRef() + "\"",
2441       llvm::inconvertibleErrorCode());
2442 }
2443 
2444 lldb::addr_t Target::GetCallableLoadAddress(lldb::addr_t load_addr,
2445                                             AddressClass addr_class) const {
2446   auto arch_plugin = GetArchitecturePlugin();
2447   return arch_plugin
2448              ? arch_plugin->GetCallableLoadAddress(load_addr, addr_class)
2449              : load_addr;
2450 }
2451 
2452 lldb::addr_t Target::GetOpcodeLoadAddress(lldb::addr_t load_addr,
2453                                           AddressClass addr_class) const {
2454   auto arch_plugin = GetArchitecturePlugin();
2455   return arch_plugin ? arch_plugin->GetOpcodeLoadAddress(load_addr, addr_class)
2456                      : load_addr;
2457 }
2458 
2459 lldb::addr_t Target::GetBreakableLoadAddress(lldb::addr_t addr) {
2460   auto arch_plugin = GetArchitecturePlugin();
2461   return arch_plugin ? arch_plugin->GetBreakableLoadAddress(addr, *this) : addr;
2462 }
2463 
2464 SourceManager &Target::GetSourceManager() {
2465   if (!m_source_manager_up)
2466     m_source_manager_up = std::make_unique<SourceManager>(shared_from_this());
2467   return *m_source_manager_up;
2468 }
2469 
2470 ClangModulesDeclVendor *Target::GetClangModulesDeclVendor() {
2471   static std::mutex s_clang_modules_decl_vendor_mutex; // If this is contended
2472                                                        // we can make it
2473                                                        // per-target
2474 
2475   {
2476     std::lock_guard<std::mutex> guard(s_clang_modules_decl_vendor_mutex);
2477 
2478     if (!m_clang_modules_decl_vendor_up) {
2479       m_clang_modules_decl_vendor_up.reset(
2480           ClangModulesDeclVendor::Create(*this));
2481     }
2482   }
2483 
2484   return m_clang_modules_decl_vendor_up.get();
2485 }
2486 
2487 Target::StopHookSP Target::CreateStopHook(StopHook::StopHookKind kind) {
2488   lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2489   Target::StopHookSP stop_hook_sp;
2490   switch (kind) {
2491   case StopHook::StopHookKind::CommandBased:
2492     stop_hook_sp.reset(new StopHookCommandLine(shared_from_this(), new_uid));
2493     break;
2494   case StopHook::StopHookKind::ScriptBased:
2495     stop_hook_sp.reset(new StopHookScripted(shared_from_this(), new_uid));
2496     break;
2497   }
2498   m_stop_hooks[new_uid] = stop_hook_sp;
2499   return stop_hook_sp;
2500 }
2501 
2502 void Target::UndoCreateStopHook(lldb::user_id_t user_id) {
2503   if (!RemoveStopHookByID(user_id))
2504     return;
2505   if (user_id == m_stop_hook_next_id)
2506     m_stop_hook_next_id--;
2507 }
2508 
2509 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2510   size_t num_removed = m_stop_hooks.erase(user_id);
2511   return (num_removed != 0);
2512 }
2513 
2514 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2515 
2516 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2517   StopHookSP found_hook;
2518 
2519   StopHookCollection::iterator specified_hook_iter;
2520   specified_hook_iter = m_stop_hooks.find(user_id);
2521   if (specified_hook_iter != m_stop_hooks.end())
2522     found_hook = (*specified_hook_iter).second;
2523   return found_hook;
2524 }
2525 
2526 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2527                                         bool active_state) {
2528   StopHookCollection::iterator specified_hook_iter;
2529   specified_hook_iter = m_stop_hooks.find(user_id);
2530   if (specified_hook_iter == m_stop_hooks.end())
2531     return false;
2532 
2533   (*specified_hook_iter).second->SetIsActive(active_state);
2534   return true;
2535 }
2536 
2537 void Target::SetAllStopHooksActiveState(bool active_state) {
2538   StopHookCollection::iterator pos, end = m_stop_hooks.end();
2539   for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2540     (*pos).second->SetIsActive(active_state);
2541   }
2542 }
2543 
2544 bool Target::RunStopHooks() {
2545   if (m_suppress_stop_hooks)
2546     return false;
2547 
2548   if (!m_process_sp)
2549     return false;
2550 
2551   // Somebody might have restarted the process:
2552   // Still return false, the return value is about US restarting the target.
2553   if (m_process_sp->GetState() != eStateStopped)
2554     return false;
2555 
2556   // <rdar://problem/12027563> make sure we check that we are not stopped
2557   // because of us running a user expression since in that case we do not want
2558   // to run the stop-hooks
2559   if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2560     return false;
2561 
2562   if (m_stop_hooks.empty())
2563     return false;
2564 
2565   // If there aren't any active stop hooks, don't bother either.
2566   bool any_active_hooks = false;
2567   for (auto hook : m_stop_hooks) {
2568     if (hook.second->IsActive()) {
2569       any_active_hooks = true;
2570       break;
2571     }
2572   }
2573   if (!any_active_hooks)
2574     return false;
2575 
2576   std::vector<ExecutionContext> exc_ctx_with_reasons;
2577 
2578   ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2579   size_t num_threads = cur_threadlist.GetSize();
2580   for (size_t i = 0; i < num_threads; i++) {
2581     lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2582     if (cur_thread_sp->ThreadStoppedForAReason()) {
2583       lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2584       exc_ctx_with_reasons.emplace_back(m_process_sp.get(), cur_thread_sp.get(),
2585                                         cur_frame_sp.get());
2586     }
2587   }
2588 
2589   // If no threads stopped for a reason, don't run the stop-hooks.
2590   size_t num_exe_ctx = exc_ctx_with_reasons.size();
2591   if (num_exe_ctx == 0)
2592     return false;
2593 
2594   StreamSP output_sp = m_debugger.GetAsyncOutputStream();
2595 
2596   bool auto_continue = false;
2597   bool hooks_ran = false;
2598   bool print_hook_header = (m_stop_hooks.size() != 1);
2599   bool print_thread_header = (num_exe_ctx != 1);
2600   bool should_stop = false;
2601   bool somebody_restarted = false;
2602 
2603   for (auto stop_entry : m_stop_hooks) {
2604     StopHookSP cur_hook_sp = stop_entry.second;
2605     if (!cur_hook_sp->IsActive())
2606       continue;
2607 
2608     bool any_thread_matched = false;
2609     for (auto exc_ctx : exc_ctx_with_reasons) {
2610       // We detect somebody restarted in the stop-hook loop, and broke out of
2611       // that loop back to here.  So break out of here too.
2612       if (somebody_restarted)
2613         break;
2614 
2615       if (!cur_hook_sp->ExecutionContextPasses(exc_ctx))
2616         continue;
2617 
2618       // We only consult the auto-continue for a stop hook if it matched the
2619       // specifier.
2620       auto_continue |= cur_hook_sp->GetAutoContinue();
2621 
2622       if (!hooks_ran)
2623         hooks_ran = true;
2624 
2625       if (print_hook_header && !any_thread_matched) {
2626         StreamString s;
2627         cur_hook_sp->GetDescription(&s, eDescriptionLevelBrief);
2628         if (s.GetSize() != 0)
2629           output_sp->Printf("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(),
2630                             s.GetData());
2631         else
2632           output_sp->Printf("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2633         any_thread_matched = true;
2634       }
2635 
2636       if (print_thread_header)
2637         output_sp->Printf("-- Thread %d\n",
2638                           exc_ctx.GetThreadPtr()->GetIndexID());
2639 
2640       StopHook::StopHookResult this_result =
2641           cur_hook_sp->HandleStop(exc_ctx, output_sp);
2642       bool this_should_stop = true;
2643 
2644       switch (this_result) {
2645       case StopHook::StopHookResult::KeepStopped:
2646         // If this hook is set to auto-continue that should override the
2647         // HandleStop result...
2648         if (cur_hook_sp->GetAutoContinue())
2649           this_should_stop = false;
2650         else
2651           this_should_stop = true;
2652 
2653         break;
2654       case StopHook::StopHookResult::RequestContinue:
2655         this_should_stop = false;
2656         break;
2657       case StopHook::StopHookResult::AlreadyContinued:
2658         // We don't have a good way to prohibit people from restarting the
2659         // target willy nilly in a stop hook.  If the hook did so, give a
2660         // gentle suggestion here and bag out if the hook processing.
2661         output_sp->Printf("\nAborting stop hooks, hook %" PRIu64
2662                           " set the program running.\n"
2663                           "  Consider using '-G true' to make "
2664                           "stop hooks auto-continue.\n",
2665                           cur_hook_sp->GetID());
2666         somebody_restarted = true;
2667         break;
2668       }
2669       // If we're already restarted, stop processing stop hooks.
2670       // FIXME: if we are doing non-stop mode for real, we would have to
2671       // check that OUR thread was restarted, otherwise we should keep
2672       // processing stop hooks.
2673       if (somebody_restarted)
2674         break;
2675 
2676       // If anybody wanted to stop, we should all stop.
2677       if (!should_stop)
2678         should_stop = this_should_stop;
2679     }
2680   }
2681 
2682   output_sp->Flush();
2683 
2684   // If one of the commands in the stop hook already restarted the target,
2685   // report that fact.
2686   if (somebody_restarted)
2687     return true;
2688 
2689   // Finally, if auto-continue was requested, do it now:
2690   // We only compute should_stop against the hook results if a hook got to run
2691   // which is why we have to do this conjoint test.
2692   if ((hooks_ran && !should_stop) || auto_continue) {
2693     Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
2694     Status error = m_process_sp->PrivateResume();
2695     if (error.Success()) {
2696       LLDB_LOG(log, "Resuming from RunStopHooks");
2697       return true;
2698     } else {
2699       LLDB_LOG(log, "Resuming from RunStopHooks failed: {0}", error);
2700       return false;
2701     }
2702   }
2703 
2704   return false;
2705 }
2706 
2707 const TargetPropertiesSP &Target::GetGlobalProperties() {
2708   // NOTE: intentional leak so we don't crash if global destructor chain gets
2709   // called as other threads still use the result of this function
2710   static TargetPropertiesSP *g_settings_sp_ptr =
2711       new TargetPropertiesSP(new TargetProperties(nullptr));
2712   return *g_settings_sp_ptr;
2713 }
2714 
2715 Status Target::Install(ProcessLaunchInfo *launch_info) {
2716   Status error;
2717   PlatformSP platform_sp(GetPlatform());
2718   if (platform_sp) {
2719     if (platform_sp->IsRemote()) {
2720       if (platform_sp->IsConnected()) {
2721         // Install all files that have an install path when connected to a
2722         // remote platform. If target.auto-install-main-executable is set then
2723         // also install the main executable even if it does not have an explicit
2724         // install path specified.
2725         const ModuleList &modules = GetImages();
2726         const size_t num_images = modules.GetSize();
2727         for (size_t idx = 0; idx < num_images; ++idx) {
2728           ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2729           if (module_sp) {
2730             const bool is_main_executable = module_sp == GetExecutableModule();
2731             FileSpec local_file(module_sp->GetFileSpec());
2732             if (local_file) {
2733               FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2734               if (!remote_file) {
2735                 if (is_main_executable && GetAutoInstallMainExecutable()) {
2736                   // Automatically install the main executable.
2737                   remote_file = platform_sp->GetRemoteWorkingDirectory();
2738                   remote_file.AppendPathComponent(
2739                       module_sp->GetFileSpec().GetFilename().GetCString());
2740                 }
2741               }
2742               if (remote_file) {
2743                 error = platform_sp->Install(local_file, remote_file);
2744                 if (error.Success()) {
2745                   module_sp->SetPlatformFileSpec(remote_file);
2746                   if (is_main_executable) {
2747                     platform_sp->SetFilePermissions(remote_file, 0700);
2748                     if (launch_info)
2749                       launch_info->SetExecutableFile(remote_file, false);
2750                   }
2751                 } else
2752                   break;
2753               }
2754             }
2755           }
2756         }
2757       }
2758     }
2759   }
2760   return error;
2761 }
2762 
2763 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2764                                 uint32_t stop_id) {
2765   return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2766 }
2767 
2768 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2769                                 Address &resolved_addr) {
2770   return m_images.ResolveFileAddress(file_addr, resolved_addr);
2771 }
2772 
2773 bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2774                                    addr_t new_section_load_addr,
2775                                    bool warn_multiple) {
2776   const addr_t old_section_load_addr =
2777       m_section_load_history.GetSectionLoadAddress(
2778           SectionLoadHistory::eStopIDNow, section_sp);
2779   if (old_section_load_addr != new_section_load_addr) {
2780     uint32_t stop_id = 0;
2781     ProcessSP process_sp(GetProcessSP());
2782     if (process_sp)
2783       stop_id = process_sp->GetStopID();
2784     else
2785       stop_id = m_section_load_history.GetLastStopID();
2786     if (m_section_load_history.SetSectionLoadAddress(
2787             stop_id, section_sp, new_section_load_addr, warn_multiple))
2788       return true; // Return true if the section load address was changed...
2789   }
2790   return false; // Return false to indicate nothing changed
2791 }
2792 
2793 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2794   size_t section_unload_count = 0;
2795   size_t num_modules = module_list.GetSize();
2796   for (size_t i = 0; i < num_modules; ++i) {
2797     section_unload_count +=
2798         UnloadModuleSections(module_list.GetModuleAtIndex(i));
2799   }
2800   return section_unload_count;
2801 }
2802 
2803 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2804   uint32_t stop_id = 0;
2805   ProcessSP process_sp(GetProcessSP());
2806   if (process_sp)
2807     stop_id = process_sp->GetStopID();
2808   else
2809     stop_id = m_section_load_history.GetLastStopID();
2810   SectionList *sections = module_sp->GetSectionList();
2811   size_t section_unload_count = 0;
2812   if (sections) {
2813     const uint32_t num_sections = sections->GetNumSections(0);
2814     for (uint32_t i = 0; i < num_sections; ++i) {
2815       section_unload_count += m_section_load_history.SetSectionUnloaded(
2816           stop_id, sections->GetSectionAtIndex(i));
2817     }
2818   }
2819   return section_unload_count;
2820 }
2821 
2822 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2823   uint32_t stop_id = 0;
2824   ProcessSP process_sp(GetProcessSP());
2825   if (process_sp)
2826     stop_id = process_sp->GetStopID();
2827   else
2828     stop_id = m_section_load_history.GetLastStopID();
2829   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2830 }
2831 
2832 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2833                                 addr_t 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   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2841                                                    load_addr);
2842 }
2843 
2844 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2845 
2846 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2847   Status error;
2848   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2849 
2850   LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
2851             launch_info.GetExecutableFile().GetPath().c_str());
2852 
2853   StateType state = eStateInvalid;
2854 
2855   // Scope to temporarily get the process state in case someone has manually
2856   // remotely connected already to a process and we can skip the platform
2857   // launching.
2858   {
2859     ProcessSP process_sp(GetProcessSP());
2860 
2861     if (process_sp) {
2862       state = process_sp->GetState();
2863       LLDB_LOGF(log,
2864                 "Target::%s the process exists, and its current state is %s",
2865                 __FUNCTION__, StateAsCString(state));
2866     } else {
2867       LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
2868                 __FUNCTION__);
2869     }
2870   }
2871 
2872   launch_info.GetFlags().Set(eLaunchFlagDebug);
2873 
2874   // Get the value of synchronous execution here.  If you wait till after you
2875   // have started to run, then you could have hit a breakpoint, whose command
2876   // might switch the value, and then you'll pick up that incorrect value.
2877   Debugger &debugger = GetDebugger();
2878   const bool synchronous_execution =
2879       debugger.GetCommandInterpreter().GetSynchronous();
2880 
2881   PlatformSP platform_sp(GetPlatform());
2882 
2883   FinalizeFileActions(launch_info);
2884 
2885   if (state == eStateConnected) {
2886     if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2887       error.SetErrorString(
2888           "can't launch in tty when launching through a remote connection");
2889       return error;
2890     }
2891   }
2892 
2893   if (!launch_info.GetArchitecture().IsValid())
2894     launch_info.GetArchitecture() = GetArchitecture();
2895 
2896   // If we're not already connected to the process, and if we have a platform
2897   // that can launch a process for debugging, go ahead and do that here.
2898   if (state != eStateConnected && platform_sp &&
2899       platform_sp->CanDebugProcess()) {
2900     LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
2901               __FUNCTION__);
2902 
2903     // If there was a previous process, delete it before we make the new one.
2904     // One subtle point, we delete the process before we release the reference
2905     // to m_process_sp.  That way even if we are the last owner, the process
2906     // will get Finalized before it gets destroyed.
2907     DeleteCurrentProcess();
2908 
2909     m_process_sp =
2910         GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2911 
2912   } else {
2913     LLDB_LOGF(log,
2914               "Target::%s the platform doesn't know how to debug a "
2915               "process, getting a process plugin to do this for us.",
2916               __FUNCTION__);
2917 
2918     if (state == eStateConnected) {
2919       assert(m_process_sp);
2920     } else {
2921       // Use a Process plugin to construct the process.
2922       const char *plugin_name = launch_info.GetProcessPluginName();
2923       CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
2924     }
2925 
2926     // Since we didn't have a platform launch the process, launch it here.
2927     if (m_process_sp)
2928       error = m_process_sp->Launch(launch_info);
2929   }
2930 
2931   if (!m_process_sp && error.Success())
2932     error.SetErrorString("failed to launch or debug process");
2933 
2934   if (!error.Success())
2935     return error;
2936 
2937   auto at_exit =
2938       llvm::make_scope_exit([&]() { m_process_sp->RestoreProcessEvents(); });
2939 
2940   if (!synchronous_execution &&
2941       launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2942     return error;
2943 
2944   ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2945   if (!hijack_listener_sp) {
2946     hijack_listener_sp = Listener::MakeListener("lldb.Target.Launch.hijack");
2947     launch_info.SetHijackListener(hijack_listener_sp);
2948     m_process_sp->HijackProcessEvents(hijack_listener_sp);
2949   }
2950 
2951   switch (m_process_sp->WaitForProcessToStop(llvm::None, nullptr, false,
2952                                              hijack_listener_sp, nullptr)) {
2953   case eStateStopped: {
2954     if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2955       break;
2956     if (synchronous_execution) {
2957       // Now we have handled the stop-from-attach, and we are just
2958       // switching to a synchronous resume.  So we should switch to the
2959       // SyncResume hijacker.
2960       m_process_sp->RestoreProcessEvents();
2961       m_process_sp->ResumeSynchronous(stream);
2962     } else {
2963       m_process_sp->RestoreProcessEvents();
2964       error = m_process_sp->PrivateResume();
2965     }
2966     if (!error.Success()) {
2967       Status error2;
2968       error2.SetErrorStringWithFormat(
2969           "process resume at entry point failed: %s", error.AsCString());
2970       error = error2;
2971     }
2972   } break;
2973   case eStateExited: {
2974     bool with_shell = !!launch_info.GetShell();
2975     const int exit_status = m_process_sp->GetExitStatus();
2976     const char *exit_desc = m_process_sp->GetExitDescription();
2977     std::string desc;
2978     if (exit_desc && exit_desc[0])
2979       desc = " (" + std::string(exit_desc) + ')';
2980     if (with_shell)
2981       error.SetErrorStringWithFormat(
2982           "process exited with status %i%s\n"
2983           "'r' and 'run' are aliases that default to launching through a "
2984           "shell.\n"
2985           "Try launching without going through a shell by using "
2986           "'process launch'.",
2987           exit_status, desc.c_str());
2988     else
2989       error.SetErrorStringWithFormat("process exited with status %i%s",
2990                                      exit_status, desc.c_str());
2991   } break;
2992   default:
2993     error.SetErrorStringWithFormat("initial process state wasn't stopped: %s",
2994                                    StateAsCString(state));
2995     break;
2996   }
2997   return error;
2998 }
2999 
3000 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
3001   auto state = eStateInvalid;
3002   auto process_sp = GetProcessSP();
3003   if (process_sp) {
3004     state = process_sp->GetState();
3005     if (process_sp->IsAlive() && state != eStateConnected) {
3006       if (state == eStateAttaching)
3007         return Status("process attach is in progress");
3008       return Status("a process is already being debugged");
3009     }
3010   }
3011 
3012   const ModuleSP old_exec_module_sp = GetExecutableModule();
3013 
3014   // If no process info was specified, then use the target executable name as
3015   // the process to attach to by default
3016   if (!attach_info.ProcessInfoSpecified()) {
3017     if (old_exec_module_sp)
3018       attach_info.GetExecutableFile().GetFilename() =
3019           old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3020 
3021     if (!attach_info.ProcessInfoSpecified()) {
3022       return Status("no process specified, create a target with a file, or "
3023                     "specify the --pid or --name");
3024     }
3025   }
3026 
3027   const auto platform_sp =
3028       GetDebugger().GetPlatformList().GetSelectedPlatform();
3029   ListenerSP hijack_listener_sp;
3030   const bool async = attach_info.GetAsync();
3031   if (!async) {
3032     hijack_listener_sp =
3033         Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3034     attach_info.SetHijackListener(hijack_listener_sp);
3035   }
3036 
3037   Status error;
3038   if (state != eStateConnected && platform_sp != nullptr &&
3039       platform_sp->CanDebugProcess()) {
3040     SetPlatform(platform_sp);
3041     process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3042   } else {
3043     if (state != eStateConnected) {
3044       const char *plugin_name = attach_info.GetProcessPluginName();
3045       process_sp =
3046           CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3047                         plugin_name, nullptr);
3048       if (process_sp == nullptr) {
3049         error.SetErrorStringWithFormat(
3050             "failed to create process using plugin %s",
3051             (plugin_name) ? plugin_name : "null");
3052         return error;
3053       }
3054     }
3055     if (hijack_listener_sp)
3056       process_sp->HijackProcessEvents(hijack_listener_sp);
3057     error = process_sp->Attach(attach_info);
3058   }
3059 
3060   if (error.Success() && process_sp) {
3061     if (async) {
3062       process_sp->RestoreProcessEvents();
3063     } else {
3064       state = process_sp->WaitForProcessToStop(
3065           llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3066       process_sp->RestoreProcessEvents();
3067 
3068       if (state != eStateStopped) {
3069         const char *exit_desc = process_sp->GetExitDescription();
3070         if (exit_desc)
3071           error.SetErrorStringWithFormat("%s", exit_desc);
3072         else
3073           error.SetErrorString(
3074               "process did not stop (no such process or permission problem?)");
3075         process_sp->Destroy(false);
3076       }
3077     }
3078   }
3079   return error;
3080 }
3081 
3082 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3083   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3084 
3085   // Finalize the file actions, and if none were given, default to opening up a
3086   // pseudo terminal
3087   PlatformSP platform_sp = GetPlatform();
3088   const bool default_to_use_pty =
3089       m_platform_sp ? m_platform_sp->IsHost() : false;
3090   LLDB_LOG(
3091       log,
3092       "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3093       bool(platform_sp),
3094       platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3095       default_to_use_pty);
3096 
3097   // If nothing for stdin or stdout or stderr was specified, then check the
3098   // process for any default settings that were set with "settings set"
3099   if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3100       info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3101       info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3102     LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3103                   "default handling");
3104 
3105     if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3106       // Do nothing, if we are launching in a remote terminal no file actions
3107       // should be done at all.
3108       return;
3109     }
3110 
3111     if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3112       LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3113                     "for stdin, stdout and stderr");
3114       info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3115       info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3116       info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3117     } else {
3118       // Check for any values that might have gotten set with any of: (lldb)
3119       // settings set target.input-path (lldb) settings set target.output-path
3120       // (lldb) settings set target.error-path
3121       FileSpec in_file_spec;
3122       FileSpec out_file_spec;
3123       FileSpec err_file_spec;
3124       // Only override with the target settings if we don't already have an
3125       // action for in, out or error
3126       if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3127         in_file_spec = GetStandardInputPath();
3128       if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3129         out_file_spec = GetStandardOutputPath();
3130       if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3131         err_file_spec = GetStandardErrorPath();
3132 
3133       LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3134                in_file_spec, out_file_spec, err_file_spec);
3135 
3136       if (in_file_spec) {
3137         info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3138         LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3139       }
3140 
3141       if (out_file_spec) {
3142         info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3143         LLDB_LOG(log, "appended stdout open file action for {0}",
3144                  out_file_spec);
3145       }
3146 
3147       if (err_file_spec) {
3148         info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3149         LLDB_LOG(log, "appended stderr open file action for {0}",
3150                  err_file_spec);
3151       }
3152 
3153       if (default_to_use_pty &&
3154           (!in_file_spec || !out_file_spec || !err_file_spec)) {
3155         llvm::Error Err = info.SetUpPtyRedirection();
3156         LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3157       }
3158     }
3159   }
3160 }
3161 
3162 // Target::StopHook
3163 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3164     : UserID(uid), m_target_sp(target_sp), m_specifier_sp(),
3165       m_thread_spec_up() {}
3166 
3167 Target::StopHook::StopHook(const StopHook &rhs)
3168     : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3169       m_specifier_sp(rhs.m_specifier_sp), m_thread_spec_up(),
3170       m_active(rhs.m_active), m_auto_continue(rhs.m_auto_continue) {
3171   if (rhs.m_thread_spec_up)
3172     m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3173 }
3174 
3175 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3176   m_specifier_sp.reset(specifier);
3177 }
3178 
3179 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3180   m_thread_spec_up.reset(specifier);
3181 }
3182 
3183 bool Target::StopHook::ExecutionContextPasses(const ExecutionContext &exc_ctx) {
3184   SymbolContextSpecifier *specifier = GetSpecifier();
3185   if (!specifier)
3186     return true;
3187 
3188   bool will_run = true;
3189   if (exc_ctx.GetFramePtr())
3190     will_run = GetSpecifier()->SymbolContextMatches(
3191         exc_ctx.GetFramePtr()->GetSymbolContext(eSymbolContextEverything));
3192   if (will_run && GetThreadSpecifier() != nullptr)
3193     will_run =
3194         GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx.GetThreadRef());
3195 
3196   return will_run;
3197 }
3198 
3199 void Target::StopHook::GetDescription(Stream *s,
3200                                       lldb::DescriptionLevel level) const {
3201 
3202   // For brief descriptions, only print the subclass description:
3203   if (level == eDescriptionLevelBrief) {
3204     GetSubclassDescription(s, level);
3205     return;
3206   }
3207 
3208   unsigned indent_level = s->GetIndentLevel();
3209 
3210   s->SetIndentLevel(indent_level + 2);
3211 
3212   s->Printf("Hook: %" PRIu64 "\n", GetID());
3213   if (m_active)
3214     s->Indent("State: enabled\n");
3215   else
3216     s->Indent("State: disabled\n");
3217 
3218   if (m_auto_continue)
3219     s->Indent("AutoContinue on\n");
3220 
3221   if (m_specifier_sp) {
3222     s->Indent();
3223     s->PutCString("Specifier:\n");
3224     s->SetIndentLevel(indent_level + 4);
3225     m_specifier_sp->GetDescription(s, level);
3226     s->SetIndentLevel(indent_level + 2);
3227   }
3228 
3229   if (m_thread_spec_up) {
3230     StreamString tmp;
3231     s->Indent("Thread:\n");
3232     m_thread_spec_up->GetDescription(&tmp, level);
3233     s->SetIndentLevel(indent_level + 4);
3234     s->Indent(tmp.GetString());
3235     s->PutCString("\n");
3236     s->SetIndentLevel(indent_level + 2);
3237   }
3238   GetSubclassDescription(s, level);
3239 }
3240 
3241 void Target::StopHookCommandLine::GetSubclassDescription(
3242     Stream *s, lldb::DescriptionLevel level) const {
3243   // The brief description just prints the first command.
3244   if (level == eDescriptionLevelBrief) {
3245     if (m_commands.GetSize() == 1)
3246       s->PutCString(m_commands.GetStringAtIndex(0));
3247     return;
3248   }
3249   s->Indent("Commands: \n");
3250   s->SetIndentLevel(s->GetIndentLevel() + 4);
3251   uint32_t num_commands = m_commands.GetSize();
3252   for (uint32_t i = 0; i < num_commands; i++) {
3253     s->Indent(m_commands.GetStringAtIndex(i));
3254     s->PutCString("\n");
3255   }
3256   s->SetIndentLevel(s->GetIndentLevel() - 4);
3257 }
3258 
3259 // Target::StopHookCommandLine
3260 void Target::StopHookCommandLine::SetActionFromString(const std::string &string) {
3261   GetCommands().SplitIntoLines(string);
3262 }
3263 
3264 void Target::StopHookCommandLine::SetActionFromStrings(
3265     const std::vector<std::string> &strings) {
3266   for (auto string : strings)
3267     GetCommands().AppendString(string.c_str());
3268 }
3269 
3270 Target::StopHook::StopHookResult
3271 Target::StopHookCommandLine::HandleStop(ExecutionContext &exc_ctx,
3272                                         StreamSP output_sp) {
3273   assert(exc_ctx.GetTargetPtr() && "Can't call PerformAction on a context "
3274                                    "with no target");
3275 
3276   if (!m_commands.GetSize())
3277     return StopHookResult::KeepStopped;
3278 
3279   CommandReturnObject result(false);
3280   result.SetImmediateOutputStream(output_sp);
3281   Debugger &debugger = exc_ctx.GetTargetPtr()->GetDebugger();
3282   CommandInterpreterRunOptions options;
3283   options.SetStopOnContinue(true);
3284   options.SetStopOnError(true);
3285   options.SetEchoCommands(false);
3286   options.SetPrintResults(true);
3287   options.SetPrintErrors(true);
3288   options.SetAddToHistory(false);
3289 
3290   // Force Async:
3291   bool old_async = debugger.GetAsyncExecution();
3292   debugger.SetAsyncExecution(true);
3293   debugger.GetCommandInterpreter().HandleCommands(GetCommands(), &exc_ctx,
3294                                                   options, result);
3295   debugger.SetAsyncExecution(old_async);
3296   lldb::ReturnStatus status = result.GetStatus();
3297   if (status == eReturnStatusSuccessContinuingNoResult ||
3298       status == eReturnStatusSuccessContinuingResult)
3299     return StopHookResult::AlreadyContinued;
3300   return StopHookResult::KeepStopped;
3301 }
3302 
3303 // Target::StopHookScripted
3304 Status Target::StopHookScripted::SetScriptCallback(
3305     std::string class_name, StructuredData::ObjectSP extra_args_sp) {
3306   Status error;
3307 
3308   ScriptInterpreter *script_interp =
3309       GetTarget()->GetDebugger().GetScriptInterpreter();
3310   if (!script_interp) {
3311     error.SetErrorString("No script interpreter installed.");
3312     return error;
3313   }
3314 
3315   m_class_name = class_name;
3316 
3317   m_extra_args = new StructuredDataImpl();
3318 
3319   if (extra_args_sp)
3320     m_extra_args->SetObjectSP(extra_args_sp);
3321 
3322   m_implementation_sp = script_interp->CreateScriptedStopHook(
3323       GetTarget(), m_class_name.c_str(), m_extra_args, error);
3324 
3325   return error;
3326 }
3327 
3328 Target::StopHook::StopHookResult
3329 Target::StopHookScripted::HandleStop(ExecutionContext &exc_ctx,
3330                                      StreamSP output_sp) {
3331   assert(exc_ctx.GetTargetPtr() && "Can't call HandleStop on a context "
3332                                    "with no target");
3333 
3334   ScriptInterpreter *script_interp =
3335       GetTarget()->GetDebugger().GetScriptInterpreter();
3336   if (!script_interp)
3337     return StopHookResult::KeepStopped;
3338 
3339   bool should_stop = script_interp->ScriptedStopHookHandleStop(
3340       m_implementation_sp, exc_ctx, output_sp);
3341 
3342   return should_stop ? StopHookResult::KeepStopped
3343                      : StopHookResult::RequestContinue;
3344 }
3345 
3346 void Target::StopHookScripted::GetSubclassDescription(
3347     Stream *s, lldb::DescriptionLevel level) const {
3348   if (level == eDescriptionLevelBrief) {
3349     s->PutCString(m_class_name);
3350     return;
3351   }
3352   s->Indent("Class:");
3353   s->Printf("%s\n", m_class_name.c_str());
3354 
3355   // Now print the extra args:
3356   // FIXME: We should use StructuredData.GetDescription on the m_extra_args
3357   // but that seems to rely on some printing plugin that doesn't exist.
3358   if (!m_extra_args->IsValid())
3359     return;
3360   StructuredData::ObjectSP object_sp = m_extra_args->GetObjectSP();
3361   if (!object_sp || !object_sp->IsValid())
3362     return;
3363 
3364   StructuredData::Dictionary *as_dict = object_sp->GetAsDictionary();
3365   if (!as_dict || !as_dict->IsValid())
3366     return;
3367 
3368   uint32_t num_keys = as_dict->GetSize();
3369   if (num_keys == 0)
3370     return;
3371 
3372   s->Indent("Args:\n");
3373   s->SetIndentLevel(s->GetIndentLevel() + 4);
3374 
3375   auto print_one_element = [&s](ConstString key,
3376                                 StructuredData::Object *object) {
3377     s->Indent();
3378     s->Printf("%s : %s\n", key.GetCString(),
3379               object->GetStringValue().str().c_str());
3380     return true;
3381   };
3382 
3383   as_dict->ForEach(print_one_element);
3384 
3385   s->SetIndentLevel(s->GetIndentLevel() - 4);
3386 }
3387 
3388 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3389     {
3390         eNoDynamicValues,
3391         "no-dynamic-values",
3392         "Don't calculate the dynamic type of values",
3393     },
3394     {
3395         eDynamicCanRunTarget,
3396         "run-target",
3397         "Calculate the dynamic type of values "
3398         "even if you have to run the target.",
3399     },
3400     {
3401         eDynamicDontRunTarget,
3402         "no-run-target",
3403         "Calculate the dynamic type of values, but don't run the target.",
3404     },
3405 };
3406 
3407 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3408   return OptionEnumValues(g_dynamic_value_types);
3409 }
3410 
3411 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3412     {
3413         eInlineBreakpointsNever,
3414         "never",
3415         "Never look for inline breakpoint locations (fastest). This setting "
3416         "should only be used if you know that no inlining occurs in your"
3417         "programs.",
3418     },
3419     {
3420         eInlineBreakpointsHeaders,
3421         "headers",
3422         "Only check for inline breakpoint locations when setting breakpoints "
3423         "in header files, but not when setting breakpoint in implementation "
3424         "source files (default).",
3425     },
3426     {
3427         eInlineBreakpointsAlways,
3428         "always",
3429         "Always look for inline breakpoint locations when setting file and "
3430         "line breakpoints (slower but most accurate).",
3431     },
3432 };
3433 
3434 enum x86DisassemblyFlavor {
3435   eX86DisFlavorDefault,
3436   eX86DisFlavorIntel,
3437   eX86DisFlavorATT
3438 };
3439 
3440 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3441     {
3442         eX86DisFlavorDefault,
3443         "default",
3444         "Disassembler default (currently att).",
3445     },
3446     {
3447         eX86DisFlavorIntel,
3448         "intel",
3449         "Intel disassembler flavor.",
3450     },
3451     {
3452         eX86DisFlavorATT,
3453         "att",
3454         "AT&T disassembler flavor.",
3455     },
3456 };
3457 
3458 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3459     {
3460         Disassembler::eHexStyleC,
3461         "c",
3462         "C-style (0xffff).",
3463     },
3464     {
3465         Disassembler::eHexStyleAsm,
3466         "asm",
3467         "Asm-style (0ffffh).",
3468     },
3469 };
3470 
3471 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3472     {
3473         eLoadScriptFromSymFileTrue,
3474         "true",
3475         "Load debug scripts inside symbol files",
3476     },
3477     {
3478         eLoadScriptFromSymFileFalse,
3479         "false",
3480         "Do not load debug scripts inside symbol files.",
3481     },
3482     {
3483         eLoadScriptFromSymFileWarn,
3484         "warn",
3485         "Warn about debug scripts inside symbol files but do not load them.",
3486     },
3487 };
3488 
3489 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
3490     {
3491         eLoadCWDlldbinitTrue,
3492         "true",
3493         "Load .lldbinit files from current directory",
3494     },
3495     {
3496         eLoadCWDlldbinitFalse,
3497         "false",
3498         "Do not load .lldbinit files from current directory",
3499     },
3500     {
3501         eLoadCWDlldbinitWarn,
3502         "warn",
3503         "Warn about loading .lldbinit files from current directory",
3504     },
3505 };
3506 
3507 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3508     {
3509         eMemoryModuleLoadLevelMinimal,
3510         "minimal",
3511         "Load minimal information when loading modules from memory. Currently "
3512         "this setting loads sections only.",
3513     },
3514     {
3515         eMemoryModuleLoadLevelPartial,
3516         "partial",
3517         "Load partial information when loading modules from memory. Currently "
3518         "this setting loads sections and function bounds.",
3519     },
3520     {
3521         eMemoryModuleLoadLevelComplete,
3522         "complete",
3523         "Load complete information when loading modules from memory. Currently "
3524         "this setting loads sections and all symbols.",
3525     },
3526 };
3527 
3528 #define LLDB_PROPERTIES_target
3529 #include "TargetProperties.inc"
3530 
3531 enum {
3532 #define LLDB_PROPERTIES_target
3533 #include "TargetPropertiesEnum.inc"
3534   ePropertyExperimental,
3535 };
3536 
3537 class TargetOptionValueProperties : public OptionValueProperties {
3538 public:
3539   TargetOptionValueProperties(ConstString name) : OptionValueProperties(name) {}
3540 
3541   // This constructor is used when creating TargetOptionValueProperties when it
3542   // is part of a new lldb_private::Target instance. It will copy all current
3543   // global property values as needed
3544   TargetOptionValueProperties(const TargetPropertiesSP &target_properties_sp)
3545       : OptionValueProperties(*target_properties_sp->GetValueProperties()) {}
3546 
3547   const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3548                                      bool will_modify,
3549                                      uint32_t idx) const override {
3550     // When getting the value for a key from the target options, we will always
3551     // try and grab the setting from the current target if there is one. Else
3552     // we just use the one from this instance.
3553     if (exe_ctx) {
3554       Target *target = exe_ctx->GetTargetPtr();
3555       if (target) {
3556         TargetOptionValueProperties *target_properties =
3557             static_cast<TargetOptionValueProperties *>(
3558                 target->GetValueProperties().get());
3559         if (this != target_properties)
3560           return target_properties->ProtectedGetPropertyAtIndex(idx);
3561       }
3562     }
3563     return ProtectedGetPropertyAtIndex(idx);
3564   }
3565 };
3566 
3567 // TargetProperties
3568 #define LLDB_PROPERTIES_target_experimental
3569 #include "TargetProperties.inc"
3570 
3571 enum {
3572 #define LLDB_PROPERTIES_target_experimental
3573 #include "TargetPropertiesEnum.inc"
3574 };
3575 
3576 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3577 public:
3578   TargetExperimentalOptionValueProperties()
3579       : OptionValueProperties(
3580             ConstString(Properties::GetExperimentalSettingsName())) {}
3581 };
3582 
3583 TargetExperimentalProperties::TargetExperimentalProperties()
3584     : Properties(OptionValuePropertiesSP(
3585           new TargetExperimentalOptionValueProperties())) {
3586   m_collection_sp->Initialize(g_target_experimental_properties);
3587 }
3588 
3589 // TargetProperties
3590 TargetProperties::TargetProperties(Target *target)
3591     : Properties(), m_launch_info(), m_target(target) {
3592   if (target) {
3593     m_collection_sp = std::make_shared<TargetOptionValueProperties>(
3594         Target::GetGlobalProperties());
3595 
3596     // Set callbacks to update launch_info whenever "settins set" updated any
3597     // of these properties
3598     m_collection_sp->SetValueChangedCallback(
3599         ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
3600     m_collection_sp->SetValueChangedCallback(
3601         ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
3602     m_collection_sp->SetValueChangedCallback(
3603         ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
3604     m_collection_sp->SetValueChangedCallback(
3605         ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
3606     m_collection_sp->SetValueChangedCallback(
3607         ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
3608     m_collection_sp->SetValueChangedCallback(
3609         ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
3610     m_collection_sp->SetValueChangedCallback(
3611         ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
3612     m_collection_sp->SetValueChangedCallback(
3613         ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
3614     m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
3615       DetachOnErrorValueChangedCallback();
3616     });
3617     m_collection_sp->SetValueChangedCallback(
3618         ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
3619     m_collection_sp->SetValueChangedCallback(
3620         ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
3621     m_collection_sp->SetValueChangedCallback(
3622         ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
3623 
3624     m_experimental_properties_up =
3625         std::make_unique<TargetExperimentalProperties>();
3626     m_collection_sp->AppendProperty(
3627         ConstString(Properties::GetExperimentalSettingsName()),
3628         ConstString("Experimental settings - setting these won't produce "
3629                     "errors if the setting is not present."),
3630         true, m_experimental_properties_up->GetValueProperties());
3631   } else {
3632     m_collection_sp =
3633         std::make_shared<TargetOptionValueProperties>(ConstString("target"));
3634     m_collection_sp->Initialize(g_target_properties);
3635     m_experimental_properties_up =
3636         std::make_unique<TargetExperimentalProperties>();
3637     m_collection_sp->AppendProperty(
3638         ConstString(Properties::GetExperimentalSettingsName()),
3639         ConstString("Experimental settings - setting these won't produce "
3640                     "errors if the setting is not present."),
3641         true, m_experimental_properties_up->GetValueProperties());
3642     m_collection_sp->AppendProperty(
3643         ConstString("process"), ConstString("Settings specific to processes."),
3644         true, Process::GetGlobalProperties()->GetValueProperties());
3645   }
3646 }
3647 
3648 TargetProperties::~TargetProperties() = default;
3649 
3650 void TargetProperties::UpdateLaunchInfoFromProperties() {
3651   Arg0ValueChangedCallback();
3652   RunArgsValueChangedCallback();
3653   EnvVarsValueChangedCallback();
3654   InputPathValueChangedCallback();
3655   OutputPathValueChangedCallback();
3656   ErrorPathValueChangedCallback();
3657   DetachOnErrorValueChangedCallback();
3658   DisableASLRValueChangedCallback();
3659   InheritTCCValueChangedCallback();
3660   DisableSTDIOValueChangedCallback();
3661 }
3662 
3663 bool TargetProperties::GetInjectLocalVariables(
3664     ExecutionContext *exe_ctx) const {
3665   const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3666       exe_ctx, false, ePropertyExperimental);
3667   OptionValueProperties *exp_values =
3668       exp_property->GetValue()->GetAsProperties();
3669   if (exp_values)
3670     return exp_values->GetPropertyAtIndexAsBoolean(
3671         exe_ctx, ePropertyInjectLocalVars, true);
3672   else
3673     return true;
3674 }
3675 
3676 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3677                                                bool b) {
3678   const Property *exp_property =
3679       m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3680   OptionValueProperties *exp_values =
3681       exp_property->GetValue()->GetAsProperties();
3682   if (exp_values)
3683     exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3684                                             true);
3685 }
3686 
3687 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3688   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3689       nullptr, ePropertyDefaultArch);
3690   if (value)
3691     return value->GetCurrentValue();
3692   return ArchSpec();
3693 }
3694 
3695 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3696   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3697       nullptr, ePropertyDefaultArch);
3698   if (value)
3699     return value->SetCurrentValue(arch, true);
3700 }
3701 
3702 bool TargetProperties::GetMoveToNearestCode() const {
3703   const uint32_t idx = ePropertyMoveToNearestCode;
3704   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3705       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3706 }
3707 
3708 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3709   const uint32_t idx = ePropertyPreferDynamic;
3710   return (lldb::DynamicValueType)
3711       m_collection_sp->GetPropertyAtIndexAsEnumeration(
3712           nullptr, idx, g_target_properties[idx].default_uint_value);
3713 }
3714 
3715 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3716   const uint32_t idx = ePropertyPreferDynamic;
3717   return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3718 }
3719 
3720 bool TargetProperties::GetPreloadSymbols() const {
3721   const uint32_t idx = ePropertyPreloadSymbols;
3722   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3723       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3724 }
3725 
3726 void TargetProperties::SetPreloadSymbols(bool b) {
3727   const uint32_t idx = ePropertyPreloadSymbols;
3728   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3729 }
3730 
3731 bool TargetProperties::GetDisableASLR() const {
3732   const uint32_t idx = ePropertyDisableASLR;
3733   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3734       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3735 }
3736 
3737 void TargetProperties::SetDisableASLR(bool b) {
3738   const uint32_t idx = ePropertyDisableASLR;
3739   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3740 }
3741 
3742 bool TargetProperties::GetInheritTCC() const {
3743   const uint32_t idx = ePropertyInheritTCC;
3744   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3745       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3746 }
3747 
3748 void TargetProperties::SetInheritTCC(bool b) {
3749   const uint32_t idx = ePropertyInheritTCC;
3750   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3751 }
3752 
3753 bool TargetProperties::GetDetachOnError() const {
3754   const uint32_t idx = ePropertyDetachOnError;
3755   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3756       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3757 }
3758 
3759 void TargetProperties::SetDetachOnError(bool b) {
3760   const uint32_t idx = ePropertyDetachOnError;
3761   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3762 }
3763 
3764 bool TargetProperties::GetDisableSTDIO() const {
3765   const uint32_t idx = ePropertyDisableSTDIO;
3766   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3767       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3768 }
3769 
3770 void TargetProperties::SetDisableSTDIO(bool b) {
3771   const uint32_t idx = ePropertyDisableSTDIO;
3772   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3773 }
3774 
3775 const char *TargetProperties::GetDisassemblyFlavor() const {
3776   const uint32_t idx = ePropertyDisassemblyFlavor;
3777   const char *return_value;
3778 
3779   x86DisassemblyFlavor flavor_value =
3780       (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3781           nullptr, idx, g_target_properties[idx].default_uint_value);
3782   return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3783   return return_value;
3784 }
3785 
3786 InlineStrategy TargetProperties::GetInlineStrategy() const {
3787   const uint32_t idx = ePropertyInlineStrategy;
3788   return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3789       nullptr, idx, g_target_properties[idx].default_uint_value);
3790 }
3791 
3792 llvm::StringRef TargetProperties::GetArg0() const {
3793   const uint32_t idx = ePropertyArg0;
3794   return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx,
3795                                                      llvm::StringRef());
3796 }
3797 
3798 void TargetProperties::SetArg0(llvm::StringRef arg) {
3799   const uint32_t idx = ePropertyArg0;
3800   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3801   m_launch_info.SetArg0(arg);
3802 }
3803 
3804 bool TargetProperties::GetRunArguments(Args &args) const {
3805   const uint32_t idx = ePropertyRunArgs;
3806   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3807 }
3808 
3809 void TargetProperties::SetRunArguments(const Args &args) {
3810   const uint32_t idx = ePropertyRunArgs;
3811   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3812   m_launch_info.GetArguments() = args;
3813 }
3814 
3815 Environment TargetProperties::ComputeEnvironment() const {
3816   Environment env;
3817 
3818   if (m_target &&
3819       m_collection_sp->GetPropertyAtIndexAsBoolean(
3820           nullptr, ePropertyInheritEnv,
3821           g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
3822     if (auto platform_sp = m_target->GetPlatform()) {
3823       Environment platform_env = platform_sp->GetEnvironment();
3824       for (const auto &KV : platform_env)
3825         env[KV.first()] = KV.second;
3826     }
3827   }
3828 
3829   Args property_unset_env;
3830   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyUnsetEnvVars,
3831                                             property_unset_env);
3832   for (const auto &var : property_unset_env)
3833     env.erase(var.ref());
3834 
3835   Args property_env;
3836   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyEnvVars,
3837                                             property_env);
3838   for (const auto &KV : Environment(property_env))
3839     env[KV.first()] = KV.second;
3840 
3841   return env;
3842 }
3843 
3844 Environment TargetProperties::GetEnvironment() const {
3845   return ComputeEnvironment();
3846 }
3847 
3848 void TargetProperties::SetEnvironment(Environment env) {
3849   // TODO: Get rid of the Args intermediate step
3850   const uint32_t idx = ePropertyEnvVars;
3851   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3852 }
3853 
3854 bool TargetProperties::GetSkipPrologue() const {
3855   const uint32_t idx = ePropertySkipPrologue;
3856   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3857       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3858 }
3859 
3860 PathMappingList &TargetProperties::GetSourcePathMap() const {
3861   const uint32_t idx = ePropertySourceMap;
3862   OptionValuePathMappings *option_value =
3863       m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3864                                                                    false, idx);
3865   assert(option_value);
3866   return option_value->GetCurrentValue();
3867 }
3868 
3869 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
3870   const uint32_t idx = ePropertyExecutableSearchPaths;
3871   OptionValueFileSpecList *option_value =
3872       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3873                                                                    false, idx);
3874   assert(option_value);
3875   option_value->AppendCurrentValue(dir);
3876 }
3877 
3878 FileSpecList TargetProperties::GetExecutableSearchPaths() {
3879   const uint32_t idx = ePropertyExecutableSearchPaths;
3880   const OptionValueFileSpecList *option_value =
3881       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3882                                                                    false, idx);
3883   assert(option_value);
3884   return option_value->GetCurrentValue();
3885 }
3886 
3887 FileSpecList TargetProperties::GetDebugFileSearchPaths() {
3888   const uint32_t idx = ePropertyDebugFileSearchPaths;
3889   const OptionValueFileSpecList *option_value =
3890       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3891                                                                    false, idx);
3892   assert(option_value);
3893   return option_value->GetCurrentValue();
3894 }
3895 
3896 FileSpecList TargetProperties::GetClangModuleSearchPaths() {
3897   const uint32_t idx = ePropertyClangModuleSearchPaths;
3898   const OptionValueFileSpecList *option_value =
3899       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3900                                                                    false, idx);
3901   assert(option_value);
3902   return option_value->GetCurrentValue();
3903 }
3904 
3905 bool TargetProperties::GetEnableAutoImportClangModules() const {
3906   const uint32_t idx = ePropertyAutoImportClangModules;
3907   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3908       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3909 }
3910 
3911 bool TargetProperties::GetEnableImportStdModule() const {
3912   const uint32_t idx = ePropertyImportStdModule;
3913   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3914       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3915 }
3916 
3917 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3918   const uint32_t idx = ePropertyAutoApplyFixIts;
3919   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3920       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3921 }
3922 
3923 uint64_t TargetProperties::GetNumberOfRetriesWithFixits() const {
3924   const uint32_t idx = ePropertyRetriesWithFixIts;
3925   return m_collection_sp->GetPropertyAtIndexAsUInt64(
3926       nullptr, idx, g_target_properties[idx].default_uint_value);
3927 }
3928 
3929 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3930   const uint32_t idx = ePropertyNotifyAboutFixIts;
3931   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3932       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3933 }
3934 
3935 bool TargetProperties::GetEnableSaveObjects() const {
3936   const uint32_t idx = ePropertySaveObjects;
3937   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3938       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3939 }
3940 
3941 bool TargetProperties::GetEnableSyntheticValue() const {
3942   const uint32_t idx = ePropertyEnableSynthetic;
3943   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3944       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3945 }
3946 
3947 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
3948   const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
3949   return m_collection_sp->GetPropertyAtIndexAsUInt64(
3950       nullptr, idx, g_target_properties[idx].default_uint_value);
3951 }
3952 
3953 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3954   const uint32_t idx = ePropertyMaxChildrenCount;
3955   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3956       nullptr, idx, g_target_properties[idx].default_uint_value);
3957 }
3958 
3959 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3960   const uint32_t idx = ePropertyMaxSummaryLength;
3961   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3962       nullptr, idx, g_target_properties[idx].default_uint_value);
3963 }
3964 
3965 uint32_t TargetProperties::GetMaximumMemReadSize() const {
3966   const uint32_t idx = ePropertyMaxMemReadSize;
3967   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3968       nullptr, idx, g_target_properties[idx].default_uint_value);
3969 }
3970 
3971 FileSpec TargetProperties::GetStandardInputPath() const {
3972   const uint32_t idx = ePropertyInputPath;
3973   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3974 }
3975 
3976 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
3977   const uint32_t idx = ePropertyInputPath;
3978   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3979 }
3980 
3981 FileSpec TargetProperties::GetStandardOutputPath() const {
3982   const uint32_t idx = ePropertyOutputPath;
3983   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3984 }
3985 
3986 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
3987   const uint32_t idx = ePropertyOutputPath;
3988   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3989 }
3990 
3991 FileSpec TargetProperties::GetStandardErrorPath() const {
3992   const uint32_t idx = ePropertyErrorPath;
3993   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3994 }
3995 
3996 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3997   const uint32_t idx = ePropertyErrorPath;
3998   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3999 }
4000 
4001 LanguageType TargetProperties::GetLanguage() const {
4002   OptionValueLanguage *value =
4003       m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
4004           nullptr, ePropertyLanguage);
4005   if (value)
4006     return value->GetCurrentValue();
4007   return LanguageType();
4008 }
4009 
4010 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
4011   const uint32_t idx = ePropertyExprPrefix;
4012   OptionValueFileSpec *file =
4013       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
4014                                                                idx);
4015   if (file) {
4016     DataBufferSP data_sp(file->GetFileContents());
4017     if (data_sp)
4018       return llvm::StringRef(
4019           reinterpret_cast<const char *>(data_sp->GetBytes()),
4020           data_sp->GetByteSize());
4021   }
4022   return "";
4023 }
4024 
4025 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4026   const uint32_t idx = ePropertyBreakpointUseAvoidList;
4027   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4028       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4029 }
4030 
4031 bool TargetProperties::GetUseHexImmediates() const {
4032   const uint32_t idx = ePropertyUseHexImmediates;
4033   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4034       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4035 }
4036 
4037 bool TargetProperties::GetUseFastStepping() const {
4038   const uint32_t idx = ePropertyUseFastStepping;
4039   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4040       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4041 }
4042 
4043 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4044   const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4045   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4046       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4047 }
4048 
4049 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4050   const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4051   return (LoadScriptFromSymFile)
4052       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4053           nullptr, idx, g_target_properties[idx].default_uint_value);
4054 }
4055 
4056 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4057   const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4058   return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4059       nullptr, idx, g_target_properties[idx].default_uint_value);
4060 }
4061 
4062 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4063   const uint32_t idx = ePropertyHexImmediateStyle;
4064   return (Disassembler::HexImmediateStyle)
4065       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4066           nullptr, idx, g_target_properties[idx].default_uint_value);
4067 }
4068 
4069 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4070   const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4071   return (MemoryModuleLoadLevel)
4072       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4073           nullptr, idx, g_target_properties[idx].default_uint_value);
4074 }
4075 
4076 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4077   const uint32_t idx = ePropertyTrapHandlerNames;
4078   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4079 }
4080 
4081 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4082   const uint32_t idx = ePropertyTrapHandlerNames;
4083   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4084 }
4085 
4086 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4087   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4088   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4089 }
4090 
4091 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4092   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4093   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4094 }
4095 
4096 bool TargetProperties::GetDisplayRecognizedArguments() const {
4097   const uint32_t idx = ePropertyDisplayRecognizedArguments;
4098   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4099 }
4100 
4101 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
4102   const uint32_t idx = ePropertyDisplayRecognizedArguments;
4103   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4104 }
4105 
4106 bool TargetProperties::GetNonStopModeEnabled() const {
4107   const uint32_t idx = ePropertyNonStopModeEnabled;
4108   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4109 }
4110 
4111 void TargetProperties::SetNonStopModeEnabled(bool b) {
4112   const uint32_t idx = ePropertyNonStopModeEnabled;
4113   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4114 }
4115 
4116 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
4117   m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4118   return m_launch_info;
4119 }
4120 
4121 void TargetProperties::SetProcessLaunchInfo(
4122     const ProcessLaunchInfo &launch_info) {
4123   m_launch_info = launch_info;
4124   SetArg0(launch_info.GetArg0());
4125   SetRunArguments(launch_info.GetArguments());
4126   SetEnvironment(launch_info.GetEnvironment());
4127   const FileAction *input_file_action =
4128       launch_info.GetFileActionForFD(STDIN_FILENO);
4129   if (input_file_action) {
4130     SetStandardInputPath(input_file_action->GetPath());
4131   }
4132   const FileAction *output_file_action =
4133       launch_info.GetFileActionForFD(STDOUT_FILENO);
4134   if (output_file_action) {
4135     SetStandardOutputPath(output_file_action->GetPath());
4136   }
4137   const FileAction *error_file_action =
4138       launch_info.GetFileActionForFD(STDERR_FILENO);
4139   if (error_file_action) {
4140     SetStandardErrorPath(error_file_action->GetPath());
4141   }
4142   SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4143   SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4144   SetInheritTCC(
4145       launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
4146   SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4147 }
4148 
4149 bool TargetProperties::GetRequireHardwareBreakpoints() const {
4150   const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4151   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4152       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4153 }
4154 
4155 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
4156   const uint32_t idx = ePropertyRequireHardwareBreakpoints;
4157   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4158 }
4159 
4160 bool TargetProperties::GetAutoInstallMainExecutable() const {
4161   const uint32_t idx = ePropertyAutoInstallMainExecutable;
4162   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4163       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
4164 }
4165 
4166 void TargetProperties::Arg0ValueChangedCallback() {
4167   m_launch_info.SetArg0(GetArg0());
4168 }
4169 
4170 void TargetProperties::RunArgsValueChangedCallback() {
4171   Args args;
4172   if (GetRunArguments(args))
4173     m_launch_info.GetArguments() = args;
4174 }
4175 
4176 void TargetProperties::EnvVarsValueChangedCallback() {
4177   m_launch_info.GetEnvironment() = ComputeEnvironment();
4178 }
4179 
4180 void TargetProperties::InputPathValueChangedCallback() {
4181   m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
4182                                      false);
4183 }
4184 
4185 void TargetProperties::OutputPathValueChangedCallback() {
4186   m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
4187                                      false, true);
4188 }
4189 
4190 void TargetProperties::ErrorPathValueChangedCallback() {
4191   m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
4192                                      false, true);
4193 }
4194 
4195 void TargetProperties::DetachOnErrorValueChangedCallback() {
4196   if (GetDetachOnError())
4197     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4198   else
4199     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4200 }
4201 
4202 void TargetProperties::DisableASLRValueChangedCallback() {
4203   if (GetDisableASLR())
4204     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4205   else
4206     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4207 }
4208 
4209 void TargetProperties::InheritTCCValueChangedCallback() {
4210   if (GetInheritTCC())
4211     m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
4212   else
4213     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
4214 }
4215 
4216 void TargetProperties::DisableSTDIOValueChangedCallback() {
4217   if (GetDisableSTDIO())
4218     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4219   else
4220     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4221 }
4222 
4223 // Target::TargetEventData
4224 
4225 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4226     : EventData(), m_target_sp(target_sp), m_module_list() {}
4227 
4228 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4229                                          const ModuleList &module_list)
4230     : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4231 
4232 Target::TargetEventData::~TargetEventData() = default;
4233 
4234 ConstString Target::TargetEventData::GetFlavorString() {
4235   static ConstString g_flavor("Target::TargetEventData");
4236   return g_flavor;
4237 }
4238 
4239 void Target::TargetEventData::Dump(Stream *s) const {
4240   for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4241     if (i != 0)
4242       *s << ", ";
4243     m_module_list.GetModuleAtIndex(i)->GetDescription(
4244         s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4245   }
4246 }
4247 
4248 const Target::TargetEventData *
4249 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4250   if (event_ptr) {
4251     const EventData *event_data = event_ptr->GetData();
4252     if (event_data &&
4253         event_data->GetFlavor() == TargetEventData::GetFlavorString())
4254       return static_cast<const TargetEventData *>(event_ptr->GetData());
4255   }
4256   return nullptr;
4257 }
4258 
4259 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4260   TargetSP target_sp;
4261   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4262   if (event_data)
4263     target_sp = event_data->m_target_sp;
4264   return target_sp;
4265 }
4266 
4267 ModuleList
4268 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4269   ModuleList module_list;
4270   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4271   if (event_data)
4272     module_list = event_data->m_module_list;
4273   return module_list;
4274 }
4275 
4276 std::recursive_mutex &Target::GetAPIMutex() {
4277   if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4278     return m_private_mutex;
4279   else
4280     return m_mutex;
4281 }
4282