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