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