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