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