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