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