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