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