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