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() {
2488   lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2489   Target::StopHookSP stop_hook_sp(new StopHook(shared_from_this(), new_uid));
2490   m_stop_hooks[new_uid] = stop_hook_sp;
2491   return stop_hook_sp;
2492 }
2493 
2494 bool Target::RemoveStopHookByID(lldb::user_id_t user_id) {
2495   size_t num_removed = m_stop_hooks.erase(user_id);
2496   return (num_removed != 0);
2497 }
2498 
2499 void Target::RemoveAllStopHooks() { m_stop_hooks.clear(); }
2500 
2501 Target::StopHookSP Target::GetStopHookByID(lldb::user_id_t user_id) {
2502   StopHookSP found_hook;
2503 
2504   StopHookCollection::iterator specified_hook_iter;
2505   specified_hook_iter = m_stop_hooks.find(user_id);
2506   if (specified_hook_iter != m_stop_hooks.end())
2507     found_hook = (*specified_hook_iter).second;
2508   return found_hook;
2509 }
2510 
2511 bool Target::SetStopHookActiveStateByID(lldb::user_id_t user_id,
2512                                         bool active_state) {
2513   StopHookCollection::iterator specified_hook_iter;
2514   specified_hook_iter = m_stop_hooks.find(user_id);
2515   if (specified_hook_iter == m_stop_hooks.end())
2516     return false;
2517 
2518   (*specified_hook_iter).second->SetIsActive(active_state);
2519   return true;
2520 }
2521 
2522 void Target::SetAllStopHooksActiveState(bool active_state) {
2523   StopHookCollection::iterator pos, end = m_stop_hooks.end();
2524   for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2525     (*pos).second->SetIsActive(active_state);
2526   }
2527 }
2528 
2529 void Target::RunStopHooks() {
2530   if (m_suppress_stop_hooks)
2531     return;
2532 
2533   if (!m_process_sp)
2534     return;
2535 
2536   // Somebody might have restarted the process:
2537   if (m_process_sp->GetState() != eStateStopped)
2538     return;
2539 
2540   // <rdar://problem/12027563> make sure we check that we are not stopped
2541   // because of us running a user expression since in that case we do not want
2542   // to run the stop-hooks
2543   if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2544     return;
2545 
2546   if (m_stop_hooks.empty())
2547     return;
2548 
2549   StopHookCollection::iterator pos, end = m_stop_hooks.end();
2550 
2551   // If there aren't any active stop hooks, don't bother either.
2552   // Also see if any of the active hooks want to auto-continue.
2553   bool any_active_hooks = false;
2554   bool auto_continue = false;
2555   for (auto hook : m_stop_hooks) {
2556     if (hook.second->IsActive()) {
2557       any_active_hooks = true;
2558       auto_continue |= hook.second->GetAutoContinue();
2559     }
2560   }
2561   if (!any_active_hooks)
2562     return;
2563 
2564   CommandReturnObject result(m_debugger.GetUseColor());
2565 
2566   std::vector<ExecutionContext> exc_ctx_with_reasons;
2567   std::vector<SymbolContext> sym_ctx_with_reasons;
2568 
2569   ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2570   size_t num_threads = cur_threadlist.GetSize();
2571   for (size_t i = 0; i < num_threads; i++) {
2572     lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2573     if (cur_thread_sp->ThreadStoppedForAReason()) {
2574       lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2575       exc_ctx_with_reasons.push_back(ExecutionContext(
2576           m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2577       sym_ctx_with_reasons.push_back(
2578           cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2579     }
2580   }
2581 
2582   // If no threads stopped for a reason, don't run the stop-hooks.
2583   size_t num_exe_ctx = exc_ctx_with_reasons.size();
2584   if (num_exe_ctx == 0)
2585     return;
2586 
2587   result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2588   result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2589 
2590   bool keep_going = true;
2591   bool hooks_ran = false;
2592   bool print_hook_header = (m_stop_hooks.size() != 1);
2593   bool print_thread_header = (num_exe_ctx != 1);
2594   bool did_restart = false;
2595 
2596   for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2597     // result.Clear();
2598     StopHookSP cur_hook_sp = (*pos).second;
2599     if (!cur_hook_sp->IsActive())
2600       continue;
2601 
2602     bool any_thread_matched = false;
2603     for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2604       if ((cur_hook_sp->GetSpecifier() == nullptr ||
2605            cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2606                sym_ctx_with_reasons[i])) &&
2607           (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2608            cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2609                exc_ctx_with_reasons[i].GetThreadRef()))) {
2610         if (!hooks_ran) {
2611           hooks_ran = true;
2612         }
2613         if (print_hook_header && !any_thread_matched) {
2614           const char *cmd =
2615               (cur_hook_sp->GetCommands().GetSize() == 1
2616                    ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2617                    : nullptr);
2618           if (cmd)
2619             result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2620                                            cur_hook_sp->GetID(), cmd);
2621           else
2622             result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2623                                            cur_hook_sp->GetID());
2624           any_thread_matched = true;
2625         }
2626 
2627         if (print_thread_header)
2628           result.AppendMessageWithFormat(
2629               "-- Thread %d\n",
2630               exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2631 
2632         CommandInterpreterRunOptions options;
2633         options.SetStopOnContinue(true);
2634         options.SetStopOnError(true);
2635         options.SetEchoCommands(false);
2636         options.SetPrintResults(true);
2637         options.SetPrintErrors(true);
2638         options.SetAddToHistory(false);
2639 
2640         // Force Async:
2641         bool old_async = GetDebugger().GetAsyncExecution();
2642         GetDebugger().SetAsyncExecution(true);
2643         GetDebugger().GetCommandInterpreter().HandleCommands(
2644             cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2645             result);
2646         GetDebugger().SetAsyncExecution(old_async);
2647         // If the command started the target going again, we should bag out of
2648         // running the stop hooks.
2649         if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2650             (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2651           // But only complain if there were more stop hooks to do:
2652           StopHookCollection::iterator tmp = pos;
2653           if (++tmp != end)
2654             result.AppendMessageWithFormat(
2655                 "\nAborting stop hooks, hook %" PRIu64
2656                 " set the program running.\n"
2657                 "  Consider using '-G true' to make "
2658                 "stop hooks auto-continue.\n",
2659                 cur_hook_sp->GetID());
2660           keep_going = false;
2661           did_restart = true;
2662         }
2663       }
2664     }
2665   }
2666   // Finally, if auto-continue was requested, do it now:
2667   if (!did_restart && auto_continue)
2668     m_process_sp->PrivateResume();
2669 
2670   result.GetImmediateOutputStream()->Flush();
2671   result.GetImmediateErrorStream()->Flush();
2672 }
2673 
2674 const TargetPropertiesSP &Target::GetGlobalProperties() {
2675   // NOTE: intentional leak so we don't crash if global destructor chain gets
2676   // called as other threads still use the result of this function
2677   static TargetPropertiesSP *g_settings_sp_ptr =
2678       new TargetPropertiesSP(new TargetProperties(nullptr));
2679   return *g_settings_sp_ptr;
2680 }
2681 
2682 Status Target::Install(ProcessLaunchInfo *launch_info) {
2683   Status error;
2684   PlatformSP platform_sp(GetPlatform());
2685   if (platform_sp) {
2686     if (platform_sp->IsRemote()) {
2687       if (platform_sp->IsConnected()) {
2688         // Install all files that have an install path when connected to a
2689         // remote platform. If target.auto-install-main-executable is set then
2690         // also install the main executable even if it does not have an explicit
2691         // install path specified.
2692         const ModuleList &modules = GetImages();
2693         const size_t num_images = modules.GetSize();
2694         for (size_t idx = 0; idx < num_images; ++idx) {
2695           ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2696           if (module_sp) {
2697             const bool is_main_executable = module_sp == GetExecutableModule();
2698             FileSpec local_file(module_sp->GetFileSpec());
2699             if (local_file) {
2700               FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2701               if (!remote_file) {
2702                 if (is_main_executable && GetAutoInstallMainExecutable()) {
2703                   // Automatically install the main executable.
2704                   remote_file = platform_sp->GetRemoteWorkingDirectory();
2705                   remote_file.AppendPathComponent(
2706                       module_sp->GetFileSpec().GetFilename().GetCString());
2707                 }
2708               }
2709               if (remote_file) {
2710                 error = platform_sp->Install(local_file, remote_file);
2711                 if (error.Success()) {
2712                   module_sp->SetPlatformFileSpec(remote_file);
2713                   if (is_main_executable) {
2714                     platform_sp->SetFilePermissions(remote_file, 0700);
2715                     if (launch_info)
2716                       launch_info->SetExecutableFile(remote_file, false);
2717                   }
2718                 } else
2719                   break;
2720               }
2721             }
2722           }
2723         }
2724       }
2725     }
2726   }
2727   return error;
2728 }
2729 
2730 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2731                                 uint32_t stop_id) {
2732   return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2733 }
2734 
2735 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2736                                 Address &resolved_addr) {
2737   return m_images.ResolveFileAddress(file_addr, resolved_addr);
2738 }
2739 
2740 bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2741                                    addr_t new_section_load_addr,
2742                                    bool warn_multiple) {
2743   const addr_t old_section_load_addr =
2744       m_section_load_history.GetSectionLoadAddress(
2745           SectionLoadHistory::eStopIDNow, section_sp);
2746   if (old_section_load_addr != new_section_load_addr) {
2747     uint32_t stop_id = 0;
2748     ProcessSP process_sp(GetProcessSP());
2749     if (process_sp)
2750       stop_id = process_sp->GetStopID();
2751     else
2752       stop_id = m_section_load_history.GetLastStopID();
2753     if (m_section_load_history.SetSectionLoadAddress(
2754             stop_id, section_sp, new_section_load_addr, warn_multiple))
2755       return true; // Return true if the section load address was changed...
2756   }
2757   return false; // Return false to indicate nothing changed
2758 }
2759 
2760 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2761   size_t section_unload_count = 0;
2762   size_t num_modules = module_list.GetSize();
2763   for (size_t i = 0; i < num_modules; ++i) {
2764     section_unload_count +=
2765         UnloadModuleSections(module_list.GetModuleAtIndex(i));
2766   }
2767   return section_unload_count;
2768 }
2769 
2770 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2771   uint32_t stop_id = 0;
2772   ProcessSP process_sp(GetProcessSP());
2773   if (process_sp)
2774     stop_id = process_sp->GetStopID();
2775   else
2776     stop_id = m_section_load_history.GetLastStopID();
2777   SectionList *sections = module_sp->GetSectionList();
2778   size_t section_unload_count = 0;
2779   if (sections) {
2780     const uint32_t num_sections = sections->GetNumSections(0);
2781     for (uint32_t i = 0; i < num_sections; ++i) {
2782       section_unload_count += m_section_load_history.SetSectionUnloaded(
2783           stop_id, sections->GetSectionAtIndex(i));
2784     }
2785   }
2786   return section_unload_count;
2787 }
2788 
2789 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2790   uint32_t stop_id = 0;
2791   ProcessSP process_sp(GetProcessSP());
2792   if (process_sp)
2793     stop_id = process_sp->GetStopID();
2794   else
2795     stop_id = m_section_load_history.GetLastStopID();
2796   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2797 }
2798 
2799 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2800                                 addr_t load_addr) {
2801   uint32_t stop_id = 0;
2802   ProcessSP process_sp(GetProcessSP());
2803   if (process_sp)
2804     stop_id = process_sp->GetStopID();
2805   else
2806     stop_id = m_section_load_history.GetLastStopID();
2807   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2808                                                    load_addr);
2809 }
2810 
2811 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2812 
2813 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2814   Status error;
2815   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2816 
2817   LLDB_LOGF(log, "Target::%s() called for %s", __FUNCTION__,
2818             launch_info.GetExecutableFile().GetPath().c_str());
2819 
2820   StateType state = eStateInvalid;
2821 
2822   // Scope to temporarily get the process state in case someone has manually
2823   // remotely connected already to a process and we can skip the platform
2824   // launching.
2825   {
2826     ProcessSP process_sp(GetProcessSP());
2827 
2828     if (process_sp) {
2829       state = process_sp->GetState();
2830       LLDB_LOGF(log,
2831                 "Target::%s the process exists, and its current state is %s",
2832                 __FUNCTION__, StateAsCString(state));
2833     } else {
2834       LLDB_LOGF(log, "Target::%s the process instance doesn't currently exist.",
2835                 __FUNCTION__);
2836     }
2837   }
2838 
2839   launch_info.GetFlags().Set(eLaunchFlagDebug);
2840 
2841   // Get the value of synchronous execution here.  If you wait till after you
2842   // have started to run, then you could have hit a breakpoint, whose command
2843   // might switch the value, and then you'll pick up that incorrect value.
2844   Debugger &debugger = GetDebugger();
2845   const bool synchronous_execution =
2846       debugger.GetCommandInterpreter().GetSynchronous();
2847 
2848   PlatformSP platform_sp(GetPlatform());
2849 
2850   FinalizeFileActions(launch_info);
2851 
2852   if (state == eStateConnected) {
2853     if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
2854       error.SetErrorString(
2855           "can't launch in tty when launching through a remote connection");
2856       return error;
2857     }
2858   }
2859 
2860   if (!launch_info.GetArchitecture().IsValid())
2861     launch_info.GetArchitecture() = GetArchitecture();
2862 
2863   // If we're not already connected to the process, and if we have a platform
2864   // that can launch a process for debugging, go ahead and do that here.
2865   if (state != eStateConnected && platform_sp &&
2866       platform_sp->CanDebugProcess()) {
2867     LLDB_LOGF(log, "Target::%s asking the platform to debug the process",
2868               __FUNCTION__);
2869 
2870     // If there was a previous process, delete it before we make the new one.
2871     // One subtle point, we delete the process before we release the reference
2872     // to m_process_sp.  That way even if we are the last owner, the process
2873     // will get Finalized before it gets destroyed.
2874     DeleteCurrentProcess();
2875 
2876     m_process_sp =
2877         GetPlatform()->DebugProcess(launch_info, debugger, this, error);
2878 
2879   } else {
2880     LLDB_LOGF(log,
2881               "Target::%s the platform doesn't know how to debug a "
2882               "process, getting a process plugin to do this for us.",
2883               __FUNCTION__);
2884 
2885     if (state == eStateConnected) {
2886       assert(m_process_sp);
2887     } else {
2888       // Use a Process plugin to construct the process.
2889       const char *plugin_name = launch_info.GetProcessPluginName();
2890       CreateProcess(launch_info.GetListener(), plugin_name, nullptr);
2891     }
2892 
2893     // Since we didn't have a platform launch the process, launch it here.
2894     if (m_process_sp)
2895       error = m_process_sp->Launch(launch_info);
2896   }
2897 
2898   if (!m_process_sp && error.Success())
2899     error.SetErrorString("failed to launch or debug process");
2900 
2901   if (!error.Success())
2902     return error;
2903 
2904   auto at_exit =
2905       llvm::make_scope_exit([&]() { m_process_sp->RestoreProcessEvents(); });
2906 
2907   if (!synchronous_execution &&
2908       launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2909     return error;
2910 
2911   ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
2912   if (!hijack_listener_sp) {
2913     hijack_listener_sp = Listener::MakeListener("lldb.Target.Launch.hijack");
2914     launch_info.SetHijackListener(hijack_listener_sp);
2915     m_process_sp->HijackProcessEvents(hijack_listener_sp);
2916   }
2917 
2918   switch (m_process_sp->WaitForProcessToStop(llvm::None, nullptr, false,
2919                                              hijack_listener_sp, nullptr)) {
2920   case eStateStopped: {
2921     if (launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
2922       break;
2923     if (synchronous_execution) {
2924       // Now we have handled the stop-from-attach, and we are just
2925       // switching to a synchronous resume.  So we should switch to the
2926       // SyncResume hijacker.
2927       m_process_sp->RestoreProcessEvents();
2928       m_process_sp->ResumeSynchronous(stream);
2929     } else {
2930       m_process_sp->RestoreProcessEvents();
2931       error = m_process_sp->PrivateResume();
2932     }
2933     if (!error.Success()) {
2934       Status error2;
2935       error2.SetErrorStringWithFormat(
2936           "process resume at entry point failed: %s", error.AsCString());
2937       error = error2;
2938     }
2939   } break;
2940   case eStateExited: {
2941     bool with_shell = !!launch_info.GetShell();
2942     const int exit_status = m_process_sp->GetExitStatus();
2943     const char *exit_desc = m_process_sp->GetExitDescription();
2944     std::string desc;
2945     if (exit_desc && exit_desc[0])
2946       desc = " (" + std::string(exit_desc) + ')';
2947     if (with_shell)
2948       error.SetErrorStringWithFormat(
2949           "process exited with status %i%s\n"
2950           "'r' and 'run' are aliases that default to launching through a "
2951           "shell.\n"
2952           "Try launching without going through a shell by using "
2953           "'process launch'.",
2954           exit_status, desc.c_str());
2955     else
2956       error.SetErrorStringWithFormat("process exited with status %i%s",
2957                                      exit_status, desc.c_str());
2958   } break;
2959   default:
2960     error.SetErrorStringWithFormat("initial process state wasn't stopped: %s",
2961                                    StateAsCString(state));
2962     break;
2963   }
2964   return error;
2965 }
2966 
2967 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
2968   auto state = eStateInvalid;
2969   auto process_sp = GetProcessSP();
2970   if (process_sp) {
2971     state = process_sp->GetState();
2972     if (process_sp->IsAlive() && state != eStateConnected) {
2973       if (state == eStateAttaching)
2974         return Status("process attach is in progress");
2975       return Status("a process is already being debugged");
2976     }
2977   }
2978 
2979   const ModuleSP old_exec_module_sp = GetExecutableModule();
2980 
2981   // If no process info was specified, then use the target executable name as
2982   // the process to attach to by default
2983   if (!attach_info.ProcessInfoSpecified()) {
2984     if (old_exec_module_sp)
2985       attach_info.GetExecutableFile().GetFilename() =
2986           old_exec_module_sp->GetPlatformFileSpec().GetFilename();
2987 
2988     if (!attach_info.ProcessInfoSpecified()) {
2989       return Status("no process specified, create a target with a file, or "
2990                     "specify the --pid or --name");
2991     }
2992   }
2993 
2994   const auto platform_sp =
2995       GetDebugger().GetPlatformList().GetSelectedPlatform();
2996   ListenerSP hijack_listener_sp;
2997   const bool async = attach_info.GetAsync();
2998   if (!async) {
2999     hijack_listener_sp =
3000         Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3001     attach_info.SetHijackListener(hijack_listener_sp);
3002   }
3003 
3004   Status error;
3005   if (state != eStateConnected && platform_sp != nullptr &&
3006       platform_sp->CanDebugProcess()) {
3007     SetPlatform(platform_sp);
3008     process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3009   } else {
3010     if (state != eStateConnected) {
3011       const char *plugin_name = attach_info.GetProcessPluginName();
3012       process_sp =
3013           CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3014                         plugin_name, nullptr);
3015       if (process_sp == nullptr) {
3016         error.SetErrorStringWithFormat(
3017             "failed to create process using plugin %s",
3018             (plugin_name) ? plugin_name : "null");
3019         return error;
3020       }
3021     }
3022     if (hijack_listener_sp)
3023       process_sp->HijackProcessEvents(hijack_listener_sp);
3024     error = process_sp->Attach(attach_info);
3025   }
3026 
3027   if (error.Success() && process_sp) {
3028     if (async) {
3029       process_sp->RestoreProcessEvents();
3030     } else {
3031       state = process_sp->WaitForProcessToStop(
3032           llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3033       process_sp->RestoreProcessEvents();
3034 
3035       if (state != eStateStopped) {
3036         const char *exit_desc = process_sp->GetExitDescription();
3037         if (exit_desc)
3038           error.SetErrorStringWithFormat("%s", exit_desc);
3039         else
3040           error.SetErrorString(
3041               "process did not stop (no such process or permission problem?)");
3042         process_sp->Destroy(false);
3043       }
3044     }
3045   }
3046   return error;
3047 }
3048 
3049 void Target::FinalizeFileActions(ProcessLaunchInfo &info) {
3050   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_PROCESS));
3051 
3052   // Finalize the file actions, and if none were given, default to opening up a
3053   // pseudo terminal
3054   PlatformSP platform_sp = GetPlatform();
3055   const bool default_to_use_pty =
3056       m_platform_sp ? m_platform_sp->IsHost() : false;
3057   LLDB_LOG(
3058       log,
3059       "have platform={0}, platform_sp->IsHost()={1}, default_to_use_pty={2}",
3060       bool(platform_sp),
3061       platform_sp ? (platform_sp->IsHost() ? "true" : "false") : "n/a",
3062       default_to_use_pty);
3063 
3064   // If nothing for stdin or stdout or stderr was specified, then check the
3065   // process for any default settings that were set with "settings set"
3066   if (info.GetFileActionForFD(STDIN_FILENO) == nullptr ||
3067       info.GetFileActionForFD(STDOUT_FILENO) == nullptr ||
3068       info.GetFileActionForFD(STDERR_FILENO) == nullptr) {
3069     LLDB_LOG(log, "at least one of stdin/stdout/stderr was not set, evaluating "
3070                   "default handling");
3071 
3072     if (info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3073       // Do nothing, if we are launching in a remote terminal no file actions
3074       // should be done at all.
3075       return;
3076     }
3077 
3078     if (info.GetFlags().Test(eLaunchFlagDisableSTDIO)) {
3079       LLDB_LOG(log, "eLaunchFlagDisableSTDIO set, adding suppression action "
3080                     "for stdin, stdout and stderr");
3081       info.AppendSuppressFileAction(STDIN_FILENO, true, false);
3082       info.AppendSuppressFileAction(STDOUT_FILENO, false, true);
3083       info.AppendSuppressFileAction(STDERR_FILENO, false, true);
3084     } else {
3085       // Check for any values that might have gotten set with any of: (lldb)
3086       // settings set target.input-path (lldb) settings set target.output-path
3087       // (lldb) settings set target.error-path
3088       FileSpec in_file_spec;
3089       FileSpec out_file_spec;
3090       FileSpec err_file_spec;
3091       // Only override with the target settings if we don't already have an
3092       // action for in, out or error
3093       if (info.GetFileActionForFD(STDIN_FILENO) == nullptr)
3094         in_file_spec = GetStandardInputPath();
3095       if (info.GetFileActionForFD(STDOUT_FILENO) == nullptr)
3096         out_file_spec = GetStandardOutputPath();
3097       if (info.GetFileActionForFD(STDERR_FILENO) == nullptr)
3098         err_file_spec = GetStandardErrorPath();
3099 
3100       LLDB_LOG(log, "target stdin='{0}', target stdout='{1}', stderr='{1}'",
3101                in_file_spec, out_file_spec, err_file_spec);
3102 
3103       if (in_file_spec) {
3104         info.AppendOpenFileAction(STDIN_FILENO, in_file_spec, true, false);
3105         LLDB_LOG(log, "appended stdin open file action for {0}", in_file_spec);
3106       }
3107 
3108       if (out_file_spec) {
3109         info.AppendOpenFileAction(STDOUT_FILENO, out_file_spec, false, true);
3110         LLDB_LOG(log, "appended stdout open file action for {0}",
3111                  out_file_spec);
3112       }
3113 
3114       if (err_file_spec) {
3115         info.AppendOpenFileAction(STDERR_FILENO, err_file_spec, false, true);
3116         LLDB_LOG(log, "appended stderr open file action for {0}",
3117                  err_file_spec);
3118       }
3119 
3120       if (default_to_use_pty &&
3121           (!in_file_spec || !out_file_spec || !err_file_spec)) {
3122         llvm::Error Err = info.SetUpPtyRedirection();
3123         LLDB_LOG_ERROR(log, std::move(Err), "SetUpPtyRedirection failed: {0}");
3124       }
3125     }
3126   }
3127 }
3128 
3129 // Target::StopHook
3130 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3131     : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3132       m_thread_spec_up() {}
3133 
3134 Target::StopHook::StopHook(const StopHook &rhs)
3135     : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3136       m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3137       m_thread_spec_up(), m_active(rhs.m_active),
3138       m_auto_continue(rhs.m_auto_continue) {
3139   if (rhs.m_thread_spec_up)
3140     m_thread_spec_up = std::make_unique<ThreadSpec>(*rhs.m_thread_spec_up);
3141 }
3142 
3143 Target::StopHook::~StopHook() = default;
3144 
3145 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3146   m_specifier_sp.reset(specifier);
3147 }
3148 
3149 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3150   m_thread_spec_up.reset(specifier);
3151 }
3152 
3153 void Target::StopHook::GetDescription(Stream *s,
3154                                       lldb::DescriptionLevel level) const {
3155   unsigned indent_level = s->GetIndentLevel();
3156 
3157   s->SetIndentLevel(indent_level + 2);
3158 
3159   s->Printf("Hook: %" PRIu64 "\n", GetID());
3160   if (m_active)
3161     s->Indent("State: enabled\n");
3162   else
3163     s->Indent("State: disabled\n");
3164 
3165   if (m_auto_continue)
3166     s->Indent("AutoContinue on\n");
3167 
3168   if (m_specifier_sp) {
3169     s->Indent();
3170     s->PutCString("Specifier:\n");
3171     s->SetIndentLevel(indent_level + 4);
3172     m_specifier_sp->GetDescription(s, level);
3173     s->SetIndentLevel(indent_level + 2);
3174   }
3175 
3176   if (m_thread_spec_up) {
3177     StreamString tmp;
3178     s->Indent("Thread:\n");
3179     m_thread_spec_up->GetDescription(&tmp, level);
3180     s->SetIndentLevel(indent_level + 4);
3181     s->Indent(tmp.GetString());
3182     s->PutCString("\n");
3183     s->SetIndentLevel(indent_level + 2);
3184   }
3185 
3186   s->Indent("Commands: \n");
3187   s->SetIndentLevel(indent_level + 4);
3188   uint32_t num_commands = m_commands.GetSize();
3189   for (uint32_t i = 0; i < num_commands; i++) {
3190     s->Indent(m_commands.GetStringAtIndex(i));
3191     s->PutCString("\n");
3192   }
3193   s->SetIndentLevel(indent_level);
3194 }
3195 
3196 static constexpr OptionEnumValueElement g_dynamic_value_types[] = {
3197     {
3198         eNoDynamicValues,
3199         "no-dynamic-values",
3200         "Don't calculate the dynamic type of values",
3201     },
3202     {
3203         eDynamicCanRunTarget,
3204         "run-target",
3205         "Calculate the dynamic type of values "
3206         "even if you have to run the target.",
3207     },
3208     {
3209         eDynamicDontRunTarget,
3210         "no-run-target",
3211         "Calculate the dynamic type of values, but don't run the target.",
3212     },
3213 };
3214 
3215 OptionEnumValues lldb_private::GetDynamicValueTypes() {
3216   return OptionEnumValues(g_dynamic_value_types);
3217 }
3218 
3219 static constexpr OptionEnumValueElement g_inline_breakpoint_enums[] = {
3220     {
3221         eInlineBreakpointsNever,
3222         "never",
3223         "Never look for inline breakpoint locations (fastest). This setting "
3224         "should only be used if you know that no inlining occurs in your"
3225         "programs.",
3226     },
3227     {
3228         eInlineBreakpointsHeaders,
3229         "headers",
3230         "Only check for inline breakpoint locations when setting breakpoints "
3231         "in header files, but not when setting breakpoint in implementation "
3232         "source files (default).",
3233     },
3234     {
3235         eInlineBreakpointsAlways,
3236         "always",
3237         "Always look for inline breakpoint locations when setting file and "
3238         "line breakpoints (slower but most accurate).",
3239     },
3240 };
3241 
3242 enum x86DisassemblyFlavor {
3243   eX86DisFlavorDefault,
3244   eX86DisFlavorIntel,
3245   eX86DisFlavorATT
3246 };
3247 
3248 static constexpr OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3249     {
3250         eX86DisFlavorDefault,
3251         "default",
3252         "Disassembler default (currently att).",
3253     },
3254     {
3255         eX86DisFlavorIntel,
3256         "intel",
3257         "Intel disassembler flavor.",
3258     },
3259     {
3260         eX86DisFlavorATT,
3261         "att",
3262         "AT&T disassembler flavor.",
3263     },
3264 };
3265 
3266 static constexpr OptionEnumValueElement g_hex_immediate_style_values[] = {
3267     {
3268         Disassembler::eHexStyleC,
3269         "c",
3270         "C-style (0xffff).",
3271     },
3272     {
3273         Disassembler::eHexStyleAsm,
3274         "asm",
3275         "Asm-style (0ffffh).",
3276     },
3277 };
3278 
3279 static constexpr OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3280     {
3281         eLoadScriptFromSymFileTrue,
3282         "true",
3283         "Load debug scripts inside symbol files",
3284     },
3285     {
3286         eLoadScriptFromSymFileFalse,
3287         "false",
3288         "Do not load debug scripts inside symbol files.",
3289     },
3290     {
3291         eLoadScriptFromSymFileWarn,
3292         "warn",
3293         "Warn about debug scripts inside symbol files but do not load them.",
3294     },
3295 };
3296 
3297 static constexpr OptionEnumValueElement g_load_cwd_lldbinit_values[] = {
3298     {
3299         eLoadCWDlldbinitTrue,
3300         "true",
3301         "Load .lldbinit files from current directory",
3302     },
3303     {
3304         eLoadCWDlldbinitFalse,
3305         "false",
3306         "Do not load .lldbinit files from current directory",
3307     },
3308     {
3309         eLoadCWDlldbinitWarn,
3310         "warn",
3311         "Warn about loading .lldbinit files from current directory",
3312     },
3313 };
3314 
3315 static constexpr OptionEnumValueElement g_memory_module_load_level_values[] = {
3316     {
3317         eMemoryModuleLoadLevelMinimal,
3318         "minimal",
3319         "Load minimal information when loading modules from memory. Currently "
3320         "this setting loads sections only.",
3321     },
3322     {
3323         eMemoryModuleLoadLevelPartial,
3324         "partial",
3325         "Load partial information when loading modules from memory. Currently "
3326         "this setting loads sections and function bounds.",
3327     },
3328     {
3329         eMemoryModuleLoadLevelComplete,
3330         "complete",
3331         "Load complete information when loading modules from memory. Currently "
3332         "this setting loads sections and all symbols.",
3333     },
3334 };
3335 
3336 #define LLDB_PROPERTIES_target
3337 #include "TargetProperties.inc"
3338 
3339 enum {
3340 #define LLDB_PROPERTIES_target
3341 #include "TargetPropertiesEnum.inc"
3342   ePropertyExperimental,
3343 };
3344 
3345 class TargetOptionValueProperties : public OptionValueProperties {
3346 public:
3347   TargetOptionValueProperties(ConstString name) : OptionValueProperties(name) {}
3348 
3349   // This constructor is used when creating TargetOptionValueProperties when it
3350   // is part of a new lldb_private::Target instance. It will copy all current
3351   // global property values as needed
3352   TargetOptionValueProperties(const TargetPropertiesSP &target_properties_sp)
3353       : OptionValueProperties(*target_properties_sp->GetValueProperties()) {}
3354 
3355   const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3356                                      bool will_modify,
3357                                      uint32_t idx) const override {
3358     // When getting the value for a key from the target options, we will always
3359     // try and grab the setting from the current target if there is one. Else
3360     // we just use the one from this instance.
3361     if (exe_ctx) {
3362       Target *target = exe_ctx->GetTargetPtr();
3363       if (target) {
3364         TargetOptionValueProperties *target_properties =
3365             static_cast<TargetOptionValueProperties *>(
3366                 target->GetValueProperties().get());
3367         if (this != target_properties)
3368           return target_properties->ProtectedGetPropertyAtIndex(idx);
3369       }
3370     }
3371     return ProtectedGetPropertyAtIndex(idx);
3372   }
3373 };
3374 
3375 // TargetProperties
3376 #define LLDB_PROPERTIES_target_experimental
3377 #include "TargetProperties.inc"
3378 
3379 enum {
3380 #define LLDB_PROPERTIES_target_experimental
3381 #include "TargetPropertiesEnum.inc"
3382 };
3383 
3384 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3385 public:
3386   TargetExperimentalOptionValueProperties()
3387       : OptionValueProperties(
3388             ConstString(Properties::GetExperimentalSettingsName())) {}
3389 };
3390 
3391 TargetExperimentalProperties::TargetExperimentalProperties()
3392     : Properties(OptionValuePropertiesSP(
3393           new TargetExperimentalOptionValueProperties())) {
3394   m_collection_sp->Initialize(g_target_experimental_properties);
3395 }
3396 
3397 // TargetProperties
3398 TargetProperties::TargetProperties(Target *target)
3399     : Properties(), m_launch_info(), m_target(target) {
3400   if (target) {
3401     m_collection_sp = std::make_shared<TargetOptionValueProperties>(
3402         Target::GetGlobalProperties());
3403 
3404     // Set callbacks to update launch_info whenever "settins set" updated any
3405     // of these properties
3406     m_collection_sp->SetValueChangedCallback(
3407         ePropertyArg0, [this] { Arg0ValueChangedCallback(); });
3408     m_collection_sp->SetValueChangedCallback(
3409         ePropertyRunArgs, [this] { RunArgsValueChangedCallback(); });
3410     m_collection_sp->SetValueChangedCallback(
3411         ePropertyEnvVars, [this] { EnvVarsValueChangedCallback(); });
3412     m_collection_sp->SetValueChangedCallback(
3413         ePropertyUnsetEnvVars, [this] { EnvVarsValueChangedCallback(); });
3414     m_collection_sp->SetValueChangedCallback(
3415         ePropertyInheritEnv, [this] { EnvVarsValueChangedCallback(); });
3416     m_collection_sp->SetValueChangedCallback(
3417         ePropertyInputPath, [this] { InputPathValueChangedCallback(); });
3418     m_collection_sp->SetValueChangedCallback(
3419         ePropertyOutputPath, [this] { OutputPathValueChangedCallback(); });
3420     m_collection_sp->SetValueChangedCallback(
3421         ePropertyErrorPath, [this] { ErrorPathValueChangedCallback(); });
3422     m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, [this] {
3423       DetachOnErrorValueChangedCallback();
3424     });
3425     m_collection_sp->SetValueChangedCallback(
3426         ePropertyDisableASLR, [this] { DisableASLRValueChangedCallback(); });
3427     m_collection_sp->SetValueChangedCallback(
3428         ePropertyInheritTCC, [this] { InheritTCCValueChangedCallback(); });
3429     m_collection_sp->SetValueChangedCallback(
3430         ePropertyDisableSTDIO, [this] { DisableSTDIOValueChangedCallback(); });
3431 
3432     m_experimental_properties_up =
3433         std::make_unique<TargetExperimentalProperties>();
3434     m_collection_sp->AppendProperty(
3435         ConstString(Properties::GetExperimentalSettingsName()),
3436         ConstString("Experimental settings - setting these won't produce "
3437                     "errors if the setting is not present."),
3438         true, m_experimental_properties_up->GetValueProperties());
3439   } else {
3440     m_collection_sp =
3441         std::make_shared<TargetOptionValueProperties>(ConstString("target"));
3442     m_collection_sp->Initialize(g_target_properties);
3443     m_experimental_properties_up =
3444         std::make_unique<TargetExperimentalProperties>();
3445     m_collection_sp->AppendProperty(
3446         ConstString(Properties::GetExperimentalSettingsName()),
3447         ConstString("Experimental settings - setting these won't produce "
3448                     "errors if the setting is not present."),
3449         true, m_experimental_properties_up->GetValueProperties());
3450     m_collection_sp->AppendProperty(
3451         ConstString("process"), ConstString("Settings specific to processes."),
3452         true, Process::GetGlobalProperties()->GetValueProperties());
3453   }
3454 }
3455 
3456 TargetProperties::~TargetProperties() = default;
3457 
3458 void TargetProperties::UpdateLaunchInfoFromProperties() {
3459   Arg0ValueChangedCallback();
3460   RunArgsValueChangedCallback();
3461   EnvVarsValueChangedCallback();
3462   InputPathValueChangedCallback();
3463   OutputPathValueChangedCallback();
3464   ErrorPathValueChangedCallback();
3465   DetachOnErrorValueChangedCallback();
3466   DisableASLRValueChangedCallback();
3467   InheritTCCValueChangedCallback();
3468   DisableSTDIOValueChangedCallback();
3469 }
3470 
3471 bool TargetProperties::GetInjectLocalVariables(
3472     ExecutionContext *exe_ctx) const {
3473   const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3474       exe_ctx, false, ePropertyExperimental);
3475   OptionValueProperties *exp_values =
3476       exp_property->GetValue()->GetAsProperties();
3477   if (exp_values)
3478     return exp_values->GetPropertyAtIndexAsBoolean(
3479         exe_ctx, ePropertyInjectLocalVars, true);
3480   else
3481     return true;
3482 }
3483 
3484 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3485                                                bool b) {
3486   const Property *exp_property =
3487       m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3488   OptionValueProperties *exp_values =
3489       exp_property->GetValue()->GetAsProperties();
3490   if (exp_values)
3491     exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3492                                             true);
3493 }
3494 
3495 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3496   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3497       nullptr, ePropertyDefaultArch);
3498   if (value)
3499     return value->GetCurrentValue();
3500   return ArchSpec();
3501 }
3502 
3503 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3504   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3505       nullptr, ePropertyDefaultArch);
3506   if (value)
3507     return value->SetCurrentValue(arch, true);
3508 }
3509 
3510 bool TargetProperties::GetMoveToNearestCode() const {
3511   const uint32_t idx = ePropertyMoveToNearestCode;
3512   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3513       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3514 }
3515 
3516 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3517   const uint32_t idx = ePropertyPreferDynamic;
3518   return (lldb::DynamicValueType)
3519       m_collection_sp->GetPropertyAtIndexAsEnumeration(
3520           nullptr, idx, g_target_properties[idx].default_uint_value);
3521 }
3522 
3523 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3524   const uint32_t idx = ePropertyPreferDynamic;
3525   return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3526 }
3527 
3528 bool TargetProperties::GetPreloadSymbols() const {
3529   const uint32_t idx = ePropertyPreloadSymbols;
3530   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3531       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3532 }
3533 
3534 void TargetProperties::SetPreloadSymbols(bool b) {
3535   const uint32_t idx = ePropertyPreloadSymbols;
3536   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3537 }
3538 
3539 bool TargetProperties::GetDisableASLR() const {
3540   const uint32_t idx = ePropertyDisableASLR;
3541   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3542       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3543 }
3544 
3545 void TargetProperties::SetDisableASLR(bool b) {
3546   const uint32_t idx = ePropertyDisableASLR;
3547   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3548 }
3549 
3550 bool TargetProperties::GetInheritTCC() const {
3551   const uint32_t idx = ePropertyInheritTCC;
3552   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3553       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3554 }
3555 
3556 void TargetProperties::SetInheritTCC(bool b) {
3557   const uint32_t idx = ePropertyInheritTCC;
3558   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3559 }
3560 
3561 bool TargetProperties::GetDetachOnError() const {
3562   const uint32_t idx = ePropertyDetachOnError;
3563   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3564       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3565 }
3566 
3567 void TargetProperties::SetDetachOnError(bool b) {
3568   const uint32_t idx = ePropertyDetachOnError;
3569   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3570 }
3571 
3572 bool TargetProperties::GetDisableSTDIO() const {
3573   const uint32_t idx = ePropertyDisableSTDIO;
3574   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3575       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3576 }
3577 
3578 void TargetProperties::SetDisableSTDIO(bool b) {
3579   const uint32_t idx = ePropertyDisableSTDIO;
3580   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3581 }
3582 
3583 const char *TargetProperties::GetDisassemblyFlavor() const {
3584   const uint32_t idx = ePropertyDisassemblyFlavor;
3585   const char *return_value;
3586 
3587   x86DisassemblyFlavor flavor_value =
3588       (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3589           nullptr, idx, g_target_properties[idx].default_uint_value);
3590   return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3591   return return_value;
3592 }
3593 
3594 InlineStrategy TargetProperties::GetInlineStrategy() const {
3595   const uint32_t idx = ePropertyInlineStrategy;
3596   return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3597       nullptr, idx, g_target_properties[idx].default_uint_value);
3598 }
3599 
3600 llvm::StringRef TargetProperties::GetArg0() const {
3601   const uint32_t idx = ePropertyArg0;
3602   return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx,
3603                                                      llvm::StringRef());
3604 }
3605 
3606 void TargetProperties::SetArg0(llvm::StringRef arg) {
3607   const uint32_t idx = ePropertyArg0;
3608   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3609   m_launch_info.SetArg0(arg);
3610 }
3611 
3612 bool TargetProperties::GetRunArguments(Args &args) const {
3613   const uint32_t idx = ePropertyRunArgs;
3614   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3615 }
3616 
3617 void TargetProperties::SetRunArguments(const Args &args) {
3618   const uint32_t idx = ePropertyRunArgs;
3619   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3620   m_launch_info.GetArguments() = args;
3621 }
3622 
3623 Environment TargetProperties::ComputeEnvironment() const {
3624   Environment env;
3625 
3626   if (m_target &&
3627       m_collection_sp->GetPropertyAtIndexAsBoolean(
3628           nullptr, ePropertyInheritEnv,
3629           g_target_properties[ePropertyInheritEnv].default_uint_value != 0)) {
3630     if (auto platform_sp = m_target->GetPlatform()) {
3631       Environment platform_env = platform_sp->GetEnvironment();
3632       for (const auto &KV : platform_env)
3633         env[KV.first()] = KV.second;
3634     }
3635   }
3636 
3637   Args property_unset_env;
3638   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyUnsetEnvVars,
3639                                             property_unset_env);
3640   for (const auto &var : property_unset_env)
3641     env.erase(var.ref());
3642 
3643   Args property_env;
3644   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, ePropertyEnvVars,
3645                                             property_env);
3646   for (const auto &KV : Environment(property_env))
3647     env[KV.first()] = KV.second;
3648 
3649   return env;
3650 }
3651 
3652 Environment TargetProperties::GetEnvironment() const {
3653   return ComputeEnvironment();
3654 }
3655 
3656 void TargetProperties::SetEnvironment(Environment env) {
3657   // TODO: Get rid of the Args intermediate step
3658   const uint32_t idx = ePropertyEnvVars;
3659   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3660 }
3661 
3662 bool TargetProperties::GetSkipPrologue() const {
3663   const uint32_t idx = ePropertySkipPrologue;
3664   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3665       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3666 }
3667 
3668 PathMappingList &TargetProperties::GetSourcePathMap() const {
3669   const uint32_t idx = ePropertySourceMap;
3670   OptionValuePathMappings *option_value =
3671       m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3672                                                                    false, idx);
3673   assert(option_value);
3674   return option_value->GetCurrentValue();
3675 }
3676 
3677 void TargetProperties::AppendExecutableSearchPaths(const FileSpec &dir) {
3678   const uint32_t idx = ePropertyExecutableSearchPaths;
3679   OptionValueFileSpecList *option_value =
3680       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3681                                                                    false, idx);
3682   assert(option_value);
3683   option_value->AppendCurrentValue(dir);
3684 }
3685 
3686 FileSpecList TargetProperties::GetExecutableSearchPaths() {
3687   const uint32_t idx = ePropertyExecutableSearchPaths;
3688   const OptionValueFileSpecList *option_value =
3689       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3690                                                                    false, idx);
3691   assert(option_value);
3692   return option_value->GetCurrentValue();
3693 }
3694 
3695 FileSpecList TargetProperties::GetDebugFileSearchPaths() {
3696   const uint32_t idx = ePropertyDebugFileSearchPaths;
3697   const OptionValueFileSpecList *option_value =
3698       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3699                                                                    false, idx);
3700   assert(option_value);
3701   return option_value->GetCurrentValue();
3702 }
3703 
3704 FileSpecList TargetProperties::GetClangModuleSearchPaths() {
3705   const uint32_t idx = ePropertyClangModuleSearchPaths;
3706   const OptionValueFileSpecList *option_value =
3707       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3708                                                                    false, idx);
3709   assert(option_value);
3710   return option_value->GetCurrentValue();
3711 }
3712 
3713 bool TargetProperties::GetEnableAutoImportClangModules() const {
3714   const uint32_t idx = ePropertyAutoImportClangModules;
3715   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3716       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3717 }
3718 
3719 bool TargetProperties::GetEnableImportStdModule() const {
3720   const uint32_t idx = ePropertyImportStdModule;
3721   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3722       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3723 }
3724 
3725 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3726   const uint32_t idx = ePropertyAutoApplyFixIts;
3727   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3728       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3729 }
3730 
3731 uint64_t TargetProperties::GetNumberOfRetriesWithFixits() const {
3732   const uint32_t idx = ePropertyRetriesWithFixIts;
3733   return m_collection_sp->GetPropertyAtIndexAsUInt64(
3734       nullptr, idx, g_target_properties[idx].default_uint_value);
3735 }
3736 
3737 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3738   const uint32_t idx = ePropertyNotifyAboutFixIts;
3739   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3740       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3741 }
3742 
3743 bool TargetProperties::GetEnableSaveObjects() const {
3744   const uint32_t idx = ePropertySaveObjects;
3745   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3746       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3747 }
3748 
3749 bool TargetProperties::GetEnableSyntheticValue() const {
3750   const uint32_t idx = ePropertyEnableSynthetic;
3751   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3752       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3753 }
3754 
3755 uint32_t TargetProperties::GetMaxZeroPaddingInFloatFormat() const {
3756   const uint32_t idx = ePropertyMaxZeroPaddingInFloatFormat;
3757   return m_collection_sp->GetPropertyAtIndexAsUInt64(
3758       nullptr, idx, g_target_properties[idx].default_uint_value);
3759 }
3760 
3761 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3762   const uint32_t idx = ePropertyMaxChildrenCount;
3763   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3764       nullptr, idx, g_target_properties[idx].default_uint_value);
3765 }
3766 
3767 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3768   const uint32_t idx = ePropertyMaxSummaryLength;
3769   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3770       nullptr, idx, g_target_properties[idx].default_uint_value);
3771 }
3772 
3773 uint32_t TargetProperties::GetMaximumMemReadSize() const {
3774   const uint32_t idx = ePropertyMaxMemReadSize;
3775   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3776       nullptr, idx, g_target_properties[idx].default_uint_value);
3777 }
3778 
3779 FileSpec TargetProperties::GetStandardInputPath() const {
3780   const uint32_t idx = ePropertyInputPath;
3781   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3782 }
3783 
3784 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
3785   const uint32_t idx = ePropertyInputPath;
3786   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3787 }
3788 
3789 FileSpec TargetProperties::GetStandardOutputPath() const {
3790   const uint32_t idx = ePropertyOutputPath;
3791   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3792 }
3793 
3794 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
3795   const uint32_t idx = ePropertyOutputPath;
3796   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3797 }
3798 
3799 FileSpec TargetProperties::GetStandardErrorPath() const {
3800   const uint32_t idx = ePropertyErrorPath;
3801   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3802 }
3803 
3804 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
3805   const uint32_t idx = ePropertyErrorPath;
3806   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
3807 }
3808 
3809 LanguageType TargetProperties::GetLanguage() const {
3810   OptionValueLanguage *value =
3811       m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
3812           nullptr, ePropertyLanguage);
3813   if (value)
3814     return value->GetCurrentValue();
3815   return LanguageType();
3816 }
3817 
3818 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
3819   const uint32_t idx = ePropertyExprPrefix;
3820   OptionValueFileSpec *file =
3821       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
3822                                                                idx);
3823   if (file) {
3824     DataBufferSP data_sp(file->GetFileContents());
3825     if (data_sp)
3826       return llvm::StringRef(
3827           reinterpret_cast<const char *>(data_sp->GetBytes()),
3828           data_sp->GetByteSize());
3829   }
3830   return "";
3831 }
3832 
3833 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
3834   const uint32_t idx = ePropertyBreakpointUseAvoidList;
3835   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3836       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3837 }
3838 
3839 bool TargetProperties::GetUseHexImmediates() const {
3840   const uint32_t idx = ePropertyUseHexImmediates;
3841   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3842       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3843 }
3844 
3845 bool TargetProperties::GetUseFastStepping() const {
3846   const uint32_t idx = ePropertyUseFastStepping;
3847   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3848       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3849 }
3850 
3851 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
3852   const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3853   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3854       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3855 }
3856 
3857 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
3858   const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3859   return (LoadScriptFromSymFile)
3860       m_collection_sp->GetPropertyAtIndexAsEnumeration(
3861           nullptr, idx, g_target_properties[idx].default_uint_value);
3862 }
3863 
3864 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
3865   const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3866   return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3867       nullptr, idx, g_target_properties[idx].default_uint_value);
3868 }
3869 
3870 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
3871   const uint32_t idx = ePropertyHexImmediateStyle;
3872   return (Disassembler::HexImmediateStyle)
3873       m_collection_sp->GetPropertyAtIndexAsEnumeration(
3874           nullptr, idx, g_target_properties[idx].default_uint_value);
3875 }
3876 
3877 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
3878   const uint32_t idx = ePropertyMemoryModuleLoadLevel;
3879   return (MemoryModuleLoadLevel)
3880       m_collection_sp->GetPropertyAtIndexAsEnumeration(
3881           nullptr, idx, g_target_properties[idx].default_uint_value);
3882 }
3883 
3884 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
3885   const uint32_t idx = ePropertyTrapHandlerNames;
3886   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3887 }
3888 
3889 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
3890   const uint32_t idx = ePropertyTrapHandlerNames;
3891   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3892 }
3893 
3894 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
3895   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3896   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3897 }
3898 
3899 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
3900   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
3901   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3902 }
3903 
3904 bool TargetProperties::GetDisplayRecognizedArguments() const {
3905   const uint32_t idx = ePropertyDisplayRecognizedArguments;
3906   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3907 }
3908 
3909 void TargetProperties::SetDisplayRecognizedArguments(bool b) {
3910   const uint32_t idx = ePropertyDisplayRecognizedArguments;
3911   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3912 }
3913 
3914 bool TargetProperties::GetNonStopModeEnabled() const {
3915   const uint32_t idx = ePropertyNonStopModeEnabled;
3916   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
3917 }
3918 
3919 void TargetProperties::SetNonStopModeEnabled(bool b) {
3920   const uint32_t idx = ePropertyNonStopModeEnabled;
3921   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3922 }
3923 
3924 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
3925   m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
3926   return m_launch_info;
3927 }
3928 
3929 void TargetProperties::SetProcessLaunchInfo(
3930     const ProcessLaunchInfo &launch_info) {
3931   m_launch_info = launch_info;
3932   SetArg0(launch_info.GetArg0());
3933   SetRunArguments(launch_info.GetArguments());
3934   SetEnvironment(launch_info.GetEnvironment());
3935   const FileAction *input_file_action =
3936       launch_info.GetFileActionForFD(STDIN_FILENO);
3937   if (input_file_action) {
3938     SetStandardInputPath(input_file_action->GetPath());
3939   }
3940   const FileAction *output_file_action =
3941       launch_info.GetFileActionForFD(STDOUT_FILENO);
3942   if (output_file_action) {
3943     SetStandardOutputPath(output_file_action->GetPath());
3944   }
3945   const FileAction *error_file_action =
3946       launch_info.GetFileActionForFD(STDERR_FILENO);
3947   if (error_file_action) {
3948     SetStandardErrorPath(error_file_action->GetPath());
3949   }
3950   SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
3951   SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
3952   SetInheritTCC(
3953       launch_info.GetFlags().Test(lldb::eLaunchFlagInheritTCCFromParent));
3954   SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
3955 }
3956 
3957 bool TargetProperties::GetRequireHardwareBreakpoints() const {
3958   const uint32_t idx = ePropertyRequireHardwareBreakpoints;
3959   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3960       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3961 }
3962 
3963 void TargetProperties::SetRequireHardwareBreakpoints(bool b) {
3964   const uint32_t idx = ePropertyRequireHardwareBreakpoints;
3965   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3966 }
3967 
3968 bool TargetProperties::GetAutoInstallMainExecutable() const {
3969   const uint32_t idx = ePropertyAutoInstallMainExecutable;
3970   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3971       nullptr, idx, g_target_properties[idx].default_uint_value != 0);
3972 }
3973 
3974 void TargetProperties::Arg0ValueChangedCallback() {
3975   m_launch_info.SetArg0(GetArg0());
3976 }
3977 
3978 void TargetProperties::RunArgsValueChangedCallback() {
3979   Args args;
3980   if (GetRunArguments(args))
3981     m_launch_info.GetArguments() = args;
3982 }
3983 
3984 void TargetProperties::EnvVarsValueChangedCallback() {
3985   m_launch_info.GetEnvironment() = ComputeEnvironment();
3986 }
3987 
3988 void TargetProperties::InputPathValueChangedCallback() {
3989   m_launch_info.AppendOpenFileAction(STDIN_FILENO, GetStandardInputPath(), true,
3990                                      false);
3991 }
3992 
3993 void TargetProperties::OutputPathValueChangedCallback() {
3994   m_launch_info.AppendOpenFileAction(STDOUT_FILENO, GetStandardOutputPath(),
3995                                      false, true);
3996 }
3997 
3998 void TargetProperties::ErrorPathValueChangedCallback() {
3999   m_launch_info.AppendOpenFileAction(STDERR_FILENO, GetStandardErrorPath(),
4000                                      false, true);
4001 }
4002 
4003 void TargetProperties::DetachOnErrorValueChangedCallback() {
4004   if (GetDetachOnError())
4005     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4006   else
4007     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4008 }
4009 
4010 void TargetProperties::DisableASLRValueChangedCallback() {
4011   if (GetDisableASLR())
4012     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4013   else
4014     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4015 }
4016 
4017 void TargetProperties::InheritTCCValueChangedCallback() {
4018   if (GetInheritTCC())
4019     m_launch_info.GetFlags().Set(lldb::eLaunchFlagInheritTCCFromParent);
4020   else
4021     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagInheritTCCFromParent);
4022 }
4023 
4024 void TargetProperties::DisableSTDIOValueChangedCallback() {
4025   if (GetDisableSTDIO())
4026     m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4027   else
4028     m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4029 }
4030 
4031 // Target::TargetEventData
4032 
4033 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4034     : EventData(), m_target_sp(target_sp), m_module_list() {}
4035 
4036 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4037                                          const ModuleList &module_list)
4038     : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4039 
4040 Target::TargetEventData::~TargetEventData() = default;
4041 
4042 ConstString Target::TargetEventData::GetFlavorString() {
4043   static ConstString g_flavor("Target::TargetEventData");
4044   return g_flavor;
4045 }
4046 
4047 void Target::TargetEventData::Dump(Stream *s) const {
4048   for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4049     if (i != 0)
4050       *s << ", ";
4051     m_module_list.GetModuleAtIndex(i)->GetDescription(
4052         s->AsRawOstream(), lldb::eDescriptionLevelBrief);
4053   }
4054 }
4055 
4056 const Target::TargetEventData *
4057 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4058   if (event_ptr) {
4059     const EventData *event_data = event_ptr->GetData();
4060     if (event_data &&
4061         event_data->GetFlavor() == TargetEventData::GetFlavorString())
4062       return static_cast<const TargetEventData *>(event_ptr->GetData());
4063   }
4064   return nullptr;
4065 }
4066 
4067 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4068   TargetSP target_sp;
4069   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4070   if (event_data)
4071     target_sp = event_data->m_target_sp;
4072   return target_sp;
4073 }
4074 
4075 ModuleList
4076 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4077   ModuleList module_list;
4078   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4079   if (event_data)
4080     module_list = event_data->m_module_list;
4081   return module_list;
4082 }
4083 
4084 std::recursive_mutex &Target::GetAPIMutex() {
4085   if (GetProcessSP() && GetProcessSP()->CurrentThreadIsPrivateStateThread())
4086     return m_private_mutex;
4087   else
4088     return m_mutex;
4089 }
4090