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