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