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