1 //===-- Target.h ------------------------------------------------*- 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 #ifndef liblldb_Target_h_
11 #define liblldb_Target_h_
12 
13 #include <list>
14 #include <map>
15 #include <memory>
16 #include <string>
17 #include <vector>
18 
19 #include "lldb/Breakpoint/BreakpointList.h"
20 #include "lldb/Breakpoint/BreakpointName.h"
21 #include "lldb/Breakpoint/WatchpointList.h"
22 #include "lldb/Core/Architecture.h"
23 #include "lldb/Core/Disassembler.h"
24 #include "lldb/Core/ModuleList.h"
25 #include "lldb/Core/UserSettingsController.h"
26 #include "lldb/Expression/Expression.h"
27 #include "lldb/Symbol/TypeSystem.h"
28 #include "lldb/Target/ExecutionContextScope.h"
29 #include "lldb/Target/PathMappingList.h"
30 #include "lldb/Target/ProcessLaunchInfo.h"
31 #include "lldb/Target/SectionLoadHistory.h"
32 #include "lldb/Utility/ArchSpec.h"
33 #include "lldb/Utility/Broadcaster.h"
34 #include "lldb/Utility/LLDBAssert.h"
35 #include "lldb/Utility/Timeout.h"
36 #include "lldb/lldb-public.h"
37 
38 namespace lldb_private {
39 
40 OptionEnumValues GetDynamicValueTypes();
41 
42 typedef enum InlineStrategy {
43   eInlineBreakpointsNever = 0,
44   eInlineBreakpointsHeaders,
45   eInlineBreakpointsAlways
46 } InlineStrategy;
47 
48 typedef enum LoadScriptFromSymFile {
49   eLoadScriptFromSymFileTrue,
50   eLoadScriptFromSymFileFalse,
51   eLoadScriptFromSymFileWarn
52 } LoadScriptFromSymFile;
53 
54 typedef enum LoadCWDlldbinitFile {
55   eLoadCWDlldbinitTrue,
56   eLoadCWDlldbinitFalse,
57   eLoadCWDlldbinitWarn
58 } LoadCWDlldbinitFile;
59 
60 typedef enum LoadDependentFiles {
61   eLoadDependentsDefault,
62   eLoadDependentsYes,
63   eLoadDependentsNo,
64 } LoadDependentFiles;
65 
66 //----------------------------------------------------------------------
67 // TargetProperties
68 //----------------------------------------------------------------------
69 class TargetExperimentalProperties : public Properties {
70 public:
71   TargetExperimentalProperties();
72 };
73 
74 class TargetProperties : public Properties {
75 public:
76   TargetProperties(Target *target);
77 
78   ~TargetProperties() override;
79 
80   ArchSpec GetDefaultArchitecture() const;
81 
82   void SetDefaultArchitecture(const ArchSpec &arch);
83 
84   bool GetMoveToNearestCode() const;
85 
86   lldb::DynamicValueType GetPreferDynamicValue() const;
87 
88   bool SetPreferDynamicValue(lldb::DynamicValueType d);
89 
90   bool GetPreloadSymbols() const;
91 
92   void SetPreloadSymbols(bool b);
93 
94   bool GetDisableASLR() const;
95 
96   void SetDisableASLR(bool b);
97 
98   bool GetDetachOnError() const;
99 
100   void SetDetachOnError(bool b);
101 
102   bool GetDisableSTDIO() const;
103 
104   void SetDisableSTDIO(bool b);
105 
106   const char *GetDisassemblyFlavor() const;
107 
108   InlineStrategy GetInlineStrategy() const;
109 
110   llvm::StringRef GetArg0() const;
111 
112   void SetArg0(llvm::StringRef arg);
113 
114   bool GetRunArguments(Args &args) const;
115 
116   void SetRunArguments(const Args &args);
117 
118   Environment GetEnvironment() const;
119   void SetEnvironment(Environment env);
120 
121   bool GetSkipPrologue() const;
122 
123   PathMappingList &GetSourcePathMap() const;
124 
125   FileSpecList &GetExecutableSearchPaths();
126 
127   FileSpecList &GetDebugFileSearchPaths();
128 
129   FileSpecList &GetClangModuleSearchPaths();
130 
131   bool GetEnableAutoImportClangModules() const;
132 
133   bool GetEnableAutoApplyFixIts() const;
134 
135   bool GetEnableNotifyAboutFixIts() const;
136 
137   bool GetEnableSaveObjects() const;
138 
139   bool GetEnableSyntheticValue() const;
140 
141   uint32_t GetMaximumNumberOfChildrenToDisplay() const;
142 
143   uint32_t GetMaximumSizeOfStringSummary() const;
144 
145   uint32_t GetMaximumMemReadSize() const;
146 
147   FileSpec GetStandardInputPath() const;
148   FileSpec GetStandardErrorPath() const;
149   FileSpec GetStandardOutputPath() const;
150 
151   void SetStandardInputPath(llvm::StringRef path);
152   void SetStandardOutputPath(llvm::StringRef path);
153   void SetStandardErrorPath(llvm::StringRef path);
154 
155   void SetStandardInputPath(const char *path) = delete;
156   void SetStandardOutputPath(const char *path) = delete;
157   void SetStandardErrorPath(const char *path) = delete;
158 
159   bool GetBreakpointsConsultPlatformAvoidList();
160 
161   lldb::LanguageType GetLanguage() const;
162 
163   llvm::StringRef GetExpressionPrefixContents();
164 
165   bool GetUseHexImmediates() const;
166 
167   bool GetUseFastStepping() const;
168 
169   bool GetDisplayExpressionsInCrashlogs() const;
170 
171   LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const;
172 
173   LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const;
174 
175   Disassembler::HexImmediateStyle GetHexImmediateStyle() const;
176 
177   MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const;
178 
179   bool GetUserSpecifiedTrapHandlerNames(Args &args) const;
180 
181   void SetUserSpecifiedTrapHandlerNames(const Args &args);
182 
183   bool GetNonStopModeEnabled() const;
184 
185   void SetNonStopModeEnabled(bool b);
186 
187   bool GetDisplayRuntimeSupportValues() const;
188 
189   void SetDisplayRuntimeSupportValues(bool b);
190 
191   bool GetDisplayRecognizedArguments() const;
192 
193   void SetDisplayRecognizedArguments(bool b);
194 
195   const ProcessLaunchInfo &GetProcessLaunchInfo();
196 
197   void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info);
198 
199   bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const;
200 
201   void SetInjectLocalVariables(ExecutionContext *exe_ctx, bool b);
202 
203   bool GetUseModernTypeLookup() const;
204 
205   void SetRequireHardwareBreakpoints(bool b);
206 
207   bool GetRequireHardwareBreakpoints() const;
208 
209 private:
210   //------------------------------------------------------------------
211   // Callbacks for m_launch_info.
212   //------------------------------------------------------------------
213   static void Arg0ValueChangedCallback(void *target_property_ptr,
214                                        OptionValue *);
215   static void RunArgsValueChangedCallback(void *target_property_ptr,
216                                           OptionValue *);
217   static void EnvVarsValueChangedCallback(void *target_property_ptr,
218                                           OptionValue *);
219   static void InheritEnvValueChangedCallback(void *target_property_ptr,
220                                              OptionValue *);
221   static void InputPathValueChangedCallback(void *target_property_ptr,
222                                             OptionValue *);
223   static void OutputPathValueChangedCallback(void *target_property_ptr,
224                                              OptionValue *);
225   static void ErrorPathValueChangedCallback(void *target_property_ptr,
226                                             OptionValue *);
227   static void DetachOnErrorValueChangedCallback(void *target_property_ptr,
228                                                 OptionValue *);
229   static void DisableASLRValueChangedCallback(void *target_property_ptr,
230                                               OptionValue *);
231   static void DisableSTDIOValueChangedCallback(void *target_property_ptr,
232                                                OptionValue *);
233 
234   //------------------------------------------------------------------
235   // Member variables.
236   //------------------------------------------------------------------
237   ProcessLaunchInfo m_launch_info;
238   std::unique_ptr<TargetExperimentalProperties> m_experimental_properties_up;
239 };
240 
241 class EvaluateExpressionOptions {
242 public:
243 // MSVC has a bug here that reports C4268: 'const' static/global data
244 // initialized with compiler generated default constructor fills the object
245 // with zeros. Confirmed that MSVC is *not* zero-initializing, it's just a
246 // bogus warning.
247 #if defined(_MSC_VER)
248 #pragma warning(push)
249 #pragma warning(disable : 4268)
250 #endif
251   static constexpr std::chrono::milliseconds default_timeout{500};
252 #if defined(_MSC_VER)
253 #pragma warning(pop)
254 #endif
255 
256   static constexpr ExecutionPolicy default_execution_policy =
257       eExecutionPolicyOnlyWhenNeeded;
258 
259   EvaluateExpressionOptions() = default;
260 
GetExecutionPolicy()261   ExecutionPolicy GetExecutionPolicy() const { return m_execution_policy; }
262 
263   void SetExecutionPolicy(ExecutionPolicy policy = eExecutionPolicyAlways) {
264     m_execution_policy = policy;
265   }
266 
GetLanguage()267   lldb::LanguageType GetLanguage() const { return m_language; }
268 
SetLanguage(lldb::LanguageType language)269   void SetLanguage(lldb::LanguageType language) { m_language = language; }
270 
DoesCoerceToId()271   bool DoesCoerceToId() const { return m_coerce_to_id; }
272 
GetPrefix()273   const char *GetPrefix() const {
274     return (m_prefix.empty() ? nullptr : m_prefix.c_str());
275   }
276 
SetPrefix(const char * prefix)277   void SetPrefix(const char *prefix) {
278     if (prefix && prefix[0])
279       m_prefix = prefix;
280     else
281       m_prefix.clear();
282   }
283 
284   void SetCoerceToId(bool coerce = true) { m_coerce_to_id = coerce; }
285 
DoesUnwindOnError()286   bool DoesUnwindOnError() const { return m_unwind_on_error; }
287 
288   void SetUnwindOnError(bool unwind = false) { m_unwind_on_error = unwind; }
289 
DoesIgnoreBreakpoints()290   bool DoesIgnoreBreakpoints() const { return m_ignore_breakpoints; }
291 
292   void SetIgnoreBreakpoints(bool ignore = false) {
293     m_ignore_breakpoints = ignore;
294   }
295 
DoesKeepInMemory()296   bool DoesKeepInMemory() const { return m_keep_in_memory; }
297 
298   void SetKeepInMemory(bool keep = true) { m_keep_in_memory = keep; }
299 
GetUseDynamic()300   lldb::DynamicValueType GetUseDynamic() const { return m_use_dynamic; }
301 
302   void
303   SetUseDynamic(lldb::DynamicValueType dynamic = lldb::eDynamicCanRunTarget) {
304     m_use_dynamic = dynamic;
305   }
306 
GetTimeout()307   const Timeout<std::micro> &GetTimeout() const { return m_timeout; }
308 
SetTimeout(const Timeout<std::micro> & timeout)309   void SetTimeout(const Timeout<std::micro> &timeout) { m_timeout = timeout; }
310 
GetOneThreadTimeout()311   const Timeout<std::micro> &GetOneThreadTimeout() const {
312     return m_one_thread_timeout;
313   }
314 
SetOneThreadTimeout(const Timeout<std::micro> & timeout)315   void SetOneThreadTimeout(const Timeout<std::micro> &timeout) {
316     m_one_thread_timeout = timeout;
317   }
318 
GetTryAllThreads()319   bool GetTryAllThreads() const { return m_try_others; }
320 
321   void SetTryAllThreads(bool try_others = true) { m_try_others = try_others; }
322 
GetStopOthers()323   bool GetStopOthers() const { return m_stop_others; }
324 
325   void SetStopOthers(bool stop_others = true) { m_stop_others = stop_others; }
326 
GetDebug()327   bool GetDebug() const { return m_debug; }
328 
SetDebug(bool b)329   void SetDebug(bool b) {
330     m_debug = b;
331     if (m_debug)
332       m_generate_debug_info = true;
333   }
334 
GetGenerateDebugInfo()335   bool GetGenerateDebugInfo() const { return m_generate_debug_info; }
336 
SetGenerateDebugInfo(bool b)337   void SetGenerateDebugInfo(bool b) { m_generate_debug_info = b; }
338 
GetColorizeErrors()339   bool GetColorizeErrors() const { return m_ansi_color_errors; }
340 
SetColorizeErrors(bool b)341   void SetColorizeErrors(bool b) { m_ansi_color_errors = b; }
342 
GetTrapExceptions()343   bool GetTrapExceptions() const { return m_trap_exceptions; }
344 
SetTrapExceptions(bool b)345   void SetTrapExceptions(bool b) { m_trap_exceptions = b; }
346 
GetREPLEnabled()347   bool GetREPLEnabled() const { return m_repl; }
348 
SetREPLEnabled(bool b)349   void SetREPLEnabled(bool b) { m_repl = b; }
350 
SetCancelCallback(lldb::ExpressionCancelCallback callback,void * baton)351   void SetCancelCallback(lldb::ExpressionCancelCallback callback, void *baton) {
352     m_cancel_callback_baton = baton;
353     m_cancel_callback = callback;
354   }
355 
InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase)356   bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const {
357     return ((m_cancel_callback != nullptr)
358                 ? m_cancel_callback(phase, m_cancel_callback_baton)
359                 : false);
360   }
361 
362   // Allows the expression contents to be remapped to point to the specified
363   // file and line using #line directives.
SetPoundLine(const char * path,uint32_t line)364   void SetPoundLine(const char *path, uint32_t line) const {
365     if (path && path[0]) {
366       m_pound_line_file = path;
367       m_pound_line_line = line;
368     } else {
369       m_pound_line_file.clear();
370       m_pound_line_line = 0;
371     }
372   }
373 
GetPoundLineFilePath()374   const char *GetPoundLineFilePath() const {
375     return (m_pound_line_file.empty() ? nullptr : m_pound_line_file.c_str());
376   }
377 
GetPoundLineLine()378   uint32_t GetPoundLineLine() const { return m_pound_line_line; }
379 
SetResultIsInternal(bool b)380   void SetResultIsInternal(bool b) { m_result_is_internal = b; }
381 
GetResultIsInternal()382   bool GetResultIsInternal() const { return m_result_is_internal; }
383 
SetAutoApplyFixIts(bool b)384   void SetAutoApplyFixIts(bool b) { m_auto_apply_fixits = b; }
385 
GetAutoApplyFixIts()386   bool GetAutoApplyFixIts() const { return m_auto_apply_fixits; }
387 
IsForUtilityExpr()388   bool IsForUtilityExpr() const { return m_running_utility_expression; }
389 
SetIsForUtilityExpr(bool b)390   void SetIsForUtilityExpr(bool b) { m_running_utility_expression = b; }
391 
392 private:
393   ExecutionPolicy m_execution_policy = default_execution_policy;
394   lldb::LanguageType m_language = lldb::eLanguageTypeUnknown;
395   std::string m_prefix;
396   bool m_coerce_to_id = false;
397   bool m_unwind_on_error = true;
398   bool m_ignore_breakpoints = false;
399   bool m_keep_in_memory = false;
400   bool m_try_others = true;
401   bool m_stop_others = true;
402   bool m_debug = false;
403   bool m_trap_exceptions = true;
404   bool m_repl = false;
405   bool m_generate_debug_info = false;
406   bool m_ansi_color_errors = false;
407   bool m_result_is_internal = false;
408   bool m_auto_apply_fixits = true;
409   /// True if the executed code should be treated as utility code that is only
410   /// used by LLDB internally.
411   bool m_running_utility_expression = false;
412 
413   lldb::DynamicValueType m_use_dynamic = lldb::eNoDynamicValues;
414   Timeout<std::micro> m_timeout = default_timeout;
415   Timeout<std::micro> m_one_thread_timeout = llvm::None;
416   lldb::ExpressionCancelCallback m_cancel_callback = nullptr;
417   void *m_cancel_callback_baton = nullptr;
418   // If m_pound_line_file is not empty and m_pound_line_line is non-zero, use
419   // #line %u "%s" before the expression content to remap where the source
420   // originates
421   mutable std::string m_pound_line_file;
422   mutable uint32_t m_pound_line_line;
423 };
424 
425 //----------------------------------------------------------------------
426 // Target
427 //----------------------------------------------------------------------
428 class Target : public std::enable_shared_from_this<Target>,
429                public TargetProperties,
430                public Broadcaster,
431                public ExecutionContextScope,
432                public ModuleList::Notifier {
433 public:
434   friend class TargetList;
435 
436   //------------------------------------------------------------------
437   /// Broadcaster event bits definitions.
438   //------------------------------------------------------------------
439   enum {
440     eBroadcastBitBreakpointChanged = (1 << 0),
441     eBroadcastBitModulesLoaded = (1 << 1),
442     eBroadcastBitModulesUnloaded = (1 << 2),
443     eBroadcastBitWatchpointChanged = (1 << 3),
444     eBroadcastBitSymbolsLoaded = (1 << 4)
445   };
446 
447   // These two functions fill out the Broadcaster interface:
448 
449   static ConstString &GetStaticBroadcasterClass();
450 
GetBroadcasterClass()451   ConstString &GetBroadcasterClass() const override {
452     return GetStaticBroadcasterClass();
453   }
454 
455   // This event data class is for use by the TargetList to broadcast new target
456   // notifications.
457   class TargetEventData : public EventData {
458   public:
459     TargetEventData(const lldb::TargetSP &target_sp);
460 
461     TargetEventData(const lldb::TargetSP &target_sp,
462                     const ModuleList &module_list);
463 
464     ~TargetEventData() override;
465 
466     static const ConstString &GetFlavorString();
467 
GetFlavor()468     const ConstString &GetFlavor() const override {
469       return TargetEventData::GetFlavorString();
470     }
471 
472     void Dump(Stream *s) const override;
473 
474     static const TargetEventData *GetEventDataFromEvent(const Event *event_ptr);
475 
476     static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr);
477 
478     static ModuleList GetModuleListFromEvent(const Event *event_ptr);
479 
GetTarget()480     const lldb::TargetSP &GetTarget() const { return m_target_sp; }
481 
GetModuleList()482     const ModuleList &GetModuleList() const { return m_module_list; }
483 
484   private:
485     lldb::TargetSP m_target_sp;
486     ModuleList m_module_list;
487 
488     DISALLOW_COPY_AND_ASSIGN(TargetEventData);
489   };
490 
491   ~Target() override;
492 
493   static void SettingsInitialize();
494 
495   static void SettingsTerminate();
496 
497   static FileSpecList GetDefaultExecutableSearchPaths();
498 
499   static FileSpecList GetDefaultDebugFileSearchPaths();
500 
501   static FileSpecList GetDefaultClangModuleSearchPaths();
502 
503   static ArchSpec GetDefaultArchitecture();
504 
505   static void SetDefaultArchitecture(const ArchSpec &arch);
506 
507   lldb::ModuleSP GetSharedModule(const ModuleSpec &module_spec,
508                                  Status *error_ptr = nullptr);
509 
510   //----------------------------------------------------------------------
511   // Settings accessors
512   //----------------------------------------------------------------------
513 
514   static const lldb::TargetPropertiesSP &GetGlobalProperties();
515 
GetAPIMutex()516   std::recursive_mutex &GetAPIMutex() { return m_mutex; }
517 
518   void DeleteCurrentProcess();
519 
520   void CleanupProcess();
521 
522   //------------------------------------------------------------------
523   /// Dump a description of this object to a Stream.
524   ///
525   /// Dump a description of the contents of this object to the
526   /// supplied stream \a s. The dumped content will be only what has
527   /// been loaded or parsed up to this point at which this function
528   /// is called, so this is a good way to see what has been parsed
529   /// in a target.
530   ///
531   /// @param[in] s
532   ///     The stream to which to dump the object description.
533   //------------------------------------------------------------------
534   void Dump(Stream *s, lldb::DescriptionLevel description_level);
535 
536   // If listener_sp is null, the listener of the owning Debugger object will be
537   // used.
538   const lldb::ProcessSP &CreateProcess(lldb::ListenerSP listener_sp,
539                                        llvm::StringRef plugin_name,
540                                        const FileSpec *crash_file);
541 
542   const lldb::ProcessSP &GetProcessSP() const;
543 
IsValid()544   bool IsValid() { return m_valid; }
545 
546   void Destroy();
547 
548   Status Launch(ProcessLaunchInfo &launch_info,
549                 Stream *stream); // Optional stream to receive first stop info
550 
551   Status Attach(ProcessAttachInfo &attach_info,
552                 Stream *stream); // Optional stream to receive first stop info
553 
554   //------------------------------------------------------------------
555   // This part handles the breakpoints.
556   //------------------------------------------------------------------
557 
558   BreakpointList &GetBreakpointList(bool internal = false);
559 
560   const BreakpointList &GetBreakpointList(bool internal = false) const;
561 
GetLastCreatedBreakpoint()562   lldb::BreakpointSP GetLastCreatedBreakpoint() {
563     return m_last_created_breakpoint;
564   }
565 
566   lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id);
567 
568   // Use this to create a file and line breakpoint to a given module or all
569   // module it is nullptr
570   lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules,
571                                       const FileSpec &file, uint32_t line_no,
572                                       uint32_t column, lldb::addr_t offset,
573                                       LazyBool check_inlines,
574                                       LazyBool skip_prologue, bool internal,
575                                       bool request_hardware,
576                                       LazyBool move_to_nearest_code);
577 
578   // Use this to create breakpoint that matches regex against the source lines
579   // in files given in source_file_list: If function_names is non-empty, also
580   // filter by function after the matches are made.
581   lldb::BreakpointSP CreateSourceRegexBreakpoint(
582       const FileSpecList *containingModules,
583       const FileSpecList *source_file_list,
584       const std::unordered_set<std::string> &function_names,
585       RegularExpression &source_regex, bool internal, bool request_hardware,
586       LazyBool move_to_nearest_code);
587 
588   // Use this to create a breakpoint from a load address
589   lldb::BreakpointSP CreateBreakpoint(lldb::addr_t load_addr, bool internal,
590                                       bool request_hardware);
591 
592   // Use this to create a breakpoint from a load address and a module file spec
593   lldb::BreakpointSP CreateAddressInModuleBreakpoint(lldb::addr_t file_addr,
594                                                      bool internal,
595                                                      const FileSpec *file_spec,
596                                                      bool request_hardware);
597 
598   // Use this to create Address breakpoints:
599   lldb::BreakpointSP CreateBreakpoint(const Address &addr, bool internal,
600                                       bool request_hardware);
601 
602   // Use this to create a function breakpoint by regexp in
603   // containingModule/containingSourceFiles, or all modules if it is nullptr
604   // When "skip_prologue is set to eLazyBoolCalculate, we use the current
605   // target setting, else we use the values passed in
606   lldb::BreakpointSP CreateFuncRegexBreakpoint(
607       const FileSpecList *containingModules,
608       const FileSpecList *containingSourceFiles, RegularExpression &func_regexp,
609       lldb::LanguageType requested_language, LazyBool skip_prologue,
610       bool internal, bool request_hardware);
611 
612   // Use this to create a function breakpoint by name in containingModule, or
613   // all modules if it is nullptr When "skip_prologue is set to
614   // eLazyBoolCalculate, we use the current target setting, else we use the
615   // values passed in. func_name_type_mask is or'ed values from the
616   // FunctionNameType enum.
617   lldb::BreakpointSP CreateBreakpoint(
618       const FileSpecList *containingModules,
619       const FileSpecList *containingSourceFiles, const char *func_name,
620       lldb::FunctionNameType func_name_type_mask, lldb::LanguageType language,
621       lldb::addr_t offset, LazyBool skip_prologue, bool internal,
622       bool request_hardware);
623 
624   lldb::BreakpointSP
625   CreateExceptionBreakpoint(enum lldb::LanguageType language, bool catch_bp,
626                             bool throw_bp, bool internal,
627                             Args *additional_args = nullptr,
628                             Status *additional_args_error = nullptr);
629 
630   lldb::BreakpointSP
631   CreateScriptedBreakpoint(const llvm::StringRef class_name,
632                            const FileSpecList *containingModules,
633                            const FileSpecList *containingSourceFiles,
634                            bool internal,
635                            bool request_hardware,
636                            StructuredData::ObjectSP extra_args_sp,
637                            Status *creation_error = nullptr);
638 
639   // This is the same as the func_name breakpoint except that you can specify a
640   // vector of names.  This is cheaper than a regular expression breakpoint in
641   // the case where you just want to set a breakpoint on a set of names you
642   // already know. func_name_type_mask is or'ed values from the
643   // FunctionNameType enum.
644   lldb::BreakpointSP CreateBreakpoint(
645       const FileSpecList *containingModules,
646       const FileSpecList *containingSourceFiles, const char *func_names[],
647       size_t num_names, lldb::FunctionNameType func_name_type_mask,
648       lldb::LanguageType language, lldb::addr_t offset, LazyBool skip_prologue,
649       bool internal, bool request_hardware);
650 
651   lldb::BreakpointSP
652   CreateBreakpoint(const FileSpecList *containingModules,
653                    const FileSpecList *containingSourceFiles,
654                    const std::vector<std::string> &func_names,
655                    lldb::FunctionNameType func_name_type_mask,
656                    lldb::LanguageType language, lldb::addr_t m_offset,
657                    LazyBool skip_prologue, bool internal,
658                    bool request_hardware);
659 
660   // Use this to create a general breakpoint:
661   lldb::BreakpointSP CreateBreakpoint(lldb::SearchFilterSP &filter_sp,
662                                       lldb::BreakpointResolverSP &resolver_sp,
663                                       bool internal, bool request_hardware,
664                                       bool resolve_indirect_symbols);
665 
666   // Use this to create a watchpoint:
667   lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size,
668                                       const CompilerType *type, uint32_t kind,
669                                       Status &error);
670 
GetLastCreatedWatchpoint()671   lldb::WatchpointSP GetLastCreatedWatchpoint() {
672     return m_last_created_watchpoint;
673   }
674 
GetWatchpointList()675   WatchpointList &GetWatchpointList() { return m_watchpoint_list; }
676 
677   // Manages breakpoint names:
678   void AddNameToBreakpoint(BreakpointID &id, const char *name, Status &error);
679 
680   void AddNameToBreakpoint(lldb::BreakpointSP &bp_sp, const char *name,
681                            Status &error);
682 
683   void RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
684                                 const ConstString &name);
685 
686   BreakpointName *FindBreakpointName(const ConstString &name, bool can_create,
687                                      Status &error);
688 
689   void DeleteBreakpointName(const ConstString &name);
690 
691   void ConfigureBreakpointName(BreakpointName &bp_name,
692                                const BreakpointOptions &options,
693                                const BreakpointName::Permissions &permissions);
694  void ApplyNameToBreakpoints(BreakpointName &bp_name);
695 
696   // This takes ownership of the name obj passed in.
697   void AddBreakpointName(BreakpointName *bp_name);
698 
699   void GetBreakpointNames(std::vector<std::string> &names);
700 
701   //This call removes ALL breakpoints regardless of permission.
702   void RemoveAllBreakpoints(bool internal_also = false);
703 
704   // This removes all the breakpoints, but obeys the ePermDelete on them.
705   void RemoveAllowedBreakpoints();
706 
707   void DisableAllBreakpoints(bool internal_also = false);
708 
709   void DisableAllowedBreakpoints();
710 
711   void EnableAllBreakpoints(bool internal_also = false);
712 
713   void EnableAllowedBreakpoints();
714 
715   bool DisableBreakpointByID(lldb::break_id_t break_id);
716 
717   bool EnableBreakpointByID(lldb::break_id_t break_id);
718 
719   bool RemoveBreakpointByID(lldb::break_id_t break_id);
720 
721   // The flag 'end_to_end', default to true, signifies that the operation is
722   // performed end to end, for both the debugger and the debuggee.
723 
724   bool RemoveAllWatchpoints(bool end_to_end = true);
725 
726   bool DisableAllWatchpoints(bool end_to_end = true);
727 
728   bool EnableAllWatchpoints(bool end_to_end = true);
729 
730   bool ClearAllWatchpointHitCounts();
731 
732   bool ClearAllWatchpointHistoricValues();
733 
734   bool IgnoreAllWatchpoints(uint32_t ignore_count);
735 
736   bool DisableWatchpointByID(lldb::watch_id_t watch_id);
737 
738   bool EnableWatchpointByID(lldb::watch_id_t watch_id);
739 
740   bool RemoveWatchpointByID(lldb::watch_id_t watch_id);
741 
742   bool IgnoreWatchpointByID(lldb::watch_id_t watch_id, uint32_t ignore_count);
743 
744   Status SerializeBreakpointsToFile(const FileSpec &file,
745                                     const BreakpointIDList &bp_ids,
746                                     bool append);
747 
748   Status CreateBreakpointsFromFile(const FileSpec &file,
749                                    BreakpointIDList &new_bps);
750 
751   Status CreateBreakpointsFromFile(const FileSpec &file,
752                                    std::vector<std::string> &names,
753                                    BreakpointIDList &new_bps);
754 
755   //------------------------------------------------------------------
756   /// Get \a load_addr as a callable code load address for this target
757   ///
758   /// Take \a load_addr and potentially add any address bits that are
759   /// needed to make the address callable. For ARM this can set bit
760   /// zero (if it already isn't) if \a load_addr is a thumb function.
761   /// If \a addr_class is set to AddressClass::eInvalid, then the address
762   /// adjustment will always happen. If it is set to an address class
763   /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
764   /// returned.
765   //------------------------------------------------------------------
766   lldb::addr_t GetCallableLoadAddress(
767       lldb::addr_t load_addr,
768       AddressClass addr_class = AddressClass::eInvalid) const;
769 
770   //------------------------------------------------------------------
771   /// Get \a load_addr as an opcode for this target.
772   ///
773   /// Take \a load_addr and potentially strip any address bits that are
774   /// needed to make the address point to an opcode. For ARM this can
775   /// clear bit zero (if it already isn't) if \a load_addr is a
776   /// thumb function and load_addr is in code.
777   /// If \a addr_class is set to AddressClass::eInvalid, then the address
778   /// adjustment will always happen. If it is set to an address class
779   /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
780   /// returned.
781   //------------------------------------------------------------------
782   lldb::addr_t
783   GetOpcodeLoadAddress(lldb::addr_t load_addr,
784                        AddressClass addr_class = AddressClass::eInvalid) const;
785 
786   // Get load_addr as breakable load address for this target. Take a addr and
787   // check if for any reason there is a better address than this to put a
788   // breakpoint on. If there is then return that address. For MIPS, if
789   // instruction at addr is a delay slot instruction then this method will find
790   // the address of its previous instruction and return that address.
791   lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr);
792 
793   void ModulesDidLoad(ModuleList &module_list);
794 
795   void ModulesDidUnload(ModuleList &module_list, bool delete_locations);
796 
797   void SymbolsDidLoad(ModuleList &module_list);
798 
799   void ClearModules(bool delete_locations);
800 
801   //------------------------------------------------------------------
802   /// Called as the last function in Process::DidExec().
803   ///
804   /// Process::DidExec() will clear a lot of state in the process,
805   /// then try to reload a dynamic loader plugin to discover what
806   /// binaries are currently available and then this function should
807   /// be called to allow the target to do any cleanup after everything
808   /// has been figured out. It can remove breakpoints that no longer
809   /// make sense as the exec might have changed the target
810   /// architecture, and unloaded some modules that might get deleted.
811   //------------------------------------------------------------------
812   void DidExec();
813 
814   //------------------------------------------------------------------
815   /// Gets the module for the main executable.
816   ///
817   /// Each process has a notion of a main executable that is the file
818   /// that will be executed or attached to. Executable files can have
819   /// dependent modules that are discovered from the object files, or
820   /// discovered at runtime as things are dynamically loaded.
821   ///
822   /// @return
823   ///     The shared pointer to the executable module which can
824   ///     contains a nullptr Module object if no executable has been
825   ///     set.
826   ///
827   /// @see DynamicLoader
828   /// @see ObjectFile::GetDependentModules (FileSpecList&)
829   /// @see Process::SetExecutableModule(lldb::ModuleSP&)
830   //------------------------------------------------------------------
831   lldb::ModuleSP GetExecutableModule();
832 
833   Module *GetExecutableModulePointer();
834 
835   //------------------------------------------------------------------
836   /// Set the main executable module.
837   ///
838   /// Each process has a notion of a main executable that is the file
839   /// that will be executed or attached to. Executable files can have
840   /// dependent modules that are discovered from the object files, or
841   /// discovered at runtime as things are dynamically loaded.
842   ///
843   /// Setting the executable causes any of the current dependent
844   /// image information to be cleared and replaced with the static
845   /// dependent image information found by calling
846   /// ObjectFile::GetDependentModules (FileSpecList&) on the main
847   /// executable and any modules on which it depends. Calling
848   /// Process::GetImages() will return the newly found images that
849   /// were obtained from all of the object files.
850   ///
851   /// @param[in] module_sp
852   ///     A shared pointer reference to the module that will become
853   ///     the main executable for this process.
854   ///
855   /// @param[in] load_dependent_files
856   ///     If \b true then ask the object files to track down any
857   ///     known dependent files.
858   ///
859   /// @see ObjectFile::GetDependentModules (FileSpecList&)
860   /// @see Process::GetImages()
861   //------------------------------------------------------------------
862   void SetExecutableModule(
863       lldb::ModuleSP &module_sp,
864       LoadDependentFiles load_dependent_files = eLoadDependentsDefault);
865 
866   bool LoadScriptingResources(std::list<Status> &errors,
867                               Stream *feedback_stream = nullptr,
868                               bool continue_on_error = true) {
869     return m_images.LoadScriptingResourcesInTarget(
870         this, errors, feedback_stream, continue_on_error);
871   }
872 
873   //------------------------------------------------------------------
874   /// Get accessor for the images for this process.
875   ///
876   /// Each process has a notion of a main executable that is the file
877   /// that will be executed or attached to. Executable files can have
878   /// dependent modules that are discovered from the object files, or
879   /// discovered at runtime as things are dynamically loaded. After
880   /// a main executable has been set, the images will contain a list
881   /// of all the files that the executable depends upon as far as the
882   /// object files know. These images will usually contain valid file
883   /// virtual addresses only. When the process is launched or attached
884   /// to, the DynamicLoader plug-in will discover where these images
885   /// were loaded in memory and will resolve the load virtual
886   /// addresses is each image, and also in images that are loaded by
887   /// code.
888   ///
889   /// @return
890   ///     A list of Module objects in a module list.
891   //------------------------------------------------------------------
GetImages()892   const ModuleList &GetImages() const { return m_images; }
893 
GetImages()894   ModuleList &GetImages() { return m_images; }
895 
896   //------------------------------------------------------------------
897   /// Return whether this FileSpec corresponds to a module that should be
898   /// considered for general searches.
899   ///
900   /// This API will be consulted by the SearchFilterForUnconstrainedSearches
901   /// and any module that returns \b true will not be searched.  Note the
902   /// SearchFilterForUnconstrainedSearches is the search filter that
903   /// gets used in the CreateBreakpoint calls when no modules is provided.
904   ///
905   /// The target call at present just consults the Platform's call of the
906   /// same name.
907   ///
908   /// @param[in] module_sp
909   ///     A shared pointer reference to the module that checked.
910   ///
911   /// @return \b true if the module should be excluded, \b false otherwise.
912   //------------------------------------------------------------------
913   bool ModuleIsExcludedForUnconstrainedSearches(const FileSpec &module_spec);
914 
915   //------------------------------------------------------------------
916   /// Return whether this module should be considered for general searches.
917   ///
918   /// This API will be consulted by the SearchFilterForUnconstrainedSearches
919   /// and any module that returns \b true will not be searched.  Note the
920   /// SearchFilterForUnconstrainedSearches is the search filter that
921   /// gets used in the CreateBreakpoint calls when no modules is provided.
922   ///
923   /// The target call at present just consults the Platform's call of the
924   /// same name.
925   ///
926   /// FIXME: When we get time we should add a way for the user to set modules
927   /// that they
928   /// don't want searched, in addition to or instead of the platform ones.
929   ///
930   /// @param[in] module_sp
931   ///     A shared pointer reference to the module that checked.
932   ///
933   /// @return \b true if the module should be excluded, \b false otherwise.
934   //------------------------------------------------------------------
935   bool
936   ModuleIsExcludedForUnconstrainedSearches(const lldb::ModuleSP &module_sp);
937 
GetArchitecture()938   const ArchSpec &GetArchitecture() const { return m_arch.GetSpec(); }
939 
940   //------------------------------------------------------------------
941   /// Set the architecture for this target.
942   ///
943   /// If the current target has no Images read in, then this just sets the
944   /// architecture, which will be used to select the architecture of the
945   /// ExecutableModule when that is set. If the current target has an
946   /// ExecutableModule, then calling SetArchitecture with a different
947   /// architecture from the currently selected one will reset the
948   /// ExecutableModule to that slice of the file backing the ExecutableModule.
949   /// If the file backing the ExecutableModule does not contain a fork of this
950   /// architecture, then this code will return false, and the architecture
951   /// won't be changed. If the input arch_spec is the same as the already set
952   /// architecture, this is a no-op.
953   ///
954   /// @param[in] arch_spec
955   ///     The new architecture.
956   ///
957   /// @param[in] set_platform
958   ///     If \b true, then the platform will be adjusted if the currently
959   ///     selected platform is not compatible with the archicture being set.
960   ///     If \b false, then just the architecture will be set even if the
961   ///     currently selected platform isn't compatible (in case it might be
962   ///     manually set following this function call).
963   ///
964   /// @return
965   ///     \b true if the architecture was successfully set, \bfalse otherwise.
966   //------------------------------------------------------------------
967   bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform = false);
968 
969   bool MergeArchitecture(const ArchSpec &arch_spec);
970 
GetArchitecturePlugin()971   Architecture *GetArchitecturePlugin() const { return m_arch.GetPlugin(); }
972 
GetDebugger()973   Debugger &GetDebugger() { return m_debugger; }
974 
975   size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len,
976                                  Status &error);
977 
978   // Reading memory through the target allows us to skip going to the process
979   // for reading memory if possible and it allows us to try and read from any
980   // constant sections in our object files on disk. If you always want live
981   // program memory, read straight from the process. If you possibly want to
982   // read from const sections in object files, read from the target. This
983   // version of ReadMemory will try and read memory from the process if the
984   // process is alive. The order is:
985   // 1 - if (prefer_file_cache == true) then read from object file cache
986   // 2 - if there is a valid process, try and read from its memory
987   // 3 - if (prefer_file_cache == false) then read from object file cache
988   size_t ReadMemory(const Address &addr, bool prefer_file_cache, void *dst,
989                     size_t dst_len, Status &error,
990                     lldb::addr_t *load_addr_ptr = nullptr);
991 
992   size_t ReadCStringFromMemory(const Address &addr, std::string &out_str,
993                                Status &error);
994 
995   size_t ReadCStringFromMemory(const Address &addr, char *dst,
996                                size_t dst_max_len, Status &result_error);
997 
998   size_t ReadScalarIntegerFromMemory(const Address &addr,
999                                      bool prefer_file_cache, uint32_t byte_size,
1000                                      bool is_signed, Scalar &scalar,
1001                                      Status &error);
1002 
1003   uint64_t ReadUnsignedIntegerFromMemory(const Address &addr,
1004                                          bool prefer_file_cache,
1005                                          size_t integer_byte_size,
1006                                          uint64_t fail_value, Status &error);
1007 
1008   bool ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1009                              Status &error, Address &pointer_addr);
1010 
GetSectionLoadList()1011   SectionLoadList &GetSectionLoadList() {
1012     return m_section_load_history.GetCurrentSectionLoadList();
1013   }
1014 
1015   static Target *GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
1016                                        const SymbolContext *sc_ptr);
1017 
1018   //------------------------------------------------------------------
1019   // lldb::ExecutionContextScope pure virtual functions
1020   //------------------------------------------------------------------
1021   lldb::TargetSP CalculateTarget() override;
1022 
1023   lldb::ProcessSP CalculateProcess() override;
1024 
1025   lldb::ThreadSP CalculateThread() override;
1026 
1027   lldb::StackFrameSP CalculateStackFrame() override;
1028 
1029   void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
1030 
1031   PathMappingList &GetImageSearchPathList();
1032 
1033   TypeSystem *GetScratchTypeSystemForLanguage(Status *error,
1034                                               lldb::LanguageType language,
1035                                               bool create_on_demand = true);
1036 
1037   PersistentExpressionState *
1038   GetPersistentExpressionStateForLanguage(lldb::LanguageType language);
1039 
1040   // Creates a UserExpression for the given language, the rest of the
1041   // parameters have the same meaning as for the UserExpression constructor.
1042   // Returns a new-ed object which the caller owns.
1043 
1044   UserExpression *GetUserExpressionForLanguage(
1045       llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
1046       Expression::ResultType desired_type,
1047       const EvaluateExpressionOptions &options, Status &error);
1048 
1049   // Creates a FunctionCaller for the given language, the rest of the
1050   // parameters have the same meaning as for the FunctionCaller constructor.
1051   // Since a FunctionCaller can't be
1052   // IR Interpreted, it makes no sense to call this with an
1053   // ExecutionContextScope that lacks
1054   // a Process.
1055   // Returns a new-ed object which the caller owns.
1056 
1057   FunctionCaller *GetFunctionCallerForLanguage(lldb::LanguageType language,
1058                                                const CompilerType &return_type,
1059                                                const Address &function_address,
1060                                                const ValueList &arg_value_list,
1061                                                const char *name, Status &error);
1062 
1063   // Creates a UtilityFunction for the given language, the rest of the
1064   // parameters have the same meaning as for the UtilityFunction constructor.
1065   // Returns a new-ed object which the caller owns.
1066 
1067   UtilityFunction *GetUtilityFunctionForLanguage(const char *expr,
1068                                                  lldb::LanguageType language,
1069                                                  const char *name,
1070                                                  Status &error);
1071 
1072   ClangASTContext *GetScratchClangASTContext(bool create_on_demand = true);
1073 
1074   lldb::ClangASTImporterSP GetClangASTImporter();
1075 
1076   //----------------------------------------------------------------------
1077   // Install any files through the platform that need be to installed prior to
1078   // launching or attaching.
1079   //----------------------------------------------------------------------
1080   Status Install(ProcessLaunchInfo *launch_info);
1081 
1082   bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr);
1083 
1084   bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr,
1085                           uint32_t stop_id = SectionLoadHistory::eStopIDNow);
1086 
1087   bool SetSectionLoadAddress(const lldb::SectionSP &section,
1088                              lldb::addr_t load_addr,
1089                              bool warn_multiple = false);
1090 
1091   size_t UnloadModuleSections(const lldb::ModuleSP &module_sp);
1092 
1093   size_t UnloadModuleSections(const ModuleList &module_list);
1094 
1095   bool SetSectionUnloaded(const lldb::SectionSP &section_sp);
1096 
1097   bool SetSectionUnloaded(const lldb::SectionSP &section_sp,
1098                           lldb::addr_t load_addr);
1099 
1100   void ClearAllLoadedSections();
1101 
1102   // Since expressions results can persist beyond the lifetime of a process,
1103   // and the const expression results are available after a process is gone, we
1104   // provide a way for expressions to be evaluated from the Target itself. If
1105   // an expression is going to be run, then it should have a frame filled in in
1106   // th execution context.
1107   lldb::ExpressionResults EvaluateExpression(
1108       llvm::StringRef expression, ExecutionContextScope *exe_scope,
1109       lldb::ValueObjectSP &result_valobj_sp,
1110       const EvaluateExpressionOptions &options = EvaluateExpressionOptions(),
1111       std::string *fixed_expression = nullptr);
1112 
1113   lldb::ExpressionVariableSP GetPersistentVariable(const ConstString &name);
1114 
1115   /// Return the next available number for numbered persistent variables.
GetNextPersistentVariableIndex()1116   unsigned GetNextPersistentVariableIndex() {
1117     return m_next_persistent_variable_index++;
1118   }
1119 
1120   lldb::addr_t GetPersistentSymbol(const ConstString &name);
1121 
1122   //------------------------------------------------------------------
1123   // Target Stop Hooks
1124   //------------------------------------------------------------------
1125   class StopHook : public UserID {
1126   public:
1127     StopHook(const StopHook &rhs);
1128 
1129     ~StopHook();
1130 
GetCommandPointer()1131     StringList *GetCommandPointer() { return &m_commands; }
1132 
GetCommands()1133     const StringList &GetCommands() { return m_commands; }
1134 
GetTarget()1135     lldb::TargetSP &GetTarget() { return m_target_sp; }
1136 
SetCommands(StringList & in_commands)1137     void SetCommands(StringList &in_commands) { m_commands = in_commands; }
1138 
1139     // Set the specifier.  The stop hook will own the specifier, and is
1140     // responsible for deleting it when we're done.
1141     void SetSpecifier(SymbolContextSpecifier *specifier);
1142 
GetSpecifier()1143     SymbolContextSpecifier *GetSpecifier() { return m_specifier_sp.get(); }
1144 
1145     // Set the Thread Specifier.  The stop hook will own the thread specifier,
1146     // and is responsible for deleting it when we're done.
1147     void SetThreadSpecifier(ThreadSpec *specifier);
1148 
GetThreadSpecifier()1149     ThreadSpec *GetThreadSpecifier() { return m_thread_spec_ap.get(); }
1150 
IsActive()1151     bool IsActive() { return m_active; }
1152 
SetIsActive(bool is_active)1153     void SetIsActive(bool is_active) { m_active = is_active; }
1154 
1155     void GetDescription(Stream *s, lldb::DescriptionLevel level) const;
1156 
1157   private:
1158     lldb::TargetSP m_target_sp;
1159     StringList m_commands;
1160     lldb::SymbolContextSpecifierSP m_specifier_sp;
1161     std::unique_ptr<ThreadSpec> m_thread_spec_ap;
1162     bool m_active;
1163 
1164     // Use CreateStopHook to make a new empty stop hook. The GetCommandPointer
1165     // and fill it with commands, and SetSpecifier to set the specifier shared
1166     // pointer (can be null, that will match anything.)
1167     StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid);
1168     friend class Target;
1169   };
1170   typedef std::shared_ptr<StopHook> StopHookSP;
1171 
1172   // Add an empty stop hook to the Target's stop hook list, and returns a
1173   // shared pointer to it in new_hook. Returns the id of the new hook.
1174   StopHookSP CreateStopHook();
1175 
1176   void RunStopHooks();
1177 
1178   size_t GetStopHookSize();
1179 
SetSuppresStopHooks(bool suppress)1180   bool SetSuppresStopHooks(bool suppress) {
1181     bool old_value = m_suppress_stop_hooks;
1182     m_suppress_stop_hooks = suppress;
1183     return old_value;
1184   }
1185 
GetSuppressStopHooks()1186   bool GetSuppressStopHooks() { return m_suppress_stop_hooks; }
1187 
1188   bool RemoveStopHookByID(lldb::user_id_t uid);
1189 
1190   void RemoveAllStopHooks();
1191 
1192   StopHookSP GetStopHookByID(lldb::user_id_t uid);
1193 
1194   bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state);
1195 
1196   void SetAllStopHooksActiveState(bool active_state);
1197 
GetNumStopHooks()1198   size_t GetNumStopHooks() const { return m_stop_hooks.size(); }
1199 
GetStopHookAtIndex(size_t index)1200   StopHookSP GetStopHookAtIndex(size_t index) {
1201     if (index >= GetNumStopHooks())
1202       return StopHookSP();
1203     StopHookCollection::iterator pos = m_stop_hooks.begin();
1204 
1205     while (index > 0) {
1206       pos++;
1207       index--;
1208     }
1209     return (*pos).second;
1210   }
1211 
GetPlatform()1212   lldb::PlatformSP GetPlatform() { return m_platform_sp; }
1213 
SetPlatform(const lldb::PlatformSP & platform_sp)1214   void SetPlatform(const lldb::PlatformSP &platform_sp) {
1215     m_platform_sp = platform_sp;
1216   }
1217 
1218   SourceManager &GetSourceManager();
1219 
1220   ClangModulesDeclVendor *GetClangModulesDeclVendor();
1221 
1222   //------------------------------------------------------------------
1223   // Methods.
1224   //------------------------------------------------------------------
1225   lldb::SearchFilterSP
1226   GetSearchFilterForModule(const FileSpec *containingModule);
1227 
1228   lldb::SearchFilterSP
1229   GetSearchFilterForModuleList(const FileSpecList *containingModuleList);
1230 
1231   lldb::SearchFilterSP
1232   GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules,
1233                                     const FileSpecList *containingSourceFiles);
1234 
1235   lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language,
1236                        const char *repl_options, bool can_create);
1237 
1238   void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp);
1239 
1240 protected:
1241   //------------------------------------------------------------------
1242   /// Implementing of ModuleList::Notifier.
1243   //------------------------------------------------------------------
1244 
1245   void ModuleAdded(const ModuleList &module_list,
1246                    const lldb::ModuleSP &module_sp) override;
1247 
1248   void ModuleRemoved(const ModuleList &module_list,
1249                      const lldb::ModuleSP &module_sp) override;
1250 
1251   void ModuleUpdated(const ModuleList &module_list,
1252                      const lldb::ModuleSP &old_module_sp,
1253                      const lldb::ModuleSP &new_module_sp) override;
1254   void WillClearList(const ModuleList &module_list) override;
1255 
1256   class Arch {
1257   public:
1258     explicit Arch(const ArchSpec &spec);
1259     const Arch &operator=(const ArchSpec &spec);
1260 
GetSpec()1261     const ArchSpec &GetSpec() const { return m_spec; }
GetPlugin()1262     Architecture *GetPlugin() const { return m_plugin_up.get(); }
1263 
1264   private:
1265     ArchSpec m_spec;
1266     std::unique_ptr<Architecture> m_plugin_up;
1267   };
1268   //------------------------------------------------------------------
1269   // Member variables.
1270   //------------------------------------------------------------------
1271   Debugger &m_debugger;
1272   lldb::PlatformSP m_platform_sp; ///< The platform for this target.
1273   std::recursive_mutex m_mutex; ///< An API mutex that is used by the lldb::SB*
1274                                 /// classes make the SB interface thread safe
1275   Arch m_arch;
1276   ModuleList m_images; ///< The list of images for this process (shared
1277                        /// libraries and anything dynamically loaded).
1278   SectionLoadHistory m_section_load_history;
1279   BreakpointList m_breakpoint_list;
1280   BreakpointList m_internal_breakpoint_list;
1281   using BreakpointNameList = std::map<ConstString, BreakpointName *>;
1282   BreakpointNameList m_breakpoint_names;
1283 
1284   lldb::BreakpointSP m_last_created_breakpoint;
1285   WatchpointList m_watchpoint_list;
1286   lldb::WatchpointSP m_last_created_watchpoint;
1287   // We want to tightly control the process destruction process so we can
1288   // correctly tear down everything that we need to, so the only class that
1289   // knows about the process lifespan is this target class.
1290   lldb::ProcessSP m_process_sp;
1291   lldb::SearchFilterSP m_search_filter_sp;
1292   PathMappingList m_image_search_paths;
1293   TypeSystemMap m_scratch_type_system_map;
1294 
1295   typedef std::map<lldb::LanguageType, lldb::REPLSP> REPLMap;
1296   REPLMap m_repl_map;
1297 
1298   lldb::ClangASTImporterSP m_ast_importer_sp;
1299   lldb::ClangModulesDeclVendorUP m_clang_modules_decl_vendor_ap;
1300 
1301   lldb::SourceManagerUP m_source_manager_ap;
1302 
1303   typedef std::map<lldb::user_id_t, StopHookSP> StopHookCollection;
1304   StopHookCollection m_stop_hooks;
1305   lldb::user_id_t m_stop_hook_next_id;
1306   bool m_valid;
1307   bool m_suppress_stop_hooks;
1308   bool m_is_dummy_target;
1309   unsigned m_next_persistent_variable_index = 0;
1310 
1311   static void ImageSearchPathsChanged(const PathMappingList &path_list,
1312                                       void *baton);
1313 
1314   //------------------------------------------------------------------
1315   // Utilities for `statistics` command.
1316   //------------------------------------------------------------------
1317 private:
1318   std::vector<uint32_t> m_stats_storage;
1319   bool m_collecting_stats = false;
1320 
1321 public:
SetCollectingStats(bool v)1322   void SetCollectingStats(bool v) { m_collecting_stats = v; }
1323 
GetCollectingStats()1324   bool GetCollectingStats() { return m_collecting_stats; }
1325 
IncrementStats(lldb_private::StatisticKind key)1326   void IncrementStats(lldb_private::StatisticKind key) {
1327     if (!GetCollectingStats())
1328       return;
1329     lldbassert(key < lldb_private::StatisticKind::StatisticMax &&
1330                "invalid statistics!");
1331     m_stats_storage[key] += 1;
1332   }
1333 
GetStatistics()1334   std::vector<uint32_t> GetStatistics() { return m_stats_storage; }
1335 
1336 private:
1337   //------------------------------------------------------------------
1338   /// Construct with optional file and arch.
1339   ///
1340   /// This member is private. Clients must use
1341   /// TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
1342   /// so all targets can be tracked from the central target list.
1343   ///
1344   /// @see TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
1345   //------------------------------------------------------------------
1346   Target(Debugger &debugger, const ArchSpec &target_arch,
1347          const lldb::PlatformSP &platform_sp, bool is_dummy_target);
1348 
1349   // Helper function.
1350   bool ProcessIsValid();
1351 
1352   // Copy breakpoints, stop hooks and so forth from the dummy target:
1353   void PrimeFromDummyTarget(Target *dummy_target);
1354 
1355   void AddBreakpoint(lldb::BreakpointSP breakpoint_sp, bool internal);
1356 
1357   void FinalizeFileActions(ProcessLaunchInfo &info);
1358 
1359   DISALLOW_COPY_AND_ASSIGN(Target);
1360 };
1361 
1362 } // namespace lldb_private
1363 
1364 #endif // liblldb_Target_h_
1365