1 //===-- Target.h ------------------------------------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #ifndef liblldb_Target_h_
10 #define liblldb_Target_h_
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"
37 namespace lldb_private {
39 OptionEnumValues GetDynamicValueTypes();
42 eInlineBreakpointsNever = 0,
43 eInlineBreakpointsHeaders,
44 eInlineBreakpointsAlways
47 enum LoadScriptFromSymFile {
48 eLoadScriptFromSymFileTrue,
49 eLoadScriptFromSymFileFalse,
50 eLoadScriptFromSymFileWarn
53 enum LoadCWDlldbinitFile {
55 eLoadCWDlldbinitFalse,
59 enum LoadDependentFiles {
60 eLoadDependentsDefault,
66 class TargetExperimentalProperties : public Properties {
68 TargetExperimentalProperties();
71 class TargetProperties : public Properties {
73 TargetProperties(Target *target);
75 ~TargetProperties() override;
77 ArchSpec GetDefaultArchitecture() const;
79 void SetDefaultArchitecture(const ArchSpec &arch);
81 bool GetMoveToNearestCode() const;
83 lldb::DynamicValueType GetPreferDynamicValue() const;
85 bool SetPreferDynamicValue(lldb::DynamicValueType d);
87 bool GetPreloadSymbols() const;
89 void SetPreloadSymbols(bool b);
91 bool GetDisableASLR() const;
93 void SetDisableASLR(bool b);
95 bool GetDetachOnError() const;
97 void SetDetachOnError(bool b);
99 bool GetDisableSTDIO() const;
101 void SetDisableSTDIO(bool b);
103 const char *GetDisassemblyFlavor() const;
105 InlineStrategy GetInlineStrategy() const;
107 llvm::StringRef GetArg0() const;
109 void SetArg0(llvm::StringRef arg);
111 bool GetRunArguments(Args &args) const;
113 void SetRunArguments(const Args &args);
115 Environment GetEnvironment() const;
116 void SetEnvironment(Environment env);
118 bool GetSkipPrologue() const;
120 PathMappingList &GetSourcePathMap() const;
122 FileSpecList GetExecutableSearchPaths();
124 void AppendExecutableSearchPaths(const FileSpec&);
126 FileSpecList GetDebugFileSearchPaths();
128 FileSpecList GetClangModuleSearchPaths();
130 bool GetEnableAutoImportClangModules() const;
132 bool GetEnableImportStdModule() const;
134 bool GetEnableAutoApplyFixIts() const;
136 bool GetEnableNotifyAboutFixIts() const;
138 bool GetEnableSaveObjects() const;
140 bool GetEnableSyntheticValue() const;
142 uint32_t GetMaximumNumberOfChildrenToDisplay() const;
144 uint32_t GetMaximumSizeOfStringSummary() const;
146 uint32_t GetMaximumMemReadSize() const;
148 FileSpec GetStandardInputPath() const;
149 FileSpec GetStandardErrorPath() const;
150 FileSpec GetStandardOutputPath() const;
152 void SetStandardInputPath(llvm::StringRef path);
153 void SetStandardOutputPath(llvm::StringRef path);
154 void SetStandardErrorPath(llvm::StringRef path);
156 void SetStandardInputPath(const char *path) = delete;
157 void SetStandardOutputPath(const char *path) = delete;
158 void SetStandardErrorPath(const char *path) = delete;
160 bool GetBreakpointsConsultPlatformAvoidList();
162 lldb::LanguageType GetLanguage() const;
164 llvm::StringRef GetExpressionPrefixContents();
166 bool GetUseHexImmediates() const;
168 bool GetUseFastStepping() const;
170 bool GetDisplayExpressionsInCrashlogs() const;
172 LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const;
174 LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const;
176 Disassembler::HexImmediateStyle GetHexImmediateStyle() const;
178 MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const;
180 bool GetUserSpecifiedTrapHandlerNames(Args &args) const;
182 void SetUserSpecifiedTrapHandlerNames(const Args &args);
184 bool GetNonStopModeEnabled() const;
186 void SetNonStopModeEnabled(bool b);
188 bool GetDisplayRuntimeSupportValues() const;
190 void SetDisplayRuntimeSupportValues(bool b);
192 bool GetDisplayRecognizedArguments() const;
194 void SetDisplayRecognizedArguments(bool b);
196 const ProcessLaunchInfo &GetProcessLaunchInfo();
198 void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info);
200 bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const;
202 void SetInjectLocalVariables(ExecutionContext *exe_ctx, bool b);
204 bool GetUseModernTypeLookup() const;
206 void SetRequireHardwareBreakpoints(bool b);
208 bool GetRequireHardwareBreakpoints() const;
211 // Callbacks for m_launch_info.
212 static void Arg0ValueChangedCallback(void *target_property_ptr,
214 static void RunArgsValueChangedCallback(void *target_property_ptr,
216 static void EnvVarsValueChangedCallback(void *target_property_ptr,
218 static void InheritEnvValueChangedCallback(void *target_property_ptr,
220 static void InputPathValueChangedCallback(void *target_property_ptr,
222 static void OutputPathValueChangedCallback(void *target_property_ptr,
224 static void ErrorPathValueChangedCallback(void *target_property_ptr,
226 static void DetachOnErrorValueChangedCallback(void *target_property_ptr,
228 static void DisableASLRValueChangedCallback(void *target_property_ptr,
230 static void DisableSTDIOValueChangedCallback(void *target_property_ptr,
234 ProcessLaunchInfo m_launch_info;
235 std::unique_ptr<TargetExperimentalProperties> m_experimental_properties_up;
238 class EvaluateExpressionOptions {
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
244 #if defined(_MSC_VER)
245 #pragma warning(push)
246 #pragma warning(disable : 4268)
248 static constexpr std::chrono::milliseconds default_timeout{500};
249 #if defined(_MSC_VER)
253 static constexpr ExecutionPolicy default_execution_policy =
254 eExecutionPolicyOnlyWhenNeeded;
256 EvaluateExpressionOptions() = default;
258 ExecutionPolicy GetExecutionPolicy() const { return m_execution_policy; }
260 void SetExecutionPolicy(ExecutionPolicy policy = eExecutionPolicyAlways) {
261 m_execution_policy = policy;
264 lldb::LanguageType GetLanguage() const { return m_language; }
266 void SetLanguage(lldb::LanguageType language) { m_language = language; }
268 bool DoesCoerceToId() const { return m_coerce_to_id; }
270 const char *GetPrefix() const {
271 return (m_prefix.empty() ? nullptr : m_prefix.c_str());
274 void SetPrefix(const char *prefix) {
275 if (prefix && prefix[0])
281 void SetCoerceToId(bool coerce = true) { m_coerce_to_id = coerce; }
283 bool DoesUnwindOnError() const { return m_unwind_on_error; }
285 void SetUnwindOnError(bool unwind = false) { m_unwind_on_error = unwind; }
287 bool DoesIgnoreBreakpoints() const { return m_ignore_breakpoints; }
289 void SetIgnoreBreakpoints(bool ignore = false) {
290 m_ignore_breakpoints = ignore;
293 bool DoesKeepInMemory() const { return m_keep_in_memory; }
295 void SetKeepInMemory(bool keep = true) { m_keep_in_memory = keep; }
297 lldb::DynamicValueType GetUseDynamic() const { return m_use_dynamic; }
300 SetUseDynamic(lldb::DynamicValueType dynamic = lldb::eDynamicCanRunTarget) {
301 m_use_dynamic = dynamic;
304 const Timeout<std::micro> &GetTimeout() const { return m_timeout; }
306 void SetTimeout(const Timeout<std::micro> &timeout) { m_timeout = timeout; }
308 const Timeout<std::micro> &GetOneThreadTimeout() const {
309 return m_one_thread_timeout;
312 void SetOneThreadTimeout(const Timeout<std::micro> &timeout) {
313 m_one_thread_timeout = timeout;
316 bool GetTryAllThreads() const { return m_try_others; }
318 void SetTryAllThreads(bool try_others = true) { m_try_others = try_others; }
320 bool GetStopOthers() const { return m_stop_others; }
322 void SetStopOthers(bool stop_others = true) { m_stop_others = stop_others; }
324 bool GetDebug() const { return m_debug; }
326 void SetDebug(bool b) {
329 m_generate_debug_info = true;
332 bool GetGenerateDebugInfo() const { return m_generate_debug_info; }
334 void SetGenerateDebugInfo(bool b) { m_generate_debug_info = b; }
336 bool GetColorizeErrors() const { return m_ansi_color_errors; }
338 void SetColorizeErrors(bool b) { m_ansi_color_errors = b; }
340 bool GetTrapExceptions() const { return m_trap_exceptions; }
342 void SetTrapExceptions(bool b) { m_trap_exceptions = b; }
344 bool GetREPLEnabled() const { return m_repl; }
346 void SetREPLEnabled(bool b) { m_repl = b; }
348 void SetCancelCallback(lldb::ExpressionCancelCallback callback, void *baton) {
349 m_cancel_callback_baton = baton;
350 m_cancel_callback = callback;
353 bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const {
354 return ((m_cancel_callback != nullptr)
355 ? m_cancel_callback(phase, m_cancel_callback_baton)
359 // Allows the expression contents to be remapped to point to the specified
360 // file and line using #line directives.
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;
366 m_pound_line_file.clear();
367 m_pound_line_line = 0;
371 const char *GetPoundLineFilePath() const {
372 return (m_pound_line_file.empty() ? nullptr : m_pound_line_file.c_str());
375 uint32_t GetPoundLineLine() const { return m_pound_line_line; }
377 void SetResultIsInternal(bool b) { m_result_is_internal = b; }
379 bool GetResultIsInternal() const { return m_result_is_internal; }
381 void SetAutoApplyFixIts(bool b) { m_auto_apply_fixits = b; }
383 bool GetAutoApplyFixIts() const { return m_auto_apply_fixits; }
385 bool IsForUtilityExpr() const { return m_running_utility_expression; }
387 void SetIsForUtilityExpr(bool b) { m_running_utility_expression = b; }
390 ExecutionPolicy m_execution_policy = default_execution_policy;
391 lldb::LanguageType m_language = lldb::eLanguageTypeUnknown;
392 std::string m_prefix;
393 bool m_coerce_to_id = false;
394 bool m_unwind_on_error = true;
395 bool m_ignore_breakpoints = false;
396 bool m_keep_in_memory = false;
397 bool m_try_others = true;
398 bool m_stop_others = true;
399 bool m_debug = false;
400 bool m_trap_exceptions = true;
402 bool m_generate_debug_info = false;
403 bool m_ansi_color_errors = false;
404 bool m_result_is_internal = false;
405 bool m_auto_apply_fixits = true;
406 /// True if the executed code should be treated as utility code that is only
407 /// used by LLDB internally.
408 bool m_running_utility_expression = false;
410 lldb::DynamicValueType m_use_dynamic = lldb::eNoDynamicValues;
411 Timeout<std::micro> m_timeout = default_timeout;
412 Timeout<std::micro> m_one_thread_timeout = llvm::None;
413 lldb::ExpressionCancelCallback m_cancel_callback = nullptr;
414 void *m_cancel_callback_baton = nullptr;
415 // If m_pound_line_file is not empty and m_pound_line_line is non-zero, use
416 // #line %u "%s" before the expression content to remap where the source
418 mutable std::string m_pound_line_file;
419 mutable uint32_t m_pound_line_line;
423 class Target : public std::enable_shared_from_this<Target>,
424 public TargetProperties,
426 public ExecutionContextScope,
427 public ModuleList::Notifier {
429 friend class TargetList;
431 /// Broadcaster event bits definitions.
433 eBroadcastBitBreakpointChanged = (1 << 0),
434 eBroadcastBitModulesLoaded = (1 << 1),
435 eBroadcastBitModulesUnloaded = (1 << 2),
436 eBroadcastBitWatchpointChanged = (1 << 3),
437 eBroadcastBitSymbolsLoaded = (1 << 4)
440 // These two functions fill out the Broadcaster interface:
442 static ConstString &GetStaticBroadcasterClass();
444 ConstString &GetBroadcasterClass() const override {
445 return GetStaticBroadcasterClass();
448 // This event data class is for use by the TargetList to broadcast new target
450 class TargetEventData : public EventData {
452 TargetEventData(const lldb::TargetSP &target_sp);
454 TargetEventData(const lldb::TargetSP &target_sp,
455 const ModuleList &module_list);
457 ~TargetEventData() override;
459 static ConstString GetFlavorString();
461 ConstString GetFlavor() const override {
462 return TargetEventData::GetFlavorString();
465 void Dump(Stream *s) const override;
467 static const TargetEventData *GetEventDataFromEvent(const Event *event_ptr);
469 static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr);
471 static ModuleList GetModuleListFromEvent(const Event *event_ptr);
473 const lldb::TargetSP &GetTarget() const { return m_target_sp; }
475 const ModuleList &GetModuleList() const { return m_module_list; }
478 lldb::TargetSP m_target_sp;
479 ModuleList m_module_list;
481 DISALLOW_COPY_AND_ASSIGN(TargetEventData);
486 static void SettingsInitialize();
488 static void SettingsTerminate();
490 static FileSpecList GetDefaultExecutableSearchPaths();
492 static FileSpecList GetDefaultDebugFileSearchPaths();
494 static ArchSpec GetDefaultArchitecture();
496 static void SetDefaultArchitecture(const ArchSpec &arch);
498 /// Find a binary on the system and return its Module,
499 /// or return an existing Module that is already in the Target.
501 /// Given a ModuleSpec, find a binary satisifying that specification,
502 /// or identify a matching Module already present in the Target,
503 /// and return a shared pointer to it.
505 /// \param[in] module_spec
506 /// The criteria that must be matched for the binary being loaded.
507 /// e.g. UUID, architecture, file path.
509 /// \param[in] notify
510 /// If notify is true, and the Module is new to this Target,
511 /// Target::ModulesDidLoad will be called.
512 /// If notify is false, it is assumed that the caller is adding
513 /// multiple Modules and will call ModulesDidLoad with the
514 /// full list at the end.
515 /// ModulesDidLoad must be called when a Module/Modules have
516 /// been added to the target, one way or the other.
518 /// \param[out] error_ptr
519 /// Optional argument, pointing to a Status object to fill in
520 /// with any results / messages while attempting to find/load
521 /// this binary. Many callers will be internal functions that
522 /// will handle / summarize the failures in a custom way and
523 /// don't use these messages.
526 /// An empty ModuleSP will be returned if no matching file
527 /// was found. If error_ptr was non-nullptr, an error message
528 /// will likely be provided.
529 lldb::ModuleSP GetOrCreateModule(const ModuleSpec &module_spec,
531 Status *error_ptr = nullptr);
533 // Settings accessors
535 static const lldb::TargetPropertiesSP &GetGlobalProperties();
537 std::recursive_mutex &GetAPIMutex() { return m_mutex; }
539 void DeleteCurrentProcess();
541 void CleanupProcess();
543 /// Dump a description of this object to a Stream.
545 /// Dump a description of the contents of this object to the
546 /// supplied stream \a s. The dumped content will be only what has
547 /// been loaded or parsed up to this point at which this function
548 /// is called, so this is a good way to see what has been parsed
552 /// The stream to which to dump the object description.
553 void Dump(Stream *s, lldb::DescriptionLevel description_level);
555 // If listener_sp is null, the listener of the owning Debugger object will be
557 const lldb::ProcessSP &CreateProcess(lldb::ListenerSP listener_sp,
558 llvm::StringRef plugin_name,
559 const FileSpec *crash_file);
561 const lldb::ProcessSP &GetProcessSP() const;
563 bool IsValid() { return m_valid; }
567 Status Launch(ProcessLaunchInfo &launch_info,
568 Stream *stream); // Optional stream to receive first stop info
570 Status Attach(ProcessAttachInfo &attach_info,
571 Stream *stream); // Optional stream to receive first stop info
573 // This part handles the breakpoints.
575 BreakpointList &GetBreakpointList(bool internal = false);
577 const BreakpointList &GetBreakpointList(bool internal = false) const;
579 lldb::BreakpointSP GetLastCreatedBreakpoint() {
580 return m_last_created_breakpoint;
583 lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id);
585 // Use this to create a file and line breakpoint to a given module or all
586 // module it is nullptr
587 lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules,
588 const FileSpec &file, uint32_t line_no,
589 uint32_t column, lldb::addr_t offset,
590 LazyBool check_inlines,
591 LazyBool skip_prologue, bool internal,
592 bool request_hardware,
593 LazyBool move_to_nearest_code);
595 // Use this to create breakpoint that matches regex against the source lines
596 // in files given in source_file_list: If function_names is non-empty, also
597 // filter by function after the matches are made.
598 lldb::BreakpointSP CreateSourceRegexBreakpoint(
599 const FileSpecList *containingModules,
600 const FileSpecList *source_file_list,
601 const std::unordered_set<std::string> &function_names,
602 RegularExpression &source_regex, bool internal, bool request_hardware,
603 LazyBool move_to_nearest_code);
605 // Use this to create a breakpoint from a load address
606 lldb::BreakpointSP CreateBreakpoint(lldb::addr_t load_addr, bool internal,
607 bool request_hardware);
609 // Use this to create a breakpoint from a load address and a module file spec
610 lldb::BreakpointSP CreateAddressInModuleBreakpoint(lldb::addr_t file_addr,
612 const FileSpec *file_spec,
613 bool request_hardware);
615 // Use this to create Address breakpoints:
616 lldb::BreakpointSP CreateBreakpoint(const Address &addr, bool internal,
617 bool request_hardware);
619 // Use this to create a function breakpoint by regexp in
620 // containingModule/containingSourceFiles, or all modules if it is nullptr
621 // When "skip_prologue is set to eLazyBoolCalculate, we use the current
622 // target setting, else we use the values passed in
623 lldb::BreakpointSP CreateFuncRegexBreakpoint(
624 const FileSpecList *containingModules,
625 const FileSpecList *containingSourceFiles, RegularExpression &func_regexp,
626 lldb::LanguageType requested_language, LazyBool skip_prologue,
627 bool internal, bool request_hardware);
629 // Use this to create a function breakpoint by name in containingModule, or
630 // all modules if it is nullptr When "skip_prologue is set to
631 // eLazyBoolCalculate, we use the current target setting, else we use the
632 // values passed in. func_name_type_mask is or'ed values from the
633 // FunctionNameType enum.
634 lldb::BreakpointSP CreateBreakpoint(
635 const FileSpecList *containingModules,
636 const FileSpecList *containingSourceFiles, const char *func_name,
637 lldb::FunctionNameType func_name_type_mask, lldb::LanguageType language,
638 lldb::addr_t offset, LazyBool skip_prologue, bool internal,
639 bool request_hardware);
642 CreateExceptionBreakpoint(enum lldb::LanguageType language, bool catch_bp,
643 bool throw_bp, bool internal,
644 Args *additional_args = nullptr,
645 Status *additional_args_error = nullptr);
648 CreateScriptedBreakpoint(const llvm::StringRef class_name,
649 const FileSpecList *containingModules,
650 const FileSpecList *containingSourceFiles,
652 bool request_hardware,
653 StructuredData::ObjectSP extra_args_sp,
654 Status *creation_error = nullptr);
656 // This is the same as the func_name breakpoint except that you can specify a
657 // vector of names. This is cheaper than a regular expression breakpoint in
658 // the case where you just want to set a breakpoint on a set of names you
659 // already know. func_name_type_mask is or'ed values from the
660 // FunctionNameType enum.
661 lldb::BreakpointSP CreateBreakpoint(
662 const FileSpecList *containingModules,
663 const FileSpecList *containingSourceFiles, const char *func_names[],
664 size_t num_names, lldb::FunctionNameType func_name_type_mask,
665 lldb::LanguageType language, lldb::addr_t offset, LazyBool skip_prologue,
666 bool internal, bool request_hardware);
669 CreateBreakpoint(const FileSpecList *containingModules,
670 const FileSpecList *containingSourceFiles,
671 const std::vector<std::string> &func_names,
672 lldb::FunctionNameType func_name_type_mask,
673 lldb::LanguageType language, lldb::addr_t m_offset,
674 LazyBool skip_prologue, bool internal,
675 bool request_hardware);
677 // Use this to create a general breakpoint:
678 lldb::BreakpointSP CreateBreakpoint(lldb::SearchFilterSP &filter_sp,
679 lldb::BreakpointResolverSP &resolver_sp,
680 bool internal, bool request_hardware,
681 bool resolve_indirect_symbols);
683 // Use this to create a watchpoint:
684 lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size,
685 const CompilerType *type, uint32_t kind,
688 lldb::WatchpointSP GetLastCreatedWatchpoint() {
689 return m_last_created_watchpoint;
692 WatchpointList &GetWatchpointList() { return m_watchpoint_list; }
694 // Manages breakpoint names:
695 void AddNameToBreakpoint(BreakpointID &id, const char *name, Status &error);
697 void AddNameToBreakpoint(lldb::BreakpointSP &bp_sp, const char *name,
700 void RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
703 BreakpointName *FindBreakpointName(ConstString name, bool can_create,
706 void DeleteBreakpointName(ConstString name);
708 void ConfigureBreakpointName(BreakpointName &bp_name,
709 const BreakpointOptions &options,
710 const BreakpointName::Permissions &permissions);
711 void ApplyNameToBreakpoints(BreakpointName &bp_name);
713 // This takes ownership of the name obj passed in.
714 void AddBreakpointName(BreakpointName *bp_name);
716 void GetBreakpointNames(std::vector<std::string> &names);
718 //This call removes ALL breakpoints regardless of permission.
719 void RemoveAllBreakpoints(bool internal_also = false);
721 // This removes all the breakpoints, but obeys the ePermDelete on them.
722 void RemoveAllowedBreakpoints();
724 void DisableAllBreakpoints(bool internal_also = false);
726 void DisableAllowedBreakpoints();
728 void EnableAllBreakpoints(bool internal_also = false);
730 void EnableAllowedBreakpoints();
732 bool DisableBreakpointByID(lldb::break_id_t break_id);
734 bool EnableBreakpointByID(lldb::break_id_t break_id);
736 bool RemoveBreakpointByID(lldb::break_id_t break_id);
738 // The flag 'end_to_end', default to true, signifies that the operation is
739 // performed end to end, for both the debugger and the debuggee.
741 bool RemoveAllWatchpoints(bool end_to_end = true);
743 bool DisableAllWatchpoints(bool end_to_end = true);
745 bool EnableAllWatchpoints(bool end_to_end = true);
747 bool ClearAllWatchpointHitCounts();
749 bool ClearAllWatchpointHistoricValues();
751 bool IgnoreAllWatchpoints(uint32_t ignore_count);
753 bool DisableWatchpointByID(lldb::watch_id_t watch_id);
755 bool EnableWatchpointByID(lldb::watch_id_t watch_id);
757 bool RemoveWatchpointByID(lldb::watch_id_t watch_id);
759 bool IgnoreWatchpointByID(lldb::watch_id_t watch_id, uint32_t ignore_count);
761 Status SerializeBreakpointsToFile(const FileSpec &file,
762 const BreakpointIDList &bp_ids,
765 Status CreateBreakpointsFromFile(const FileSpec &file,
766 BreakpointIDList &new_bps);
768 Status CreateBreakpointsFromFile(const FileSpec &file,
769 std::vector<std::string> &names,
770 BreakpointIDList &new_bps);
772 /// Get \a load_addr as a callable code load address for this target
774 /// Take \a load_addr and potentially add any address bits that are
775 /// needed to make the address callable. For ARM this can set bit
776 /// zero (if it already isn't) if \a load_addr is a thumb function.
777 /// If \a addr_class is set to AddressClass::eInvalid, then the address
778 /// adjustment will always happen. If it is set to an address class
779 /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
781 lldb::addr_t GetCallableLoadAddress(
782 lldb::addr_t load_addr,
783 AddressClass addr_class = AddressClass::eInvalid) const;
785 /// Get \a load_addr as an opcode for this target.
787 /// Take \a load_addr and potentially strip any address bits that are
788 /// needed to make the address point to an opcode. For ARM this can
789 /// clear bit zero (if it already isn't) if \a load_addr is a
790 /// thumb function and load_addr is in code.
791 /// If \a addr_class is set to AddressClass::eInvalid, then the address
792 /// adjustment will always happen. If it is set to an address class
793 /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
796 GetOpcodeLoadAddress(lldb::addr_t load_addr,
797 AddressClass addr_class = AddressClass::eInvalid) const;
799 // Get load_addr as breakable load address for this target. Take a addr and
800 // check if for any reason there is a better address than this to put a
801 // breakpoint on. If there is then return that address. For MIPS, if
802 // instruction at addr is a delay slot instruction then this method will find
803 // the address of its previous instruction and return that address.
804 lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr);
806 void ModulesDidLoad(ModuleList &module_list);
808 void ModulesDidUnload(ModuleList &module_list, bool delete_locations);
810 void SymbolsDidLoad(ModuleList &module_list);
812 void ClearModules(bool delete_locations);
814 /// Called as the last function in Process::DidExec().
816 /// Process::DidExec() will clear a lot of state in the process,
817 /// then try to reload a dynamic loader plugin to discover what
818 /// binaries are currently available and then this function should
819 /// be called to allow the target to do any cleanup after everything
820 /// has been figured out. It can remove breakpoints that no longer
821 /// make sense as the exec might have changed the target
822 /// architecture, and unloaded some modules that might get deleted.
825 /// Gets the module for the main executable.
827 /// Each process has a notion of a main executable that is the file
828 /// that will be executed or attached to. Executable files can have
829 /// dependent modules that are discovered from the object files, or
830 /// discovered at runtime as things are dynamically loaded.
833 /// The shared pointer to the executable module which can
834 /// contains a nullptr Module object if no executable has been
837 /// \see DynamicLoader
838 /// \see ObjectFile::GetDependentModules (FileSpecList&)
839 /// \see Process::SetExecutableModule(lldb::ModuleSP&)
840 lldb::ModuleSP GetExecutableModule();
842 Module *GetExecutableModulePointer();
844 /// Set the main executable module.
846 /// Each process has a notion of a main executable that is the file
847 /// that will be executed or attached to. Executable files can have
848 /// dependent modules that are discovered from the object files, or
849 /// discovered at runtime as things are dynamically loaded.
851 /// Setting the executable causes any of the current dependent
852 /// image information to be cleared and replaced with the static
853 /// dependent image information found by calling
854 /// ObjectFile::GetDependentModules (FileSpecList&) on the main
855 /// executable and any modules on which it depends. Calling
856 /// Process::GetImages() will return the newly found images that
857 /// were obtained from all of the object files.
859 /// \param[in] module_sp
860 /// A shared pointer reference to the module that will become
861 /// the main executable for this process.
863 /// \param[in] load_dependent_files
864 /// If \b true then ask the object files to track down any
865 /// known dependent files.
867 /// \see ObjectFile::GetDependentModules (FileSpecList&)
868 /// \see Process::GetImages()
869 void SetExecutableModule(
870 lldb::ModuleSP &module_sp,
871 LoadDependentFiles load_dependent_files = eLoadDependentsDefault);
873 bool LoadScriptingResources(std::list<Status> &errors,
874 Stream *feedback_stream = nullptr,
875 bool continue_on_error = true) {
876 return m_images.LoadScriptingResourcesInTarget(
877 this, errors, feedback_stream, continue_on_error);
880 /// Get accessor for the images for this process.
882 /// Each process has a notion of a main executable that is the file
883 /// that will be executed or attached to. Executable files can have
884 /// dependent modules that are discovered from the object files, or
885 /// discovered at runtime as things are dynamically loaded. After
886 /// a main executable has been set, the images will contain a list
887 /// of all the files that the executable depends upon as far as the
888 /// object files know. These images will usually contain valid file
889 /// virtual addresses only. When the process is launched or attached
890 /// to, the DynamicLoader plug-in will discover where these images
891 /// were loaded in memory and will resolve the load virtual
892 /// addresses is each image, and also in images that are loaded by
896 /// A list of Module objects in a module list.
897 const ModuleList &GetImages() const { return m_images; }
899 ModuleList &GetImages() { return m_images; }
901 /// Return whether this FileSpec corresponds to a module that should be
902 /// considered for general searches.
904 /// This API will be consulted by the SearchFilterForUnconstrainedSearches
905 /// and any module that returns \b true will not be searched. Note the
906 /// SearchFilterForUnconstrainedSearches is the search filter that
907 /// gets used in the CreateBreakpoint calls when no modules is provided.
909 /// The target call at present just consults the Platform's call of the
912 /// \param[in] module_sp
913 /// A shared pointer reference to the module that checked.
915 /// \return \b true if the module should be excluded, \b false otherwise.
916 bool ModuleIsExcludedForUnconstrainedSearches(const FileSpec &module_spec);
918 /// Return whether this module should be considered for general searches.
920 /// This API will be consulted by the SearchFilterForUnconstrainedSearches
921 /// and any module that returns \b true will not be searched. Note the
922 /// SearchFilterForUnconstrainedSearches is the search filter that
923 /// gets used in the CreateBreakpoint calls when no modules is provided.
925 /// The target call at present just consults the Platform's call of the
928 /// FIXME: When we get time we should add a way for the user to set modules
930 /// don't want searched, in addition to or instead of the platform ones.
932 /// \param[in] module_sp
933 /// A shared pointer reference to the module that checked.
935 /// \return \b true if the module should be excluded, \b false otherwise.
937 ModuleIsExcludedForUnconstrainedSearches(const lldb::ModuleSP &module_sp);
939 const ArchSpec &GetArchitecture() const { return m_arch.GetSpec(); }
941 /// Set the architecture for this target.
943 /// If the current target has no Images read in, then this just sets the
944 /// architecture, which will be used to select the architecture of the
945 /// ExecutableModule when that is set. If the current target has an
946 /// ExecutableModule, then calling SetArchitecture with a different
947 /// architecture from the currently selected one will reset the
948 /// ExecutableModule to that slice of the file backing the ExecutableModule.
949 /// If the file backing the ExecutableModule does not contain a fork of this
950 /// architecture, then this code will return false, and the architecture
951 /// won't be changed. If the input arch_spec is the same as the already set
952 /// architecture, this is a no-op.
954 /// \param[in] arch_spec
955 /// The new architecture.
957 /// \param[in] set_platform
958 /// If \b true, then the platform will be adjusted if the currently
959 /// selected platform is not compatible with the archicture being set.
960 /// If \b false, then just the architecture will be set even if the
961 /// currently selected platform isn't compatible (in case it might be
962 /// manually set following this function call).
965 /// \b true if the architecture was successfully set, \bfalse otherwise.
966 bool SetArchitecture(const ArchSpec &arch_spec, bool set_platform = false);
968 bool MergeArchitecture(const ArchSpec &arch_spec);
970 Architecture *GetArchitecturePlugin() const { return m_arch.GetPlugin(); }
972 Debugger &GetDebugger() { return m_debugger; }
974 size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len,
977 // Reading memory through the target allows us to skip going to the process
978 // for reading memory if possible and it allows us to try and read from any
979 // constant sections in our object files on disk. If you always want live
980 // program memory, read straight from the process. If you possibly want to
981 // read from const sections in object files, read from the target. This
982 // version of ReadMemory will try and read memory from the process if the
983 // process is alive. The order is:
984 // 1 - if (prefer_file_cache == true) then read from object file cache
985 // 2 - if there is a valid process, try and read from its memory
986 // 3 - if (prefer_file_cache == false) then read from object file cache
987 size_t ReadMemory(const Address &addr, bool prefer_file_cache, void *dst,
988 size_t dst_len, Status &error,
989 lldb::addr_t *load_addr_ptr = nullptr);
991 size_t ReadCStringFromMemory(const Address &addr, std::string &out_str,
994 size_t ReadCStringFromMemory(const Address &addr, char *dst,
995 size_t dst_max_len, Status &result_error);
997 size_t ReadScalarIntegerFromMemory(const Address &addr,
998 bool prefer_file_cache, uint32_t byte_size,
999 bool is_signed, Scalar &scalar,
1002 uint64_t ReadUnsignedIntegerFromMemory(const Address &addr,
1003 bool prefer_file_cache,
1004 size_t integer_byte_size,
1005 uint64_t fail_value, Status &error);
1007 bool ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
1008 Status &error, Address &pointer_addr);
1010 SectionLoadList &GetSectionLoadList() {
1011 return m_section_load_history.GetCurrentSectionLoadList();
1014 static Target *GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
1015 const SymbolContext *sc_ptr);
1017 // lldb::ExecutionContextScope pure virtual functions
1018 lldb::TargetSP CalculateTarget() override;
1020 lldb::ProcessSP CalculateProcess() override;
1022 lldb::ThreadSP CalculateThread() override;
1024 lldb::StackFrameSP CalculateStackFrame() override;
1026 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
1028 PathMappingList &GetImageSearchPathList();
1030 TypeSystem *GetScratchTypeSystemForLanguage(Status *error,
1031 lldb::LanguageType language,
1032 bool create_on_demand = true);
1034 PersistentExpressionState *
1035 GetPersistentExpressionStateForLanguage(lldb::LanguageType language);
1037 // Creates a UserExpression for the given language, the rest of the
1038 // parameters have the same meaning as for the UserExpression constructor.
1039 // Returns a new-ed object which the caller owns.
1041 UserExpression *GetUserExpressionForLanguage(
1042 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
1043 Expression::ResultType desired_type,
1044 const EvaluateExpressionOptions &options,
1045 ValueObject *ctx_obj, Status &error);
1047 // Creates a FunctionCaller for the given language, the rest of the
1048 // parameters have the same meaning as for the FunctionCaller constructor.
1049 // Since a FunctionCaller can't be
1050 // IR Interpreted, it makes no sense to call this with an
1051 // ExecutionContextScope that lacks
1053 // Returns a new-ed object which the caller owns.
1055 FunctionCaller *GetFunctionCallerForLanguage(lldb::LanguageType language,
1056 const CompilerType &return_type,
1057 const Address &function_address,
1058 const ValueList &arg_value_list,
1059 const char *name, Status &error);
1061 // Creates a UtilityFunction for the given language, the rest of the
1062 // parameters have the same meaning as for the UtilityFunction constructor.
1063 // Returns a new-ed object which the caller owns.
1065 UtilityFunction *GetUtilityFunctionForLanguage(const char *expr,
1066 lldb::LanguageType language,
1070 ClangASTContext *GetScratchClangASTContext(bool create_on_demand = true);
1072 lldb::ClangASTImporterSP GetClangASTImporter();
1074 // Install any files through the platform that need be to installed prior to
1075 // launching or attaching.
1076 Status Install(ProcessLaunchInfo *launch_info);
1078 bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr);
1080 bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr,
1081 uint32_t stop_id = SectionLoadHistory::eStopIDNow);
1083 bool SetSectionLoadAddress(const lldb::SectionSP §ion,
1084 lldb::addr_t load_addr,
1085 bool warn_multiple = false);
1087 size_t UnloadModuleSections(const lldb::ModuleSP &module_sp);
1089 size_t UnloadModuleSections(const ModuleList &module_list);
1091 bool SetSectionUnloaded(const lldb::SectionSP §ion_sp);
1093 bool SetSectionUnloaded(const lldb::SectionSP §ion_sp,
1094 lldb::addr_t load_addr);
1096 void ClearAllLoadedSections();
1098 // Since expressions results can persist beyond the lifetime of a process,
1099 // and the const expression results are available after a process is gone, we
1100 // provide a way for expressions to be evaluated from the Target itself. If
1101 // an expression is going to be run, then it should have a frame filled in in
1102 // the execution context.
1103 lldb::ExpressionResults EvaluateExpression(
1104 llvm::StringRef expression, ExecutionContextScope *exe_scope,
1105 lldb::ValueObjectSP &result_valobj_sp,
1106 const EvaluateExpressionOptions &options = EvaluateExpressionOptions(),
1107 std::string *fixed_expression = nullptr,
1108 ValueObject *ctx_obj = nullptr);
1110 lldb::ExpressionVariableSP GetPersistentVariable(ConstString name);
1112 /// Return the next available number for numbered persistent variables.
1113 unsigned GetNextPersistentVariableIndex() {
1114 return m_next_persistent_variable_index++;
1117 lldb::addr_t GetPersistentSymbol(ConstString name);
1119 // Target Stop Hooks
1120 class StopHook : public UserID {
1122 StopHook(const StopHook &rhs);
1126 StringList *GetCommandPointer() { return &m_commands; }
1128 const StringList &GetCommands() { return m_commands; }
1130 lldb::TargetSP &GetTarget() { return m_target_sp; }
1132 void SetCommands(StringList &in_commands) { m_commands = in_commands; }
1134 // Set the specifier. The stop hook will own the specifier, and is
1135 // responsible for deleting it when we're done.
1136 void SetSpecifier(SymbolContextSpecifier *specifier);
1138 SymbolContextSpecifier *GetSpecifier() { return m_specifier_sp.get(); }
1140 // Set the Thread Specifier. The stop hook will own the thread specifier,
1141 // and is responsible for deleting it when we're done.
1142 void SetThreadSpecifier(ThreadSpec *specifier);
1144 ThreadSpec *GetThreadSpecifier() { return m_thread_spec_up.get(); }
1146 bool IsActive() { return m_active; }
1148 void SetIsActive(bool is_active) { m_active = is_active; }
1150 void SetAutoContinue(bool auto_continue) {m_auto_continue = auto_continue;}
1152 bool GetAutoContinue() const { return m_auto_continue; }
1154 void GetDescription(Stream *s, lldb::DescriptionLevel level) const;
1157 lldb::TargetSP m_target_sp;
1158 StringList m_commands;
1159 lldb::SymbolContextSpecifierSP m_specifier_sp;
1160 std::unique_ptr<ThreadSpec> m_thread_spec_up;
1161 bool m_active = true;
1162 bool m_auto_continue = false;
1164 // Use CreateStopHook to make a new empty stop hook. The GetCommandPointer
1165 // and fill it with commands, and SetSpecifier to set the specifier shared
1166 // pointer (can be null, that will match anything.)
1167 StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid);
1168 friend class Target;
1170 typedef std::shared_ptr<StopHook> StopHookSP;
1172 // Add an empty stop hook to the Target's stop hook list, and returns a
1173 // shared pointer to it in new_hook. Returns the id of the new hook.
1174 StopHookSP CreateStopHook();
1176 void RunStopHooks();
1178 size_t GetStopHookSize();
1180 bool SetSuppresStopHooks(bool suppress) {
1181 bool old_value = m_suppress_stop_hooks;
1182 m_suppress_stop_hooks = suppress;
1186 bool GetSuppressStopHooks() { return m_suppress_stop_hooks; }
1188 bool RemoveStopHookByID(lldb::user_id_t uid);
1190 void RemoveAllStopHooks();
1192 StopHookSP GetStopHookByID(lldb::user_id_t uid);
1194 bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state);
1196 void SetAllStopHooksActiveState(bool active_state);
1198 size_t GetNumStopHooks() const { return m_stop_hooks.size(); }
1200 StopHookSP GetStopHookAtIndex(size_t index) {
1201 if (index >= GetNumStopHooks())
1202 return StopHookSP();
1203 StopHookCollection::iterator pos = m_stop_hooks.begin();
1209 return (*pos).second;
1212 lldb::PlatformSP GetPlatform() { return m_platform_sp; }
1214 void SetPlatform(const lldb::PlatformSP &platform_sp) {
1215 m_platform_sp = platform_sp;
1218 SourceManager &GetSourceManager();
1220 ClangModulesDeclVendor *GetClangModulesDeclVendor();
1223 lldb::SearchFilterSP
1224 GetSearchFilterForModule(const FileSpec *containingModule);
1226 lldb::SearchFilterSP
1227 GetSearchFilterForModuleList(const FileSpecList *containingModuleList);
1229 lldb::SearchFilterSP
1230 GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules,
1231 const FileSpecList *containingSourceFiles);
1233 lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language,
1234 const char *repl_options, bool can_create);
1236 void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp);
1239 /// Implementing of ModuleList::Notifier.
1241 void NotifyModuleAdded(const ModuleList &module_list,
1242 const lldb::ModuleSP &module_sp) override;
1244 void NotifyModuleRemoved(const ModuleList &module_list,
1245 const lldb::ModuleSP &module_sp) override;
1247 void NotifyModuleUpdated(const ModuleList &module_list,
1248 const lldb::ModuleSP &old_module_sp,
1249 const lldb::ModuleSP &new_module_sp) override;
1251 void NotifyWillClearList(const ModuleList &module_list) override;
1253 void NotifyModulesRemoved(lldb_private::ModuleList &module_list) override;
1257 explicit Arch(const ArchSpec &spec);
1258 const Arch &operator=(const ArchSpec &spec);
1260 const ArchSpec &GetSpec() const { return m_spec; }
1261 Architecture *GetPlugin() const { return m_plugin_up.get(); }
1265 std::unique_ptr<Architecture> m_plugin_up;
1267 // Member variables.
1268 Debugger &m_debugger;
1269 lldb::PlatformSP m_platform_sp; ///< The platform for this target.
1270 std::recursive_mutex m_mutex; ///< An API mutex that is used by the lldb::SB*
1271 /// classes make the SB interface thread safe
1273 ModuleList m_images; ///< The list of images for this process (shared
1274 /// libraries and anything dynamically loaded).
1275 SectionLoadHistory m_section_load_history;
1276 BreakpointList m_breakpoint_list;
1277 BreakpointList m_internal_breakpoint_list;
1278 using BreakpointNameList = std::map<ConstString, BreakpointName *>;
1279 BreakpointNameList m_breakpoint_names;
1281 lldb::BreakpointSP m_last_created_breakpoint;
1282 WatchpointList m_watchpoint_list;
1283 lldb::WatchpointSP m_last_created_watchpoint;
1284 // We want to tightly control the process destruction process so we can
1285 // correctly tear down everything that we need to, so the only class that
1286 // knows about the process lifespan is this target class.
1287 lldb::ProcessSP m_process_sp;
1288 lldb::SearchFilterSP m_search_filter_sp;
1289 PathMappingList m_image_search_paths;
1290 TypeSystemMap m_scratch_type_system_map;
1292 typedef std::map<lldb::LanguageType, lldb::REPLSP> REPLMap;
1295 lldb::ClangASTImporterSP m_ast_importer_sp;
1296 lldb::ClangModulesDeclVendorUP m_clang_modules_decl_vendor_up;
1298 lldb::SourceManagerUP m_source_manager_up;
1300 typedef std::map<lldb::user_id_t, StopHookSP> StopHookCollection;
1301 StopHookCollection m_stop_hooks;
1302 lldb::user_id_t m_stop_hook_next_id;
1304 bool m_suppress_stop_hooks;
1305 bool m_is_dummy_target;
1306 unsigned m_next_persistent_variable_index = 0;
1308 static void ImageSearchPathsChanged(const PathMappingList &path_list,
1311 // Utilities for `statistics` command.
1313 std::vector<uint32_t> m_stats_storage;
1314 bool m_collecting_stats = false;
1317 void SetCollectingStats(bool v) { m_collecting_stats = v; }
1319 bool GetCollectingStats() { return m_collecting_stats; }
1321 void IncrementStats(lldb_private::StatisticKind key) {
1322 if (!GetCollectingStats())
1324 lldbassert(key < lldb_private::StatisticKind::StatisticMax &&
1325 "invalid statistics!");
1326 m_stats_storage[key] += 1;
1329 std::vector<uint32_t> GetStatistics() { return m_stats_storage; }
1332 /// Construct with optional file and arch.
1334 /// This member is private. Clients must use
1335 /// TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
1336 /// so all targets can be tracked from the central target list.
1338 /// \see TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
1339 Target(Debugger &debugger, const ArchSpec &target_arch,
1340 const lldb::PlatformSP &platform_sp, bool is_dummy_target);
1343 bool ProcessIsValid();
1345 // Copy breakpoints, stop hooks and so forth from the dummy target:
1346 void PrimeFromDummyTarget(Target *dummy_target);
1348 void AddBreakpoint(lldb::BreakpointSP breakpoint_sp, bool internal);
1350 void FinalizeFileActions(ProcessLaunchInfo &info);
1352 DISALLOW_COPY_AND_ASSIGN(Target);
1355 } // namespace lldb_private
1357 #endif // liblldb_Target_h_