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