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