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