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