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