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