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