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