1 //===-- Target.h ------------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #ifndef liblldb_Target_h_
11 #define liblldb_Target_h_
21 // Other libraries and framework includes
23 #include "lldb/Breakpoint/BreakpointList.h"
24 #include "lldb/Breakpoint/BreakpointName.h"
25 #include "lldb/Breakpoint/WatchpointList.h"
26 #include "lldb/Core/Architecture.h"
27 #include "lldb/Core/Broadcaster.h"
28 #include "lldb/Core/Disassembler.h"
29 #include "lldb/Core/ModuleList.h"
30 #include "lldb/Core/UserSettingsController.h"
31 #include "lldb/Expression/Expression.h"
32 #include "lldb/Symbol/TypeSystem.h"
33 #include "lldb/Target/ExecutionContextScope.h"
34 #include "lldb/Target/PathMappingList.h"
35 #include "lldb/Target/ProcessLaunchInfo.h"
36 #include "lldb/Target/SectionLoadHistory.h"
37 #include "lldb/Utility/ArchSpec.h"
38 #include "lldb/Utility/LLDBAssert.h"
39 #include "lldb/Utility/Timeout.h"
40 #include "lldb/lldb-public.h"
42 namespace lldb_private {
44 extern OptionEnumValueElement g_dynamic_value_types[];
46 typedef enum InlineStrategy {
47 eInlineBreakpointsNever = 0,
48 eInlineBreakpointsHeaders,
49 eInlineBreakpointsAlways
52 typedef enum LoadScriptFromSymFile {
53 eLoadScriptFromSymFileTrue,
54 eLoadScriptFromSymFileFalse,
55 eLoadScriptFromSymFileWarn
56 } LoadScriptFromSymFile;
58 typedef enum LoadCWDlldbinitFile {
60 eLoadCWDlldbinitFalse,
62 } LoadCWDlldbinitFile;
64 //----------------------------------------------------------------------
66 //----------------------------------------------------------------------
67 class TargetExperimentalProperties : public Properties {
69 TargetExperimentalProperties();
72 class TargetProperties : public Properties {
74 TargetProperties(Target *target);
76 ~TargetProperties() override;
78 ArchSpec GetDefaultArchitecture() const;
80 void SetDefaultArchitecture(const ArchSpec &arch);
82 bool GetMoveToNearestCode() const;
84 lldb::DynamicValueType GetPreferDynamicValue() const;
86 bool SetPreferDynamicValue(lldb::DynamicValueType d);
88 bool GetPreloadSymbols() const;
90 void SetPreloadSymbols(bool b);
92 bool GetDisableASLR() const;
94 void SetDisableASLR(bool b);
96 bool GetDetachOnError() const;
98 void SetDetachOnError(bool b);
100 bool GetDisableSTDIO() const;
102 void SetDisableSTDIO(bool b);
104 const char *GetDisassemblyFlavor() const;
106 InlineStrategy GetInlineStrategy() const;
108 llvm::StringRef GetArg0() const;
110 void SetArg0(llvm::StringRef arg);
112 bool GetRunArguments(Args &args) const;
114 void SetRunArguments(const Args &args);
116 Environment GetEnvironment() const;
117 void SetEnvironment(Environment env);
119 bool GetSkipPrologue() const;
121 PathMappingList &GetSourcePathMap() const;
123 FileSpecList &GetExecutableSearchPaths();
125 FileSpecList &GetDebugFileSearchPaths();
127 FileSpecList &GetClangModuleSearchPaths();
129 bool GetEnableAutoImportClangModules() const;
131 bool GetEnableAutoApplyFixIts() const;
133 bool GetEnableNotifyAboutFixIts() const;
135 bool GetEnableSaveObjects() const;
137 bool GetEnableSyntheticValue() const;
139 uint32_t GetMaximumNumberOfChildrenToDisplay() const;
141 uint32_t GetMaximumSizeOfStringSummary() const;
143 uint32_t GetMaximumMemReadSize() const;
145 FileSpec GetStandardInputPath() const;
146 FileSpec GetStandardErrorPath() const;
147 FileSpec GetStandardOutputPath() const;
149 void SetStandardInputPath(llvm::StringRef path);
150 void SetStandardOutputPath(llvm::StringRef path);
151 void SetStandardErrorPath(llvm::StringRef path);
153 void SetStandardInputPath(const char *path) = delete;
154 void SetStandardOutputPath(const char *path) = delete;
155 void SetStandardErrorPath(const char *path) = delete;
157 bool GetBreakpointsConsultPlatformAvoidList();
159 lldb::LanguageType GetLanguage() const;
161 llvm::StringRef GetExpressionPrefixContents();
163 bool GetUseHexImmediates() const;
165 bool GetUseFastStepping() const;
167 bool GetDisplayExpressionsInCrashlogs() const;
169 LoadScriptFromSymFile GetLoadScriptFromSymbolFile() const;
171 LoadCWDlldbinitFile GetLoadCWDlldbinitFile() const;
173 Disassembler::HexImmediateStyle GetHexImmediateStyle() const;
175 MemoryModuleLoadLevel GetMemoryModuleLoadLevel() const;
177 bool GetUserSpecifiedTrapHandlerNames(Args &args) const;
179 void SetUserSpecifiedTrapHandlerNames(const Args &args);
181 bool GetNonStopModeEnabled() const;
183 void SetNonStopModeEnabled(bool b);
185 bool GetDisplayRuntimeSupportValues() const;
187 void SetDisplayRuntimeSupportValues(bool b);
189 const ProcessLaunchInfo &GetProcessLaunchInfo();
191 void SetProcessLaunchInfo(const ProcessLaunchInfo &launch_info);
193 bool GetInjectLocalVariables(ExecutionContext *exe_ctx) const;
195 void SetInjectLocalVariables(ExecutionContext *exe_ctx, bool b);
197 bool GetUseModernTypeLookup() const;
200 //------------------------------------------------------------------
201 // Callbacks for m_launch_info.
202 //------------------------------------------------------------------
203 static void Arg0ValueChangedCallback(void *target_property_ptr,
205 static void RunArgsValueChangedCallback(void *target_property_ptr,
207 static void EnvVarsValueChangedCallback(void *target_property_ptr,
209 static void InheritEnvValueChangedCallback(void *target_property_ptr,
211 static void InputPathValueChangedCallback(void *target_property_ptr,
213 static void OutputPathValueChangedCallback(void *target_property_ptr,
215 static void ErrorPathValueChangedCallback(void *target_property_ptr,
217 static void DetachOnErrorValueChangedCallback(void *target_property_ptr,
219 static void DisableASLRValueChangedCallback(void *target_property_ptr,
221 static void DisableSTDIOValueChangedCallback(void *target_property_ptr,
224 //------------------------------------------------------------------
226 //------------------------------------------------------------------
227 ProcessLaunchInfo m_launch_info;
228 std::unique_ptr<TargetExperimentalProperties> m_experimental_properties_up;
231 class EvaluateExpressionOptions {
233 // MSVC has a bug here that reports C4268: 'const' static/global data
234 // initialized with compiler generated default constructor fills the object
235 // with zeros. Confirmed that MSVC is *not* zero-initializing, it's just a
237 #if defined(_MSC_VER)
238 #pragma warning(push)
239 #pragma warning(disable : 4268)
241 static constexpr std::chrono::milliseconds default_timeout{500};
242 #if defined(_MSC_VER)
246 static constexpr ExecutionPolicy default_execution_policy =
247 eExecutionPolicyOnlyWhenNeeded;
249 EvaluateExpressionOptions() = default;
251 ExecutionPolicy GetExecutionPolicy() const { return m_execution_policy; }
253 void SetExecutionPolicy(ExecutionPolicy policy = eExecutionPolicyAlways) {
254 m_execution_policy = policy;
257 lldb::LanguageType GetLanguage() const { return m_language; }
259 void SetLanguage(lldb::LanguageType language) { m_language = language; }
261 bool DoesCoerceToId() const { return m_coerce_to_id; }
263 const char *GetPrefix() const {
264 return (m_prefix.empty() ? nullptr : m_prefix.c_str());
267 void SetPrefix(const char *prefix) {
268 if (prefix && prefix[0])
274 void SetCoerceToId(bool coerce = true) { m_coerce_to_id = coerce; }
276 bool DoesUnwindOnError() const { return m_unwind_on_error; }
278 void SetUnwindOnError(bool unwind = false) { m_unwind_on_error = unwind; }
280 bool DoesIgnoreBreakpoints() const { return m_ignore_breakpoints; }
282 void SetIgnoreBreakpoints(bool ignore = false) {
283 m_ignore_breakpoints = ignore;
286 bool DoesKeepInMemory() const { return m_keep_in_memory; }
288 void SetKeepInMemory(bool keep = true) { m_keep_in_memory = keep; }
290 lldb::DynamicValueType GetUseDynamic() const { return m_use_dynamic; }
293 SetUseDynamic(lldb::DynamicValueType dynamic = lldb::eDynamicCanRunTarget) {
294 m_use_dynamic = dynamic;
297 const Timeout<std::micro> &GetTimeout() const { return m_timeout; }
299 void SetTimeout(const Timeout<std::micro> &timeout) { m_timeout = timeout; }
301 const Timeout<std::micro> &GetOneThreadTimeout() const {
302 return m_one_thread_timeout;
305 void SetOneThreadTimeout(const Timeout<std::micro> &timeout) {
306 m_one_thread_timeout = timeout;
309 bool GetTryAllThreads() const { return m_try_others; }
311 void SetTryAllThreads(bool try_others = true) { m_try_others = try_others; }
313 bool GetStopOthers() const { return m_stop_others; }
315 void SetStopOthers(bool stop_others = true) { m_stop_others = stop_others; }
317 bool GetDebug() const { return m_debug; }
319 void SetDebug(bool b) {
322 m_generate_debug_info = true;
325 bool GetGenerateDebugInfo() const { return m_generate_debug_info; }
327 void SetGenerateDebugInfo(bool b) { m_generate_debug_info = b; }
329 bool GetColorizeErrors() const { return m_ansi_color_errors; }
331 void SetColorizeErrors(bool b) { m_ansi_color_errors = b; }
333 bool GetTrapExceptions() const { return m_trap_exceptions; }
335 void SetTrapExceptions(bool b) { m_trap_exceptions = b; }
337 bool GetREPLEnabled() const { return m_repl; }
339 void SetREPLEnabled(bool b) { m_repl = b; }
341 void SetCancelCallback(lldb::ExpressionCancelCallback callback, void *baton) {
342 m_cancel_callback_baton = baton;
343 m_cancel_callback = callback;
346 bool InvokeCancelCallback(lldb::ExpressionEvaluationPhase phase) const {
347 return ((m_cancel_callback != nullptr)
348 ? m_cancel_callback(phase, m_cancel_callback_baton)
352 // Allows the expression contents to be remapped to point to the specified
353 // file and line using #line directives.
354 void SetPoundLine(const char *path, uint32_t line) const {
355 if (path && path[0]) {
356 m_pound_line_file = path;
357 m_pound_line_line = line;
359 m_pound_line_file.clear();
360 m_pound_line_line = 0;
364 const char *GetPoundLineFilePath() const {
365 return (m_pound_line_file.empty() ? nullptr : m_pound_line_file.c_str());
368 uint32_t GetPoundLineLine() const { return m_pound_line_line; }
370 void SetResultIsInternal(bool b) { m_result_is_internal = b; }
372 bool GetResultIsInternal() const { return m_result_is_internal; }
374 void SetAutoApplyFixIts(bool b) { m_auto_apply_fixits = b; }
376 bool GetAutoApplyFixIts() const { return m_auto_apply_fixits; }
379 ExecutionPolicy m_execution_policy = default_execution_policy;
380 lldb::LanguageType m_language = lldb::eLanguageTypeUnknown;
381 std::string m_prefix;
382 bool m_coerce_to_id = false;
383 bool m_unwind_on_error = true;
384 bool m_ignore_breakpoints = false;
385 bool m_keep_in_memory = false;
386 bool m_try_others = true;
387 bool m_stop_others = true;
388 bool m_debug = false;
389 bool m_trap_exceptions = true;
391 bool m_generate_debug_info = false;
392 bool m_ansi_color_errors = false;
393 bool m_result_is_internal = false;
394 bool m_auto_apply_fixits = true;
395 lldb::DynamicValueType m_use_dynamic = lldb::eNoDynamicValues;
396 Timeout<std::micro> m_timeout = default_timeout;
397 Timeout<std::micro> m_one_thread_timeout = llvm::None;
398 lldb::ExpressionCancelCallback m_cancel_callback = nullptr;
399 void *m_cancel_callback_baton = nullptr;
400 // If m_pound_line_file is not empty and m_pound_line_line is non-zero, use
401 // #line %u "%s" before the expression content to remap where the source
403 mutable std::string m_pound_line_file;
404 mutable uint32_t m_pound_line_line;
407 //----------------------------------------------------------------------
409 //----------------------------------------------------------------------
410 class Target : public std::enable_shared_from_this<Target>,
411 public TargetProperties,
413 public ExecutionContextScope,
414 public ModuleList::Notifier {
416 friend class TargetList;
418 //------------------------------------------------------------------
419 /// Broadcaster event bits definitions.
420 //------------------------------------------------------------------
422 eBroadcastBitBreakpointChanged = (1 << 0),
423 eBroadcastBitModulesLoaded = (1 << 1),
424 eBroadcastBitModulesUnloaded = (1 << 2),
425 eBroadcastBitWatchpointChanged = (1 << 3),
426 eBroadcastBitSymbolsLoaded = (1 << 4)
429 // These two functions fill out the Broadcaster interface:
431 static ConstString &GetStaticBroadcasterClass();
433 ConstString &GetBroadcasterClass() const override {
434 return GetStaticBroadcasterClass();
437 // This event data class is for use by the TargetList to broadcast new target
439 class TargetEventData : public EventData {
441 TargetEventData(const lldb::TargetSP &target_sp);
443 TargetEventData(const lldb::TargetSP &target_sp,
444 const ModuleList &module_list);
446 ~TargetEventData() override;
448 static const ConstString &GetFlavorString();
450 const ConstString &GetFlavor() const override {
451 return TargetEventData::GetFlavorString();
454 void Dump(Stream *s) const override;
456 static const TargetEventData *GetEventDataFromEvent(const Event *event_ptr);
458 static lldb::TargetSP GetTargetFromEvent(const Event *event_ptr);
460 static ModuleList GetModuleListFromEvent(const Event *event_ptr);
462 const lldb::TargetSP &GetTarget() const { return m_target_sp; }
464 const ModuleList &GetModuleList() const { return m_module_list; }
467 lldb::TargetSP m_target_sp;
468 ModuleList m_module_list;
470 DISALLOW_COPY_AND_ASSIGN(TargetEventData);
475 static void SettingsInitialize();
477 static void SettingsTerminate();
479 static FileSpecList GetDefaultExecutableSearchPaths();
481 static FileSpecList GetDefaultDebugFileSearchPaths();
483 static FileSpecList GetDefaultClangModuleSearchPaths();
485 static ArchSpec GetDefaultArchitecture();
487 static void SetDefaultArchitecture(const ArchSpec &arch);
489 lldb::ModuleSP GetSharedModule(const ModuleSpec &module_spec,
490 Status *error_ptr = nullptr);
492 //----------------------------------------------------------------------
493 // Settings accessors
494 //----------------------------------------------------------------------
496 static const lldb::TargetPropertiesSP &GetGlobalProperties();
498 std::recursive_mutex &GetAPIMutex() { return m_mutex; }
500 void DeleteCurrentProcess();
502 void CleanupProcess();
504 //------------------------------------------------------------------
505 /// Dump a description of this object to a Stream.
507 /// Dump a description of the contents of this object to the
508 /// supplied stream \a s. The dumped content will be only what has
509 /// been loaded or parsed up to this point at which this function
510 /// is called, so this is a good way to see what has been parsed
514 /// The stream to which to dump the object description.
515 //------------------------------------------------------------------
516 void Dump(Stream *s, lldb::DescriptionLevel description_level);
518 const lldb::ProcessSP &CreateProcess(lldb::ListenerSP listener,
519 llvm::StringRef plugin_name,
520 const FileSpec *crash_file);
522 const lldb::ProcessSP &GetProcessSP() const;
524 bool IsValid() { return m_valid; }
528 Status Launch(ProcessLaunchInfo &launch_info,
529 Stream *stream); // Optional stream to receive first stop info
531 Status Attach(ProcessAttachInfo &attach_info,
532 Stream *stream); // Optional stream to receive first stop info
534 //------------------------------------------------------------------
535 // This part handles the breakpoints.
536 //------------------------------------------------------------------
538 BreakpointList &GetBreakpointList(bool internal = false);
540 const BreakpointList &GetBreakpointList(bool internal = false) const;
542 lldb::BreakpointSP GetLastCreatedBreakpoint() {
543 return m_last_created_breakpoint;
546 lldb::BreakpointSP GetBreakpointByID(lldb::break_id_t break_id);
548 // Use this to create a file and line breakpoint to a given module or all
549 // module it is nullptr
550 lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules,
551 const FileSpec &file, uint32_t line_no,
553 LazyBool check_inlines,
554 LazyBool skip_prologue, bool internal,
555 bool request_hardware,
556 LazyBool move_to_nearest_code);
558 // Use this to create breakpoint that matches regex against the source lines
559 // in files given in source_file_list: If function_names is non-empty, also
560 // filter by function after the matches are made.
561 lldb::BreakpointSP CreateSourceRegexBreakpoint(
562 const FileSpecList *containingModules,
563 const FileSpecList *source_file_list,
564 const std::unordered_set<std::string> &function_names,
565 RegularExpression &source_regex, bool internal, bool request_hardware,
566 LazyBool move_to_nearest_code);
568 // Use this to create a breakpoint from a load address
569 lldb::BreakpointSP CreateBreakpoint(lldb::addr_t load_addr, bool internal,
570 bool request_hardware);
572 // Use this to create a breakpoint from a load address and a module file spec
573 lldb::BreakpointSP CreateAddressInModuleBreakpoint(lldb::addr_t file_addr,
575 const FileSpec *file_spec,
576 bool request_hardware);
578 // Use this to create Address breakpoints:
579 lldb::BreakpointSP CreateBreakpoint(const Address &addr, bool internal,
580 bool request_hardware);
582 // Use this to create a function breakpoint by regexp in
583 // containingModule/containingSourceFiles, or all modules if it is nullptr
584 // When "skip_prologue is set to eLazyBoolCalculate, we use the current
585 // target setting, else we use the values passed in
586 lldb::BreakpointSP CreateFuncRegexBreakpoint(
587 const FileSpecList *containingModules,
588 const FileSpecList *containingSourceFiles, RegularExpression &func_regexp,
589 lldb::LanguageType requested_language, LazyBool skip_prologue,
590 bool internal, bool request_hardware);
592 // Use this to create a function breakpoint by name in containingModule, or
593 // all modules if it is nullptr When "skip_prologue is set to
594 // eLazyBoolCalculate, we use the current target setting, else we use the
595 // values passed in. func_name_type_mask is or'ed values from the
596 // FunctionNameType enum.
597 lldb::BreakpointSP CreateBreakpoint(const FileSpecList *containingModules,
598 const FileSpecList *containingSourceFiles,
599 const char *func_name,
600 uint32_t func_name_type_mask,
601 lldb::LanguageType language,
603 LazyBool skip_prologue, bool internal,
604 bool request_hardware);
607 CreateExceptionBreakpoint(enum lldb::LanguageType language, bool catch_bp,
608 bool throw_bp, bool internal,
609 Args *additional_args = nullptr,
610 Status *additional_args_error = nullptr);
612 // This is the same as the func_name breakpoint except that you can specify a
613 // vector of names. This is cheaper than a regular expression breakpoint in
614 // the case where you just want to set a breakpoint on a set of names you
615 // already know. func_name_type_mask is or'ed values from the
616 // FunctionNameType enum.
618 CreateBreakpoint(const FileSpecList *containingModules,
619 const FileSpecList *containingSourceFiles,
620 const char *func_names[], size_t num_names,
621 uint32_t func_name_type_mask, lldb::LanguageType language,
622 lldb::addr_t offset, LazyBool skip_prologue, bool internal,
623 bool request_hardware);
626 CreateBreakpoint(const FileSpecList *containingModules,
627 const FileSpecList *containingSourceFiles,
628 const std::vector<std::string> &func_names,
629 uint32_t func_name_type_mask, lldb::LanguageType language,
630 lldb::addr_t m_offset, LazyBool skip_prologue, bool internal,
631 bool request_hardware);
633 // Use this to create a general breakpoint:
634 lldb::BreakpointSP CreateBreakpoint(lldb::SearchFilterSP &filter_sp,
635 lldb::BreakpointResolverSP &resolver_sp,
636 bool internal, bool request_hardware,
637 bool resolve_indirect_symbols);
639 // Use this to create a watchpoint:
640 lldb::WatchpointSP CreateWatchpoint(lldb::addr_t addr, size_t size,
641 const CompilerType *type, uint32_t kind,
644 lldb::WatchpointSP GetLastCreatedWatchpoint() {
645 return m_last_created_watchpoint;
648 WatchpointList &GetWatchpointList() { return m_watchpoint_list; }
650 // Manages breakpoint names:
651 void AddNameToBreakpoint(BreakpointID &id, const char *name, Status &error);
653 void AddNameToBreakpoint(lldb::BreakpointSP &bp_sp, const char *name,
656 void RemoveNameFromBreakpoint(lldb::BreakpointSP &bp_sp,
657 const ConstString &name);
659 BreakpointName *FindBreakpointName(const ConstString &name, bool can_create,
662 void DeleteBreakpointName(const ConstString &name);
664 void ConfigureBreakpointName(BreakpointName &bp_name,
665 const BreakpointOptions &options,
666 const BreakpointName::Permissions &permissions);
667 void ApplyNameToBreakpoints(BreakpointName &bp_name);
670 // This takes ownership of the name obj passed in.
671 void AddBreakpointName(BreakpointName *bp_name);
673 void GetBreakpointNames(std::vector<std::string> &names);
675 //This call removes ALL breakpoints regardless of permission.
676 void RemoveAllBreakpoints(bool internal_also = false);
678 // This removes all the breakpoints, but obeys the ePermDelete on them.
679 void RemoveAllowedBreakpoints();
681 void DisableAllBreakpoints(bool internal_also = false);
683 void DisableAllowedBreakpoints();
685 void EnableAllBreakpoints(bool internal_also = false);
687 void EnableAllowedBreakpoints();
689 bool DisableBreakpointByID(lldb::break_id_t break_id);
691 bool EnableBreakpointByID(lldb::break_id_t break_id);
693 bool RemoveBreakpointByID(lldb::break_id_t break_id);
695 // The flag 'end_to_end', default to true, signifies that the operation is
696 // performed end to end, for both the debugger and the debuggee.
698 bool RemoveAllWatchpoints(bool end_to_end = true);
700 bool DisableAllWatchpoints(bool end_to_end = true);
702 bool EnableAllWatchpoints(bool end_to_end = true);
704 bool ClearAllWatchpointHitCounts();
706 bool ClearAllWatchpointHistoricValues();
708 bool IgnoreAllWatchpoints(uint32_t ignore_count);
710 bool DisableWatchpointByID(lldb::watch_id_t watch_id);
712 bool EnableWatchpointByID(lldb::watch_id_t watch_id);
714 bool RemoveWatchpointByID(lldb::watch_id_t watch_id);
716 bool IgnoreWatchpointByID(lldb::watch_id_t watch_id, uint32_t ignore_count);
718 Status SerializeBreakpointsToFile(const FileSpec &file,
719 const BreakpointIDList &bp_ids,
722 Status CreateBreakpointsFromFile(const FileSpec &file,
723 BreakpointIDList &new_bps);
725 Status CreateBreakpointsFromFile(const FileSpec &file,
726 std::vector<std::string> &names,
727 BreakpointIDList &new_bps);
729 //------------------------------------------------------------------
730 /// Get \a load_addr as a callable code load address for this target
732 /// Take \a load_addr and potentially add any address bits that are
733 /// needed to make the address callable. For ARM this can set bit
734 /// zero (if it already isn't) if \a load_addr is a thumb function.
735 /// If \a addr_class is set to AddressClass::eInvalid, then the address
736 /// adjustment will always happen. If it is set to an address class
737 /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
739 //------------------------------------------------------------------
740 lldb::addr_t GetCallableLoadAddress(
741 lldb::addr_t load_addr,
742 AddressClass addr_class = AddressClass::eInvalid) const;
744 //------------------------------------------------------------------
745 /// Get \a load_addr as an opcode for this target.
747 /// Take \a load_addr and potentially strip any address bits that are
748 /// needed to make the address point to an opcode. For ARM this can
749 /// clear bit zero (if it already isn't) if \a load_addr is a
750 /// thumb function and load_addr is in code.
751 /// If \a addr_class is set to AddressClass::eInvalid, then the address
752 /// adjustment will always happen. If it is set to an address class
753 /// that doesn't have code in it, LLDB_INVALID_ADDRESS will be
755 //------------------------------------------------------------------
756 lldb::addr_t GetOpcodeLoadAddress(
757 lldb::addr_t load_addr,
758 AddressClass addr_class = AddressClass::eInvalid) const;
760 // Get load_addr as breakable load address for this target. Take a addr and
761 // check if for any reason there is a better address than this to put a
762 // breakpoint on. If there is then return that address. For MIPS, if
763 // instruction at addr is a delay slot instruction then this method will find
764 // the address of its previous instruction and return that address.
765 lldb::addr_t GetBreakableLoadAddress(lldb::addr_t addr);
767 void ModulesDidLoad(ModuleList &module_list);
769 void ModulesDidUnload(ModuleList &module_list, bool delete_locations);
771 void SymbolsDidLoad(ModuleList &module_list);
773 void ClearModules(bool delete_locations);
775 //------------------------------------------------------------------
776 /// Called as the last function in Process::DidExec().
778 /// Process::DidExec() will clear a lot of state in the process,
779 /// then try to reload a dynamic loader plugin to discover what
780 /// binaries are currently available and then this function should
781 /// be called to allow the target to do any cleanup after everything
782 /// has been figured out. It can remove breakpoints that no longer
783 /// make sense as the exec might have changed the target
784 /// architecture, and unloaded some modules that might get deleted.
785 //------------------------------------------------------------------
788 //------------------------------------------------------------------
789 /// Gets the module for the main executable.
791 /// Each process has a notion of a main executable that is the file
792 /// that will be executed or attached to. Executable files can have
793 /// dependent modules that are discovered from the object files, or
794 /// discovered at runtime as things are dynamically loaded.
797 /// The shared pointer to the executable module which can
798 /// contains a nullptr Module object if no executable has been
801 /// @see DynamicLoader
802 /// @see ObjectFile::GetDependentModules (FileSpecList&)
803 /// @see Process::SetExecutableModule(lldb::ModuleSP&)
804 //------------------------------------------------------------------
805 lldb::ModuleSP GetExecutableModule();
807 Module *GetExecutableModulePointer();
809 //------------------------------------------------------------------
810 /// Set the main executable module.
812 /// Each process has a notion of a main executable that is the file
813 /// that will be executed or attached to. Executable files can have
814 /// dependent modules that are discovered from the object files, or
815 /// discovered at runtime as things are dynamically loaded.
817 /// Setting the executable causes any of the current dependent
818 /// image information to be cleared and replaced with the static
819 /// dependent image information found by calling
820 /// ObjectFile::GetDependentModules (FileSpecList&) on the main
821 /// executable and any modules on which it depends. Calling
822 /// Process::GetImages() will return the newly found images that
823 /// were obtained from all of the object files.
825 /// @param[in] module_sp
826 /// A shared pointer reference to the module that will become
827 /// the main executable for this process.
829 /// @param[in] get_dependent_files
830 /// If \b true then ask the object files to track down any
831 /// known dependent files.
833 /// @see ObjectFile::GetDependentModules (FileSpecList&)
834 /// @see Process::GetImages()
835 //------------------------------------------------------------------
836 void SetExecutableModule(lldb::ModuleSP &module_sp, bool get_dependent_files);
838 bool LoadScriptingResources(std::list<Status> &errors,
839 Stream *feedback_stream = nullptr,
840 bool continue_on_error = true) {
841 return m_images.LoadScriptingResourcesInTarget(
842 this, errors, feedback_stream, continue_on_error);
845 //------------------------------------------------------------------
846 /// Get accessor for the images for this process.
848 /// Each process has a notion of a main executable that is the file
849 /// that will be executed or attached to. Executable files can have
850 /// dependent modules that are discovered from the object files, or
851 /// discovered at runtime as things are dynamically loaded. After
852 /// a main executable has been set, the images will contain a list
853 /// of all the files that the executable depends upon as far as the
854 /// object files know. These images will usually contain valid file
855 /// virtual addresses only. When the process is launched or attached
856 /// to, the DynamicLoader plug-in will discover where these images
857 /// were loaded in memory and will resolve the load virtual
858 /// addresses is each image, and also in images that are loaded by
862 /// A list of Module objects in a module list.
863 //------------------------------------------------------------------
864 const ModuleList &GetImages() const { return m_images; }
866 ModuleList &GetImages() { return m_images; }
868 //------------------------------------------------------------------
869 /// Return whether this FileSpec corresponds to a module that should be
870 /// considered for general searches.
872 /// This API will be consulted by the SearchFilterForUnconstrainedSearches
873 /// and any module that returns \b true will not be searched. Note the
874 /// SearchFilterForUnconstrainedSearches is the search filter that
875 /// gets used in the CreateBreakpoint calls when no modules is provided.
877 /// The target call at present just consults the Platform's call of the
880 /// @param[in] module_sp
881 /// A shared pointer reference to the module that checked.
883 /// @return \b true if the module should be excluded, \b false otherwise.
884 //------------------------------------------------------------------
885 bool ModuleIsExcludedForUnconstrainedSearches(const FileSpec &module_spec);
887 //------------------------------------------------------------------
888 /// Return whether this module should be considered for general searches.
890 /// This API will be consulted by the SearchFilterForUnconstrainedSearches
891 /// and any module that returns \b true will not be searched. Note the
892 /// SearchFilterForUnconstrainedSearches is the search filter that
893 /// gets used in the CreateBreakpoint calls when no modules is provided.
895 /// The target call at present just consults the Platform's call of the
898 /// FIXME: When we get time we should add a way for the user to set modules
900 /// don't want searched, in addition to or instead of the platform ones.
902 /// @param[in] module_sp
903 /// A shared pointer reference to the module that checked.
905 /// @return \b true if the module should be excluded, \b false otherwise.
906 //------------------------------------------------------------------
908 ModuleIsExcludedForUnconstrainedSearches(const lldb::ModuleSP &module_sp);
910 const ArchSpec &GetArchitecture() const { return m_arch.GetSpec(); }
912 //------------------------------------------------------------------
913 /// Set the architecture for this target.
915 /// If the current target has no Images read in, then this just sets the
916 /// architecture, which will
917 /// be used to select the architecture of the ExecutableModule when that is
919 /// If the current target has an ExecutableModule, then calling
920 /// SetArchitecture with a different
921 /// architecture from the currently selected one will reset the
922 /// ExecutableModule to that slice
923 /// of the file backing the ExecutableModule. If the file backing the
924 /// ExecutableModule does not
925 /// contain a fork of this architecture, then this code will return false, and
927 /// won't be changed.
928 /// If the input arch_spec is the same as the already set architecture, this
931 /// @param[in] arch_spec
932 /// The new architecture.
935 /// \b true if the architecture was successfully set, \bfalse otherwise.
936 //------------------------------------------------------------------
937 bool SetArchitecture(const ArchSpec &arch_spec);
939 bool MergeArchitecture(const ArchSpec &arch_spec);
941 Architecture *GetArchitecturePlugin() const { return m_arch.GetPlugin(); }
943 Debugger &GetDebugger() { return m_debugger; }
945 size_t ReadMemoryFromFileCache(const Address &addr, void *dst, size_t dst_len,
948 // Reading memory through the target allows us to skip going to the process
949 // for reading memory if possible and it allows us to try and read from any
950 // constant sections in our object files on disk. If you always want live
951 // program memory, read straight from the process. If you possibly want to
952 // read from const sections in object files, read from the target. This
953 // version of ReadMemory will try and read memory from the process if the
954 // process is alive. The order is:
955 // 1 - if (prefer_file_cache == true) then read from object file cache
956 // 2 - if there is a valid process, try and read from its memory
957 // 3 - if (prefer_file_cache == false) then read from object file cache
958 size_t ReadMemory(const Address &addr, bool prefer_file_cache, void *dst,
959 size_t dst_len, Status &error,
960 lldb::addr_t *load_addr_ptr = nullptr);
962 size_t ReadCStringFromMemory(const Address &addr, std::string &out_str,
965 size_t ReadCStringFromMemory(const Address &addr, char *dst,
966 size_t dst_max_len, Status &result_error);
968 size_t ReadScalarIntegerFromMemory(const Address &addr,
969 bool prefer_file_cache, uint32_t byte_size,
970 bool is_signed, Scalar &scalar,
973 uint64_t ReadUnsignedIntegerFromMemory(const Address &addr,
974 bool prefer_file_cache,
975 size_t integer_byte_size,
976 uint64_t fail_value, Status &error);
978 bool ReadPointerFromMemory(const Address &addr, bool prefer_file_cache,
979 Status &error, Address &pointer_addr);
981 SectionLoadList &GetSectionLoadList() {
982 return m_section_load_history.GetCurrentSectionLoadList();
985 static Target *GetTargetFromContexts(const ExecutionContext *exe_ctx_ptr,
986 const SymbolContext *sc_ptr);
988 //------------------------------------------------------------------
989 // lldb::ExecutionContextScope pure virtual functions
990 //------------------------------------------------------------------
991 lldb::TargetSP CalculateTarget() override;
993 lldb::ProcessSP CalculateProcess() override;
995 lldb::ThreadSP CalculateThread() override;
997 lldb::StackFrameSP CalculateStackFrame() override;
999 void CalculateExecutionContext(ExecutionContext &exe_ctx) override;
1001 PathMappingList &GetImageSearchPathList();
1003 TypeSystem *GetScratchTypeSystemForLanguage(Status *error,
1004 lldb::LanguageType language,
1005 bool create_on_demand = true);
1007 PersistentExpressionState *
1008 GetPersistentExpressionStateForLanguage(lldb::LanguageType language);
1010 // Creates a UserExpression for the given language, the rest of the
1011 // parameters have the same meaning as for the UserExpression constructor.
1012 // Returns a new-ed object which the caller owns.
1014 UserExpression *GetUserExpressionForLanguage(
1015 llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language,
1016 Expression::ResultType desired_type,
1017 const EvaluateExpressionOptions &options, Status &error);
1019 // Creates a FunctionCaller for the given language, the rest of the
1020 // parameters have the same meaning as for the FunctionCaller constructor.
1021 // Since a FunctionCaller can't be
1022 // IR Interpreted, it makes no sense to call this with an
1023 // ExecutionContextScope that lacks
1025 // Returns a new-ed object which the caller owns.
1027 FunctionCaller *GetFunctionCallerForLanguage(lldb::LanguageType language,
1028 const CompilerType &return_type,
1029 const Address &function_address,
1030 const ValueList &arg_value_list,
1031 const char *name, Status &error);
1033 // Creates a UtilityFunction for the given language, the rest of the
1034 // parameters have the same meaning as for the UtilityFunction constructor.
1035 // Returns a new-ed object which the caller owns.
1037 UtilityFunction *GetUtilityFunctionForLanguage(const char *expr,
1038 lldb::LanguageType language,
1042 ClangASTContext *GetScratchClangASTContext(bool create_on_demand = true);
1044 lldb::ClangASTImporterSP GetClangASTImporter();
1046 //----------------------------------------------------------------------
1047 // Install any files through the platform that need be to installed prior to
1048 // launching or attaching.
1049 //----------------------------------------------------------------------
1050 Status Install(ProcessLaunchInfo *launch_info);
1052 bool ResolveFileAddress(lldb::addr_t load_addr, Address &so_addr);
1054 bool ResolveLoadAddress(lldb::addr_t load_addr, Address &so_addr,
1055 uint32_t stop_id = SectionLoadHistory::eStopIDNow);
1057 bool SetSectionLoadAddress(const lldb::SectionSP §ion,
1058 lldb::addr_t load_addr,
1059 bool warn_multiple = false);
1061 size_t UnloadModuleSections(const lldb::ModuleSP &module_sp);
1063 size_t UnloadModuleSections(const ModuleList &module_list);
1065 bool SetSectionUnloaded(const lldb::SectionSP §ion_sp);
1067 bool SetSectionUnloaded(const lldb::SectionSP §ion_sp,
1068 lldb::addr_t load_addr);
1070 void ClearAllLoadedSections();
1072 // Since expressions results can persist beyond the lifetime of a process,
1073 // and the const expression results are available after a process is gone, we
1074 // provide a way for expressions to be evaluated from the Target itself. If
1075 // an expression is going to be run, then it should have a frame filled in in
1076 // th execution context.
1077 lldb::ExpressionResults EvaluateExpression(
1078 llvm::StringRef expression, ExecutionContextScope *exe_scope,
1079 lldb::ValueObjectSP &result_valobj_sp,
1080 const EvaluateExpressionOptions &options = EvaluateExpressionOptions(),
1081 std::string *fixed_expression = nullptr);
1083 lldb::ExpressionVariableSP GetPersistentVariable(const ConstString &name);
1085 /// Return the next available number for numbered persistent variables.
1086 unsigned GetNextPersistentVariableIndex() {
1087 return m_next_persistent_variable_index++;
1090 lldb::addr_t GetPersistentSymbol(const ConstString &name);
1092 //------------------------------------------------------------------
1093 // Target Stop Hooks
1094 //------------------------------------------------------------------
1095 class StopHook : public UserID {
1097 StopHook(const StopHook &rhs);
1101 StringList *GetCommandPointer() { return &m_commands; }
1103 const StringList &GetCommands() { return m_commands; }
1105 lldb::TargetSP &GetTarget() { return m_target_sp; }
1107 void SetCommands(StringList &in_commands) { m_commands = in_commands; }
1109 // Set the specifier. The stop hook will own the specifier, and is
1110 // responsible for deleting it when we're done.
1111 void SetSpecifier(SymbolContextSpecifier *specifier);
1113 SymbolContextSpecifier *GetSpecifier() { return m_specifier_sp.get(); }
1115 // Set the Thread Specifier. The stop hook will own the thread specifier,
1116 // and is responsible for deleting it when we're done.
1117 void SetThreadSpecifier(ThreadSpec *specifier);
1119 ThreadSpec *GetThreadSpecifier() { return m_thread_spec_ap.get(); }
1121 bool IsActive() { return m_active; }
1123 void SetIsActive(bool is_active) { m_active = is_active; }
1125 void GetDescription(Stream *s, lldb::DescriptionLevel level) const;
1128 lldb::TargetSP m_target_sp;
1129 StringList m_commands;
1130 lldb::SymbolContextSpecifierSP m_specifier_sp;
1131 std::unique_ptr<ThreadSpec> m_thread_spec_ap;
1134 // Use CreateStopHook to make a new empty stop hook. The GetCommandPointer
1135 // and fill it with commands, and SetSpecifier to set the specifier shared
1136 // pointer (can be null, that will match anything.)
1137 StopHook(lldb::TargetSP target_sp, lldb::user_id_t uid);
1138 friend class Target;
1140 typedef std::shared_ptr<StopHook> StopHookSP;
1142 // Add an empty stop hook to the Target's stop hook list, and returns a
1143 // shared pointer to it in new_hook. Returns the id of the new hook.
1144 StopHookSP CreateStopHook();
1146 void RunStopHooks();
1148 size_t GetStopHookSize();
1150 bool SetSuppresStopHooks(bool suppress) {
1151 bool old_value = m_suppress_stop_hooks;
1152 m_suppress_stop_hooks = suppress;
1156 bool GetSuppressStopHooks() { return m_suppress_stop_hooks; }
1158 bool RemoveStopHookByID(lldb::user_id_t uid);
1160 void RemoveAllStopHooks();
1162 StopHookSP GetStopHookByID(lldb::user_id_t uid);
1164 bool SetStopHookActiveStateByID(lldb::user_id_t uid, bool active_state);
1166 void SetAllStopHooksActiveState(bool active_state);
1168 size_t GetNumStopHooks() const { return m_stop_hooks.size(); }
1170 StopHookSP GetStopHookAtIndex(size_t index) {
1171 if (index >= GetNumStopHooks())
1172 return StopHookSP();
1173 StopHookCollection::iterator pos = m_stop_hooks.begin();
1179 return (*pos).second;
1182 lldb::PlatformSP GetPlatform() { return m_platform_sp; }
1184 void SetPlatform(const lldb::PlatformSP &platform_sp) {
1185 m_platform_sp = platform_sp;
1188 SourceManager &GetSourceManager();
1190 ClangModulesDeclVendor *GetClangModulesDeclVendor();
1192 //------------------------------------------------------------------
1194 //------------------------------------------------------------------
1195 lldb::SearchFilterSP
1196 GetSearchFilterForModule(const FileSpec *containingModule);
1198 lldb::SearchFilterSP
1199 GetSearchFilterForModuleList(const FileSpecList *containingModuleList);
1201 lldb::SearchFilterSP
1202 GetSearchFilterForModuleAndCUList(const FileSpecList *containingModules,
1203 const FileSpecList *containingSourceFiles);
1205 lldb::REPLSP GetREPL(Status &err, lldb::LanguageType language,
1206 const char *repl_options, bool can_create);
1208 void SetREPL(lldb::LanguageType language, lldb::REPLSP repl_sp);
1211 //------------------------------------------------------------------
1212 /// Implementing of ModuleList::Notifier.
1213 //------------------------------------------------------------------
1215 void ModuleAdded(const ModuleList &module_list,
1216 const lldb::ModuleSP &module_sp) override;
1218 void ModuleRemoved(const ModuleList &module_list,
1219 const lldb::ModuleSP &module_sp) override;
1221 void ModuleUpdated(const ModuleList &module_list,
1222 const lldb::ModuleSP &old_module_sp,
1223 const lldb::ModuleSP &new_module_sp) override;
1224 void WillClearList(const ModuleList &module_list) override;
1228 explicit Arch(const ArchSpec &spec);
1229 const Arch &operator=(const ArchSpec &spec);
1231 const ArchSpec &GetSpec() const { return m_spec; }
1232 Architecture *GetPlugin() const { return m_plugin_up.get(); }
1236 std::unique_ptr<Architecture> m_plugin_up;
1238 //------------------------------------------------------------------
1239 // Member variables.
1240 //------------------------------------------------------------------
1241 Debugger &m_debugger;
1242 lldb::PlatformSP m_platform_sp; ///< The platform for this target.
1243 std::recursive_mutex m_mutex; ///< An API mutex that is used by the lldb::SB*
1244 /// classes make the SB interface thread safe
1246 ModuleList m_images; ///< The list of images for this process (shared
1247 /// libraries and anything dynamically loaded).
1248 SectionLoadHistory m_section_load_history;
1249 BreakpointList m_breakpoint_list;
1250 BreakpointList m_internal_breakpoint_list;
1251 using BreakpointNameList = std::map<ConstString, BreakpointName *>;
1252 BreakpointNameList m_breakpoint_names;
1254 lldb::BreakpointSP m_last_created_breakpoint;
1255 WatchpointList m_watchpoint_list;
1256 lldb::WatchpointSP m_last_created_watchpoint;
1257 // We want to tightly control the process destruction process so we can
1258 // correctly tear down everything that we need to, so the only class that
1259 // knows about the process lifespan is this target class.
1260 lldb::ProcessSP m_process_sp;
1261 lldb::SearchFilterSP m_search_filter_sp;
1262 PathMappingList m_image_search_paths;
1263 TypeSystemMap m_scratch_type_system_map;
1265 typedef std::map<lldb::LanguageType, lldb::REPLSP> REPLMap;
1268 lldb::ClangASTImporterSP m_ast_importer_sp;
1269 lldb::ClangModulesDeclVendorUP m_clang_modules_decl_vendor_ap;
1271 lldb::SourceManagerUP m_source_manager_ap;
1273 typedef std::map<lldb::user_id_t, StopHookSP> StopHookCollection;
1274 StopHookCollection m_stop_hooks;
1275 lldb::user_id_t m_stop_hook_next_id;
1277 bool m_suppress_stop_hooks;
1278 bool m_is_dummy_target;
1279 unsigned m_next_persistent_variable_index = 0;
1281 static void ImageSearchPathsChanged(const PathMappingList &path_list,
1284 //------------------------------------------------------------------
1285 // Utilities for `statistics` command.
1286 //------------------------------------------------------------------
1288 std::vector<uint32_t> m_stats_storage;
1289 bool m_collecting_stats = false;
1292 void SetCollectingStats(bool v) { m_collecting_stats = v; }
1294 bool GetCollectingStats() { return m_collecting_stats; }
1296 void IncrementStats(lldb_private::StatisticKind key) {
1297 if (!GetCollectingStats())
1299 lldbassert(key < lldb_private::StatisticKind::StatisticMax &&
1300 "invalid statistics!");
1301 m_stats_storage[key] += 1;
1304 std::vector<uint32_t> GetStatistics() { return m_stats_storage; }
1307 //------------------------------------------------------------------
1308 /// Construct with optional file and arch.
1310 /// This member is private. Clients must use
1311 /// TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
1312 /// so all targets can be tracked from the central target list.
1314 /// @see TargetList::CreateTarget(const FileSpec*, const ArchSpec*)
1315 //------------------------------------------------------------------
1316 Target(Debugger &debugger, const ArchSpec &target_arch,
1317 const lldb::PlatformSP &platform_sp, bool is_dummy_target);
1320 bool ProcessIsValid();
1322 // Copy breakpoints, stop hooks and so forth from the dummy target:
1323 void PrimeFromDummyTarget(Target *dummy_target);
1325 void AddBreakpoint(lldb::BreakpointSP breakpoint_sp, bool internal);
1327 DISALLOW_COPY_AND_ASSIGN(Target);
1330 } // namespace lldb_private
1332 #endif // liblldb_Target_h_