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