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