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