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