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