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