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