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