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     llvm::StringRef prefix = GetExpressionPrefixContents();
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   // Somebody might have restarted the process:
2684   if (m_process_sp->GetState() != eStateStopped)
2685     return;
2686 
2687   // <rdar://problem/12027563> make sure we check that we are not stopped
2688   // because of us running a user expression
2689   // since in that case we do not want to run the stop-hooks
2690   if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2691     return;
2692 
2693   if (m_stop_hooks.empty())
2694     return;
2695 
2696   StopHookCollection::iterator pos, end = m_stop_hooks.end();
2697 
2698   // If there aren't any active stop hooks, don't bother either:
2699   bool any_active_hooks = false;
2700   for (pos = m_stop_hooks.begin(); pos != end; pos++) {
2701     if ((*pos).second->IsActive()) {
2702       any_active_hooks = true;
2703       break;
2704     }
2705   }
2706   if (!any_active_hooks)
2707     return;
2708 
2709   CommandReturnObject result;
2710 
2711   std::vector<ExecutionContext> exc_ctx_with_reasons;
2712   std::vector<SymbolContext> sym_ctx_with_reasons;
2713 
2714   ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2715   size_t num_threads = cur_threadlist.GetSize();
2716   for (size_t i = 0; i < num_threads; i++) {
2717     lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex(i);
2718     if (cur_thread_sp->ThreadStoppedForAReason()) {
2719       lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2720       exc_ctx_with_reasons.push_back(ExecutionContext(
2721           m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2722       sym_ctx_with_reasons.push_back(
2723           cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2724     }
2725   }
2726 
2727   // If no threads stopped for a reason, don't run the stop-hooks.
2728   size_t num_exe_ctx = exc_ctx_with_reasons.size();
2729   if (num_exe_ctx == 0)
2730     return;
2731 
2732   result.SetImmediateOutputStream(m_debugger.GetAsyncOutputStream());
2733   result.SetImmediateErrorStream(m_debugger.GetAsyncErrorStream());
2734 
2735   bool keep_going = true;
2736   bool hooks_ran = false;
2737   bool print_hook_header = (m_stop_hooks.size() != 1);
2738   bool print_thread_header = (num_exe_ctx != 1);
2739 
2740   for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++) {
2741     // result.Clear();
2742     StopHookSP cur_hook_sp = (*pos).second;
2743     if (!cur_hook_sp->IsActive())
2744       continue;
2745 
2746     bool any_thread_matched = false;
2747     for (size_t i = 0; keep_going && i < num_exe_ctx; i++) {
2748       if ((cur_hook_sp->GetSpecifier() == nullptr ||
2749            cur_hook_sp->GetSpecifier()->SymbolContextMatches(
2750                sym_ctx_with_reasons[i])) &&
2751           (cur_hook_sp->GetThreadSpecifier() == nullptr ||
2752            cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(
2753                exc_ctx_with_reasons[i].GetThreadRef()))) {
2754         if (!hooks_ran) {
2755           hooks_ran = true;
2756         }
2757         if (print_hook_header && !any_thread_matched) {
2758           const char *cmd =
2759               (cur_hook_sp->GetCommands().GetSize() == 1
2760                    ? cur_hook_sp->GetCommands().GetStringAtIndex(0)
2761                    : nullptr);
2762           if (cmd)
2763             result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n",
2764                                            cur_hook_sp->GetID(), cmd);
2765           else
2766             result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n",
2767                                            cur_hook_sp->GetID());
2768           any_thread_matched = true;
2769         }
2770 
2771         if (print_thread_header)
2772           result.AppendMessageWithFormat(
2773               "-- Thread %d\n",
2774               exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2775 
2776         CommandInterpreterRunOptions options;
2777         options.SetStopOnContinue(true);
2778         options.SetStopOnError(true);
2779         options.SetEchoCommands(false);
2780         options.SetPrintResults(true);
2781         options.SetAddToHistory(false);
2782 
2783         GetDebugger().GetCommandInterpreter().HandleCommands(
2784             cur_hook_sp->GetCommands(), &exc_ctx_with_reasons[i], options,
2785             result);
2786 
2787         // If the command started the target going again, we should bag out of
2788         // running the stop hooks.
2789         if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2790             (result.GetStatus() == eReturnStatusSuccessContinuingResult)) {
2791           // But only complain if there were more stop hooks to do:
2792           StopHookCollection::iterator tmp = pos;
2793           if (++tmp != end)
2794             result.AppendMessageWithFormat("\nAborting stop hooks, hook %" PRIu64
2795                                            " set the program running.\n",
2796                                            cur_hook_sp->GetID());
2797           keep_going = false;
2798         }
2799       }
2800     }
2801   }
2802 
2803   result.GetImmediateOutputStream()->Flush();
2804   result.GetImmediateErrorStream()->Flush();
2805 }
2806 
2807 const TargetPropertiesSP &Target::GetGlobalProperties() {
2808   // NOTE: intentional leak so we don't crash if global destructor chain gets
2809   // called as other threads still use the result of this function
2810   static TargetPropertiesSP *g_settings_sp_ptr =
2811       new TargetPropertiesSP(new TargetProperties(nullptr));
2812   return *g_settings_sp_ptr;
2813 }
2814 
2815 Status Target::Install(ProcessLaunchInfo *launch_info) {
2816   Status error;
2817   PlatformSP platform_sp(GetPlatform());
2818   if (platform_sp) {
2819     if (platform_sp->IsRemote()) {
2820       if (platform_sp->IsConnected()) {
2821         // Install all files that have an install path, and always install the
2822         // main executable when connected to a remote platform
2823         const ModuleList &modules = GetImages();
2824         const size_t num_images = modules.GetSize();
2825         for (size_t idx = 0; idx < num_images; ++idx) {
2826           ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2827           if (module_sp) {
2828             const bool is_main_executable = module_sp == GetExecutableModule();
2829             FileSpec local_file(module_sp->GetFileSpec());
2830             if (local_file) {
2831               FileSpec remote_file(module_sp->GetRemoteInstallFileSpec());
2832               if (!remote_file) {
2833                 if (is_main_executable) // TODO: add setting for always
2834                                         // installing main executable???
2835                 {
2836                   // Always install the main executable
2837                   remote_file = platform_sp->GetRemoteWorkingDirectory();
2838                   remote_file.AppendPathComponent(
2839                       module_sp->GetFileSpec().GetFilename().GetCString());
2840                 }
2841               }
2842               if (remote_file) {
2843                 error = platform_sp->Install(local_file, remote_file);
2844                 if (error.Success()) {
2845                   module_sp->SetPlatformFileSpec(remote_file);
2846                   if (is_main_executable) {
2847                     platform_sp->SetFilePermissions(remote_file, 0700);
2848                     if (launch_info)
2849                       launch_info->SetExecutableFile(remote_file, false);
2850                   }
2851                 } else
2852                   break;
2853               }
2854             }
2855           }
2856         }
2857       }
2858     }
2859   }
2860   return error;
2861 }
2862 
2863 bool Target::ResolveLoadAddress(addr_t load_addr, Address &so_addr,
2864                                 uint32_t stop_id) {
2865   return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2866 }
2867 
2868 bool Target::ResolveFileAddress(lldb::addr_t file_addr,
2869                                 Address &resolved_addr) {
2870   return m_images.ResolveFileAddress(file_addr, resolved_addr);
2871 }
2872 
2873 bool Target::SetSectionLoadAddress(const SectionSP &section_sp,
2874                                    addr_t new_section_load_addr,
2875                                    bool warn_multiple) {
2876   const addr_t old_section_load_addr =
2877       m_section_load_history.GetSectionLoadAddress(
2878           SectionLoadHistory::eStopIDNow, section_sp);
2879   if (old_section_load_addr != new_section_load_addr) {
2880     uint32_t stop_id = 0;
2881     ProcessSP process_sp(GetProcessSP());
2882     if (process_sp)
2883       stop_id = process_sp->GetStopID();
2884     else
2885       stop_id = m_section_load_history.GetLastStopID();
2886     if (m_section_load_history.SetSectionLoadAddress(
2887             stop_id, section_sp, new_section_load_addr, warn_multiple))
2888       return true; // Return true if the section load address was changed...
2889   }
2890   return false; // Return false to indicate nothing changed
2891 }
2892 
2893 size_t Target::UnloadModuleSections(const ModuleList &module_list) {
2894   size_t section_unload_count = 0;
2895   size_t num_modules = module_list.GetSize();
2896   for (size_t i = 0; i < num_modules; ++i) {
2897     section_unload_count +=
2898         UnloadModuleSections(module_list.GetModuleAtIndex(i));
2899   }
2900   return section_unload_count;
2901 }
2902 
2903 size_t Target::UnloadModuleSections(const lldb::ModuleSP &module_sp) {
2904   uint32_t stop_id = 0;
2905   ProcessSP process_sp(GetProcessSP());
2906   if (process_sp)
2907     stop_id = process_sp->GetStopID();
2908   else
2909     stop_id = m_section_load_history.GetLastStopID();
2910   SectionList *sections = module_sp->GetSectionList();
2911   size_t section_unload_count = 0;
2912   if (sections) {
2913     const uint32_t num_sections = sections->GetNumSections(0);
2914     for (uint32_t i = 0; i < num_sections; ++i) {
2915       section_unload_count += m_section_load_history.SetSectionUnloaded(
2916           stop_id, sections->GetSectionAtIndex(i));
2917     }
2918   }
2919   return section_unload_count;
2920 }
2921 
2922 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp) {
2923   uint32_t stop_id = 0;
2924   ProcessSP process_sp(GetProcessSP());
2925   if (process_sp)
2926     stop_id = process_sp->GetStopID();
2927   else
2928     stop_id = m_section_load_history.GetLastStopID();
2929   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp);
2930 }
2931 
2932 bool Target::SetSectionUnloaded(const lldb::SectionSP &section_sp,
2933                                 addr_t load_addr) {
2934   uint32_t stop_id = 0;
2935   ProcessSP process_sp(GetProcessSP());
2936   if (process_sp)
2937     stop_id = process_sp->GetStopID();
2938   else
2939     stop_id = m_section_load_history.GetLastStopID();
2940   return m_section_load_history.SetSectionUnloaded(stop_id, section_sp,
2941                                                    load_addr);
2942 }
2943 
2944 void Target::ClearAllLoadedSections() { m_section_load_history.Clear(); }
2945 
2946 Status Target::Launch(ProcessLaunchInfo &launch_info, Stream *stream) {
2947   Status error;
2948   Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_TARGET));
2949 
2950   if (log)
2951     log->Printf("Target::%s() called for %s", __FUNCTION__,
2952                 launch_info.GetExecutableFile().GetPath().c_str());
2953 
2954   StateType state = eStateInvalid;
2955 
2956   // Scope to temporarily get the process state in case someone has manually
2957   // remotely connected already to a process and we can skip the platform
2958   // launching.
2959   {
2960     ProcessSP process_sp(GetProcessSP());
2961 
2962     if (process_sp) {
2963       state = process_sp->GetState();
2964       if (log)
2965         log->Printf(
2966             "Target::%s the process exists, and its current state is %s",
2967             __FUNCTION__, StateAsCString(state));
2968     } else {
2969       if (log)
2970         log->Printf("Target::%s the process instance doesn't currently exist.",
2971                     __FUNCTION__);
2972     }
2973   }
2974 
2975   launch_info.GetFlags().Set(eLaunchFlagDebug);
2976 
2977   // Get the value of synchronous execution here.  If you wait till after you
2978   // have started to
2979   // run, then you could have hit a breakpoint, whose command might switch the
2980   // value, and
2981   // then you'll pick up that incorrect value.
2982   Debugger &debugger = GetDebugger();
2983   const bool synchronous_execution =
2984       debugger.GetCommandInterpreter().GetSynchronous();
2985 
2986   PlatformSP platform_sp(GetPlatform());
2987 
2988   // Finalize the file actions, and if none were given, default to opening
2989   // up a pseudo terminal
2990   const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
2991   if (log)
2992     log->Printf("Target::%s have platform=%s, platform_sp->IsHost()=%s, "
2993                 "default_to_use_pty=%s",
2994                 __FUNCTION__, platform_sp ? "true" : "false",
2995                 platform_sp ? (platform_sp->IsHost() ? "true" : "false")
2996                             : "n/a",
2997                 default_to_use_pty ? "true" : "false");
2998 
2999   launch_info.FinalizeFileActions(this, default_to_use_pty);
3000 
3001   if (state == eStateConnected) {
3002     if (launch_info.GetFlags().Test(eLaunchFlagLaunchInTTY)) {
3003       error.SetErrorString(
3004           "can't launch in tty when launching through a remote connection");
3005       return error;
3006     }
3007   }
3008 
3009   if (!launch_info.GetArchitecture().IsValid())
3010     launch_info.GetArchitecture() = GetArchitecture();
3011 
3012   // If we're not already connected to the process, and if we have a platform
3013   // that can launch a process for debugging, go ahead and do that here.
3014   if (state != eStateConnected && platform_sp &&
3015       platform_sp->CanDebugProcess()) {
3016     if (log)
3017       log->Printf("Target::%s asking the platform to debug the process",
3018                   __FUNCTION__);
3019 
3020     // Get a weak pointer to the previous process if we have one
3021     ProcessWP process_wp;
3022     if (m_process_sp)
3023       process_wp = m_process_sp;
3024     m_process_sp =
3025         GetPlatform()->DebugProcess(launch_info, debugger, this, error);
3026 
3027     // Cleanup the old process since someone might still have a strong
3028     // reference to this process and we would like to allow it to cleanup
3029     // as much as it can without the object being destroyed. We try to
3030     // lock the shared pointer and if that works, then someone else still
3031     // has a strong reference to the process.
3032 
3033     ProcessSP old_process_sp(process_wp.lock());
3034     if (old_process_sp)
3035       old_process_sp->Finalize();
3036   } else {
3037     if (log)
3038       log->Printf("Target::%s the platform doesn't know how to debug a "
3039                   "process, getting a process plugin to do this for us.",
3040                   __FUNCTION__);
3041 
3042     if (state == eStateConnected) {
3043       assert(m_process_sp);
3044     } else {
3045       // Use a Process plugin to construct the process.
3046       const char *plugin_name = launch_info.GetProcessPluginName();
3047       CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name,
3048                     nullptr);
3049     }
3050 
3051     // Since we didn't have a platform launch the process, launch it here.
3052     if (m_process_sp)
3053       error = m_process_sp->Launch(launch_info);
3054   }
3055 
3056   if (!m_process_sp) {
3057     if (error.Success())
3058       error.SetErrorString("failed to launch or debug process");
3059     return error;
3060   }
3061 
3062   if (error.Success()) {
3063     if (synchronous_execution ||
3064         !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
3065       ListenerSP hijack_listener_sp(launch_info.GetHijackListener());
3066       if (!hijack_listener_sp) {
3067         hijack_listener_sp =
3068             Listener::MakeListener("lldb.Target.Launch.hijack");
3069         launch_info.SetHijackListener(hijack_listener_sp);
3070         m_process_sp->HijackProcessEvents(hijack_listener_sp);
3071       }
3072 
3073       StateType state = m_process_sp->WaitForProcessToStop(
3074           llvm::None, nullptr, false, hijack_listener_sp, nullptr);
3075 
3076       if (state == eStateStopped) {
3077         if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry)) {
3078           if (synchronous_execution) {
3079             error = m_process_sp->PrivateResume();
3080             if (error.Success()) {
3081               state = m_process_sp->WaitForProcessToStop(
3082                   llvm::None, nullptr, true, hijack_listener_sp, stream);
3083               const bool must_be_alive =
3084                   false; // eStateExited is ok, so this must be false
3085               if (!StateIsStoppedState(state, must_be_alive)) {
3086                 error.SetErrorStringWithFormat("process isn't stopped: %s",
3087                                                StateAsCString(state));
3088               }
3089             }
3090           } else {
3091             m_process_sp->RestoreProcessEvents();
3092             error = m_process_sp->PrivateResume();
3093           }
3094           if (!error.Success()) {
3095             Status error2;
3096             error2.SetErrorStringWithFormat(
3097                 "process resume at entry point failed: %s", error.AsCString());
3098             error = error2;
3099           }
3100         }
3101       } else if (state == eStateExited) {
3102         bool with_shell = !!launch_info.GetShell();
3103         const int exit_status = m_process_sp->GetExitStatus();
3104         const char *exit_desc = m_process_sp->GetExitDescription();
3105 #define LAUNCH_SHELL_MESSAGE                                                   \
3106   "\n'r' and 'run' are aliases that default to launching through a "           \
3107   "shell.\nTry launching without going through a shell by using 'process "     \
3108   "launch'."
3109         if (exit_desc && exit_desc[0]) {
3110           if (with_shell)
3111             error.SetErrorStringWithFormat(
3112                 "process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE,
3113                 exit_status, exit_desc);
3114           else
3115             error.SetErrorStringWithFormat("process exited with status %i (%s)",
3116                                            exit_status, exit_desc);
3117         } else {
3118           if (with_shell)
3119             error.SetErrorStringWithFormat(
3120                 "process exited with status %i" LAUNCH_SHELL_MESSAGE,
3121                 exit_status);
3122           else
3123             error.SetErrorStringWithFormat("process exited with status %i",
3124                                            exit_status);
3125         }
3126       } else {
3127         error.SetErrorStringWithFormat(
3128             "initial process state wasn't stopped: %s", StateAsCString(state));
3129       }
3130     }
3131     m_process_sp->RestoreProcessEvents();
3132   } else {
3133     Status error2;
3134     error2.SetErrorStringWithFormat("process launch failed: %s",
3135                                     error.AsCString());
3136     error = error2;
3137   }
3138   return error;
3139 }
3140 
3141 Status Target::Attach(ProcessAttachInfo &attach_info, Stream *stream) {
3142   auto state = eStateInvalid;
3143   auto process_sp = GetProcessSP();
3144   if (process_sp) {
3145     state = process_sp->GetState();
3146     if (process_sp->IsAlive() && state != eStateConnected) {
3147       if (state == eStateAttaching)
3148         return Status("process attach is in progress");
3149       return Status("a process is already being debugged");
3150     }
3151   }
3152 
3153   const ModuleSP old_exec_module_sp = GetExecutableModule();
3154 
3155   // If no process info was specified, then use the target executable
3156   // name as the process to attach to by default
3157   if (!attach_info.ProcessInfoSpecified()) {
3158     if (old_exec_module_sp)
3159       attach_info.GetExecutableFile().GetFilename() =
3160           old_exec_module_sp->GetPlatformFileSpec().GetFilename();
3161 
3162     if (!attach_info.ProcessInfoSpecified()) {
3163       return Status("no process specified, create a target with a file, or "
3164                     "specify the --pid or --name");
3165     }
3166   }
3167 
3168   const auto platform_sp =
3169       GetDebugger().GetPlatformList().GetSelectedPlatform();
3170   ListenerSP hijack_listener_sp;
3171   const bool async = attach_info.GetAsync();
3172   if (!async) {
3173     hijack_listener_sp =
3174         Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3175     attach_info.SetHijackListener(hijack_listener_sp);
3176   }
3177 
3178   Status error;
3179   if (state != eStateConnected && platform_sp != nullptr &&
3180       platform_sp->CanDebugProcess()) {
3181     SetPlatform(platform_sp);
3182     process_sp = platform_sp->Attach(attach_info, GetDebugger(), this, error);
3183   } else {
3184     if (state != eStateConnected) {
3185       const char *plugin_name = attach_info.GetProcessPluginName();
3186       process_sp =
3187           CreateProcess(attach_info.GetListenerForProcess(GetDebugger()),
3188                         plugin_name, nullptr);
3189       if (process_sp == nullptr) {
3190         error.SetErrorStringWithFormat(
3191             "failed to create process using plugin %s",
3192             (plugin_name) ? plugin_name : "null");
3193         return error;
3194       }
3195     }
3196     if (hijack_listener_sp)
3197       process_sp->HijackProcessEvents(hijack_listener_sp);
3198     error = process_sp->Attach(attach_info);
3199   }
3200 
3201   if (error.Success() && process_sp) {
3202     if (async) {
3203       process_sp->RestoreProcessEvents();
3204     } else {
3205       state = process_sp->WaitForProcessToStop(
3206           llvm::None, nullptr, false, attach_info.GetHijackListener(), stream);
3207       process_sp->RestoreProcessEvents();
3208 
3209       if (state != eStateStopped) {
3210         const char *exit_desc = process_sp->GetExitDescription();
3211         if (exit_desc)
3212           error.SetErrorStringWithFormat("%s", exit_desc);
3213         else
3214           error.SetErrorString(
3215               "process did not stop (no such process or permission problem?)");
3216         process_sp->Destroy(false);
3217       }
3218     }
3219   }
3220   return error;
3221 }
3222 
3223 //--------------------------------------------------------------
3224 // Target::StopHook
3225 //--------------------------------------------------------------
3226 Target::StopHook::StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid)
3227     : UserID(uid), m_target_sp(target_sp), m_commands(), m_specifier_sp(),
3228       m_thread_spec_ap(), m_active(true) {}
3229 
3230 Target::StopHook::StopHook(const StopHook &rhs)
3231     : UserID(rhs.GetID()), m_target_sp(rhs.m_target_sp),
3232       m_commands(rhs.m_commands), m_specifier_sp(rhs.m_specifier_sp),
3233       m_thread_spec_ap(), m_active(rhs.m_active) {
3234   if (rhs.m_thread_spec_ap)
3235     m_thread_spec_ap.reset(new ThreadSpec(*rhs.m_thread_spec_ap.get()));
3236 }
3237 
3238 Target::StopHook::~StopHook() = default;
3239 
3240 void Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier) {
3241   m_specifier_sp.reset(specifier);
3242 }
3243 
3244 void Target::StopHook::SetThreadSpecifier(ThreadSpec *specifier) {
3245   m_thread_spec_ap.reset(specifier);
3246 }
3247 
3248 void Target::StopHook::GetDescription(Stream *s,
3249                                       lldb::DescriptionLevel level) const {
3250   int indent_level = s->GetIndentLevel();
3251 
3252   s->SetIndentLevel(indent_level + 2);
3253 
3254   s->Printf("Hook: %" PRIu64 "\n", GetID());
3255   if (m_active)
3256     s->Indent("State: enabled\n");
3257   else
3258     s->Indent("State: disabled\n");
3259 
3260   if (m_specifier_sp) {
3261     s->Indent();
3262     s->PutCString("Specifier:\n");
3263     s->SetIndentLevel(indent_level + 4);
3264     m_specifier_sp->GetDescription(s, level);
3265     s->SetIndentLevel(indent_level + 2);
3266   }
3267 
3268   if (m_thread_spec_ap) {
3269     StreamString tmp;
3270     s->Indent("Thread:\n");
3271     m_thread_spec_ap->GetDescription(&tmp, level);
3272     s->SetIndentLevel(indent_level + 4);
3273     s->Indent(tmp.GetString());
3274     s->PutCString("\n");
3275     s->SetIndentLevel(indent_level + 2);
3276   }
3277 
3278   s->Indent("Commands: \n");
3279   s->SetIndentLevel(indent_level + 4);
3280   uint32_t num_commands = m_commands.GetSize();
3281   for (uint32_t i = 0; i < num_commands; i++) {
3282     s->Indent(m_commands.GetStringAtIndex(i));
3283     s->PutCString("\n");
3284   }
3285   s->SetIndentLevel(indent_level);
3286 }
3287 
3288 //--------------------------------------------------------------
3289 // class TargetProperties
3290 //--------------------------------------------------------------
3291 
3292 OptionEnumValueElement lldb_private::g_dynamic_value_types[] = {
3293     {eNoDynamicValues, "no-dynamic-values",
3294      "Don't calculate the dynamic type of values"},
3295     {eDynamicCanRunTarget, "run-target", "Calculate the dynamic type of values "
3296                                          "even if you have to run the target."},
3297     {eDynamicDontRunTarget, "no-run-target",
3298      "Calculate the dynamic type of values, but don't run the target."},
3299     {0, nullptr, nullptr}};
3300 
3301 static OptionEnumValueElement g_inline_breakpoint_enums[] = {
3302     {eInlineBreakpointsNever, "never", "Never look for inline breakpoint "
3303                                        "locations (fastest). This setting "
3304                                        "should only be used if you know that "
3305                                        "no inlining occurs in your programs."},
3306     {eInlineBreakpointsHeaders, "headers",
3307      "Only check for inline breakpoint locations when setting breakpoints in "
3308      "header files, but not when setting breakpoint in implementation source "
3309      "files (default)."},
3310     {eInlineBreakpointsAlways, "always",
3311      "Always look for inline breakpoint locations when setting file and line "
3312      "breakpoints (slower but most accurate)."},
3313     {0, nullptr, nullptr}};
3314 
3315 typedef enum x86DisassemblyFlavor {
3316   eX86DisFlavorDefault,
3317   eX86DisFlavorIntel,
3318   eX86DisFlavorATT
3319 } x86DisassemblyFlavor;
3320 
3321 static OptionEnumValueElement g_x86_dis_flavor_value_types[] = {
3322     {eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3323     {eX86DisFlavorIntel, "intel", "Intel disassembler flavor."},
3324     {eX86DisFlavorATT, "att", "AT&T disassembler flavor."},
3325     {0, nullptr, nullptr}};
3326 
3327 static OptionEnumValueElement g_hex_immediate_style_values[] = {
3328     {Disassembler::eHexStyleC, "c", "C-style (0xffff)."},
3329     {Disassembler::eHexStyleAsm, "asm", "Asm-style (0ffffh)."},
3330     {0, nullptr, nullptr}};
3331 
3332 static OptionEnumValueElement g_load_script_from_sym_file_values[] = {
3333     {eLoadScriptFromSymFileTrue, "true",
3334      "Load debug scripts inside symbol files"},
3335     {eLoadScriptFromSymFileFalse, "false",
3336      "Do not load debug scripts inside symbol files."},
3337     {eLoadScriptFromSymFileWarn, "warn",
3338      "Warn about debug scripts inside symbol files but do not load them."},
3339     {0, nullptr, nullptr}};
3340 
3341 static OptionEnumValueElement g_load_current_working_dir_lldbinit_values[] = {
3342     {eLoadCWDlldbinitTrue, "true",
3343      "Load .lldbinit files from current directory"},
3344     {eLoadCWDlldbinitFalse, "false",
3345      "Do not load .lldbinit files from current directory"},
3346     {eLoadCWDlldbinitWarn, "warn",
3347      "Warn about loading .lldbinit files from current directory"},
3348     {0, nullptr, nullptr}};
3349 
3350 static OptionEnumValueElement g_memory_module_load_level_values[] = {
3351     {eMemoryModuleLoadLevelMinimal, "minimal",
3352      "Load minimal information when loading modules from memory. Currently "
3353      "this setting loads sections only."},
3354     {eMemoryModuleLoadLevelPartial, "partial",
3355      "Load partial information when loading modules from memory. Currently "
3356      "this setting loads sections and function bounds."},
3357     {eMemoryModuleLoadLevelComplete, "complete",
3358      "Load complete information when loading modules from memory. Currently "
3359      "this setting loads sections and all symbols."},
3360     {0, nullptr, nullptr}};
3361 
3362 static PropertyDefinition g_properties[] = {
3363     {"default-arch", OptionValue::eTypeArch, true, 0, nullptr, nullptr,
3364      "Default architecture to choose, when there's a choice."},
3365     {"move-to-nearest-code", OptionValue::eTypeBoolean, false, true, nullptr,
3366      nullptr, "Move breakpoints to nearest code."},
3367     {"language", OptionValue::eTypeLanguage, false, eLanguageTypeUnknown,
3368      nullptr, nullptr,
3369      "The language to use when interpreting expressions entered in commands."},
3370     {"expr-prefix", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3371      "Path to a file containing expressions to be prepended to all "
3372      "expressions."},
3373     {"prefer-dynamic-value", OptionValue::eTypeEnum, false,
3374      eDynamicDontRunTarget, nullptr, g_dynamic_value_types,
3375      "Should printed values be shown as their dynamic value."},
3376     {"enable-synthetic-value", OptionValue::eTypeBoolean, false, true, nullptr,
3377      nullptr, "Should synthetic values be used by default whenever available."},
3378     {"skip-prologue", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3379      "Skip function prologues when setting breakpoints by name."},
3380     {"source-map", OptionValue::eTypePathMap, false, 0, nullptr, nullptr,
3381      "Source path remappings are used to track the change of location between "
3382      "a source file when built, and "
3383      "where it exists on the current system.  It consists of an array of "
3384      "duples, the first element of each duple is "
3385      "some part (starting at the root) of the path to the file when it was "
3386      "built, "
3387      "and the second is where the remainder of the original build hierarchy is "
3388      "rooted on the local system.  "
3389      "Each element of the array is checked in order and the first one that "
3390      "results in a match wins."},
3391     {"exec-search-paths", OptionValue::eTypeFileSpecList, false, 0, nullptr,
3392      nullptr, "Executable search paths to use when locating executable files "
3393               "whose paths don't match the local file system."},
3394     {"debug-file-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3395      nullptr, nullptr,
3396      "List of directories to be searched when locating debug symbol files."},
3397     {"clang-module-search-paths", OptionValue::eTypeFileSpecList, false, 0,
3398      nullptr, nullptr,
3399      "List of directories to be searched when locating modules for Clang."},
3400     {"auto-import-clang-modules", OptionValue::eTypeBoolean, false, true,
3401      nullptr, nullptr,
3402      "Automatically load Clang modules referred to by the program."},
3403     {"auto-apply-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3404      nullptr, "Automatically apply fix-it hints to expressions."},
3405     {"notify-about-fixits", OptionValue::eTypeBoolean, false, true, nullptr,
3406      nullptr, "Print the fixed expression text."},
3407     {"save-jit-objects", OptionValue::eTypeBoolean, false, false, nullptr,
3408      nullptr, "Save intermediate object files generated by the LLVM JIT"},
3409     {"max-children-count", OptionValue::eTypeSInt64, false, 256, nullptr,
3410      nullptr, "Maximum number of children to expand in any level of depth."},
3411     {"max-string-summary-length", OptionValue::eTypeSInt64, false, 1024,
3412      nullptr, nullptr,
3413      "Maximum number of characters to show when using %s in summary strings."},
3414     {"max-memory-read-size", OptionValue::eTypeSInt64, false, 1024, nullptr,
3415      nullptr, "Maximum number of bytes that 'memory read' will fetch before "
3416               "--force must be specified."},
3417     {"breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean, false,
3418      true, nullptr, nullptr, "Consult the platform module avoid list when "
3419                              "setting non-module specific breakpoints."},
3420     {"arg0", OptionValue::eTypeString, false, 0, nullptr, nullptr,
3421      "The first argument passed to the program in the argument array which can "
3422      "be different from the executable itself."},
3423     {"run-args", OptionValue::eTypeArgs, false, 0, nullptr, nullptr,
3424      "A list containing all the arguments to be passed to the executable when "
3425      "it is run. Note that this does NOT include the argv[0] which is in "
3426      "target.arg0."},
3427     {"env-vars", OptionValue::eTypeDictionary, false, OptionValue::eTypeString,
3428      nullptr, nullptr, "A list of all the environment variables to be passed "
3429                        "to the executable's environment, and their values."},
3430     {"inherit-env", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3431      "Inherit the environment from the process that is running LLDB."},
3432     {"input-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3433      "The file/path to be used by the executable program for reading its "
3434      "standard input."},
3435     {"output-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3436      "The file/path to be used by the executable program for writing its "
3437      "standard output."},
3438     {"error-path", OptionValue::eTypeFileSpec, false, 0, nullptr, nullptr,
3439      "The file/path to be used by the executable program for writing its "
3440      "standard error."},
3441     {"detach-on-error", OptionValue::eTypeBoolean, false, true, nullptr,
3442      nullptr, "debugserver will detach (rather than killing) a process if it "
3443               "loses connection with lldb."},
3444     {"preload-symbols", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3445      "Enable loading of symbol tables before they are needed."},
3446     {"disable-aslr", OptionValue::eTypeBoolean, false, true, nullptr, nullptr,
3447      "Disable Address Space Layout Randomization (ASLR)"},
3448     {"disable-stdio", OptionValue::eTypeBoolean, false, false, nullptr, nullptr,
3449      "Disable stdin/stdout for process (e.g. for a GUI application)"},
3450     {"inline-breakpoint-strategy", OptionValue::eTypeEnum, false,
3451      eInlineBreakpointsAlways, nullptr, g_inline_breakpoint_enums,
3452      "The strategy to use when settings breakpoints by file and line. "
3453      "Breakpoint locations can end up being inlined by the compiler, so that a "
3454      "compile unit 'a.c' might contain an inlined function from another source "
3455      "file. "
3456      "Usually this is limited to breakpoint locations from inlined functions "
3457      "from header or other include files, or more accurately "
3458      "non-implementation source files. "
3459      "Sometimes code might #include implementation files and cause inlined "
3460      "breakpoint locations in inlined implementation files. "
3461      "Always checking for inlined breakpoint locations can be expensive "
3462      "(memory and time), so if you have a project with many headers "
3463      "and find that setting breakpoints is slow, then you can change this "
3464      "setting to headers. "
3465      "This setting allows you to control exactly which strategy is used when "
3466      "setting "
3467      "file and line breakpoints."},
3468     // FIXME: This is the wrong way to do per-architecture settings, but we
3469     // don't have a general per architecture settings system in place yet.
3470     {"x86-disassembly-flavor", OptionValue::eTypeEnum, false,
3471      eX86DisFlavorDefault, nullptr, g_x86_dis_flavor_value_types,
3472      "The default disassembly flavor to use for x86 or x86-64 targets."},
3473     {"use-hex-immediates", OptionValue::eTypeBoolean, false, true, nullptr,
3474      nullptr, "Show immediates in disassembly as hexadecimal."},
3475     {"hex-immediate-style", OptionValue::eTypeEnum, false,
3476      Disassembler::eHexStyleC, nullptr, g_hex_immediate_style_values,
3477      "Which style to use for printing hexadecimal disassembly values."},
3478     {"use-fast-stepping", OptionValue::eTypeBoolean, false, true, nullptr,
3479      nullptr, "Use a fast stepping algorithm based on running from branch to "
3480               "branch rather than instruction single-stepping."},
3481     {"load-script-from-symbol-file", OptionValue::eTypeEnum, false,
3482      eLoadScriptFromSymFileWarn, nullptr, g_load_script_from_sym_file_values,
3483      "Allow LLDB to load scripting resources embedded in symbol files when "
3484      "available."},
3485     {"load-cwd-lldbinit", OptionValue::eTypeEnum, false, eLoadCWDlldbinitWarn,
3486      nullptr, g_load_current_working_dir_lldbinit_values,
3487      "Allow LLDB to .lldbinit files from the current directory automatically."},
3488     {"memory-module-load-level", OptionValue::eTypeEnum, false,
3489      eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3490      "Loading modules from memory can be slow as reading the symbol tables and "
3491      "other data can take a long time depending on your connection to the "
3492      "debug target. "
3493      "This setting helps users control how much information gets loaded when "
3494      "loading modules from memory."
3495      "'complete' is the default value for this setting which will load all "
3496      "sections and symbols by reading them from memory (slowest, most "
3497      "accurate). "
3498      "'partial' will load sections and attempt to find function bounds without "
3499      "downloading the symbol table (faster, still accurate, missing symbol "
3500      "names). "
3501      "'minimal' is the fastest setting and will load section data with no "
3502      "symbols, but should rarely be used as stack frames in these memory "
3503      "regions will be inaccurate and not provide any context (fastest). "},
3504     {"display-expression-in-crashlogs", OptionValue::eTypeBoolean, false, false,
3505      nullptr, nullptr, "Expressions that crash will show up in crash logs if "
3506                        "the host system supports executable specific crash log "
3507                        "strings and this setting is set to true."},
3508     {"trap-handler-names", OptionValue::eTypeArray, true,
3509      OptionValue::eTypeString, nullptr, nullptr,
3510      "A list of trap handler function names, e.g. a common Unix user process "
3511      "one is _sigtramp."},
3512     {"display-runtime-support-values", OptionValue::eTypeBoolean, false, false,
3513      nullptr, nullptr, "If true, LLDB will show variables that are meant to "
3514                        "support the operation of a language's runtime "
3515                        "support."},
3516     {"non-stop-mode", OptionValue::eTypeBoolean, false, 0, nullptr, nullptr,
3517      "Disable lock-step debugging, instead control threads independently."},
3518     {nullptr, OptionValue::eTypeInvalid, false, 0, nullptr, nullptr, nullptr}};
3519 
3520 enum {
3521   ePropertyDefaultArch,
3522   ePropertyMoveToNearestCode,
3523   ePropertyLanguage,
3524   ePropertyExprPrefix,
3525   ePropertyPreferDynamic,
3526   ePropertyEnableSynthetic,
3527   ePropertySkipPrologue,
3528   ePropertySourceMap,
3529   ePropertyExecutableSearchPaths,
3530   ePropertyDebugFileSearchPaths,
3531   ePropertyClangModuleSearchPaths,
3532   ePropertyAutoImportClangModules,
3533   ePropertyAutoApplyFixIts,
3534   ePropertyNotifyAboutFixIts,
3535   ePropertySaveObjects,
3536   ePropertyMaxChildrenCount,
3537   ePropertyMaxSummaryLength,
3538   ePropertyMaxMemReadSize,
3539   ePropertyBreakpointUseAvoidList,
3540   ePropertyArg0,
3541   ePropertyRunArgs,
3542   ePropertyEnvVars,
3543   ePropertyInheritEnv,
3544   ePropertyInputPath,
3545   ePropertyOutputPath,
3546   ePropertyErrorPath,
3547   ePropertyDetachOnError,
3548   ePropertyPreloadSymbols,
3549   ePropertyDisableASLR,
3550   ePropertyDisableSTDIO,
3551   ePropertyInlineStrategy,
3552   ePropertyDisassemblyFlavor,
3553   ePropertyUseHexImmediates,
3554   ePropertyHexImmediateStyle,
3555   ePropertyUseFastStepping,
3556   ePropertyLoadScriptFromSymbolFile,
3557   ePropertyLoadCWDlldbinitFile,
3558   ePropertyMemoryModuleLoadLevel,
3559   ePropertyDisplayExpressionsInCrashlogs,
3560   ePropertyTrapHandlerNames,
3561   ePropertyDisplayRuntimeSupportValues,
3562   ePropertyNonStopModeEnabled,
3563   ePropertyExperimental
3564 };
3565 
3566 class TargetOptionValueProperties : public OptionValueProperties {
3567 public:
3568   TargetOptionValueProperties(const ConstString &name)
3569       : OptionValueProperties(name), m_target(nullptr), m_got_host_env(false) {}
3570 
3571   // This constructor is used when creating TargetOptionValueProperties when it
3572   // is part of a new lldb_private::Target instance. It will copy all current
3573   // global property values as needed
3574   TargetOptionValueProperties(Target *target,
3575                               const TargetPropertiesSP &target_properties_sp)
3576       : OptionValueProperties(*target_properties_sp->GetValueProperties()),
3577         m_target(target), m_got_host_env(false) {}
3578 
3579   const Property *GetPropertyAtIndex(const ExecutionContext *exe_ctx,
3580                                      bool will_modify,
3581                                      uint32_t idx) const override {
3582     // When getting the value for a key from the target options, we will always
3583     // try and grab the setting from the current target if there is one. Else we
3584     // just
3585     // use the one from this instance.
3586     if (idx == ePropertyEnvVars)
3587       GetHostEnvironmentIfNeeded();
3588 
3589     if (exe_ctx) {
3590       Target *target = exe_ctx->GetTargetPtr();
3591       if (target) {
3592         TargetOptionValueProperties *target_properties =
3593             static_cast<TargetOptionValueProperties *>(
3594                 target->GetValueProperties().get());
3595         if (this != target_properties)
3596           return target_properties->ProtectedGetPropertyAtIndex(idx);
3597       }
3598     }
3599     return ProtectedGetPropertyAtIndex(idx);
3600   }
3601 
3602   lldb::TargetSP GetTargetSP() { return m_target->shared_from_this(); }
3603 
3604 protected:
3605   void GetHostEnvironmentIfNeeded() const {
3606     if (!m_got_host_env) {
3607       if (m_target) {
3608         m_got_host_env = true;
3609         const uint32_t idx = ePropertyInheritEnv;
3610         if (GetPropertyAtIndexAsBoolean(
3611                 nullptr, idx, g_properties[idx].default_uint_value != 0)) {
3612           PlatformSP platform_sp(m_target->GetPlatform());
3613           if (platform_sp) {
3614             Environment env = platform_sp->GetEnvironment();
3615             OptionValueDictionary *env_dict =
3616                 GetPropertyAtIndexAsOptionValueDictionary(nullptr,
3617                                                           ePropertyEnvVars);
3618             if (env_dict) {
3619               const bool can_replace = false;
3620               for (const auto &KV : env) {
3621                 // Don't allow existing keys to be replaced with ones we get
3622                 // from the platform environment
3623                 env_dict->SetValueForKey(
3624                     ConstString(KV.first()),
3625                     OptionValueSP(new OptionValueString(KV.second.c_str())),
3626                     can_replace);
3627               }
3628             }
3629           }
3630         }
3631       }
3632     }
3633   }
3634   Target *m_target;
3635   mutable bool m_got_host_env;
3636 };
3637 
3638 //----------------------------------------------------------------------
3639 // TargetProperties
3640 //----------------------------------------------------------------------
3641 static PropertyDefinition g_experimental_properties[]{
3642     {"inject-local-vars", OptionValue::eTypeBoolean, true, true, nullptr,
3643      nullptr,
3644      "If true, inject local variables explicitly into the expression text.  "
3645      "This will fix symbol resolution when there are name collisions between "
3646      "ivars and local variables.  "
3647      "But it can make expressions run much more slowly."},
3648     {"use-modern-type-lookup", OptionValue::eTypeBoolean, true, false, nullptr,
3649      nullptr, "If true, use Clang's modern type lookup infrastructure."},
3650     {nullptr, OptionValue::eTypeInvalid, true, 0, nullptr, nullptr, nullptr}};
3651 
3652 enum { ePropertyInjectLocalVars = 0, ePropertyUseModernTypeLookup };
3653 
3654 class TargetExperimentalOptionValueProperties : public OptionValueProperties {
3655 public:
3656   TargetExperimentalOptionValueProperties()
3657       : OptionValueProperties(
3658             ConstString(Properties::GetExperimentalSettingsName())) {}
3659 };
3660 
3661 TargetExperimentalProperties::TargetExperimentalProperties()
3662     : Properties(OptionValuePropertiesSP(
3663           new TargetExperimentalOptionValueProperties())) {
3664   m_collection_sp->Initialize(g_experimental_properties);
3665 }
3666 
3667 //----------------------------------------------------------------------
3668 // TargetProperties
3669 //----------------------------------------------------------------------
3670 TargetProperties::TargetProperties(Target *target)
3671     : Properties(), m_launch_info() {
3672   if (target) {
3673     m_collection_sp.reset(
3674         new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
3675 
3676     // Set callbacks to update launch_info whenever "settins set" updated any of
3677     // these properties
3678     m_collection_sp->SetValueChangedCallback(
3679         ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3680     m_collection_sp->SetValueChangedCallback(
3681         ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3682     m_collection_sp->SetValueChangedCallback(
3683         ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3684     m_collection_sp->SetValueChangedCallback(
3685         ePropertyInputPath, TargetProperties::InputPathValueChangedCallback,
3686         this);
3687     m_collection_sp->SetValueChangedCallback(
3688         ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback,
3689         this);
3690     m_collection_sp->SetValueChangedCallback(
3691         ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback,
3692         this);
3693     m_collection_sp->SetValueChangedCallback(
3694         ePropertyDetachOnError,
3695         TargetProperties::DetachOnErrorValueChangedCallback, this);
3696     m_collection_sp->SetValueChangedCallback(
3697         ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback,
3698         this);
3699     m_collection_sp->SetValueChangedCallback(
3700         ePropertyDisableSTDIO,
3701         TargetProperties::DisableSTDIOValueChangedCallback, this);
3702 
3703     m_experimental_properties_up.reset(new TargetExperimentalProperties());
3704     m_collection_sp->AppendProperty(
3705         ConstString(Properties::GetExperimentalSettingsName()),
3706         ConstString("Experimental settings - setting these won't produce "
3707                     "errors if the setting is not present."),
3708         true, m_experimental_properties_up->GetValueProperties());
3709 
3710     // Update m_launch_info once it was created
3711     Arg0ValueChangedCallback(this, nullptr);
3712     RunArgsValueChangedCallback(this, nullptr);
3713     // EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in
3714     // Target::GetPlatform()
3715     InputPathValueChangedCallback(this, nullptr);
3716     OutputPathValueChangedCallback(this, nullptr);
3717     ErrorPathValueChangedCallback(this, nullptr);
3718     DetachOnErrorValueChangedCallback(this, nullptr);
3719     DisableASLRValueChangedCallback(this, nullptr);
3720     DisableSTDIOValueChangedCallback(this, nullptr);
3721   } else {
3722     m_collection_sp.reset(
3723         new TargetOptionValueProperties(ConstString("target")));
3724     m_collection_sp->Initialize(g_properties);
3725     m_experimental_properties_up.reset(new TargetExperimentalProperties());
3726     m_collection_sp->AppendProperty(
3727         ConstString(Properties::GetExperimentalSettingsName()),
3728         ConstString("Experimental settings - setting these won't produce "
3729                     "errors if the setting is not present."),
3730         true, m_experimental_properties_up->GetValueProperties());
3731     m_collection_sp->AppendProperty(
3732         ConstString("process"), ConstString("Settings specific to processes."),
3733         true, Process::GetGlobalProperties()->GetValueProperties());
3734   }
3735 }
3736 
3737 TargetProperties::~TargetProperties() = default;
3738 
3739 bool TargetProperties::GetInjectLocalVariables(
3740     ExecutionContext *exe_ctx) const {
3741   const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3742       exe_ctx, false, ePropertyExperimental);
3743   OptionValueProperties *exp_values =
3744       exp_property->GetValue()->GetAsProperties();
3745   if (exp_values)
3746     return exp_values->GetPropertyAtIndexAsBoolean(
3747         exe_ctx, ePropertyInjectLocalVars, true);
3748   else
3749     return true;
3750 }
3751 
3752 void TargetProperties::SetInjectLocalVariables(ExecutionContext *exe_ctx,
3753                                                bool b) {
3754   const Property *exp_property =
3755       m_collection_sp->GetPropertyAtIndex(exe_ctx, true, ePropertyExperimental);
3756   OptionValueProperties *exp_values =
3757       exp_property->GetValue()->GetAsProperties();
3758   if (exp_values)
3759     exp_values->SetPropertyAtIndexAsBoolean(exe_ctx, ePropertyInjectLocalVars,
3760                                             true);
3761 }
3762 
3763 bool TargetProperties::GetUseModernTypeLookup() const {
3764   const Property *exp_property = m_collection_sp->GetPropertyAtIndex(
3765       nullptr, false, ePropertyExperimental);
3766   OptionValueProperties *exp_values =
3767       exp_property->GetValue()->GetAsProperties();
3768   if (exp_values)
3769     return exp_values->GetPropertyAtIndexAsBoolean(
3770         nullptr, ePropertyUseModernTypeLookup, true);
3771   else
3772     return true;
3773 }
3774 
3775 ArchSpec TargetProperties::GetDefaultArchitecture() const {
3776   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3777       nullptr, ePropertyDefaultArch);
3778   if (value)
3779     return value->GetCurrentValue();
3780   return ArchSpec();
3781 }
3782 
3783 void TargetProperties::SetDefaultArchitecture(const ArchSpec &arch) {
3784   OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(
3785       nullptr, ePropertyDefaultArch);
3786   if (value)
3787     return value->SetCurrentValue(arch, true);
3788 }
3789 
3790 bool TargetProperties::GetMoveToNearestCode() const {
3791   const uint32_t idx = ePropertyMoveToNearestCode;
3792   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3793       nullptr, idx, g_properties[idx].default_uint_value != 0);
3794 }
3795 
3796 lldb::DynamicValueType TargetProperties::GetPreferDynamicValue() const {
3797   const uint32_t idx = ePropertyPreferDynamic;
3798   return (lldb::DynamicValueType)
3799       m_collection_sp->GetPropertyAtIndexAsEnumeration(
3800           nullptr, idx, g_properties[idx].default_uint_value);
3801 }
3802 
3803 bool TargetProperties::SetPreferDynamicValue(lldb::DynamicValueType d) {
3804   const uint32_t idx = ePropertyPreferDynamic;
3805   return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3806 }
3807 
3808 bool TargetProperties::GetPreloadSymbols() const {
3809   const uint32_t idx = ePropertyPreloadSymbols;
3810   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3811       nullptr, idx, g_properties[idx].default_uint_value != 0);
3812 }
3813 
3814 void TargetProperties::SetPreloadSymbols(bool b) {
3815   const uint32_t idx = ePropertyPreloadSymbols;
3816   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3817 }
3818 
3819 bool TargetProperties::GetDisableASLR() const {
3820   const uint32_t idx = ePropertyDisableASLR;
3821   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3822       nullptr, idx, g_properties[idx].default_uint_value != 0);
3823 }
3824 
3825 void TargetProperties::SetDisableASLR(bool b) {
3826   const uint32_t idx = ePropertyDisableASLR;
3827   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3828 }
3829 
3830 bool TargetProperties::GetDetachOnError() const {
3831   const uint32_t idx = ePropertyDetachOnError;
3832   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3833       nullptr, idx, g_properties[idx].default_uint_value != 0);
3834 }
3835 
3836 void TargetProperties::SetDetachOnError(bool b) {
3837   const uint32_t idx = ePropertyDetachOnError;
3838   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3839 }
3840 
3841 bool TargetProperties::GetDisableSTDIO() const {
3842   const uint32_t idx = ePropertyDisableSTDIO;
3843   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3844       nullptr, idx, g_properties[idx].default_uint_value != 0);
3845 }
3846 
3847 void TargetProperties::SetDisableSTDIO(bool b) {
3848   const uint32_t idx = ePropertyDisableSTDIO;
3849   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3850 }
3851 
3852 const char *TargetProperties::GetDisassemblyFlavor() const {
3853   const uint32_t idx = ePropertyDisassemblyFlavor;
3854   const char *return_value;
3855 
3856   x86DisassemblyFlavor flavor_value =
3857       (x86DisassemblyFlavor)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3858           nullptr, idx, g_properties[idx].default_uint_value);
3859   return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3860   return return_value;
3861 }
3862 
3863 InlineStrategy TargetProperties::GetInlineStrategy() const {
3864   const uint32_t idx = ePropertyInlineStrategy;
3865   return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(
3866       nullptr, idx, g_properties[idx].default_uint_value);
3867 }
3868 
3869 llvm::StringRef TargetProperties::GetArg0() const {
3870   const uint32_t idx = ePropertyArg0;
3871   return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, llvm::StringRef());
3872 }
3873 
3874 void TargetProperties::SetArg0(llvm::StringRef arg) {
3875   const uint32_t idx = ePropertyArg0;
3876   m_collection_sp->SetPropertyAtIndexAsString(
3877       nullptr, idx, arg);
3878   m_launch_info.SetArg0(arg);
3879 }
3880 
3881 bool TargetProperties::GetRunArguments(Args &args) const {
3882   const uint32_t idx = ePropertyRunArgs;
3883   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3884 }
3885 
3886 void TargetProperties::SetRunArguments(const Args &args) {
3887   const uint32_t idx = ePropertyRunArgs;
3888   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3889   m_launch_info.GetArguments() = args;
3890 }
3891 
3892 Environment TargetProperties::GetEnvironment() const {
3893   // TODO: Get rid of the Args intermediate step
3894   Args env;
3895   const uint32_t idx = ePropertyEnvVars;
3896   m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3897   return Environment(env);
3898 }
3899 
3900 void TargetProperties::SetEnvironment(Environment env) {
3901   // TODO: Get rid of the Args intermediate step
3902   const uint32_t idx = ePropertyEnvVars;
3903   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, Args(env));
3904   m_launch_info.GetEnvironment() = std::move(env);
3905 }
3906 
3907 bool TargetProperties::GetSkipPrologue() const {
3908   const uint32_t idx = ePropertySkipPrologue;
3909   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3910       nullptr, idx, g_properties[idx].default_uint_value != 0);
3911 }
3912 
3913 PathMappingList &TargetProperties::GetSourcePathMap() const {
3914   const uint32_t idx = ePropertySourceMap;
3915   OptionValuePathMappings *option_value =
3916       m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr,
3917                                                                    false, idx);
3918   assert(option_value);
3919   return option_value->GetCurrentValue();
3920 }
3921 
3922 FileSpecList &TargetProperties::GetExecutableSearchPaths() {
3923   const uint32_t idx = ePropertyExecutableSearchPaths;
3924   OptionValueFileSpecList *option_value =
3925       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3926                                                                    false, idx);
3927   assert(option_value);
3928   return option_value->GetCurrentValue();
3929 }
3930 
3931 FileSpecList &TargetProperties::GetDebugFileSearchPaths() {
3932   const uint32_t idx = ePropertyDebugFileSearchPaths;
3933   OptionValueFileSpecList *option_value =
3934       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3935                                                                    false, idx);
3936   assert(option_value);
3937   return option_value->GetCurrentValue();
3938 }
3939 
3940 FileSpecList &TargetProperties::GetClangModuleSearchPaths() {
3941   const uint32_t idx = ePropertyClangModuleSearchPaths;
3942   OptionValueFileSpecList *option_value =
3943       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr,
3944                                                                    false, idx);
3945   assert(option_value);
3946   return option_value->GetCurrentValue();
3947 }
3948 
3949 bool TargetProperties::GetEnableAutoImportClangModules() const {
3950   const uint32_t idx = ePropertyAutoImportClangModules;
3951   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3952       nullptr, idx, g_properties[idx].default_uint_value != 0);
3953 }
3954 
3955 bool TargetProperties::GetEnableAutoApplyFixIts() const {
3956   const uint32_t idx = ePropertyAutoApplyFixIts;
3957   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3958       nullptr, idx, g_properties[idx].default_uint_value != 0);
3959 }
3960 
3961 bool TargetProperties::GetEnableNotifyAboutFixIts() const {
3962   const uint32_t idx = ePropertyNotifyAboutFixIts;
3963   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3964       nullptr, idx, g_properties[idx].default_uint_value != 0);
3965 }
3966 
3967 bool TargetProperties::GetEnableSaveObjects() const {
3968   const uint32_t idx = ePropertySaveObjects;
3969   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3970       nullptr, idx, g_properties[idx].default_uint_value != 0);
3971 }
3972 
3973 bool TargetProperties::GetEnableSyntheticValue() const {
3974   const uint32_t idx = ePropertyEnableSynthetic;
3975   return m_collection_sp->GetPropertyAtIndexAsBoolean(
3976       nullptr, idx, g_properties[idx].default_uint_value != 0);
3977 }
3978 
3979 uint32_t TargetProperties::GetMaximumNumberOfChildrenToDisplay() const {
3980   const uint32_t idx = ePropertyMaxChildrenCount;
3981   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3982       nullptr, idx, g_properties[idx].default_uint_value);
3983 }
3984 
3985 uint32_t TargetProperties::GetMaximumSizeOfStringSummary() const {
3986   const uint32_t idx = ePropertyMaxSummaryLength;
3987   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3988       nullptr, idx, g_properties[idx].default_uint_value);
3989 }
3990 
3991 uint32_t TargetProperties::GetMaximumMemReadSize() const {
3992   const uint32_t idx = ePropertyMaxMemReadSize;
3993   return m_collection_sp->GetPropertyAtIndexAsSInt64(
3994       nullptr, idx, g_properties[idx].default_uint_value);
3995 }
3996 
3997 FileSpec TargetProperties::GetStandardInputPath() const {
3998   const uint32_t idx = ePropertyInputPath;
3999   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4000 }
4001 
4002 void TargetProperties::SetStandardInputPath(llvm::StringRef path) {
4003   const uint32_t idx = ePropertyInputPath;
4004   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4005 }
4006 
4007 FileSpec TargetProperties::GetStandardOutputPath() const {
4008   const uint32_t idx = ePropertyOutputPath;
4009   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4010 }
4011 
4012 void TargetProperties::SetStandardOutputPath(llvm::StringRef path) {
4013   const uint32_t idx = ePropertyOutputPath;
4014   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4015 }
4016 
4017 FileSpec TargetProperties::GetStandardErrorPath() const {
4018   const uint32_t idx = ePropertyErrorPath;
4019   return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
4020 }
4021 
4022 void TargetProperties::SetStandardErrorPath(llvm::StringRef path) {
4023   const uint32_t idx = ePropertyErrorPath;
4024   m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, path);
4025 }
4026 
4027 LanguageType TargetProperties::GetLanguage() const {
4028   OptionValueLanguage *value =
4029       m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(
4030           nullptr, ePropertyLanguage);
4031   if (value)
4032     return value->GetCurrentValue();
4033   return LanguageType();
4034 }
4035 
4036 llvm::StringRef TargetProperties::GetExpressionPrefixContents() {
4037   const uint32_t idx = ePropertyExprPrefix;
4038   OptionValueFileSpec *file =
4039       m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false,
4040                                                                idx);
4041   if (file) {
4042     DataBufferSP data_sp(file->GetFileContents());
4043     if (data_sp)
4044       return llvm::StringRef(
4045           reinterpret_cast<const char *>(data_sp->GetBytes()),
4046           data_sp->GetByteSize());
4047   }
4048   return "";
4049 }
4050 
4051 bool TargetProperties::GetBreakpointsConsultPlatformAvoidList() {
4052   const uint32_t idx = ePropertyBreakpointUseAvoidList;
4053   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4054       nullptr, idx, g_properties[idx].default_uint_value != 0);
4055 }
4056 
4057 bool TargetProperties::GetUseHexImmediates() const {
4058   const uint32_t idx = ePropertyUseHexImmediates;
4059   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4060       nullptr, idx, g_properties[idx].default_uint_value != 0);
4061 }
4062 
4063 bool TargetProperties::GetUseFastStepping() const {
4064   const uint32_t idx = ePropertyUseFastStepping;
4065   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4066       nullptr, idx, g_properties[idx].default_uint_value != 0);
4067 }
4068 
4069 bool TargetProperties::GetDisplayExpressionsInCrashlogs() const {
4070   const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
4071   return m_collection_sp->GetPropertyAtIndexAsBoolean(
4072       nullptr, idx, g_properties[idx].default_uint_value != 0);
4073 }
4074 
4075 LoadScriptFromSymFile TargetProperties::GetLoadScriptFromSymbolFile() const {
4076   const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
4077   return (LoadScriptFromSymFile)
4078       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4079           nullptr, idx, g_properties[idx].default_uint_value);
4080 }
4081 
4082 LoadCWDlldbinitFile TargetProperties::GetLoadCWDlldbinitFile() const {
4083   const uint32_t idx = ePropertyLoadCWDlldbinitFile;
4084   return (LoadCWDlldbinitFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(
4085       nullptr, idx, g_properties[idx].default_uint_value);
4086 }
4087 
4088 Disassembler::HexImmediateStyle TargetProperties::GetHexImmediateStyle() const {
4089   const uint32_t idx = ePropertyHexImmediateStyle;
4090   return (Disassembler::HexImmediateStyle)
4091       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4092           nullptr, idx, g_properties[idx].default_uint_value);
4093 }
4094 
4095 MemoryModuleLoadLevel TargetProperties::GetMemoryModuleLoadLevel() const {
4096   const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4097   return (MemoryModuleLoadLevel)
4098       m_collection_sp->GetPropertyAtIndexAsEnumeration(
4099           nullptr, idx, g_properties[idx].default_uint_value);
4100 }
4101 
4102 bool TargetProperties::GetUserSpecifiedTrapHandlerNames(Args &args) const {
4103   const uint32_t idx = ePropertyTrapHandlerNames;
4104   return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4105 }
4106 
4107 void TargetProperties::SetUserSpecifiedTrapHandlerNames(const Args &args) {
4108   const uint32_t idx = ePropertyTrapHandlerNames;
4109   m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4110 }
4111 
4112 bool TargetProperties::GetDisplayRuntimeSupportValues() const {
4113   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4114   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4115 }
4116 
4117 void TargetProperties::SetDisplayRuntimeSupportValues(bool b) {
4118   const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4119   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4120 }
4121 
4122 bool TargetProperties::GetNonStopModeEnabled() const {
4123   const uint32_t idx = ePropertyNonStopModeEnabled;
4124   return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4125 }
4126 
4127 void TargetProperties::SetNonStopModeEnabled(bool b) {
4128   const uint32_t idx = ePropertyNonStopModeEnabled;
4129   m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4130 }
4131 
4132 const ProcessLaunchInfo &TargetProperties::GetProcessLaunchInfo() {
4133   m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4134   return m_launch_info;
4135 }
4136 
4137 void TargetProperties::SetProcessLaunchInfo(
4138     const ProcessLaunchInfo &launch_info) {
4139   m_launch_info = launch_info;
4140   SetArg0(launch_info.GetArg0());
4141   SetRunArguments(launch_info.GetArguments());
4142   SetEnvironment(launch_info.GetEnvironment());
4143   const FileAction *input_file_action =
4144       launch_info.GetFileActionForFD(STDIN_FILENO);
4145   if (input_file_action) {
4146     SetStandardInputPath(input_file_action->GetPath());
4147   }
4148   const FileAction *output_file_action =
4149       launch_info.GetFileActionForFD(STDOUT_FILENO);
4150   if (output_file_action) {
4151     SetStandardOutputPath(output_file_action->GetPath());
4152   }
4153   const FileAction *error_file_action =
4154       launch_info.GetFileActionForFD(STDERR_FILENO);
4155   if (error_file_action) {
4156     SetStandardErrorPath(error_file_action->GetPath());
4157   }
4158   SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4159   SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4160   SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4161 }
4162 
4163 void TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr,
4164                                                 OptionValue *) {
4165   TargetProperties *this_ =
4166       reinterpret_cast<TargetProperties *>(target_property_ptr);
4167   this_->m_launch_info.SetArg0(this_->GetArg0());
4168 }
4169 
4170 void TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr,
4171                                                    OptionValue *) {
4172   TargetProperties *this_ =
4173       reinterpret_cast<TargetProperties *>(target_property_ptr);
4174   Args args;
4175   if (this_->GetRunArguments(args))
4176     this_->m_launch_info.GetArguments() = args;
4177 }
4178 
4179 void TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr,
4180                                                    OptionValue *) {
4181   TargetProperties *this_ =
4182       reinterpret_cast<TargetProperties *>(target_property_ptr);
4183   this_->m_launch_info.GetEnvironment() = this_->GetEnvironment();
4184 }
4185 
4186 void TargetProperties::InputPathValueChangedCallback(void *target_property_ptr,
4187                                                      OptionValue *) {
4188   TargetProperties *this_ =
4189       reinterpret_cast<TargetProperties *>(target_property_ptr);
4190   this_->m_launch_info.AppendOpenFileAction(
4191       STDIN_FILENO, this_->GetStandardInputPath(), true, false);
4192 }
4193 
4194 void TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr,
4195                                                       OptionValue *) {
4196   TargetProperties *this_ =
4197       reinterpret_cast<TargetProperties *>(target_property_ptr);
4198   this_->m_launch_info.AppendOpenFileAction(
4199       STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
4200 }
4201 
4202 void TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr,
4203                                                      OptionValue *) {
4204   TargetProperties *this_ =
4205       reinterpret_cast<TargetProperties *>(target_property_ptr);
4206   this_->m_launch_info.AppendOpenFileAction(
4207       STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
4208 }
4209 
4210 void TargetProperties::DetachOnErrorValueChangedCallback(
4211     void *target_property_ptr, OptionValue *) {
4212   TargetProperties *this_ =
4213       reinterpret_cast<TargetProperties *>(target_property_ptr);
4214   if (this_->GetDetachOnError())
4215     this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4216   else
4217     this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4218 }
4219 
4220 void TargetProperties::DisableASLRValueChangedCallback(
4221     void *target_property_ptr, OptionValue *) {
4222   TargetProperties *this_ =
4223       reinterpret_cast<TargetProperties *>(target_property_ptr);
4224   if (this_->GetDisableASLR())
4225     this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4226   else
4227     this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4228 }
4229 
4230 void TargetProperties::DisableSTDIOValueChangedCallback(
4231     void *target_property_ptr, OptionValue *) {
4232   TargetProperties *this_ =
4233       reinterpret_cast<TargetProperties *>(target_property_ptr);
4234   if (this_->GetDisableSTDIO())
4235     this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4236   else
4237     this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4238 }
4239 
4240 //----------------------------------------------------------------------
4241 // Target::TargetEventData
4242 //----------------------------------------------------------------------
4243 
4244 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp)
4245     : EventData(), m_target_sp(target_sp), m_module_list() {}
4246 
4247 Target::TargetEventData::TargetEventData(const lldb::TargetSP &target_sp,
4248                                          const ModuleList &module_list)
4249     : EventData(), m_target_sp(target_sp), m_module_list(module_list) {}
4250 
4251 Target::TargetEventData::~TargetEventData() = default;
4252 
4253 const ConstString &Target::TargetEventData::GetFlavorString() {
4254   static ConstString g_flavor("Target::TargetEventData");
4255   return g_flavor;
4256 }
4257 
4258 void Target::TargetEventData::Dump(Stream *s) const {
4259   for (size_t i = 0; i < m_module_list.GetSize(); ++i) {
4260     if (i != 0)
4261       *s << ", ";
4262     m_module_list.GetModuleAtIndex(i)->GetDescription(
4263         s, lldb::eDescriptionLevelBrief);
4264   }
4265 }
4266 
4267 const Target::TargetEventData *
4268 Target::TargetEventData::GetEventDataFromEvent(const Event *event_ptr) {
4269   if (event_ptr) {
4270     const EventData *event_data = event_ptr->GetData();
4271     if (event_data &&
4272         event_data->GetFlavor() == TargetEventData::GetFlavorString())
4273       return static_cast<const TargetEventData *>(event_ptr->GetData());
4274   }
4275   return nullptr;
4276 }
4277 
4278 TargetSP Target::TargetEventData::GetTargetFromEvent(const Event *event_ptr) {
4279   TargetSP target_sp;
4280   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4281   if (event_data)
4282     target_sp = event_data->m_target_sp;
4283   return target_sp;
4284 }
4285 
4286 ModuleList
4287 Target::TargetEventData::GetModuleListFromEvent(const Event *event_ptr) {
4288   ModuleList module_list;
4289   const TargetEventData *event_data = GetEventDataFromEvent(event_ptr);
4290   if (event_data)
4291     module_list = event_data->m_module_list;
4292   return module_list;
4293 }
4294