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