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