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)
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 {
2239     result_valobj_sp.reset();
2240 
2241     ExpressionResults execution_results = eExpressionSetupError;
2242 
2243     if (expr_cstr == nullptr || expr_cstr[0] == '\0')
2244         return execution_results;
2245 
2246     // We shouldn't run stop hooks in expressions.
2247     // Be sure to reset this if you return anywhere within this function.
2248     bool old_suppress_value = m_suppress_stop_hooks;
2249     m_suppress_stop_hooks = true;
2250 
2251     ExecutionContext exe_ctx;
2252 
2253     if (exe_scope)
2254     {
2255         exe_scope->CalculateExecutionContext(exe_ctx);
2256     }
2257     else if (m_process_sp)
2258     {
2259         m_process_sp->CalculateExecutionContext(exe_ctx);
2260     }
2261     else
2262     {
2263         CalculateExecutionContext(exe_ctx);
2264     }
2265 
2266     // Make sure we aren't just trying to see the value of a persistent
2267     // variable (something like "$0")
2268     lldb::ExpressionVariableSP persistent_var_sp;
2269     // Only check for persistent variables the expression starts with a '$'
2270     if (expr_cstr[0] == '$')
2271         persistent_var_sp = GetScratchTypeSystemForLanguage(nullptr, eLanguageTypeC)->GetPersistentExpressionState()->GetVariable (expr_cstr);
2272 
2273     if (persistent_var_sp)
2274     {
2275         result_valobj_sp = persistent_var_sp->GetValueObject ();
2276         execution_results = eExpressionCompleted;
2277     }
2278     else
2279     {
2280         const char *prefix = GetExpressionPrefixContentsAsCString();
2281         Error error;
2282         execution_results = UserExpression::Evaluate (exe_ctx,
2283                                                       options,
2284                                                       expr_cstr,
2285                                                       prefix,
2286                                                       result_valobj_sp,
2287                                                       error);
2288     }
2289 
2290     m_suppress_stop_hooks = old_suppress_value;
2291 
2292     return execution_results;
2293 }
2294 
2295 lldb::ExpressionVariableSP
2296 Target::GetPersistentVariable(const ConstString &name)
2297 {
2298     lldb::ExpressionVariableSP variable_sp;
2299     m_scratch_type_system_map.ForEach([this, name, &variable_sp](TypeSystem *type_system) -> bool
2300     {
2301         if (PersistentExpressionState *persistent_state = type_system->GetPersistentExpressionState())
2302         {
2303             variable_sp = persistent_state->GetVariable(name);
2304 
2305             if (variable_sp)
2306                 return false;   // Stop iterating the ForEach
2307         }
2308         return true;    // Keep iterating the ForEach
2309     });
2310     return variable_sp;
2311 }
2312 
2313 lldb::addr_t
2314 Target::GetPersistentSymbol(const ConstString &name)
2315 {
2316     lldb::addr_t address = LLDB_INVALID_ADDRESS;
2317 
2318     m_scratch_type_system_map.ForEach([this, name, &address](TypeSystem *type_system) -> bool
2319     {
2320         if (PersistentExpressionState *persistent_state = type_system->GetPersistentExpressionState())
2321         {
2322             address = persistent_state->LookupSymbol(name);
2323             if (address != LLDB_INVALID_ADDRESS)
2324                 return false;   // Stop iterating the ForEach
2325         }
2326         return true;    // Keep iterating the ForEach
2327     });
2328     return address;
2329 }
2330 
2331 lldb::addr_t
2332 Target::GetCallableLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
2333 {
2334     addr_t code_addr = load_addr;
2335     switch (m_arch.GetMachine())
2336     {
2337     case llvm::Triple::mips:
2338     case llvm::Triple::mipsel:
2339     case llvm::Triple::mips64:
2340     case llvm::Triple::mips64el:
2341         switch (addr_class)
2342         {
2343         case eAddressClassData:
2344         case eAddressClassDebug:
2345             return LLDB_INVALID_ADDRESS;
2346 
2347         case eAddressClassUnknown:
2348         case eAddressClassInvalid:
2349         case eAddressClassCode:
2350         case eAddressClassCodeAlternateISA:
2351         case eAddressClassRuntime:
2352             if ((code_addr & 2ull) || (addr_class == eAddressClassCodeAlternateISA))
2353                 code_addr |= 1ull;
2354             break;
2355         }
2356         break;
2357 
2358     case llvm::Triple::arm:
2359     case llvm::Triple::thumb:
2360         switch (addr_class)
2361         {
2362         case eAddressClassData:
2363         case eAddressClassDebug:
2364             return LLDB_INVALID_ADDRESS;
2365 
2366         case eAddressClassUnknown:
2367         case eAddressClassInvalid:
2368         case eAddressClassCode:
2369         case eAddressClassCodeAlternateISA:
2370         case eAddressClassRuntime:
2371             // Check if bit zero it no set?
2372             if ((code_addr & 1ull) == 0)
2373             {
2374                 // Bit zero isn't set, check if the address is a multiple of 2?
2375                 if (code_addr & 2ull)
2376                 {
2377                     // The address is a multiple of 2 so it must be thumb, set bit zero
2378                     code_addr |= 1ull;
2379                 }
2380                 else if (addr_class == eAddressClassCodeAlternateISA)
2381                 {
2382                     // We checked the address and the address claims to be the alternate ISA
2383                     // which means thumb, so set bit zero.
2384                     code_addr |= 1ull;
2385                 }
2386             }
2387             break;
2388         }
2389         break;
2390 
2391     default:
2392         break;
2393     }
2394     return code_addr;
2395 }
2396 
2397 lldb::addr_t
2398 Target::GetOpcodeLoadAddress (lldb::addr_t load_addr, AddressClass addr_class) const
2399 {
2400     addr_t opcode_addr = load_addr;
2401     switch (m_arch.GetMachine())
2402     {
2403     case llvm::Triple::mips:
2404     case llvm::Triple::mipsel:
2405     case llvm::Triple::mips64:
2406     case llvm::Triple::mips64el:
2407     case llvm::Triple::arm:
2408     case llvm::Triple::thumb:
2409         switch (addr_class)
2410         {
2411         case eAddressClassData:
2412         case eAddressClassDebug:
2413             return LLDB_INVALID_ADDRESS;
2414 
2415         case eAddressClassInvalid:
2416         case eAddressClassUnknown:
2417         case eAddressClassCode:
2418         case eAddressClassCodeAlternateISA:
2419         case eAddressClassRuntime:
2420             opcode_addr &= ~(1ull);
2421             break;
2422         }
2423         break;
2424 
2425     default:
2426         break;
2427     }
2428     return opcode_addr;
2429 }
2430 
2431 lldb::addr_t
2432 Target::GetBreakableLoadAddress (lldb::addr_t addr)
2433 {
2434     addr_t breakable_addr = addr;
2435     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_BREAKPOINTS));
2436 
2437     switch (m_arch.GetMachine())
2438     {
2439     default:
2440         break;
2441     case llvm::Triple::mips:
2442     case llvm::Triple::mipsel:
2443     case llvm::Triple::mips64:
2444     case llvm::Triple::mips64el:
2445     {
2446         addr_t function_start = 0;
2447         addr_t current_offset = 0;
2448         uint32_t loop_count = 0;
2449         Address resolved_addr;
2450         uint32_t arch_flags = m_arch.GetFlags ();
2451         bool IsMips16 = arch_flags & ArchSpec::eMIPSAse_mips16;
2452         bool IsMicromips = arch_flags & ArchSpec::eMIPSAse_micromips;
2453         SectionLoadList &section_load_list = GetSectionLoadList();
2454 
2455         if (section_load_list.IsEmpty())
2456             // No sections are loaded, so we must assume we are not running yet
2457             // and need to operate only on file address.
2458             m_images.ResolveFileAddress (addr, resolved_addr);
2459         else
2460             section_load_list.ResolveLoadAddress(addr, resolved_addr);
2461 
2462         // Get the function boundaries to make sure we don't scan back before the beginning of the current function.
2463         ModuleSP temp_addr_module_sp (resolved_addr.GetModule());
2464         if (temp_addr_module_sp)
2465         {
2466             SymbolContext sc;
2467             uint32_t resolve_scope = eSymbolContextFunction | eSymbolContextSymbol;
2468             temp_addr_module_sp->ResolveSymbolContextForAddress(resolved_addr, resolve_scope, sc);
2469             Address sym_addr;
2470             if (sc.function)
2471                 sym_addr = sc.function->GetAddressRange().GetBaseAddress();
2472             else if (sc.symbol)
2473                 sym_addr = sc.symbol->GetAddress();
2474 
2475             function_start = sym_addr.GetLoadAddress(this);
2476             if (function_start == LLDB_INVALID_ADDRESS)
2477                 function_start = sym_addr.GetFileAddress();
2478 
2479             if (function_start)
2480                 current_offset = addr - function_start;
2481         }
2482 
2483         // If breakpoint address is start of function then we dont have to do anything.
2484         if (current_offset == 0)
2485             return breakable_addr;
2486         else
2487             loop_count = current_offset / 2;
2488 
2489         if (loop_count > 3)
2490         {
2491             // Scan previous 6 bytes
2492             if (IsMips16 | IsMicromips)
2493                 loop_count = 3;
2494             // For mips-only, instructions are always 4 bytes, so scan previous 4 bytes only.
2495             else
2496                 loop_count = 2;
2497         }
2498 
2499         // Create Disassembler Instance
2500         lldb::DisassemblerSP disasm_sp(Disassembler::FindPlugin(m_arch, nullptr, nullptr));
2501 
2502         ExecutionContext exe_ctx;
2503         CalculateExecutionContext(exe_ctx);
2504         InstructionList instruction_list;
2505         InstructionSP prev_insn;
2506         bool prefer_file_cache = true; // Read from file
2507         uint32_t inst_to_choose = 0;
2508 
2509         for (uint32_t i = 1; i <= loop_count; i++)
2510         {
2511             // Adjust the address to read from.
2512             resolved_addr.Slide (-2);
2513             AddressRange range(resolved_addr, i*2);
2514             uint32_t insn_size = 0;
2515 
2516             disasm_sp->ParseInstructions(&exe_ctx, range, nullptr, prefer_file_cache);
2517 
2518             uint32_t num_insns = disasm_sp->GetInstructionList().GetSize();
2519             if (num_insns)
2520             {
2521                 prev_insn = disasm_sp->GetInstructionList().GetInstructionAtIndex(0);
2522                 insn_size = prev_insn->GetOpcode().GetByteSize();
2523                 if (i == 1 && insn_size == 2)
2524                 {
2525                     // This looks like a valid 2-byte instruction (but it could be a part of upper 4 byte instruction).
2526                     instruction_list.Append(prev_insn);
2527                     inst_to_choose = 1;
2528                 }
2529                 else if (i == 2)
2530                 {
2531                     // Here we may get one 4-byte instruction or two 2-byte instructions.
2532                     if (num_insns == 2)
2533                     {
2534                         // Looks like there are two 2-byte instructions above our breakpoint target address.
2535                         // 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.
2536                         // In both cases we don't care because in this case lower 2-byte instruction is definitely a valid instruction
2537                         // and whatever i=1 iteration has found out is true.
2538                         inst_to_choose = 1;
2539                         break;
2540                     }
2541                     else if (insn_size == 4)
2542                     {
2543                         // This instruction claims its a valid 4-byte instruction. But it could be a part of it's upper 4-byte instruction.
2544                         // Lets try scanning upper 2 bytes to verify this.
2545                         instruction_list.Append(prev_insn);
2546                         inst_to_choose = 2;
2547                     }
2548                 }
2549                 else if (i == 3)
2550                 {
2551                     if (insn_size == 4)
2552                         // FIXME: We reached here that means instruction at [target - 4] has already claimed to be a 4-byte instruction,
2553                         // and now instruction at [target - 6] is also claiming that it's a 4-byte instruction. This can not be true.
2554                         // In this case we can not decide the valid previous instruction so we let lldb set the breakpoint at the address given by user.
2555                         inst_to_choose = 0;
2556                     else
2557                         // This is straight-forward
2558                         inst_to_choose = 2;
2559                     break;
2560                 }
2561             }
2562             else
2563             {
2564                 // Decode failed, bytes do not form a valid instruction. So whatever previous iteration has found out is true.
2565                 if (i > 1)
2566                 {
2567                     inst_to_choose = i - 1;
2568                     break;
2569                 }
2570             }
2571         }
2572 
2573         // Check if we are able to find any valid instruction.
2574         if (inst_to_choose)
2575         {
2576             if (inst_to_choose > instruction_list.GetSize())
2577                 inst_to_choose--;
2578             prev_insn = instruction_list.GetInstructionAtIndex(inst_to_choose - 1);
2579 
2580             if (prev_insn->HasDelaySlot())
2581             {
2582                 uint32_t shift_size = prev_insn->GetOpcode().GetByteSize();
2583                 // Adjust the breakable address
2584                 breakable_addr = addr - shift_size;
2585                 if (log)
2586                     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);
2587             }
2588         }
2589         break;
2590     }
2591     }
2592     return breakable_addr;
2593 }
2594 
2595 SourceManager &
2596 Target::GetSourceManager ()
2597 {
2598     if (!m_source_manager_ap)
2599         m_source_manager_ap.reset (new SourceManager(shared_from_this()));
2600     return *m_source_manager_ap;
2601 }
2602 
2603 ClangModulesDeclVendor *
2604 Target::GetClangModulesDeclVendor ()
2605 {
2606     static Mutex s_clang_modules_decl_vendor_mutex; // If this is contended we can make it per-target
2607 
2608     {
2609         Mutex::Locker clang_modules_decl_vendor_locker(s_clang_modules_decl_vendor_mutex);
2610 
2611         if (!m_clang_modules_decl_vendor_ap)
2612         {
2613             m_clang_modules_decl_vendor_ap.reset(ClangModulesDeclVendor::Create(*this));
2614         }
2615     }
2616 
2617     return m_clang_modules_decl_vendor_ap.get();
2618 }
2619 
2620 Target::StopHookSP
2621 Target::CreateStopHook ()
2622 {
2623     lldb::user_id_t new_uid = ++m_stop_hook_next_id;
2624     Target::StopHookSP stop_hook_sp (new StopHook(shared_from_this(), new_uid));
2625     m_stop_hooks[new_uid] = stop_hook_sp;
2626     return stop_hook_sp;
2627 }
2628 
2629 bool
2630 Target::RemoveStopHookByID (lldb::user_id_t user_id)
2631 {
2632     size_t num_removed = m_stop_hooks.erase(user_id);
2633     return (num_removed != 0);
2634 }
2635 
2636 void
2637 Target::RemoveAllStopHooks ()
2638 {
2639     m_stop_hooks.clear();
2640 }
2641 
2642 Target::StopHookSP
2643 Target::GetStopHookByID (lldb::user_id_t user_id)
2644 {
2645     StopHookSP found_hook;
2646 
2647     StopHookCollection::iterator specified_hook_iter;
2648     specified_hook_iter = m_stop_hooks.find (user_id);
2649     if (specified_hook_iter != m_stop_hooks.end())
2650         found_hook = (*specified_hook_iter).second;
2651     return found_hook;
2652 }
2653 
2654 bool
2655 Target::SetStopHookActiveStateByID (lldb::user_id_t user_id, bool active_state)
2656 {
2657     StopHookCollection::iterator specified_hook_iter;
2658     specified_hook_iter = m_stop_hooks.find (user_id);
2659     if (specified_hook_iter == m_stop_hooks.end())
2660         return false;
2661 
2662     (*specified_hook_iter).second->SetIsActive (active_state);
2663     return true;
2664 }
2665 
2666 void
2667 Target::SetAllStopHooksActiveState (bool active_state)
2668 {
2669     StopHookCollection::iterator pos, end = m_stop_hooks.end();
2670     for (pos = m_stop_hooks.begin(); pos != end; pos++)
2671     {
2672         (*pos).second->SetIsActive (active_state);
2673     }
2674 }
2675 
2676 void
2677 Target::RunStopHooks ()
2678 {
2679     if (m_suppress_stop_hooks)
2680         return;
2681 
2682     if (!m_process_sp)
2683         return;
2684 
2685     // <rdar://problem/12027563> make sure we check that we are not stopped because of us running a user expression
2686     // since in that case we do not want to run the stop-hooks
2687     if (m_process_sp->GetModIDRef().IsLastResumeForUserExpression())
2688         return;
2689 
2690     if (m_stop_hooks.empty())
2691         return;
2692 
2693     StopHookCollection::iterator pos, end = m_stop_hooks.end();
2694 
2695     // If there aren't any active stop hooks, don't bother either:
2696     bool any_active_hooks = false;
2697     for (pos = m_stop_hooks.begin(); pos != end; pos++)
2698     {
2699         if ((*pos).second->IsActive())
2700         {
2701             any_active_hooks = true;
2702             break;
2703         }
2704     }
2705     if (!any_active_hooks)
2706         return;
2707 
2708     CommandReturnObject result;
2709 
2710     std::vector<ExecutionContext> exc_ctx_with_reasons;
2711     std::vector<SymbolContext> sym_ctx_with_reasons;
2712 
2713     ThreadList &cur_threadlist = m_process_sp->GetThreadList();
2714     size_t num_threads = cur_threadlist.GetSize();
2715     for (size_t i = 0; i < num_threads; i++)
2716     {
2717         lldb::ThreadSP cur_thread_sp = cur_threadlist.GetThreadAtIndex (i);
2718         if (cur_thread_sp->ThreadStoppedForAReason())
2719         {
2720             lldb::StackFrameSP cur_frame_sp = cur_thread_sp->GetStackFrameAtIndex(0);
2721             exc_ctx_with_reasons.push_back(ExecutionContext(m_process_sp.get(), cur_thread_sp.get(), cur_frame_sp.get()));
2722             sym_ctx_with_reasons.push_back(cur_frame_sp->GetSymbolContext(eSymbolContextEverything));
2723         }
2724     }
2725 
2726     // If no threads stopped for a reason, don't run the stop-hooks.
2727     size_t num_exe_ctx = exc_ctx_with_reasons.size();
2728     if (num_exe_ctx == 0)
2729         return;
2730 
2731     result.SetImmediateOutputStream (m_debugger.GetAsyncOutputStream());
2732     result.SetImmediateErrorStream (m_debugger.GetAsyncErrorStream());
2733 
2734     bool keep_going = true;
2735     bool hooks_ran = false;
2736     bool print_hook_header = (m_stop_hooks.size() != 1);
2737     bool print_thread_header = (num_exe_ctx != 1);
2738 
2739     for (pos = m_stop_hooks.begin(); keep_going && pos != end; pos++)
2740     {
2741         // result.Clear();
2742         StopHookSP cur_hook_sp = (*pos).second;
2743         if (!cur_hook_sp->IsActive())
2744             continue;
2745 
2746         bool any_thread_matched = false;
2747         for (size_t i = 0; keep_going && i < num_exe_ctx; i++)
2748         {
2749             if ((cur_hook_sp->GetSpecifier() == nullptr
2750                   || cur_hook_sp->GetSpecifier()->SymbolContextMatches(sym_ctx_with_reasons[i]))
2751                 && (cur_hook_sp->GetThreadSpecifier() == nullptr
2752                     || cur_hook_sp->GetThreadSpecifier()->ThreadPassesBasicTests(exc_ctx_with_reasons[i].GetThreadRef())))
2753             {
2754                 if (!hooks_ran)
2755                 {
2756                     hooks_ran = true;
2757                 }
2758                 if (print_hook_header && !any_thread_matched)
2759                 {
2760                     const char *cmd = (cur_hook_sp->GetCommands().GetSize() == 1 ?
2761                                        cur_hook_sp->GetCommands().GetStringAtIndex(0) :
2762                                        nullptr);
2763                     if (cmd)
2764                         result.AppendMessageWithFormat("\n- Hook %" PRIu64 " (%s)\n", cur_hook_sp->GetID(), cmd);
2765                     else
2766                         result.AppendMessageWithFormat("\n- Hook %" PRIu64 "\n", cur_hook_sp->GetID());
2767                     any_thread_matched = true;
2768                 }
2769 
2770                 if (print_thread_header)
2771                     result.AppendMessageWithFormat("-- Thread %d\n", exc_ctx_with_reasons[i].GetThreadPtr()->GetIndexID());
2772 
2773                 CommandInterpreterRunOptions options;
2774                 options.SetStopOnContinue (true);
2775                 options.SetStopOnError (true);
2776                 options.SetEchoCommands (false);
2777                 options.SetPrintResults (true);
2778                 options.SetAddToHistory (false);
2779 
2780                 GetDebugger().GetCommandInterpreter().HandleCommands (cur_hook_sp->GetCommands(),
2781                                                                       &exc_ctx_with_reasons[i],
2782                                                                       options,
2783                                                                       result);
2784 
2785                 // If the command started the target going again, we should bag out of
2786                 // running the stop hooks.
2787                 if ((result.GetStatus() == eReturnStatusSuccessContinuingNoResult) ||
2788                     (result.GetStatus() == eReturnStatusSuccessContinuingResult))
2789                 {
2790                     result.AppendMessageWithFormat ("Aborting stop hooks, hook %" PRIu64 " set the program running.", cur_hook_sp->GetID());
2791                     keep_going = false;
2792                 }
2793             }
2794         }
2795     }
2796 
2797     result.GetImmediateOutputStream()->Flush();
2798     result.GetImmediateErrorStream()->Flush();
2799 }
2800 
2801 const TargetPropertiesSP &
2802 Target::GetGlobalProperties()
2803 {
2804     // NOTE: intentional leak so we don't crash if global destructor chain gets
2805     // called as other threads still use the result of this function
2806     static TargetPropertiesSP *g_settings_sp_ptr = nullptr;
2807     static std::once_flag g_once_flag;
2808     std::call_once(g_once_flag,  []() {
2809         g_settings_sp_ptr = new TargetPropertiesSP(new TargetProperties(nullptr));
2810     });
2811     return *g_settings_sp_ptr;
2812 }
2813 
2814 Error
2815 Target::Install (ProcessLaunchInfo *launch_info)
2816 {
2817     Error error;
2818     PlatformSP platform_sp (GetPlatform());
2819     if (platform_sp)
2820     {
2821         if (platform_sp->IsRemote())
2822         {
2823             if (platform_sp->IsConnected())
2824             {
2825                 // Install all files that have an install path, and always install the
2826                 // main executable when connected to a remote platform
2827                 const ModuleList& modules = GetImages();
2828                 const size_t num_images = modules.GetSize();
2829                 for (size_t idx = 0; idx < num_images; ++idx)
2830                 {
2831                     const bool is_main_executable = idx == 0;
2832                     ModuleSP module_sp(modules.GetModuleAtIndex(idx));
2833                     if (module_sp)
2834                     {
2835                         FileSpec local_file (module_sp->GetFileSpec());
2836                         if (local_file)
2837                         {
2838                             FileSpec remote_file (module_sp->GetRemoteInstallFileSpec());
2839                             if (!remote_file)
2840                             {
2841                                 if (is_main_executable) // TODO: add setting for always installing main executable???
2842                                 {
2843                                     // Always install the main executable
2844                                     remote_file = platform_sp->GetRemoteWorkingDirectory();
2845                                     remote_file.AppendPathComponent(module_sp->GetFileSpec().GetFilename().GetCString());
2846                                 }
2847                             }
2848                             if (remote_file)
2849                             {
2850                                 error = platform_sp->Install(local_file, remote_file);
2851                                 if (error.Success())
2852                                 {
2853                                     module_sp->SetPlatformFileSpec(remote_file);
2854                                     if (is_main_executable)
2855                                     {
2856                                         platform_sp->SetFilePermissions(remote_file, 0700);
2857                                         if (launch_info)
2858                                             launch_info->SetExecutableFile(remote_file, false);
2859                                     }
2860                                 }
2861                                 else
2862                                     break;
2863                             }
2864                         }
2865                     }
2866                 }
2867             }
2868         }
2869     }
2870     return error;
2871 }
2872 
2873 bool
2874 Target::ResolveLoadAddress (addr_t load_addr, Address &so_addr, uint32_t stop_id)
2875 {
2876     return m_section_load_history.ResolveLoadAddress(stop_id, load_addr, so_addr);
2877 }
2878 
2879 bool
2880 Target::ResolveFileAddress (lldb::addr_t file_addr, Address &resolved_addr)
2881 {
2882     return m_images.ResolveFileAddress(file_addr, resolved_addr);
2883 }
2884 
2885 bool
2886 Target::SetSectionLoadAddress (const SectionSP &section_sp, addr_t new_section_load_addr, bool warn_multiple)
2887 {
2888     const addr_t old_section_load_addr = m_section_load_history.GetSectionLoadAddress (SectionLoadHistory::eStopIDNow, section_sp);
2889     if (old_section_load_addr != new_section_load_addr)
2890     {
2891         uint32_t stop_id = 0;
2892         ProcessSP process_sp(GetProcessSP());
2893         if (process_sp)
2894             stop_id = process_sp->GetStopID();
2895         else
2896             stop_id = m_section_load_history.GetLastStopID();
2897         if (m_section_load_history.SetSectionLoadAddress (stop_id, section_sp, new_section_load_addr, warn_multiple))
2898             return true; // Return true if the section load address was changed...
2899     }
2900     return false; // Return false to indicate nothing changed
2901 }
2902 
2903 size_t
2904 Target::UnloadModuleSections (const ModuleList &module_list)
2905 {
2906     size_t section_unload_count = 0;
2907     size_t num_modules = module_list.GetSize();
2908     for (size_t i=0; i<num_modules; ++i)
2909     {
2910         section_unload_count += UnloadModuleSections (module_list.GetModuleAtIndex(i));
2911     }
2912     return section_unload_count;
2913 }
2914 
2915 size_t
2916 Target::UnloadModuleSections (const lldb::ModuleSP &module_sp)
2917 {
2918     uint32_t stop_id = 0;
2919     ProcessSP process_sp(GetProcessSP());
2920     if (process_sp)
2921         stop_id = process_sp->GetStopID();
2922     else
2923         stop_id = m_section_load_history.GetLastStopID();
2924     SectionList *sections = module_sp->GetSectionList();
2925     size_t section_unload_count = 0;
2926     if (sections)
2927     {
2928         const uint32_t num_sections = sections->GetNumSections(0);
2929         for (uint32_t i = 0; i < num_sections; ++i)
2930         {
2931             section_unload_count += m_section_load_history.SetSectionUnloaded(stop_id, sections->GetSectionAtIndex(i));
2932         }
2933     }
2934     return section_unload_count;
2935 }
2936 
2937 bool
2938 Target::SetSectionUnloaded (const lldb::SectionSP &section_sp)
2939 {
2940     uint32_t stop_id = 0;
2941     ProcessSP process_sp(GetProcessSP());
2942     if (process_sp)
2943         stop_id = process_sp->GetStopID();
2944     else
2945         stop_id = m_section_load_history.GetLastStopID();
2946     return m_section_load_history.SetSectionUnloaded (stop_id, section_sp);
2947 }
2948 
2949 bool
2950 Target::SetSectionUnloaded (const lldb::SectionSP &section_sp, addr_t load_addr)
2951 {
2952     uint32_t stop_id = 0;
2953     ProcessSP process_sp(GetProcessSP());
2954     if (process_sp)
2955         stop_id = process_sp->GetStopID();
2956     else
2957         stop_id = m_section_load_history.GetLastStopID();
2958     return m_section_load_history.SetSectionUnloaded (stop_id, section_sp, load_addr);
2959 }
2960 
2961 void
2962 Target::ClearAllLoadedSections ()
2963 {
2964     m_section_load_history.Clear();
2965 }
2966 
2967 Error
2968 Target::Launch (ProcessLaunchInfo &launch_info, Stream *stream)
2969 {
2970     Error error;
2971     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_TARGET));
2972 
2973     if (log)
2974         log->Printf ("Target::%s() called for %s", __FUNCTION__, launch_info.GetExecutableFile().GetPath().c_str ());
2975 
2976     StateType state = eStateInvalid;
2977 
2978     // Scope to temporarily get the process state in case someone has manually
2979     // remotely connected already to a process and we can skip the platform
2980     // launching.
2981     {
2982         ProcessSP process_sp (GetProcessSP());
2983 
2984         if (process_sp)
2985         {
2986             state = process_sp->GetState();
2987             if (log)
2988                 log->Printf ("Target::%s the process exists, and its current state is %s", __FUNCTION__, StateAsCString (state));
2989         }
2990         else
2991         {
2992             if (log)
2993                 log->Printf ("Target::%s the process instance doesn't currently exist.", __FUNCTION__);
2994         }
2995     }
2996 
2997     launch_info.GetFlags().Set (eLaunchFlagDebug);
2998 
2999     // Get the value of synchronous execution here.  If you wait till after you have started to
3000     // run, then you could have hit a breakpoint, whose command might switch the value, and
3001     // then you'll pick up that incorrect value.
3002     Debugger &debugger = GetDebugger();
3003     const bool synchronous_execution = debugger.GetCommandInterpreter().GetSynchronous ();
3004 
3005     PlatformSP platform_sp (GetPlatform());
3006 
3007     // Finalize the file actions, and if none were given, default to opening
3008     // up a pseudo terminal
3009     const bool default_to_use_pty = platform_sp ? platform_sp->IsHost() : false;
3010     if (log)
3011         log->Printf ("Target::%s have platform=%s, platform_sp->IsHost()=%s, default_to_use_pty=%s",
3012                      __FUNCTION__,
3013                      platform_sp ? "true" : "false",
3014                      platform_sp ? (platform_sp->IsHost () ? "true" : "false") : "n/a",
3015                      default_to_use_pty ? "true" : "false");
3016 
3017     launch_info.FinalizeFileActions (this, default_to_use_pty);
3018 
3019     if (state == eStateConnected)
3020     {
3021         if (launch_info.GetFlags().Test (eLaunchFlagLaunchInTTY))
3022         {
3023             error.SetErrorString("can't launch in tty when launching through a remote connection");
3024             return error;
3025         }
3026     }
3027 
3028     if (!launch_info.GetArchitecture().IsValid())
3029         launch_info.GetArchitecture() = GetArchitecture();
3030 
3031     // 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.
3032     if (state != eStateConnected && platform_sp && platform_sp->CanDebugProcess ())
3033     {
3034         if (log)
3035             log->Printf ("Target::%s asking the platform to debug the process", __FUNCTION__);
3036 
3037         // Get a weak pointer to the previous process if we have one
3038         ProcessWP process_wp;
3039         if (m_process_sp)
3040             process_wp = m_process_sp;
3041         m_process_sp = GetPlatform()->DebugProcess (launch_info,
3042                                                     debugger,
3043                                                     this,
3044                                                     error);
3045 
3046         // Cleanup the old process since someone might still have a strong
3047         // reference to this process and we would like to allow it to cleanup
3048         // as much as it can without the object being destroyed. We try to
3049         // lock the shared pointer and if that works, then someone else still
3050         // has a strong reference to the process.
3051 
3052         ProcessSP old_process_sp(process_wp.lock());
3053         if (old_process_sp)
3054             old_process_sp->Finalize();
3055     }
3056     else
3057     {
3058         if (log)
3059             log->Printf ("Target::%s the platform doesn't know how to debug a process, getting a process plugin to do this for us.", __FUNCTION__);
3060 
3061         if (state == eStateConnected)
3062         {
3063             assert(m_process_sp);
3064         }
3065         else
3066         {
3067             // Use a Process plugin to construct the process.
3068             const char *plugin_name = launch_info.GetProcessPluginName();
3069             CreateProcess(launch_info.GetListenerForProcess(debugger), plugin_name, nullptr);
3070         }
3071 
3072         // Since we didn't have a platform launch the process, launch it here.
3073         if (m_process_sp)
3074             error = m_process_sp->Launch (launch_info);
3075     }
3076 
3077     if (!m_process_sp)
3078     {
3079         if (error.Success())
3080             error.SetErrorString("failed to launch or debug process");
3081         return error;
3082     }
3083 
3084     if (error.Success())
3085     {
3086         if (synchronous_execution || !launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3087         {
3088             ListenerSP hijack_listener_sp (launch_info.GetHijackListener());
3089             if (!hijack_listener_sp)
3090             {
3091                 hijack_listener_sp = Listener::MakeListener("lldb.Target.Launch.hijack");
3092                 launch_info.SetHijackListener(hijack_listener_sp);
3093                 m_process_sp->HijackProcessEvents(hijack_listener_sp);
3094             }
3095 
3096             StateType state = m_process_sp->WaitForProcessToStop(nullptr, nullptr, false, hijack_listener_sp, nullptr);
3097 
3098             if (state == eStateStopped)
3099             {
3100                 if (!launch_info.GetFlags().Test(eLaunchFlagStopAtEntry))
3101                 {
3102                     if (synchronous_execution)
3103                     {
3104                         error = m_process_sp->PrivateResume();
3105                         if (error.Success())
3106                         {
3107                             state = m_process_sp->WaitForProcessToStop(nullptr, nullptr, true, hijack_listener_sp, stream);
3108                             const bool must_be_alive = false; // eStateExited is ok, so this must be false
3109                             if (!StateIsStoppedState(state, must_be_alive))
3110                             {
3111                                 error.SetErrorStringWithFormat("process isn't stopped: %s", StateAsCString(state));
3112                             }
3113                         }
3114                     }
3115                     else
3116                     {
3117                         m_process_sp->RestoreProcessEvents();
3118                         error = m_process_sp->PrivateResume();
3119                     }
3120                     if (!error.Success())
3121                     {
3122                         Error error2;
3123                         error2.SetErrorStringWithFormat("process resume at entry point failed: %s", error.AsCString());
3124                         error = error2;
3125                     }
3126                 }
3127             }
3128             else if (state == eStateExited)
3129             {
3130                 bool with_shell = !!launch_info.GetShell();
3131                 const int exit_status = m_process_sp->GetExitStatus();
3132                 const char *exit_desc = m_process_sp->GetExitDescription();
3133 #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'."
3134                 if (exit_desc && exit_desc[0])
3135                 {
3136                     if (with_shell)
3137                         error.SetErrorStringWithFormat ("process exited with status %i (%s)" LAUNCH_SHELL_MESSAGE, exit_status, exit_desc);
3138                     else
3139                         error.SetErrorStringWithFormat ("process exited with status %i (%s)", exit_status, exit_desc);
3140                 }
3141                 else
3142                 {
3143                     if (with_shell)
3144                         error.SetErrorStringWithFormat ("process exited with status %i" LAUNCH_SHELL_MESSAGE, exit_status);
3145                     else
3146                         error.SetErrorStringWithFormat ("process exited with status %i", exit_status);
3147                 }
3148             }
3149             else
3150             {
3151                 error.SetErrorStringWithFormat ("initial process state wasn't stopped: %s", StateAsCString(state));
3152             }
3153         }
3154         m_process_sp->RestoreProcessEvents ();
3155     }
3156     else
3157     {
3158         Error error2;
3159         error2.SetErrorStringWithFormat ("process launch failed: %s", error.AsCString());
3160         error = error2;
3161     }
3162     return error;
3163 }
3164 
3165 Error
3166 Target::Attach (ProcessAttachInfo &attach_info, Stream *stream)
3167 {
3168     auto state = eStateInvalid;
3169     auto process_sp = GetProcessSP ();
3170     if (process_sp)
3171     {
3172         state = process_sp->GetState ();
3173         if (process_sp->IsAlive () && state != eStateConnected)
3174         {
3175             if (state == eStateAttaching)
3176                 return Error ("process attach is in progress");
3177             return Error ("a process is already being debugged");
3178         }
3179     }
3180 
3181     const ModuleSP old_exec_module_sp = GetExecutableModule ();
3182 
3183     // If no process info was specified, then use the target executable
3184     // name as the process to attach to by default
3185     if (!attach_info.ProcessInfoSpecified ())
3186     {
3187         if (old_exec_module_sp)
3188             attach_info.GetExecutableFile ().GetFilename () = old_exec_module_sp->GetPlatformFileSpec ().GetFilename ();
3189 
3190         if (!attach_info.ProcessInfoSpecified ())
3191         {
3192             return Error ("no process specified, create a target with a file, or specify the --pid or --name");
3193         }
3194     }
3195 
3196     const auto platform_sp = GetDebugger ().GetPlatformList ().GetSelectedPlatform ();
3197     ListenerSP hijack_listener_sp;
3198     const bool async = attach_info.GetAsync();
3199     if (!async)
3200     {
3201         hijack_listener_sp = Listener::MakeListener("lldb.Target.Attach.attach.hijack");
3202         attach_info.SetHijackListener (hijack_listener_sp);
3203     }
3204 
3205     Error error;
3206     if (state != eStateConnected && platform_sp != nullptr && platform_sp->CanDebugProcess ())
3207     {
3208         SetPlatform (platform_sp);
3209         process_sp = platform_sp->Attach (attach_info, GetDebugger (), this, error);
3210     }
3211     else
3212     {
3213         if (state != eStateConnected)
3214         {
3215             const char *plugin_name = attach_info.GetProcessPluginName ();
3216             process_sp = CreateProcess (attach_info.GetListenerForProcess (GetDebugger ()), plugin_name, nullptr);
3217             if (process_sp == nullptr)
3218             {
3219                 error.SetErrorStringWithFormat ("failed to create process using plugin %s", (plugin_name) ? plugin_name : "null");
3220                 return error;
3221             }
3222         }
3223         if (hijack_listener_sp)
3224             process_sp->HijackProcessEvents (hijack_listener_sp);
3225         error = process_sp->Attach (attach_info);
3226     }
3227 
3228     if (error.Success () && process_sp)
3229     {
3230         if (async)
3231         {
3232             process_sp->RestoreProcessEvents ();
3233         }
3234         else
3235         {
3236             state = process_sp->WaitForProcessToStop (nullptr, nullptr, false, attach_info.GetHijackListener(), stream);
3237             process_sp->RestoreProcessEvents ();
3238 
3239             if (state != eStateStopped)
3240             {
3241                 const char *exit_desc = process_sp->GetExitDescription ();
3242                 if (exit_desc)
3243                     error.SetErrorStringWithFormat ("%s", exit_desc);
3244                 else
3245                     error.SetErrorString ("process did not stop (no such process or permission problem?)");
3246                 process_sp->Destroy (false);
3247             }
3248         }
3249     }
3250     return error;
3251 }
3252 
3253 //--------------------------------------------------------------
3254 // Target::StopHook
3255 //--------------------------------------------------------------
3256 Target::StopHook::StopHook (lldb::TargetSP target_sp, lldb::user_id_t uid) :
3257         UserID (uid),
3258         m_target_sp (target_sp),
3259         m_commands (),
3260         m_specifier_sp (),
3261         m_thread_spec_ap(),
3262         m_active (true)
3263 {
3264 }
3265 
3266 Target::StopHook::StopHook (const StopHook &rhs) :
3267         UserID (rhs.GetID()),
3268         m_target_sp (rhs.m_target_sp),
3269         m_commands (rhs.m_commands),
3270         m_specifier_sp (rhs.m_specifier_sp),
3271         m_thread_spec_ap (),
3272         m_active (rhs.m_active)
3273 {
3274     if (rhs.m_thread_spec_ap)
3275         m_thread_spec_ap.reset (new ThreadSpec(*rhs.m_thread_spec_ap.get()));
3276 }
3277 
3278 Target::StopHook::~StopHook() = default;
3279 
3280 void
3281 Target::StopHook::SetSpecifier(SymbolContextSpecifier *specifier)
3282 {
3283     m_specifier_sp.reset(specifier);
3284 }
3285 
3286 void
3287 Target::StopHook::SetThreadSpecifier (ThreadSpec *specifier)
3288 {
3289     m_thread_spec_ap.reset (specifier);
3290 }
3291 
3292 void
3293 Target::StopHook::GetDescription (Stream *s, lldb::DescriptionLevel level) const
3294 {
3295     int indent_level = s->GetIndentLevel();
3296 
3297     s->SetIndentLevel(indent_level + 2);
3298 
3299     s->Printf ("Hook: %" PRIu64 "\n", GetID());
3300     if (m_active)
3301         s->Indent ("State: enabled\n");
3302     else
3303         s->Indent ("State: disabled\n");
3304 
3305     if (m_specifier_sp)
3306     {
3307         s->Indent();
3308         s->PutCString ("Specifier:\n");
3309         s->SetIndentLevel (indent_level + 4);
3310         m_specifier_sp->GetDescription (s, level);
3311         s->SetIndentLevel (indent_level + 2);
3312     }
3313 
3314     if (m_thread_spec_ap)
3315     {
3316         StreamString tmp;
3317         s->Indent("Thread:\n");
3318         m_thread_spec_ap->GetDescription (&tmp, level);
3319         s->SetIndentLevel (indent_level + 4);
3320         s->Indent (tmp.GetData());
3321         s->PutCString ("\n");
3322         s->SetIndentLevel (indent_level + 2);
3323     }
3324 
3325     s->Indent ("Commands: \n");
3326     s->SetIndentLevel (indent_level + 4);
3327     uint32_t num_commands = m_commands.GetSize();
3328     for (uint32_t i = 0; i < num_commands; i++)
3329     {
3330         s->Indent(m_commands.GetStringAtIndex(i));
3331         s->PutCString ("\n");
3332     }
3333     s->SetIndentLevel (indent_level);
3334 }
3335 
3336 //--------------------------------------------------------------
3337 // class TargetProperties
3338 //--------------------------------------------------------------
3339 
3340 OptionEnumValueElement
3341 lldb_private::g_dynamic_value_types[] =
3342 {
3343     { eNoDynamicValues,      "no-dynamic-values", "Don't calculate the dynamic type of values"},
3344     { eDynamicCanRunTarget,  "run-target",        "Calculate the dynamic type of values even if you have to run the target."},
3345     { eDynamicDontRunTarget, "no-run-target",     "Calculate the dynamic type of values, but don't run the target."},
3346     { 0, nullptr, nullptr }
3347 };
3348 
3349 static OptionEnumValueElement
3350 g_inline_breakpoint_enums[] =
3351 {
3352     { 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."},
3353     { eInlineBreakpointsHeaders, "headers",   "Only check for inline breakpoint locations when setting breakpoints in header files, but not when setting breakpoint in implementation source files (default)."},
3354     { eInlineBreakpointsAlways,  "always",    "Always look for inline breakpoint locations when setting file and line breakpoints (slower but most accurate)."},
3355     { 0, nullptr, nullptr }
3356 };
3357 
3358 typedef enum x86DisassemblyFlavor
3359 {
3360     eX86DisFlavorDefault,
3361     eX86DisFlavorIntel,
3362     eX86DisFlavorATT
3363 } x86DisassemblyFlavor;
3364 
3365 static OptionEnumValueElement
3366 g_x86_dis_flavor_value_types[] =
3367 {
3368     { eX86DisFlavorDefault, "default", "Disassembler default (currently att)."},
3369     { eX86DisFlavorIntel,   "intel",   "Intel disassembler flavor."},
3370     { eX86DisFlavorATT,     "att",     "AT&T disassembler flavor."},
3371     { 0, nullptr, nullptr }
3372 };
3373 
3374 static OptionEnumValueElement
3375 g_hex_immediate_style_values[] =
3376 {
3377     { Disassembler::eHexStyleC,        "c",      "C-style (0xffff)."},
3378     { Disassembler::eHexStyleAsm,      "asm",    "Asm-style (0ffffh)."},
3379     { 0, nullptr, nullptr }
3380 };
3381 
3382 static OptionEnumValueElement
3383 g_load_script_from_sym_file_values[] =
3384 {
3385     { eLoadScriptFromSymFileTrue,    "true",    "Load debug scripts inside symbol files"},
3386     { eLoadScriptFromSymFileFalse,   "false",   "Do not load debug scripts inside symbol files."},
3387     { eLoadScriptFromSymFileWarn,    "warn",    "Warn about debug scripts inside symbol files but do not load them."},
3388     { 0, nullptr, nullptr }
3389 };
3390 
3391 static OptionEnumValueElement
3392 g_load_current_working_dir_lldbinit_values[] =
3393 {
3394     { eLoadCWDlldbinitTrue,    "true",    "Load .lldbinit files from current directory"},
3395     { eLoadCWDlldbinitFalse,   "false",   "Do not load .lldbinit files from current directory"},
3396     { eLoadCWDlldbinitWarn,    "warn",    "Warn about loading .lldbinit files from current directory"},
3397     { 0, nullptr, nullptr }
3398 };
3399 
3400 static OptionEnumValueElement
3401 g_memory_module_load_level_values[] =
3402 {
3403     { eMemoryModuleLoadLevelMinimal,  "minimal" , "Load minimal information when loading modules from memory. Currently this setting loads sections only."},
3404     { eMemoryModuleLoadLevelPartial,  "partial" , "Load partial information when loading modules from memory. Currently this setting loads sections and function bounds."},
3405     { eMemoryModuleLoadLevelComplete, "complete", "Load complete information when loading modules from memory. Currently this setting loads sections and all symbols."},
3406     { 0, nullptr, nullptr }
3407 };
3408 
3409 static PropertyDefinition
3410 g_properties[] =
3411 {
3412     { "default-arch"                       , OptionValue::eTypeArch      , true , 0                         , nullptr, nullptr, "Default architecture to choose, when there's a choice." },
3413     { "move-to-nearest-code"               , OptionValue::eTypeBoolean   , false, true                      , nullptr, nullptr, "Move breakpoints to nearest code." },
3414     { "language"                           , OptionValue::eTypeLanguage  , false, eLanguageTypeUnknown      , nullptr, nullptr, "The language to use when interpreting expressions entered in commands." },
3415     { "expr-prefix"                        , OptionValue::eTypeFileSpec  , false, 0                         , nullptr, nullptr, "Path to a file containing expressions to be prepended to all expressions." },
3416     { "prefer-dynamic-value"               , OptionValue::eTypeEnum      , false, eDynamicDontRunTarget     , nullptr, g_dynamic_value_types, "Should printed values be shown as their dynamic value." },
3417     { "enable-synthetic-value"             , OptionValue::eTypeBoolean   , false, true                      , nullptr, nullptr, "Should synthetic values be used by default whenever available." },
3418     { "skip-prologue"                      , OptionValue::eTypeBoolean   , false, true                      , nullptr, nullptr, "Skip function prologues when setting breakpoints by name." },
3419     { "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 "
3420       "where it exists on the current system.  It consists of an array of duples, the first element of each duple is "
3421       "some part (starting at the root) of the path to the file when it was built, "
3422       "and the second is where the remainder of the original build hierarchy is rooted on the local system.  "
3423       "Each element of the array is checked in order and the first one that results in a match wins." },
3424     { "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." },
3425     { "debug-file-search-paths"            , OptionValue::eTypeFileSpecList, false, 0                       , nullptr, nullptr, "List of directories to be searched when locating debug symbol files." },
3426     { "clang-module-search-paths"          , OptionValue::eTypeFileSpecList, false, 0                       , nullptr, nullptr, "List of directories to be searched when locating modules for Clang." },
3427     { "auto-import-clang-modules"          , OptionValue::eTypeBoolean   , false, true                      , nullptr, nullptr, "Automatically load Clang modules referred to by the program." },
3428     { "max-children-count"                 , OptionValue::eTypeSInt64    , false, 256                       , nullptr, nullptr, "Maximum number of children to expand in any level of depth." },
3429     { "max-string-summary-length"          , OptionValue::eTypeSInt64    , false, 1024                      , nullptr, nullptr, "Maximum number of characters to show when using %s in summary strings." },
3430     { "max-memory-read-size"               , OptionValue::eTypeSInt64    , false, 1024                      , nullptr, nullptr, "Maximum number of bytes that 'memory read' will fetch before --force must be specified." },
3431     { "breakpoints-use-platform-avoid-list", OptionValue::eTypeBoolean   , false, true                      , nullptr, nullptr, "Consult the platform module avoid list when setting non-module specific breakpoints." },
3432     { "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." },
3433     { "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." },
3434     { "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." },
3435     { "inherit-env"                        , OptionValue::eTypeBoolean   , false, true                      , nullptr, nullptr, "Inherit the environment from the process that is running LLDB." },
3436     { "input-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , nullptr, nullptr, "The file/path to be used by the executable program for reading its standard input." },
3437     { "output-path"                        , OptionValue::eTypeFileSpec  , false, 0                         , nullptr, nullptr, "The file/path to be used by the executable program for writing its standard output." },
3438     { "error-path"                         , OptionValue::eTypeFileSpec  , false, 0                         , nullptr, nullptr, "The file/path to be used by the executable program for writing its standard error." },
3439     { "detach-on-error"                    , OptionValue::eTypeBoolean   , false, true                      , nullptr, nullptr, "debugserver will detach (rather than killing) a process if it loses connection with lldb." },
3440     { "disable-aslr"                       , OptionValue::eTypeBoolean   , false, true                      , nullptr, nullptr, "Disable Address Space Layout Randomization (ASLR)" },
3441     { "disable-stdio"                      , OptionValue::eTypeBoolean   , false, false                     , nullptr, nullptr, "Disable stdin/stdout for process (e.g. for a GUI application)" },
3442     { "inline-breakpoint-strategy"         , OptionValue::eTypeEnum      , false, eInlineBreakpointsAlways  , nullptr, g_inline_breakpoint_enums, "The strategy to use when settings breakpoints by file and line. "
3443         "Breakpoint locations can end up being inlined by the compiler, so that a compile unit 'a.c' might contain an inlined function from another source file. "
3444         "Usually this is limited to breakpoint locations from inlined functions from header or other include files, or more accurately non-implementation source files. "
3445         "Sometimes code might #include implementation files and cause inlined breakpoint locations in inlined implementation files. "
3446         "Always checking for inlined breakpoint locations can be expensive (memory and time), so if you have a project with many headers "
3447         "and find that setting breakpoints is slow, then you can change this setting to headers. "
3448         "This setting allows you to control exactly which strategy is used when setting "
3449         "file and line breakpoints." },
3450     // 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.
3451     { "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." },
3452     { "use-hex-immediates"                 , OptionValue::eTypeBoolean   , false, true,                       nullptr, nullptr, "Show immediates in disassembly as hexadecimal." },
3453     { "hex-immediate-style"                , OptionValue::eTypeEnum   ,    false, Disassembler::eHexStyleC,   nullptr, g_hex_immediate_style_values, "Which style to use for printing hexadecimal disassembly values." },
3454     { "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." },
3455     { "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." },
3456     { "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." },
3457     { "memory-module-load-level"           , OptionValue::eTypeEnum   ,    false, eMemoryModuleLoadLevelComplete, nullptr, g_memory_module_load_level_values,
3458         "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. "
3459         "This setting helps users control how much information gets loaded when loading modules from memory."
3460         "'complete' is the default value for this setting which will load all sections and symbols by reading them from memory (slowest, most accurate). "
3461         "'partial' will load sections and attempt to find function bounds without downloading the symbol table (faster, still accurate, missing symbol names). "
3462         "'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). " },
3463     { "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." },
3464     { "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." },
3465     { "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." },
3466     { "non-stop-mode"                      , OptionValue::eTypeBoolean   , false, 0,                          nullptr, nullptr, "Disable lock-step debugging, instead control threads independently." },
3467     { nullptr                                 , OptionValue::eTypeInvalid   , false, 0                         , nullptr, nullptr, nullptr }
3468 };
3469 
3470 enum
3471 {
3472     ePropertyDefaultArch,
3473     ePropertyMoveToNearestCode,
3474     ePropertyLanguage,
3475     ePropertyExprPrefix,
3476     ePropertyPreferDynamic,
3477     ePropertyEnableSynthetic,
3478     ePropertySkipPrologue,
3479     ePropertySourceMap,
3480     ePropertyExecutableSearchPaths,
3481     ePropertyDebugFileSearchPaths,
3482     ePropertyClangModuleSearchPaths,
3483     ePropertyAutoImportClangModules,
3484     ePropertyMaxChildrenCount,
3485     ePropertyMaxSummaryLength,
3486     ePropertyMaxMemReadSize,
3487     ePropertyBreakpointUseAvoidList,
3488     ePropertyArg0,
3489     ePropertyRunArgs,
3490     ePropertyEnvVars,
3491     ePropertyInheritEnv,
3492     ePropertyInputPath,
3493     ePropertyOutputPath,
3494     ePropertyErrorPath,
3495     ePropertyDetachOnError,
3496     ePropertyDisableASLR,
3497     ePropertyDisableSTDIO,
3498     ePropertyInlineStrategy,
3499     ePropertyDisassemblyFlavor,
3500     ePropertyUseHexImmediates,
3501     ePropertyHexImmediateStyle,
3502     ePropertyUseFastStepping,
3503     ePropertyLoadScriptFromSymbolFile,
3504     ePropertyLoadCWDlldbinitFile,
3505     ePropertyMemoryModuleLoadLevel,
3506     ePropertyDisplayExpressionsInCrashlogs,
3507     ePropertyTrapHandlerNames,
3508     ePropertyDisplayRuntimeSupportValues,
3509     ePropertyNonStopModeEnabled
3510 };
3511 
3512 class TargetOptionValueProperties : public OptionValueProperties
3513 {
3514 public:
3515     TargetOptionValueProperties (const ConstString &name) :
3516         OptionValueProperties (name),
3517         m_target(nullptr),
3518         m_got_host_env (false)
3519     {
3520     }
3521 
3522     // This constructor is used when creating TargetOptionValueProperties when it
3523     // is part of a new lldb_private::Target instance. It will copy all current
3524     // global property values as needed
3525     TargetOptionValueProperties (Target *target, const TargetPropertiesSP &target_properties_sp) :
3526         OptionValueProperties(*target_properties_sp->GetValueProperties()),
3527         m_target (target),
3528         m_got_host_env (false)
3529     {
3530     }
3531 
3532     const Property *
3533     GetPropertyAtIndex(const ExecutionContext *exe_ctx, bool will_modify, uint32_t idx) const override
3534     {
3535         // When getting the value for a key from the target options, we will always
3536         // try and grab the setting from the current target if there is one. Else we just
3537         // use the one from this instance.
3538         if (idx == ePropertyEnvVars)
3539             GetHostEnvironmentIfNeeded ();
3540 
3541         if (exe_ctx)
3542         {
3543             Target *target = exe_ctx->GetTargetPtr();
3544             if (target)
3545             {
3546                 TargetOptionValueProperties *target_properties = static_cast<TargetOptionValueProperties *>(target->GetValueProperties().get());
3547                 if (this != target_properties)
3548                     return target_properties->ProtectedGetPropertyAtIndex (idx);
3549             }
3550         }
3551         return ProtectedGetPropertyAtIndex (idx);
3552     }
3553 
3554     lldb::TargetSP
3555     GetTargetSP ()
3556     {
3557         return m_target->shared_from_this();
3558     }
3559 
3560 protected:
3561     void
3562     GetHostEnvironmentIfNeeded () const
3563     {
3564         if (!m_got_host_env)
3565         {
3566             if (m_target)
3567             {
3568                 m_got_host_env = true;
3569                 const uint32_t idx = ePropertyInheritEnv;
3570                 if (GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0))
3571                 {
3572                     PlatformSP platform_sp (m_target->GetPlatform());
3573                     if (platform_sp)
3574                     {
3575                         StringList env;
3576                         if (platform_sp->GetEnvironment(env))
3577                         {
3578                             OptionValueDictionary *env_dict = GetPropertyAtIndexAsOptionValueDictionary(nullptr, ePropertyEnvVars);
3579                             if (env_dict)
3580                             {
3581                                 const bool can_replace = false;
3582                                 const size_t envc = env.GetSize();
3583                                 for (size_t idx=0; idx<envc; idx++)
3584                                 {
3585                                     const char *env_entry = env.GetStringAtIndex (idx);
3586                                     if (env_entry)
3587                                     {
3588                                         const char *equal_pos = ::strchr(env_entry, '=');
3589                                         ConstString key;
3590                                         // It is ok to have environment variables with no values
3591                                         const char *value = nullptr;
3592                                         if (equal_pos)
3593                                         {
3594                                             key.SetCStringWithLength(env_entry, equal_pos - env_entry);
3595                                             if (equal_pos[1])
3596                                                 value = equal_pos + 1;
3597                                         }
3598                                         else
3599                                         {
3600                                             key.SetCString(env_entry);
3601                                         }
3602                                         // Don't allow existing keys to be replaced with ones we get from the platform environment
3603                                         env_dict->SetValueForKey(key, OptionValueSP(new OptionValueString(value)), can_replace);
3604                                     }
3605                                 }
3606                             }
3607                         }
3608                     }
3609                 }
3610             }
3611         }
3612     }
3613     Target *m_target;
3614     mutable bool m_got_host_env;
3615 };
3616 
3617 //----------------------------------------------------------------------
3618 // TargetProperties
3619 //----------------------------------------------------------------------
3620 TargetProperties::TargetProperties (Target *target) :
3621     Properties (),
3622     m_launch_info ()
3623 {
3624     if (target)
3625     {
3626         m_collection_sp.reset (new TargetOptionValueProperties(target, Target::GetGlobalProperties()));
3627 
3628         // Set callbacks to update launch_info whenever "settins set" updated any of these properties
3629         m_collection_sp->SetValueChangedCallback(ePropertyArg0, TargetProperties::Arg0ValueChangedCallback, this);
3630         m_collection_sp->SetValueChangedCallback(ePropertyRunArgs, TargetProperties::RunArgsValueChangedCallback, this);
3631         m_collection_sp->SetValueChangedCallback(ePropertyEnvVars, TargetProperties::EnvVarsValueChangedCallback, this);
3632         m_collection_sp->SetValueChangedCallback(ePropertyInputPath, TargetProperties::InputPathValueChangedCallback, this);
3633         m_collection_sp->SetValueChangedCallback(ePropertyOutputPath, TargetProperties::OutputPathValueChangedCallback, this);
3634         m_collection_sp->SetValueChangedCallback(ePropertyErrorPath, TargetProperties::ErrorPathValueChangedCallback, this);
3635         m_collection_sp->SetValueChangedCallback(ePropertyDetachOnError, TargetProperties::DetachOnErrorValueChangedCallback, this);
3636         m_collection_sp->SetValueChangedCallback(ePropertyDisableASLR, TargetProperties::DisableASLRValueChangedCallback, this);
3637         m_collection_sp->SetValueChangedCallback(ePropertyDisableSTDIO, TargetProperties::DisableSTDIOValueChangedCallback, this);
3638 
3639         // Update m_launch_info once it was created
3640         Arg0ValueChangedCallback(this, nullptr);
3641         RunArgsValueChangedCallback(this, nullptr);
3642         //EnvVarsValueChangedCallback(this, nullptr); // FIXME: cause segfault in Target::GetPlatform()
3643         InputPathValueChangedCallback(this, nullptr);
3644         OutputPathValueChangedCallback(this, nullptr);
3645         ErrorPathValueChangedCallback(this, nullptr);
3646         DetachOnErrorValueChangedCallback(this, nullptr);
3647         DisableASLRValueChangedCallback(this, nullptr);
3648         DisableSTDIOValueChangedCallback(this, nullptr);
3649     }
3650     else
3651     {
3652         m_collection_sp.reset (new TargetOptionValueProperties(ConstString("target")));
3653         m_collection_sp->Initialize(g_properties);
3654         m_collection_sp->AppendProperty(ConstString("process"),
3655                                         ConstString("Settings specify to processes."),
3656                                         true,
3657                                         Process::GetGlobalProperties()->GetValueProperties());
3658     }
3659 }
3660 
3661 TargetProperties::~TargetProperties() = default;
3662 
3663 ArchSpec
3664 TargetProperties::GetDefaultArchitecture () const
3665 {
3666     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(nullptr, ePropertyDefaultArch);
3667     if (value)
3668         return value->GetCurrentValue();
3669     return ArchSpec();
3670 }
3671 
3672 void
3673 TargetProperties::SetDefaultArchitecture (const ArchSpec& arch)
3674 {
3675     OptionValueArch *value = m_collection_sp->GetPropertyAtIndexAsOptionValueArch(nullptr, ePropertyDefaultArch);
3676     if (value)
3677         return value->SetCurrentValue(arch, true);
3678 }
3679 
3680 bool
3681 TargetProperties::GetMoveToNearestCode() const
3682 {
3683     const uint32_t idx = ePropertyMoveToNearestCode;
3684     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3685 }
3686 
3687 lldb::DynamicValueType
3688 TargetProperties::GetPreferDynamicValue() const
3689 {
3690     const uint32_t idx = ePropertyPreferDynamic;
3691     return (lldb::DynamicValueType)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3692 }
3693 
3694 bool
3695 TargetProperties::SetPreferDynamicValue (lldb::DynamicValueType d)
3696 {
3697     const uint32_t idx = ePropertyPreferDynamic;
3698     return m_collection_sp->SetPropertyAtIndexAsEnumeration(nullptr, idx, d);
3699 }
3700 
3701 bool
3702 TargetProperties::GetDisableASLR () const
3703 {
3704     const uint32_t idx = ePropertyDisableASLR;
3705     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3706 }
3707 
3708 void
3709 TargetProperties::SetDisableASLR (bool b)
3710 {
3711     const uint32_t idx = ePropertyDisableASLR;
3712     m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3713 }
3714 
3715 bool
3716 TargetProperties::GetDetachOnError () const
3717 {
3718     const uint32_t idx = ePropertyDetachOnError;
3719     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3720 }
3721 
3722 void
3723 TargetProperties::SetDetachOnError (bool b)
3724 {
3725     const uint32_t idx = ePropertyDetachOnError;
3726     m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3727 }
3728 
3729 bool
3730 TargetProperties::GetDisableSTDIO () const
3731 {
3732     const uint32_t idx = ePropertyDisableSTDIO;
3733     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3734 }
3735 
3736 void
3737 TargetProperties::SetDisableSTDIO (bool b)
3738 {
3739     const uint32_t idx = ePropertyDisableSTDIO;
3740     m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
3741 }
3742 
3743 const char *
3744 TargetProperties::GetDisassemblyFlavor () const
3745 {
3746     const uint32_t idx = ePropertyDisassemblyFlavor;
3747     const char *return_value;
3748 
3749     x86DisassemblyFlavor flavor_value = (x86DisassemblyFlavor) m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3750     return_value = g_x86_dis_flavor_value_types[flavor_value].string_value;
3751     return return_value;
3752 }
3753 
3754 InlineStrategy
3755 TargetProperties::GetInlineStrategy () const
3756 {
3757     const uint32_t idx = ePropertyInlineStrategy;
3758     return (InlineStrategy)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3759 }
3760 
3761 const char *
3762 TargetProperties::GetArg0 () const
3763 {
3764     const uint32_t idx = ePropertyArg0;
3765     return m_collection_sp->GetPropertyAtIndexAsString(nullptr, idx, nullptr);
3766 }
3767 
3768 void
3769 TargetProperties::SetArg0 (const char *arg)
3770 {
3771     const uint32_t idx = ePropertyArg0;
3772     m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, arg);
3773     m_launch_info.SetArg0(arg);
3774 }
3775 
3776 bool
3777 TargetProperties::GetRunArguments (Args &args) const
3778 {
3779     const uint32_t idx = ePropertyRunArgs;
3780     return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
3781 }
3782 
3783 void
3784 TargetProperties::SetRunArguments (const Args &args)
3785 {
3786     const uint32_t idx = ePropertyRunArgs;
3787     m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
3788     m_launch_info.GetArguments() = args;
3789 }
3790 
3791 size_t
3792 TargetProperties::GetEnvironmentAsArgs (Args &env) const
3793 {
3794     const uint32_t idx = ePropertyEnvVars;
3795     return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, env);
3796 }
3797 
3798 void
3799 TargetProperties::SetEnvironmentFromArgs (const Args &env)
3800 {
3801     const uint32_t idx = ePropertyEnvVars;
3802     m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, env);
3803     m_launch_info.GetEnvironmentEntries() = env;
3804 }
3805 
3806 bool
3807 TargetProperties::GetSkipPrologue() const
3808 {
3809     const uint32_t idx = ePropertySkipPrologue;
3810     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3811 }
3812 
3813 PathMappingList &
3814 TargetProperties::GetSourcePathMap () const
3815 {
3816     const uint32_t idx = ePropertySourceMap;
3817     OptionValuePathMappings *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValuePathMappings(nullptr, false, idx);
3818     assert(option_value);
3819     return option_value->GetCurrentValue();
3820 }
3821 
3822 FileSpecList &
3823 TargetProperties::GetExecutableSearchPaths ()
3824 {
3825     const uint32_t idx = ePropertyExecutableSearchPaths;
3826     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx);
3827     assert(option_value);
3828     return option_value->GetCurrentValue();
3829 }
3830 
3831 FileSpecList &
3832 TargetProperties::GetDebugFileSearchPaths ()
3833 {
3834     const uint32_t idx = ePropertyDebugFileSearchPaths;
3835     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx);
3836     assert(option_value);
3837     return option_value->GetCurrentValue();
3838 }
3839 
3840 FileSpecList &
3841 TargetProperties::GetClangModuleSearchPaths ()
3842 {
3843     const uint32_t idx = ePropertyClangModuleSearchPaths;
3844     OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, false, idx);
3845     assert(option_value);
3846     return option_value->GetCurrentValue();
3847 }
3848 
3849 bool
3850 TargetProperties::GetEnableAutoImportClangModules() const
3851 {
3852     const uint32_t idx = ePropertyAutoImportClangModules;
3853     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3854 }
3855 
3856 bool
3857 TargetProperties::GetEnableSyntheticValue () const
3858 {
3859     const uint32_t idx = ePropertyEnableSynthetic;
3860     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3861 }
3862 
3863 uint32_t
3864 TargetProperties::GetMaximumNumberOfChildrenToDisplay() const
3865 {
3866     const uint32_t idx = ePropertyMaxChildrenCount;
3867     return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value);
3868 }
3869 
3870 uint32_t
3871 TargetProperties::GetMaximumSizeOfStringSummary() const
3872 {
3873     const uint32_t idx = ePropertyMaxSummaryLength;
3874     return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value);
3875 }
3876 
3877 uint32_t
3878 TargetProperties::GetMaximumMemReadSize () const
3879 {
3880     const uint32_t idx = ePropertyMaxMemReadSize;
3881     return m_collection_sp->GetPropertyAtIndexAsSInt64(nullptr, idx, g_properties[idx].default_uint_value);
3882 }
3883 
3884 FileSpec
3885 TargetProperties::GetStandardInputPath () const
3886 {
3887     const uint32_t idx = ePropertyInputPath;
3888     return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3889 }
3890 
3891 void
3892 TargetProperties::SetStandardInputPath (const char *p)
3893 {
3894     const uint32_t idx = ePropertyInputPath;
3895     m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
3896 }
3897 
3898 FileSpec
3899 TargetProperties::GetStandardOutputPath () const
3900 {
3901     const uint32_t idx = ePropertyOutputPath;
3902     return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3903 }
3904 
3905 void
3906 TargetProperties::SetStandardOutputPath (const char *p)
3907 {
3908     const uint32_t idx = ePropertyOutputPath;
3909     m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
3910 }
3911 
3912 FileSpec
3913 TargetProperties::GetStandardErrorPath () const
3914 {
3915     const uint32_t idx = ePropertyErrorPath;
3916     return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx);
3917 }
3918 
3919 LanguageType
3920 TargetProperties::GetLanguage () const
3921 {
3922     OptionValueLanguage *value = m_collection_sp->GetPropertyAtIndexAsOptionValueLanguage(nullptr, ePropertyLanguage);
3923     if (value)
3924         return value->GetCurrentValue();
3925     return LanguageType();
3926 }
3927 
3928 const char *
3929 TargetProperties::GetExpressionPrefixContentsAsCString ()
3930 {
3931     const uint32_t idx = ePropertyExprPrefix;
3932     OptionValueFileSpec *file = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpec(nullptr, false, idx);
3933     if (file)
3934     {
3935         const bool null_terminate = true;
3936         DataBufferSP data_sp(file->GetFileContents(null_terminate));
3937         if (data_sp)
3938             return (const char *) data_sp->GetBytes();
3939     }
3940     return nullptr;
3941 }
3942 
3943 void
3944 TargetProperties::SetStandardErrorPath (const char *p)
3945 {
3946     const uint32_t idx = ePropertyErrorPath;
3947     m_collection_sp->SetPropertyAtIndexAsString(nullptr, idx, p);
3948 }
3949 
3950 bool
3951 TargetProperties::GetBreakpointsConsultPlatformAvoidList ()
3952 {
3953     const uint32_t idx = ePropertyBreakpointUseAvoidList;
3954     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3955 }
3956 
3957 bool
3958 TargetProperties::GetUseHexImmediates () const
3959 {
3960     const uint32_t idx = ePropertyUseHexImmediates;
3961     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3962 }
3963 
3964 bool
3965 TargetProperties::GetUseFastStepping () const
3966 {
3967     const uint32_t idx = ePropertyUseFastStepping;
3968     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3969 }
3970 
3971 bool
3972 TargetProperties::GetDisplayExpressionsInCrashlogs () const
3973 {
3974     const uint32_t idx = ePropertyDisplayExpressionsInCrashlogs;
3975     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, g_properties[idx].default_uint_value != 0);
3976 }
3977 
3978 LoadScriptFromSymFile
3979 TargetProperties::GetLoadScriptFromSymbolFile () const
3980 {
3981     const uint32_t idx = ePropertyLoadScriptFromSymbolFile;
3982     return (LoadScriptFromSymFile)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3983 }
3984 
3985 LoadCWDlldbinitFile
3986 TargetProperties::GetLoadCWDlldbinitFile () const
3987 {
3988     const uint32_t idx = ePropertyLoadCWDlldbinitFile;
3989     return (LoadCWDlldbinitFile) m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3990 }
3991 
3992 Disassembler::HexImmediateStyle
3993 TargetProperties::GetHexImmediateStyle () const
3994 {
3995     const uint32_t idx = ePropertyHexImmediateStyle;
3996     return (Disassembler::HexImmediateStyle)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
3997 }
3998 
3999 MemoryModuleLoadLevel
4000 TargetProperties::GetMemoryModuleLoadLevel() const
4001 {
4002     const uint32_t idx = ePropertyMemoryModuleLoadLevel;
4003     return (MemoryModuleLoadLevel)m_collection_sp->GetPropertyAtIndexAsEnumeration(nullptr, idx, g_properties[idx].default_uint_value);
4004 }
4005 
4006 bool
4007 TargetProperties::GetUserSpecifiedTrapHandlerNames (Args &args) const
4008 {
4009     const uint32_t idx = ePropertyTrapHandlerNames;
4010     return m_collection_sp->GetPropertyAtIndexAsArgs(nullptr, idx, args);
4011 }
4012 
4013 void
4014 TargetProperties::SetUserSpecifiedTrapHandlerNames (const Args &args)
4015 {
4016     const uint32_t idx = ePropertyTrapHandlerNames;
4017     m_collection_sp->SetPropertyAtIndexFromArgs(nullptr, idx, args);
4018 }
4019 
4020 bool
4021 TargetProperties::GetDisplayRuntimeSupportValues () const
4022 {
4023     const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4024     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4025 }
4026 
4027 void
4028 TargetProperties::SetDisplayRuntimeSupportValues (bool b)
4029 {
4030     const uint32_t idx = ePropertyDisplayRuntimeSupportValues;
4031     m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4032 }
4033 
4034 bool
4035 TargetProperties::GetNonStopModeEnabled () const
4036 {
4037     const uint32_t idx = ePropertyNonStopModeEnabled;
4038     return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, false);
4039 }
4040 
4041 void
4042 TargetProperties::SetNonStopModeEnabled (bool b)
4043 {
4044     const uint32_t idx = ePropertyNonStopModeEnabled;
4045     m_collection_sp->SetPropertyAtIndexAsBoolean(nullptr, idx, b);
4046 }
4047 
4048 const ProcessLaunchInfo &
4049 TargetProperties::GetProcessLaunchInfo ()
4050 {
4051     m_launch_info.SetArg0(GetArg0()); // FIXME: Arg0 callback doesn't work
4052     return m_launch_info;
4053 }
4054 
4055 void
4056 TargetProperties::SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info)
4057 {
4058     m_launch_info = launch_info;
4059     SetArg0(launch_info.GetArg0());
4060     SetRunArguments(launch_info.GetArguments());
4061     SetEnvironmentFromArgs(launch_info.GetEnvironmentEntries());
4062     const FileAction *input_file_action = launch_info.GetFileActionForFD(STDIN_FILENO);
4063     if (input_file_action)
4064     {
4065         const char *input_path = input_file_action->GetPath();
4066         if (input_path)
4067             SetStandardInputPath(input_path);
4068     }
4069     const FileAction *output_file_action = launch_info.GetFileActionForFD(STDOUT_FILENO);
4070     if (output_file_action)
4071     {
4072         const char *output_path = output_file_action->GetPath();
4073         if (output_path)
4074             SetStandardOutputPath(output_path);
4075     }
4076     const FileAction *error_file_action = launch_info.GetFileActionForFD(STDERR_FILENO);
4077     if (error_file_action)
4078     {
4079         const char *error_path = error_file_action->GetPath();
4080         if (error_path)
4081             SetStandardErrorPath(error_path);
4082     }
4083     SetDetachOnError(launch_info.GetFlags().Test(lldb::eLaunchFlagDetachOnError));
4084     SetDisableASLR(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableASLR));
4085     SetDisableSTDIO(launch_info.GetFlags().Test(lldb::eLaunchFlagDisableSTDIO));
4086 }
4087 
4088 void
4089 TargetProperties::Arg0ValueChangedCallback(void *target_property_ptr, OptionValue *)
4090 {
4091     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4092     this_->m_launch_info.SetArg0(this_->GetArg0());
4093 }
4094 
4095 void
4096 TargetProperties::RunArgsValueChangedCallback(void *target_property_ptr, OptionValue *)
4097 {
4098     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4099     Args args;
4100     if (this_->GetRunArguments(args))
4101         this_->m_launch_info.GetArguments() = args;
4102 }
4103 
4104 void
4105 TargetProperties::EnvVarsValueChangedCallback(void *target_property_ptr, OptionValue *)
4106 {
4107     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4108     Args args;
4109     if (this_->GetEnvironmentAsArgs(args))
4110         this_->m_launch_info.GetEnvironmentEntries() = args;
4111 }
4112 
4113 void
4114 TargetProperties::InputPathValueChangedCallback(void *target_property_ptr, OptionValue *)
4115 {
4116     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4117     this_->m_launch_info.AppendOpenFileAction(STDIN_FILENO, this_->GetStandardInputPath(), true, false);
4118 }
4119 
4120 void
4121 TargetProperties::OutputPathValueChangedCallback(void *target_property_ptr, OptionValue *)
4122 {
4123     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4124     this_->m_launch_info.AppendOpenFileAction(STDOUT_FILENO, this_->GetStandardOutputPath(), false, true);
4125 }
4126 
4127 void
4128 TargetProperties::ErrorPathValueChangedCallback(void *target_property_ptr, OptionValue *)
4129 {
4130     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4131     this_->m_launch_info.AppendOpenFileAction(STDERR_FILENO, this_->GetStandardErrorPath(), false, true);
4132 }
4133 
4134 void
4135 TargetProperties::DetachOnErrorValueChangedCallback(void *target_property_ptr, OptionValue *)
4136 {
4137     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4138     if (this_->GetDetachOnError())
4139         this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDetachOnError);
4140     else
4141         this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDetachOnError);
4142 }
4143 
4144 void
4145 TargetProperties::DisableASLRValueChangedCallback(void *target_property_ptr, OptionValue *)
4146 {
4147     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4148     if (this_->GetDisableASLR())
4149         this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableASLR);
4150     else
4151         this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableASLR);
4152 }
4153 
4154 void
4155 TargetProperties::DisableSTDIOValueChangedCallback(void *target_property_ptr, OptionValue *)
4156 {
4157     TargetProperties *this_ = reinterpret_cast<TargetProperties *>(target_property_ptr);
4158     if (this_->GetDisableSTDIO())
4159         this_->m_launch_info.GetFlags().Set(lldb::eLaunchFlagDisableSTDIO);
4160     else
4161         this_->m_launch_info.GetFlags().Clear(lldb::eLaunchFlagDisableSTDIO);
4162 }
4163 
4164 //----------------------------------------------------------------------
4165 // Target::TargetEventData
4166 //----------------------------------------------------------------------
4167 
4168 Target::TargetEventData::TargetEventData (const lldb::TargetSP &target_sp) :
4169     EventData (),
4170     m_target_sp (target_sp),
4171     m_module_list ()
4172 {
4173 }
4174 
4175 Target::TargetEventData::TargetEventData (const lldb::TargetSP &target_sp, const ModuleList &module_list) :
4176     EventData (),
4177     m_target_sp (target_sp),
4178     m_module_list (module_list)
4179 {
4180 }
4181 
4182 Target::TargetEventData::~TargetEventData() = default;
4183 
4184 const ConstString &
4185 Target::TargetEventData::GetFlavorString ()
4186 {
4187     static ConstString g_flavor ("Target::TargetEventData");
4188     return g_flavor;
4189 }
4190 
4191 void
4192 Target::TargetEventData::Dump (Stream *s) const
4193 {
4194     for (size_t i = 0; i < m_module_list.GetSize(); ++i)
4195     {
4196         if (i != 0)
4197              *s << ", ";
4198         m_module_list.GetModuleAtIndex(i)->GetDescription(s, lldb::eDescriptionLevelBrief);
4199     }
4200 }
4201 
4202 const Target::TargetEventData *
4203 Target::TargetEventData::GetEventDataFromEvent (const Event *event_ptr)
4204 {
4205     if (event_ptr)
4206     {
4207         const EventData *event_data = event_ptr->GetData();
4208         if (event_data && event_data->GetFlavor() == TargetEventData::GetFlavorString())
4209             return static_cast <const TargetEventData *> (event_ptr->GetData());
4210     }
4211     return nullptr;
4212 }
4213 
4214 TargetSP
4215 Target::TargetEventData::GetTargetFromEvent (const Event *event_ptr)
4216 {
4217     TargetSP target_sp;
4218     const TargetEventData *event_data = GetEventDataFromEvent (event_ptr);
4219     if (event_data)
4220         target_sp = event_data->m_target_sp;
4221     return target_sp;
4222 }
4223 
4224 ModuleList
4225 Target::TargetEventData::GetModuleListFromEvent (const Event *event_ptr)
4226 {
4227     ModuleList module_list;
4228     const TargetEventData *event_data = GetEventDataFromEvent (event_ptr);
4229     if (event_data)
4230         module_list = event_data->m_module_list;
4231     return module_list;
4232 }
4233