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