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