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