1 //===-- Process.h -----------------------------------------------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #ifndef liblldb_Process_h_ 11 #define liblldb_Process_h_ 12 13 #include "lldb/Host/Config.h" 14 15 // C Includes 16 #include <limits.h> 17 18 // C++ Includes 19 #include <list> 20 #include <iosfwd> 21 #include <vector> 22 23 // Other libraries and framework includes 24 // Project includes 25 #include "lldb/lldb-private.h" 26 #include "lldb/Core/ArchSpec.h" 27 #include "lldb/Core/Broadcaster.h" 28 #include "lldb/Core/Communication.h" 29 #include "lldb/Core/Error.h" 30 #include "lldb/Core/Event.h" 31 #include "lldb/Core/ThreadSafeValue.h" 32 #include "lldb/Core/PluginInterface.h" 33 #include "lldb/Core/StructuredData.h" 34 #include "lldb/Core/UserSettingsController.h" 35 #include "lldb/Breakpoint/BreakpointSiteList.h" 36 #include "lldb/Host/HostThread.h" 37 #include "lldb/Host/ProcessRunLock.h" 38 #include "lldb/Interpreter/Options.h" 39 #include "lldb/Target/ExecutionContextScope.h" 40 #include "lldb/Target/Memory.h" 41 #include "lldb/Target/ProcessInfo.h" 42 #include "lldb/Target/ProcessLaunchInfo.h" 43 #include "lldb/Target/QueueList.h" 44 #include "lldb/Target/ThreadList.h" 45 #include "lldb/Target/InstrumentationRuntime.h" 46 47 namespace lldb_private { 48 49 template <typename B, typename S> 50 struct Range; 51 52 //---------------------------------------------------------------------- 53 // ProcessProperties 54 //---------------------------------------------------------------------- 55 class ProcessProperties : public Properties 56 { 57 public: 58 // Pass NULL for "process" if the ProcessProperties are to be the global copy 59 ProcessProperties (lldb_private::Process *process); 60 61 virtual 62 ~ProcessProperties(); 63 64 bool 65 GetDisableMemoryCache() const; 66 67 uint64_t 68 GetMemoryCacheLineSize () const; 69 70 Args 71 GetExtraStartupCommands () const; 72 73 void 74 SetExtraStartupCommands (const Args &args); 75 76 FileSpec 77 GetPythonOSPluginPath () const; 78 79 void 80 SetPythonOSPluginPath (const FileSpec &file); 81 82 bool 83 GetIgnoreBreakpointsInExpressions () const; 84 85 void 86 SetIgnoreBreakpointsInExpressions (bool ignore); 87 88 bool 89 GetUnwindOnErrorInExpressions () const; 90 91 void 92 SetUnwindOnErrorInExpressions (bool ignore); 93 94 bool 95 GetStopOnSharedLibraryEvents () const; 96 97 void 98 SetStopOnSharedLibraryEvents (bool stop); 99 100 bool 101 GetDetachKeepsStopped () const; 102 103 void 104 SetDetachKeepsStopped (bool keep_stopped); 105 106 protected: 107 108 static void 109 OptionValueChangedCallback (void *baton, OptionValue *option_value); 110 111 Process * m_process; // Can be NULL for global ProcessProperties 112 }; 113 114 typedef std::shared_ptr<ProcessProperties> ProcessPropertiesSP; 115 116 //---------------------------------------------------------------------- 117 // ProcessInstanceInfo 118 // 119 // Describes an existing process and any discoverable information that 120 // pertains to that process. 121 //---------------------------------------------------------------------- 122 class ProcessInstanceInfo : public ProcessInfo 123 { 124 public: ProcessInstanceInfo()125 ProcessInstanceInfo () : 126 ProcessInfo (), 127 m_euid (UINT32_MAX), 128 m_egid (UINT32_MAX), 129 m_parent_pid (LLDB_INVALID_PROCESS_ID) 130 { 131 } 132 ProcessInstanceInfo(const char * name,const ArchSpec & arch,lldb::pid_t pid)133 ProcessInstanceInfo (const char *name, 134 const ArchSpec &arch, 135 lldb::pid_t pid) : 136 ProcessInfo (name, arch, pid), 137 m_euid (UINT32_MAX), 138 m_egid (UINT32_MAX), 139 m_parent_pid (LLDB_INVALID_PROCESS_ID) 140 { 141 } 142 143 void Clear()144 Clear () 145 { 146 ProcessInfo::Clear(); 147 m_euid = UINT32_MAX; 148 m_egid = UINT32_MAX; 149 m_parent_pid = LLDB_INVALID_PROCESS_ID; 150 } 151 152 uint32_t GetEffectiveUserID()153 GetEffectiveUserID() const 154 { 155 return m_euid; 156 } 157 158 uint32_t GetEffectiveGroupID()159 GetEffectiveGroupID() const 160 { 161 return m_egid; 162 } 163 164 bool EffectiveUserIDIsValid()165 EffectiveUserIDIsValid () const 166 { 167 return m_euid != UINT32_MAX; 168 } 169 170 bool EffectiveGroupIDIsValid()171 EffectiveGroupIDIsValid () const 172 { 173 return m_egid != UINT32_MAX; 174 } 175 176 void SetEffectiveUserID(uint32_t uid)177 SetEffectiveUserID (uint32_t uid) 178 { 179 m_euid = uid; 180 } 181 182 void SetEffectiveGroupID(uint32_t gid)183 SetEffectiveGroupID (uint32_t gid) 184 { 185 m_egid = gid; 186 } 187 188 lldb::pid_t GetParentProcessID()189 GetParentProcessID () const 190 { 191 return m_parent_pid; 192 } 193 194 void SetParentProcessID(lldb::pid_t pid)195 SetParentProcessID (lldb::pid_t pid) 196 { 197 m_parent_pid = pid; 198 } 199 200 bool ParentProcessIDIsValid()201 ParentProcessIDIsValid() const 202 { 203 return m_parent_pid != LLDB_INVALID_PROCESS_ID; 204 } 205 206 void 207 Dump (Stream &s, Platform *platform) const; 208 209 static void 210 DumpTableHeader (Stream &s, Platform *platform, bool show_args, bool verbose); 211 212 void 213 DumpAsTableRow (Stream &s, Platform *platform, bool show_args, bool verbose) const; 214 215 protected: 216 uint32_t m_euid; 217 uint32_t m_egid; 218 lldb::pid_t m_parent_pid; 219 }; 220 221 //---------------------------------------------------------------------- 222 // ProcessAttachInfo 223 // 224 // Describes any information that is required to attach to a process. 225 //---------------------------------------------------------------------- 226 227 class ProcessAttachInfo : public ProcessInstanceInfo 228 { 229 public: ProcessAttachInfo()230 ProcessAttachInfo() : 231 ProcessInstanceInfo(), 232 m_listener_sp(), 233 m_hijack_listener_sp(), 234 m_plugin_name (), 235 m_resume_count (0), 236 m_wait_for_launch (false), 237 m_ignore_existing (true), 238 m_continue_once_attached (false), 239 m_detach_on_error (true) 240 { 241 } 242 ProcessAttachInfo(const ProcessLaunchInfo & launch_info)243 ProcessAttachInfo (const ProcessLaunchInfo &launch_info) : 244 ProcessInstanceInfo(), 245 m_listener_sp(), 246 m_hijack_listener_sp(), 247 m_plugin_name (), 248 m_resume_count (0), 249 m_wait_for_launch (false), 250 m_ignore_existing (true), 251 m_continue_once_attached (false), 252 m_detach_on_error(true) 253 { 254 ProcessInfo::operator= (launch_info); 255 SetProcessPluginName (launch_info.GetProcessPluginName()); 256 SetResumeCount (launch_info.GetResumeCount()); 257 SetListener(launch_info.GetListener()); 258 SetHijackListener(launch_info.GetHijackListener()); 259 m_detach_on_error = launch_info.GetDetachOnError(); 260 } 261 262 bool GetWaitForLaunch()263 GetWaitForLaunch () const 264 { 265 return m_wait_for_launch; 266 } 267 268 void SetWaitForLaunch(bool b)269 SetWaitForLaunch (bool b) 270 { 271 m_wait_for_launch = b; 272 } 273 274 bool GetIgnoreExisting()275 GetIgnoreExisting () const 276 { 277 return m_ignore_existing; 278 } 279 280 void SetIgnoreExisting(bool b)281 SetIgnoreExisting (bool b) 282 { 283 m_ignore_existing = b; 284 } 285 286 bool GetContinueOnceAttached()287 GetContinueOnceAttached () const 288 { 289 return m_continue_once_attached; 290 } 291 292 void SetContinueOnceAttached(bool b)293 SetContinueOnceAttached (bool b) 294 { 295 m_continue_once_attached = b; 296 } 297 298 uint32_t GetResumeCount()299 GetResumeCount () const 300 { 301 return m_resume_count; 302 } 303 304 void SetResumeCount(uint32_t c)305 SetResumeCount (uint32_t c) 306 { 307 m_resume_count = c; 308 } 309 310 const char * GetProcessPluginName()311 GetProcessPluginName () const 312 { 313 if (m_plugin_name.empty()) 314 return NULL; 315 return m_plugin_name.c_str(); 316 } 317 318 void SetProcessPluginName(const char * plugin)319 SetProcessPluginName (const char *plugin) 320 { 321 if (plugin && plugin[0]) 322 m_plugin_name.assign (plugin); 323 else 324 m_plugin_name.clear(); 325 } 326 327 void Clear()328 Clear () 329 { 330 ProcessInstanceInfo::Clear(); 331 m_plugin_name.clear(); 332 m_resume_count = 0; 333 m_wait_for_launch = false; 334 m_ignore_existing = true; 335 m_continue_once_attached = false; 336 } 337 338 bool ProcessInfoSpecified()339 ProcessInfoSpecified () const 340 { 341 if (GetExecutableFile()) 342 return true; 343 if (GetProcessID() != LLDB_INVALID_PROCESS_ID) 344 return true; 345 if (GetParentProcessID() != LLDB_INVALID_PROCESS_ID) 346 return true; 347 return false; 348 } 349 350 lldb::ListenerSP GetHijackListener()351 GetHijackListener () const 352 { 353 return m_hijack_listener_sp; 354 } 355 356 void SetHijackListener(const lldb::ListenerSP & listener_sp)357 SetHijackListener (const lldb::ListenerSP &listener_sp) 358 { 359 m_hijack_listener_sp = listener_sp; 360 } 361 362 bool GetDetachOnError()363 GetDetachOnError () const 364 { 365 return m_detach_on_error; 366 } 367 368 void SetDetachOnError(bool enable)369 SetDetachOnError (bool enable) 370 { 371 m_detach_on_error = enable; 372 } 373 374 // Get and set the actual listener that will be used for the process events 375 lldb::ListenerSP GetListener()376 GetListener () const 377 { 378 return m_listener_sp; 379 } 380 381 void SetListener(const lldb::ListenerSP & listener_sp)382 SetListener (const lldb::ListenerSP &listener_sp) 383 { 384 m_listener_sp = listener_sp; 385 } 386 387 388 Listener & 389 GetListenerForProcess (Debugger &debugger); 390 391 protected: 392 lldb::ListenerSP m_listener_sp; 393 lldb::ListenerSP m_hijack_listener_sp; 394 std::string m_plugin_name; 395 uint32_t m_resume_count; // How many times do we resume after launching 396 bool m_wait_for_launch; 397 bool m_ignore_existing; 398 bool m_continue_once_attached; // Supports the use-case scenario of immediately continuing the process once attached. 399 bool m_detach_on_error; // If we are debugging remotely, instruct the stub to detach rather than killing the target on error. 400 }; 401 402 class ProcessLaunchCommandOptions : public Options 403 { 404 public: 405 ProcessLaunchCommandOptions(CommandInterpreter & interpreter)406 ProcessLaunchCommandOptions (CommandInterpreter &interpreter) : 407 Options(interpreter) 408 { 409 // Keep default values of all options in one place: OptionParsingStarting () 410 OptionParsingStarting (); 411 } 412 ~ProcessLaunchCommandOptions()413 ~ProcessLaunchCommandOptions () 414 { 415 } 416 417 Error 418 SetOptionValue (uint32_t option_idx, const char *option_arg); 419 420 void OptionParsingStarting()421 OptionParsingStarting () 422 { 423 launch_info.Clear(); 424 disable_aslr = eLazyBoolCalculate; 425 } 426 427 const OptionDefinition* GetDefinitions()428 GetDefinitions () 429 { 430 return g_option_table; 431 } 432 433 // Options table: Required for subclasses of Options. 434 435 static OptionDefinition g_option_table[]; 436 437 // Instance variables to hold the values for command options. 438 439 ProcessLaunchInfo launch_info; 440 lldb_private::LazyBool disable_aslr; 441 }; 442 443 //---------------------------------------------------------------------- 444 // ProcessInstanceInfoMatch 445 // 446 // A class to help matching one ProcessInstanceInfo to another. 447 //---------------------------------------------------------------------- 448 449 class ProcessInstanceInfoMatch 450 { 451 public: ProcessInstanceInfoMatch()452 ProcessInstanceInfoMatch () : 453 m_match_info (), 454 m_name_match_type (eNameMatchIgnore), 455 m_match_all_users (false) 456 { 457 } 458 ProcessInstanceInfoMatch(const char * process_name,NameMatchType process_name_match_type)459 ProcessInstanceInfoMatch (const char *process_name, 460 NameMatchType process_name_match_type) : 461 m_match_info (), 462 m_name_match_type (process_name_match_type), 463 m_match_all_users (false) 464 { 465 m_match_info.GetExecutableFile().SetFile(process_name, false); 466 } 467 468 ProcessInstanceInfo & GetProcessInfo()469 GetProcessInfo () 470 { 471 return m_match_info; 472 } 473 474 const ProcessInstanceInfo & GetProcessInfo()475 GetProcessInfo () const 476 { 477 return m_match_info; 478 } 479 480 bool GetMatchAllUsers()481 GetMatchAllUsers () const 482 { 483 return m_match_all_users; 484 } 485 486 void SetMatchAllUsers(bool b)487 SetMatchAllUsers (bool b) 488 { 489 m_match_all_users = b; 490 } 491 492 NameMatchType GetNameMatchType()493 GetNameMatchType () const 494 { 495 return m_name_match_type; 496 } 497 498 void SetNameMatchType(NameMatchType name_match_type)499 SetNameMatchType (NameMatchType name_match_type) 500 { 501 m_name_match_type = name_match_type; 502 } 503 504 bool 505 NameMatches (const char *process_name) const; 506 507 bool 508 Matches (const ProcessInstanceInfo &proc_info) const; 509 510 bool 511 MatchAllProcesses () const; 512 void 513 Clear (); 514 515 protected: 516 ProcessInstanceInfo m_match_info; 517 NameMatchType m_name_match_type; 518 bool m_match_all_users; 519 }; 520 521 class ProcessInstanceInfoList 522 { 523 public: ProcessInstanceInfoList()524 ProcessInstanceInfoList () : 525 m_infos() 526 { 527 } 528 529 void Clear()530 Clear() 531 { 532 m_infos.clear(); 533 } 534 535 size_t GetSize()536 GetSize() 537 { 538 return m_infos.size(); 539 } 540 541 void Append(const ProcessInstanceInfo & info)542 Append (const ProcessInstanceInfo &info) 543 { 544 m_infos.push_back (info); 545 } 546 547 const char * GetProcessNameAtIndex(size_t idx)548 GetProcessNameAtIndex (size_t idx) 549 { 550 if (idx < m_infos.size()) 551 return m_infos[idx].GetName(); 552 return NULL; 553 } 554 555 size_t GetProcessNameLengthAtIndex(size_t idx)556 GetProcessNameLengthAtIndex (size_t idx) 557 { 558 if (idx < m_infos.size()) 559 return m_infos[idx].GetNameLength(); 560 return 0; 561 } 562 563 lldb::pid_t GetProcessIDAtIndex(size_t idx)564 GetProcessIDAtIndex (size_t idx) 565 { 566 if (idx < m_infos.size()) 567 return m_infos[idx].GetProcessID(); 568 return 0; 569 } 570 571 bool GetInfoAtIndex(size_t idx,ProcessInstanceInfo & info)572 GetInfoAtIndex (size_t idx, ProcessInstanceInfo &info) 573 { 574 if (idx < m_infos.size()) 575 { 576 info = m_infos[idx]; 577 return true; 578 } 579 return false; 580 } 581 582 // You must ensure "idx" is valid before calling this function 583 const ProcessInstanceInfo & GetProcessInfoAtIndex(size_t idx)584 GetProcessInfoAtIndex (size_t idx) const 585 { 586 assert (idx < m_infos.size()); 587 return m_infos[idx]; 588 } 589 590 protected: 591 typedef std::vector<ProcessInstanceInfo> collection; 592 collection m_infos; 593 }; 594 595 596 // This class tracks the Modification state of the process. Things that can currently modify 597 // the program are running the program (which will up the StopID) and writing memory (which 598 // will up the MemoryID.) 599 // FIXME: Should we also include modification of register states? 600 601 class ProcessModID 602 { 603 friend bool operator== (const ProcessModID &lhs, const ProcessModID &rhs); 604 public: ProcessModID()605 ProcessModID () : 606 m_stop_id (0), 607 m_last_natural_stop_id(0), 608 m_resume_id (0), 609 m_memory_id (0), 610 m_last_user_expression_resume (0), 611 m_running_user_expression (false) 612 {} 613 ProcessModID(const ProcessModID & rhs)614 ProcessModID (const ProcessModID &rhs) : 615 m_stop_id (rhs.m_stop_id), 616 m_memory_id (rhs.m_memory_id) 617 {} 618 619 const ProcessModID & operator= (const ProcessModID &rhs) 620 { 621 if (this != &rhs) 622 { 623 m_stop_id = rhs.m_stop_id; 624 m_memory_id = rhs.m_memory_id; 625 } 626 return *this; 627 } 628 ~ProcessModID()629 ~ProcessModID () {} 630 BumpStopID()631 void BumpStopID () { 632 m_stop_id++; 633 if (!IsLastResumeForUserExpression()) 634 m_last_natural_stop_id++; 635 } 636 BumpMemoryID()637 void BumpMemoryID () { m_memory_id++; } 638 BumpResumeID()639 void BumpResumeID () { 640 m_resume_id++; 641 if (m_running_user_expression > 0) 642 m_last_user_expression_resume = m_resume_id; 643 } 644 GetStopID()645 uint32_t GetStopID() const { return m_stop_id; } GetLastNaturalStopID()646 uint32_t GetLastNaturalStopID() const { return m_last_natural_stop_id; } GetMemoryID()647 uint32_t GetMemoryID () const { return m_memory_id; } GetResumeID()648 uint32_t GetResumeID () const { return m_resume_id; } GetLastUserExpressionResumeID()649 uint32_t GetLastUserExpressionResumeID () const { return m_last_user_expression_resume; } 650 MemoryIDEqual(const ProcessModID & compare)651 bool MemoryIDEqual (const ProcessModID &compare) const 652 { 653 return m_memory_id == compare.m_memory_id; 654 } 655 StopIDEqual(const ProcessModID & compare)656 bool StopIDEqual (const ProcessModID &compare) const 657 { 658 return m_stop_id == compare.m_stop_id; 659 } 660 SetInvalid()661 void SetInvalid () 662 { 663 m_stop_id = UINT32_MAX; 664 } 665 IsValid()666 bool IsValid () const 667 { 668 return m_stop_id != UINT32_MAX; 669 } 670 671 bool IsLastResumeForUserExpression()672 IsLastResumeForUserExpression () const 673 { 674 // If we haven't yet resumed the target, then it can't be for a user expression... 675 if (m_resume_id == 0) 676 return false; 677 678 return m_resume_id == m_last_user_expression_resume; 679 } 680 681 void SetRunningUserExpression(bool on)682 SetRunningUserExpression (bool on) 683 { 684 if (on) 685 m_running_user_expression++; 686 else 687 m_running_user_expression--; 688 } 689 690 void SetStopEventForLastNaturalStopID(lldb::EventSP event_sp)691 SetStopEventForLastNaturalStopID (lldb::EventSP event_sp) 692 { 693 m_last_natural_stop_event = event_sp; 694 } 695 GetStopEventForStopID(uint32_t stop_id)696 lldb::EventSP GetStopEventForStopID (uint32_t stop_id) const 697 { 698 if (stop_id == m_last_natural_stop_id) 699 return m_last_natural_stop_event; 700 return lldb::EventSP(); 701 } 702 703 private: 704 uint32_t m_stop_id; 705 uint32_t m_last_natural_stop_id; 706 uint32_t m_resume_id; 707 uint32_t m_memory_id; 708 uint32_t m_last_user_expression_resume; 709 uint32_t m_running_user_expression; 710 lldb::EventSP m_last_natural_stop_event; 711 }; 712 inline bool operator== (const ProcessModID &lhs, const ProcessModID &rhs) 713 { 714 if (lhs.StopIDEqual (rhs) 715 && lhs.MemoryIDEqual (rhs)) 716 return true; 717 else 718 return false; 719 } 720 721 inline bool operator!= (const ProcessModID &lhs, const ProcessModID &rhs) 722 { 723 if (!lhs.StopIDEqual (rhs) 724 || !lhs.MemoryIDEqual (rhs)) 725 return true; 726 else 727 return false; 728 } 729 730 //---------------------------------------------------------------------- 731 /// @class Process Process.h "lldb/Target/Process.h" 732 /// @brief A plug-in interface definition class for debugging a process. 733 //---------------------------------------------------------------------- 734 class Process : 735 public std::enable_shared_from_this<Process>, 736 public ProcessProperties, 737 public UserID, 738 public Broadcaster, 739 public ExecutionContextScope, 740 public PluginInterface 741 { 742 friend class ClangFunction; // For WaitForStateChangeEventsPrivate 743 friend class Debugger; // For PopProcessIOHandler and ProcessIOHandlerIsActive 744 friend class ProcessEventData; 745 friend class StopInfo; 746 friend class Target; 747 friend class ThreadList; 748 749 public: 750 751 //------------------------------------------------------------------ 752 /// Broadcaster event bits definitions. 753 //------------------------------------------------------------------ 754 enum 755 { 756 eBroadcastBitStateChanged = (1 << 0), 757 eBroadcastBitInterrupt = (1 << 1), 758 eBroadcastBitSTDOUT = (1 << 2), 759 eBroadcastBitSTDERR = (1 << 3), 760 eBroadcastBitProfileData = (1 << 4) 761 }; 762 763 enum 764 { 765 eBroadcastInternalStateControlStop = (1<<0), 766 eBroadcastInternalStateControlPause = (1<<1), 767 eBroadcastInternalStateControlResume = (1<<2) 768 }; 769 770 typedef Range<lldb::addr_t, lldb::addr_t> LoadRange; 771 // We use a read/write lock to allow on or more clients to 772 // access the process state while the process is stopped (reader). 773 // We lock the write lock to control access to the process 774 // while it is running (readers, or clients that want the process 775 // stopped can block waiting for the process to stop, or just 776 // try to lock it to see if they can immediately access the stopped 777 // process. If the try read lock fails, then the process is running. 778 typedef ProcessRunLock::ProcessRunLocker StopLocker; 779 780 // These two functions fill out the Broadcaster interface: 781 782 static ConstString &GetStaticBroadcasterClass (); 783 GetBroadcasterClass()784 virtual ConstString &GetBroadcasterClass() const 785 { 786 return GetStaticBroadcasterClass(); 787 } 788 789 790 //------------------------------------------------------------------ 791 /// A notification structure that can be used by clients to listen 792 /// for changes in a process's lifetime. 793 /// 794 /// @see RegisterNotificationCallbacks (const Notifications&) 795 /// @see UnregisterNotificationCallbacks (const Notifications&) 796 //------------------------------------------------------------------ 797 #ifndef SWIG 798 typedef struct 799 { 800 void *baton; 801 void (*initialize)(void *baton, Process *process); 802 void (*process_state_changed) (void *baton, Process *process, lldb::StateType state); 803 } Notifications; 804 805 class ProcessEventData : 806 public EventData 807 { 808 friend class Process; 809 810 public: 811 ProcessEventData (); 812 ProcessEventData (const lldb::ProcessSP &process, lldb::StateType state); 813 814 virtual ~ProcessEventData(); 815 816 static const ConstString & 817 GetFlavorString (); 818 819 virtual const ConstString & 820 GetFlavor () const; 821 822 lldb::ProcessSP GetProcessSP()823 GetProcessSP() const 824 { 825 return m_process_wp.lock(); 826 } 827 828 lldb::StateType GetState()829 GetState() const 830 { 831 return m_state; 832 } 833 bool GetRestarted()834 GetRestarted () const 835 { 836 return m_restarted; 837 } 838 839 size_t GetNumRestartedReasons()840 GetNumRestartedReasons () 841 { 842 return m_restarted_reasons.size(); 843 } 844 845 const char * GetRestartedReasonAtIndex(size_t idx)846 GetRestartedReasonAtIndex(size_t idx) 847 { 848 if (idx > m_restarted_reasons.size()) 849 return NULL; 850 else 851 return m_restarted_reasons[idx].c_str(); 852 } 853 854 bool GetInterrupted()855 GetInterrupted () const 856 { 857 return m_interrupted; 858 } 859 860 virtual void 861 Dump (Stream *s) const; 862 863 virtual void 864 DoOnRemoval (Event *event_ptr); 865 866 static const Process::ProcessEventData * 867 GetEventDataFromEvent (const Event *event_ptr); 868 869 static lldb::ProcessSP 870 GetProcessFromEvent (const Event *event_ptr); 871 872 static lldb::StateType 873 GetStateFromEvent (const Event *event_ptr); 874 875 static bool 876 GetRestartedFromEvent (const Event *event_ptr); 877 878 static size_t 879 GetNumRestartedReasons(const Event *event_ptr); 880 881 static const char * 882 GetRestartedReasonAtIndex(const Event *event_ptr, size_t idx); 883 884 static void 885 AddRestartedReason (Event *event_ptr, const char *reason); 886 887 static void 888 SetRestartedInEvent (Event *event_ptr, bool new_value); 889 890 static bool 891 GetInterruptedFromEvent (const Event *event_ptr); 892 893 static void 894 SetInterruptedInEvent (Event *event_ptr, bool new_value); 895 896 static bool 897 SetUpdateStateOnRemoval (Event *event_ptr); 898 899 private: 900 901 void SetUpdateStateOnRemoval()902 SetUpdateStateOnRemoval() 903 { 904 m_update_state++; 905 } 906 void SetRestarted(bool new_value)907 SetRestarted (bool new_value) 908 { 909 m_restarted = new_value; 910 } 911 void SetInterrupted(bool new_value)912 SetInterrupted (bool new_value) 913 { 914 m_interrupted = new_value; 915 } 916 void AddRestartedReason(const char * reason)917 AddRestartedReason (const char *reason) 918 { 919 m_restarted_reasons.push_back(reason); 920 } 921 922 lldb::ProcessWP m_process_wp; 923 lldb::StateType m_state; 924 std::vector<std::string> m_restarted_reasons; 925 bool m_restarted; // For "eStateStopped" events, this is true if the target was automatically restarted. 926 int m_update_state; 927 bool m_interrupted; 928 DISALLOW_COPY_AND_ASSIGN (ProcessEventData); 929 930 }; 931 932 #endif 933 934 static void 935 SettingsInitialize (); 936 937 static void 938 SettingsTerminate (); 939 940 static const ProcessPropertiesSP & 941 GetGlobalProperties(); 942 943 //------------------------------------------------------------------ 944 /// Construct with a shared pointer to a target, and the Process listener. 945 /// Uses the Host UnixSignalsSP by default. 946 //------------------------------------------------------------------ 947 Process(Target &target, Listener &listener); 948 949 //------------------------------------------------------------------ 950 /// Construct with a shared pointer to a target, the Process listener, 951 /// and the appropriate UnixSignalsSP for the process. 952 //------------------------------------------------------------------ 953 Process(Target &target, Listener &listener, const lldb::UnixSignalsSP &unix_signals_sp); 954 955 //------------------------------------------------------------------ 956 /// Destructor. 957 /// 958 /// The destructor is virtual since this class is designed to be 959 /// inherited from by the plug-in instance. 960 //------------------------------------------------------------------ 961 virtual 962 ~Process(); 963 964 //------------------------------------------------------------------ 965 /// Find a Process plug-in that can debug \a module using the 966 /// currently selected architecture. 967 /// 968 /// Scans all loaded plug-in interfaces that implement versions of 969 /// the Process plug-in interface and returns the first instance 970 /// that can debug the file. 971 /// 972 /// @param[in] module_sp 973 /// The module shared pointer that this process will debug. 974 /// 975 /// @param[in] plugin_name 976 /// If NULL, select the best plug-in for the binary. If non-NULL 977 /// then look for a plugin whose PluginInfo's name matches 978 /// this string. 979 /// 980 /// @see Process::CanDebug () 981 //------------------------------------------------------------------ 982 static lldb::ProcessSP 983 FindPlugin (Target &target, 984 const char *plugin_name, 985 Listener &listener, 986 const FileSpec *crash_file_path); 987 988 989 990 //------------------------------------------------------------------ 991 /// Static function that can be used with the \b host function 992 /// Host::StartMonitoringChildProcess (). 993 /// 994 /// This function can be used by lldb_private::Process subclasses 995 /// when they want to watch for a local process and have its exit 996 /// status automatically set when the host child process exits. 997 /// Subclasses should call Host::StartMonitoringChildProcess () 998 /// with: 999 /// callback = Process::SetHostProcessExitStatus 1000 /// callback_baton = NULL 1001 /// pid = Process::GetID() 1002 /// monitor_signals = false 1003 //------------------------------------------------------------------ 1004 static bool 1005 SetProcessExitStatus (void *callback_baton, // The callback baton which should be set to NULL 1006 lldb::pid_t pid, // The process ID we want to monitor 1007 bool exited, 1008 int signo, // Zero for no signal 1009 int status); // Exit value of process if signal is zero 1010 1011 lldb::ByteOrder 1012 GetByteOrder () const; 1013 1014 uint32_t 1015 GetAddressByteSize () const; 1016 1017 uint32_t GetUniqueID()1018 GetUniqueID() const 1019 { 1020 return m_process_unique_id; 1021 } 1022 //------------------------------------------------------------------ 1023 /// Check if a plug-in instance can debug the file in \a module. 1024 /// 1025 /// Each plug-in is given a chance to say whether it can debug 1026 /// the file in \a module. If the Process plug-in instance can 1027 /// debug a file on the current system, it should return \b true. 1028 /// 1029 /// @return 1030 /// Returns \b true if this Process plug-in instance can 1031 /// debug the executable, \b false otherwise. 1032 //------------------------------------------------------------------ 1033 virtual bool 1034 CanDebug (Target &target, 1035 bool plugin_specified_by_name) = 0; 1036 1037 1038 //------------------------------------------------------------------ 1039 /// This object is about to be destroyed, do any necessary cleanup. 1040 /// 1041 /// Subclasses that override this method should always call this 1042 /// superclass method. 1043 //------------------------------------------------------------------ 1044 virtual void 1045 Finalize(); 1046 1047 1048 //------------------------------------------------------------------ 1049 /// Return whether this object is valid (i.e. has not been finalized.) 1050 /// 1051 /// @return 1052 /// Returns \b true if this Process has not been finalized 1053 /// and \b false otherwise. 1054 //------------------------------------------------------------------ 1055 bool IsValid()1056 IsValid() const 1057 { 1058 return !m_finalize_called; 1059 } 1060 1061 //------------------------------------------------------------------ 1062 /// Return a multi-word command object that can be used to expose 1063 /// plug-in specific commands. 1064 /// 1065 /// This object will be used to resolve plug-in commands and can be 1066 /// triggered by a call to: 1067 /// 1068 /// (lldb) process commmand <args> 1069 /// 1070 /// @return 1071 /// A CommandObject which can be one of the concrete subclasses 1072 /// of CommandObject like CommandObjectRaw, CommandObjectParsed, 1073 /// or CommandObjectMultiword. 1074 //------------------------------------------------------------------ 1075 virtual CommandObject * GetPluginCommandObject()1076 GetPluginCommandObject() 1077 { 1078 return NULL; 1079 } 1080 1081 //------------------------------------------------------------------ 1082 /// Launch a new process. 1083 /// 1084 /// Launch a new process by spawning a new process using the 1085 /// target object's executable module's file as the file to launch. 1086 /// 1087 /// This function is not meant to be overridden by Process 1088 /// subclasses. It will first call Process::WillLaunch (Module *) 1089 /// and if that returns \b true, Process::DoLaunch (Module*, 1090 /// char const *[],char const *[],const char *,const char *, 1091 /// const char *) will be called to actually do the launching. If 1092 /// DoLaunch returns \b true, then Process::DidLaunch() will be 1093 /// called. 1094 /// 1095 /// @param[in] launch_info 1096 /// Details regarding the environment, STDIN/STDOUT/STDERR 1097 /// redirection, working path, etc. related to the requested launch. 1098 /// 1099 /// @return 1100 /// An error object. Call GetID() to get the process ID if 1101 /// the error object is success. 1102 //------------------------------------------------------------------ 1103 virtual Error 1104 Launch (ProcessLaunchInfo &launch_info); 1105 1106 virtual Error 1107 LoadCore (); 1108 1109 virtual Error DoLoadCore()1110 DoLoadCore () 1111 { 1112 Error error; 1113 error.SetErrorStringWithFormat("error: %s does not support loading core files.", GetPluginName().GetCString()); 1114 return error; 1115 } 1116 1117 //------------------------------------------------------------------ 1118 /// Get the dynamic loader plug-in for this process. 1119 /// 1120 /// The default action is to let the DynamicLoader plug-ins check 1121 /// the main executable and the DynamicLoader will select itself 1122 /// automatically. Subclasses can override this if inspecting the 1123 /// executable is not desired, or if Process subclasses can only 1124 /// use a specific DynamicLoader plug-in. 1125 //------------------------------------------------------------------ 1126 virtual DynamicLoader * 1127 GetDynamicLoader (); 1128 1129 //------------------------------------------------------------------ 1130 // Returns AUXV structure found in many ELF-based environments. 1131 // 1132 // The default action is to return an empty data buffer. 1133 // 1134 // @return 1135 // A data buffer containing the contents of the AUXV data. 1136 //------------------------------------------------------------------ 1137 virtual const lldb::DataBufferSP 1138 GetAuxvData(); 1139 1140 //------------------------------------------------------------------ 1141 /// Sometimes processes know how to retrieve and load shared libraries. 1142 /// This is normally done by DynamicLoader plug-ins, but sometimes the 1143 /// connection to the process allows retrieving this information. The 1144 /// dynamic loader plug-ins can use this function if they can't 1145 /// determine the current shared library load state. 1146 /// 1147 /// @return 1148 /// The number of shared libraries that were loaded 1149 //------------------------------------------------------------------ 1150 virtual size_t LoadModules()1151 LoadModules () 1152 { 1153 return 0; 1154 } 1155 1156 protected: 1157 virtual JITLoaderList & 1158 GetJITLoaders (); 1159 1160 public: 1161 //------------------------------------------------------------------ 1162 /// Get the system runtime plug-in for this process. 1163 /// 1164 /// @return 1165 /// Returns a pointer to the SystemRuntime plugin for this Process 1166 /// if one is available. Else returns NULL. 1167 //------------------------------------------------------------------ 1168 virtual SystemRuntime * 1169 GetSystemRuntime (); 1170 1171 //------------------------------------------------------------------ 1172 /// Attach to an existing process using the process attach info. 1173 /// 1174 /// This function is not meant to be overridden by Process 1175 /// subclasses. It will first call WillAttach (lldb::pid_t) 1176 /// or WillAttach (const char *), and if that returns \b 1177 /// true, DoAttach (lldb::pid_t) or DoAttach (const char *) will 1178 /// be called to actually do the attach. If DoAttach returns \b 1179 /// true, then Process::DidAttach() will be called. 1180 /// 1181 /// @param[in] pid 1182 /// The process ID that we should attempt to attach to. 1183 /// 1184 /// @return 1185 /// Returns \a pid if attaching was successful, or 1186 /// LLDB_INVALID_PROCESS_ID if attaching fails. 1187 //------------------------------------------------------------------ 1188 virtual Error 1189 Attach (ProcessAttachInfo &attach_info); 1190 1191 //------------------------------------------------------------------ 1192 /// Attach to a remote system via a URL 1193 /// 1194 /// @param[in] strm 1195 /// A stream where output intended for the user 1196 /// (if the driver has a way to display that) generated during 1197 /// the connection. This may be NULL if no output is needed.A 1198 /// 1199 /// @param[in] remote_url 1200 /// The URL format that we are connecting to. 1201 /// 1202 /// @return 1203 /// Returns an error object. 1204 //------------------------------------------------------------------ 1205 virtual Error 1206 ConnectRemote (Stream *strm, const char *remote_url); 1207 1208 bool GetShouldDetach()1209 GetShouldDetach () const 1210 { 1211 return m_should_detach; 1212 } 1213 1214 void SetShouldDetach(bool b)1215 SetShouldDetach (bool b) 1216 { 1217 m_should_detach = b; 1218 } 1219 1220 //------------------------------------------------------------------ 1221 /// Get the image information address for the current process. 1222 /// 1223 /// Some runtimes have system functions that can help dynamic 1224 /// loaders locate the dynamic loader information needed to observe 1225 /// shared libraries being loaded or unloaded. This function is 1226 /// in the Process interface (as opposed to the DynamicLoader 1227 /// interface) to ensure that remote debugging can take advantage of 1228 /// this functionality. 1229 /// 1230 /// @return 1231 /// The address of the dynamic loader information, or 1232 /// LLDB_INVALID_ADDRESS if this is not supported by this 1233 /// interface. 1234 //------------------------------------------------------------------ 1235 virtual lldb::addr_t 1236 GetImageInfoAddress (); 1237 1238 //------------------------------------------------------------------ 1239 /// Load a shared library into this process. 1240 /// 1241 /// Try and load a shared library into the current process. This 1242 /// call might fail in the dynamic loader plug-in says it isn't safe 1243 /// to try and load shared libraries at the moment. 1244 /// 1245 /// @param[in] image_spec 1246 /// The image file spec that points to the shared library that 1247 /// you want to load. 1248 /// 1249 /// @param[out] error 1250 /// An error object that gets filled in with any errors that 1251 /// might occur when trying to load the shared library. 1252 /// 1253 /// @return 1254 /// A token that represents the shared library that can be 1255 /// later used to unload the shared library. A value of 1256 /// LLDB_INVALID_IMAGE_TOKEN will be returned if the shared 1257 /// library can't be opened. 1258 //------------------------------------------------------------------ 1259 virtual uint32_t 1260 LoadImage (const FileSpec &image_spec, Error &error); 1261 1262 virtual Error 1263 UnloadImage (uint32_t image_token); 1264 1265 //------------------------------------------------------------------ 1266 /// Register for process and thread notifications. 1267 /// 1268 /// Clients can register notification callbacks by filling out a 1269 /// Process::Notifications structure and calling this function. 1270 /// 1271 /// @param[in] callbacks 1272 /// A structure that contains the notification baton and 1273 /// callback functions. 1274 /// 1275 /// @see Process::Notifications 1276 //------------------------------------------------------------------ 1277 #ifndef SWIG 1278 void 1279 RegisterNotificationCallbacks (const Process::Notifications& callbacks); 1280 #endif 1281 //------------------------------------------------------------------ 1282 /// Unregister for process and thread notifications. 1283 /// 1284 /// Clients can unregister notification callbacks by passing a copy of 1285 /// the original baton and callbacks in \a callbacks. 1286 /// 1287 /// @param[in] callbacks 1288 /// A structure that contains the notification baton and 1289 /// callback functions. 1290 /// 1291 /// @return 1292 /// Returns \b true if the notification callbacks were 1293 /// successfully removed from the process, \b false otherwise. 1294 /// 1295 /// @see Process::Notifications 1296 //------------------------------------------------------------------ 1297 #ifndef SWIG 1298 bool 1299 UnregisterNotificationCallbacks (const Process::Notifications& callbacks); 1300 #endif 1301 //================================================================== 1302 // Built in Process Control functions 1303 //================================================================== 1304 //------------------------------------------------------------------ 1305 /// Resumes all of a process's threads as configured using the 1306 /// Thread run control functions. 1307 /// 1308 /// Threads for a process should be updated with one of the run 1309 /// control actions (resume, step, or suspend) that they should take 1310 /// when the process is resumed. If no run control action is given 1311 /// to a thread it will be resumed by default. 1312 /// 1313 /// This function is not meant to be overridden by Process 1314 /// subclasses. This function will take care of disabling any 1315 /// breakpoints that threads may be stopped at, single stepping, and 1316 /// re-enabling breakpoints, and enabling the basic flow control 1317 /// that the plug-in instances need not worry about. 1318 /// 1319 /// N.B. This function also sets the Write side of the Run Lock, 1320 /// which is unset when the corresponding stop event is pulled off 1321 /// the Public Event Queue. If you need to resume the process without 1322 /// setting the Run Lock, use PrivateResume (though you should only do 1323 /// that from inside the Process class. 1324 /// 1325 /// @return 1326 /// Returns an error object. 1327 /// 1328 /// @see Thread:Resume() 1329 /// @see Thread:Step() 1330 /// @see Thread:Suspend() 1331 //------------------------------------------------------------------ 1332 Error 1333 Resume(); 1334 1335 Error 1336 ResumeSynchronous (Stream *stream); 1337 //------------------------------------------------------------------ 1338 /// Halts a running process. 1339 /// 1340 /// This function is not meant to be overridden by Process 1341 /// subclasses. 1342 /// If the process is successfully halted, a eStateStopped 1343 /// process event with GetInterrupted will be broadcast. If false, we will 1344 /// halt the process with no events generated by the halt. 1345 /// 1346 /// @param[in] clear_thread_plans 1347 /// If true, when the process stops, clear all thread plans. 1348 /// 1349 /// @return 1350 /// Returns an error object. If the error is empty, the process is halted. 1351 /// otherwise the halt has failed. 1352 //------------------------------------------------------------------ 1353 Error 1354 Halt (bool clear_thread_plans = false); 1355 1356 //------------------------------------------------------------------ 1357 /// Detaches from a running or stopped process. 1358 /// 1359 /// This function is not meant to be overridden by Process 1360 /// subclasses. 1361 /// 1362 /// @param[in] keep_stopped 1363 /// If true, don't resume the process on detach. 1364 /// 1365 /// @return 1366 /// Returns an error object. 1367 //------------------------------------------------------------------ 1368 Error 1369 Detach (bool keep_stopped); 1370 1371 //------------------------------------------------------------------ 1372 /// Kills the process and shuts down all threads that were spawned 1373 /// to track and monitor the process. 1374 /// 1375 /// This function is not meant to be overridden by Process 1376 /// subclasses. 1377 /// 1378 /// @param[in] force_kill 1379 /// Whether lldb should force a kill (instead of a detach) from 1380 /// the inferior process. Normally if lldb launched a binary and 1381 /// Destory is called, lldb kills it. If lldb attached to a 1382 /// running process and Destory is called, lldb detaches. If 1383 /// this behavior needs to be over-ridden, this is the bool that 1384 /// can be used. 1385 /// 1386 /// @return 1387 /// Returns an error object. 1388 //------------------------------------------------------------------ 1389 Error 1390 Destroy(bool force_kill); 1391 1392 //------------------------------------------------------------------ 1393 /// Sends a process a UNIX signal \a signal. 1394 /// 1395 /// This function is not meant to be overridden by Process 1396 /// subclasses. 1397 /// 1398 /// @return 1399 /// Returns an error object. 1400 //------------------------------------------------------------------ 1401 Error 1402 Signal (int signal); 1403 1404 void 1405 SetUnixSignals(const lldb::UnixSignalsSP &signals_sp); 1406 1407 const lldb::UnixSignalsSP & 1408 GetUnixSignals(); 1409 1410 //================================================================== 1411 // Plug-in Process Control Overrides 1412 //================================================================== 1413 1414 //------------------------------------------------------------------ 1415 /// Called before attaching to a process. 1416 /// 1417 /// Allow Process plug-ins to execute some code before attaching a 1418 /// process. 1419 /// 1420 /// @return 1421 /// Returns an error object. 1422 //------------------------------------------------------------------ 1423 virtual Error WillAttachToProcessWithID(lldb::pid_t pid)1424 WillAttachToProcessWithID (lldb::pid_t pid) 1425 { 1426 return Error(); 1427 } 1428 1429 //------------------------------------------------------------------ 1430 /// Called before attaching to a process. 1431 /// 1432 /// Allow Process plug-ins to execute some code before attaching a 1433 /// process. 1434 /// 1435 /// @return 1436 /// Returns an error object. 1437 //------------------------------------------------------------------ 1438 virtual Error WillAttachToProcessWithName(const char * process_name,bool wait_for_launch)1439 WillAttachToProcessWithName (const char *process_name, bool wait_for_launch) 1440 { 1441 return Error(); 1442 } 1443 1444 //------------------------------------------------------------------ 1445 /// Attach to a remote system via a URL 1446 /// 1447 /// @param[in] strm 1448 /// A stream where output intended for the user 1449 /// (if the driver has a way to display that) generated during 1450 /// the connection. This may be NULL if no output is needed.A 1451 /// 1452 /// @param[in] remote_url 1453 /// The URL format that we are connecting to. 1454 /// 1455 /// @return 1456 /// Returns an error object. 1457 //------------------------------------------------------------------ 1458 virtual Error DoConnectRemote(Stream * strm,const char * remote_url)1459 DoConnectRemote (Stream *strm, const char *remote_url) 1460 { 1461 Error error; 1462 error.SetErrorString ("remote connections are not supported"); 1463 return error; 1464 } 1465 1466 //------------------------------------------------------------------ 1467 /// Attach to an existing process using a process ID. 1468 /// 1469 /// @param[in] pid 1470 /// The process ID that we should attempt to attach to. 1471 /// 1472 /// @param[in] attach_info 1473 /// Information on how to do the attach. For example, GetUserID() 1474 /// will return the uid to attach as. 1475 /// 1476 /// @return 1477 /// Returns a successful Error attaching was successful, or 1478 /// an appropriate (possibly platform-specific) error code if 1479 /// attaching fails. 1480 /// hanming : need flag 1481 //------------------------------------------------------------------ 1482 virtual Error DoAttachToProcessWithID(lldb::pid_t pid,const ProcessAttachInfo & attach_info)1483 DoAttachToProcessWithID (lldb::pid_t pid, const ProcessAttachInfo &attach_info) 1484 { 1485 Error error; 1486 error.SetErrorStringWithFormat("error: %s does not support attaching to a process by pid", GetPluginName().GetCString()); 1487 return error; 1488 } 1489 1490 //------------------------------------------------------------------ 1491 /// Attach to an existing process using a partial process name. 1492 /// 1493 /// @param[in] process_name 1494 /// The name of the process to attach to. 1495 /// 1496 /// @param[in] attach_info 1497 /// Information on how to do the attach. For example, GetUserID() 1498 /// will return the uid to attach as. 1499 /// 1500 /// @return 1501 /// Returns a successful Error attaching was successful, or 1502 /// an appropriate (possibly platform-specific) error code if 1503 /// attaching fails. 1504 //------------------------------------------------------------------ 1505 virtual Error DoAttachToProcessWithName(const char * process_name,const ProcessAttachInfo & attach_info)1506 DoAttachToProcessWithName (const char *process_name, const ProcessAttachInfo &attach_info) 1507 { 1508 Error error; 1509 error.SetErrorString("attach by name is not supported"); 1510 return error; 1511 } 1512 1513 //------------------------------------------------------------------ 1514 /// Called after attaching a process. 1515 /// 1516 /// @param[in] process_arch 1517 /// If you can figure out the process architecture after attach, fill it in here. 1518 /// 1519 /// Allow Process plug-ins to execute some code after attaching to 1520 /// a process. 1521 //------------------------------------------------------------------ 1522 virtual void DidAttach(ArchSpec & process_arch)1523 DidAttach (ArchSpec &process_arch) 1524 { 1525 process_arch.Clear(); 1526 } 1527 1528 1529 //------------------------------------------------------------------ 1530 /// Called after a process re-execs itself. 1531 /// 1532 /// Allow Process plug-ins to execute some code after a process has 1533 /// exec'ed itself. Subclasses typically should override DoDidExec() 1534 /// as the lldb_private::Process class needs to remove its dynamic 1535 /// loader, runtime, ABI and other plug-ins, as well as unload all 1536 /// shared libraries. 1537 //------------------------------------------------------------------ 1538 virtual void 1539 DidExec (); 1540 1541 //------------------------------------------------------------------ 1542 /// Subclasses of Process should implement this function if they 1543 /// need to do anything after a process exec's itself. 1544 //------------------------------------------------------------------ 1545 virtual void DoDidExec()1546 DoDidExec () 1547 { 1548 } 1549 1550 //------------------------------------------------------------------ 1551 /// Called before launching to a process. 1552 /// 1553 /// Allow Process plug-ins to execute some code before launching a 1554 /// process. 1555 /// 1556 /// @return 1557 /// Returns an error object. 1558 //------------------------------------------------------------------ 1559 virtual Error WillLaunch(Module * module)1560 WillLaunch (Module* module) 1561 { 1562 return Error(); 1563 } 1564 1565 //------------------------------------------------------------------ 1566 /// Launch a new process. 1567 /// 1568 /// Launch a new process by spawning a new process using 1569 /// \a exe_module's file as the file to launch. Launch details are 1570 /// provided in \a launch_info. 1571 /// 1572 /// @param[in] exe_module 1573 /// The module from which to extract the file specification and 1574 /// launch. 1575 /// 1576 /// @param[in] launch_info 1577 /// Details (e.g. arguments, stdio redirection, etc.) for the 1578 /// requested launch. 1579 /// 1580 /// @return 1581 /// An Error instance indicating success or failure of the 1582 /// operation. 1583 //------------------------------------------------------------------ 1584 virtual Error DoLaunch(Module * exe_module,ProcessLaunchInfo & launch_info)1585 DoLaunch (Module *exe_module, 1586 ProcessLaunchInfo &launch_info) 1587 { 1588 Error error; 1589 error.SetErrorStringWithFormat("error: %s does not support launching processes", GetPluginName().GetCString()); 1590 return error; 1591 } 1592 1593 1594 //------------------------------------------------------------------ 1595 /// Called after launching a process. 1596 /// 1597 /// Allow Process plug-ins to execute some code after launching 1598 /// a process. 1599 //------------------------------------------------------------------ 1600 virtual void DidLaunch()1601 DidLaunch () {} 1602 1603 1604 1605 //------------------------------------------------------------------ 1606 /// Called before resuming to a process. 1607 /// 1608 /// Allow Process plug-ins to execute some code before resuming a 1609 /// process. 1610 /// 1611 /// @return 1612 /// Returns an error object. 1613 //------------------------------------------------------------------ 1614 virtual Error WillResume()1615 WillResume () { return Error(); } 1616 1617 //------------------------------------------------------------------ 1618 /// Resumes all of a process's threads as configured using the 1619 /// Thread run control functions. 1620 /// 1621 /// Threads for a process should be updated with one of the run 1622 /// control actions (resume, step, or suspend) that they should take 1623 /// when the process is resumed. If no run control action is given 1624 /// to a thread it will be resumed by default. 1625 /// 1626 /// @return 1627 /// Returns \b true if the process successfully resumes using 1628 /// the thread run control actions, \b false otherwise. 1629 /// 1630 /// @see Thread:Resume() 1631 /// @see Thread:Step() 1632 /// @see Thread:Suspend() 1633 //------------------------------------------------------------------ 1634 virtual Error DoResume()1635 DoResume () 1636 { 1637 Error error; 1638 error.SetErrorStringWithFormat("error: %s does not support resuming processes", GetPluginName().GetCString()); 1639 return error; 1640 } 1641 1642 1643 //------------------------------------------------------------------ 1644 /// Called after resuming a process. 1645 /// 1646 /// Allow Process plug-ins to execute some code after resuming 1647 /// a process. 1648 //------------------------------------------------------------------ 1649 virtual void DidResume()1650 DidResume () {} 1651 1652 1653 //------------------------------------------------------------------ 1654 /// Called before halting to a process. 1655 /// 1656 /// Allow Process plug-ins to execute some code before halting a 1657 /// process. 1658 /// 1659 /// @return 1660 /// Returns an error object. 1661 //------------------------------------------------------------------ 1662 virtual Error WillHalt()1663 WillHalt () { return Error(); } 1664 1665 //------------------------------------------------------------------ 1666 /// Halts a running process. 1667 /// 1668 /// DoHalt must produce one and only one stop StateChanged event if it actually 1669 /// stops the process. If the stop happens through some natural event (for 1670 /// instance a SIGSTOP), then forwarding that event will do. Otherwise, you must 1671 /// generate the event manually. Note also, the private event thread is stopped when 1672 /// DoHalt is run to prevent the events generated while halting to trigger 1673 /// other state changes before the halt is complete. 1674 /// 1675 /// @param[out] caused_stop 1676 /// If true, then this Halt caused the stop, otherwise, the 1677 /// process was already stopped. 1678 /// 1679 /// @return 1680 /// Returns \b true if the process successfully halts, \b false 1681 /// otherwise. 1682 //------------------------------------------------------------------ 1683 virtual Error DoHalt(bool & caused_stop)1684 DoHalt (bool &caused_stop) 1685 { 1686 Error error; 1687 error.SetErrorStringWithFormat("error: %s does not support halting processes", GetPluginName().GetCString()); 1688 return error; 1689 } 1690 1691 1692 //------------------------------------------------------------------ 1693 /// Called after halting a process. 1694 /// 1695 /// Allow Process plug-ins to execute some code after halting 1696 /// a process. 1697 //------------------------------------------------------------------ 1698 virtual void DidHalt()1699 DidHalt () {} 1700 1701 //------------------------------------------------------------------ 1702 /// Called before detaching from a process. 1703 /// 1704 /// Allow Process plug-ins to execute some code before detaching 1705 /// from a process. 1706 /// 1707 /// @return 1708 /// Returns an error object. 1709 //------------------------------------------------------------------ 1710 virtual Error WillDetach()1711 WillDetach () 1712 { 1713 return Error(); 1714 } 1715 1716 //------------------------------------------------------------------ 1717 /// Detaches from a running or stopped process. 1718 /// 1719 /// @return 1720 /// Returns \b true if the process successfully detaches, \b 1721 /// false otherwise. 1722 //------------------------------------------------------------------ 1723 virtual Error DoDetach(bool keep_stopped)1724 DoDetach (bool keep_stopped) 1725 { 1726 Error error; 1727 error.SetErrorStringWithFormat("error: %s does not support detaching from processes", GetPluginName().GetCString()); 1728 return error; 1729 } 1730 1731 1732 //------------------------------------------------------------------ 1733 /// Called after detaching from a process. 1734 /// 1735 /// Allow Process plug-ins to execute some code after detaching 1736 /// from a process. 1737 //------------------------------------------------------------------ 1738 virtual void DidDetach()1739 DidDetach () {} 1740 1741 virtual bool DetachRequiresHalt()1742 DetachRequiresHalt() { return false; } 1743 1744 //------------------------------------------------------------------ 1745 /// Called before sending a signal to a process. 1746 /// 1747 /// Allow Process plug-ins to execute some code before sending a 1748 /// signal to a process. 1749 /// 1750 /// @return 1751 /// Returns no error if it is safe to proceed with a call to 1752 /// Process::DoSignal(int), otherwise an error describing what 1753 /// prevents the signal from being sent. 1754 //------------------------------------------------------------------ 1755 virtual Error WillSignal()1756 WillSignal () { return Error(); } 1757 1758 //------------------------------------------------------------------ 1759 /// Sends a process a UNIX signal \a signal. 1760 /// 1761 /// @return 1762 /// Returns an error object. 1763 //------------------------------------------------------------------ 1764 virtual Error DoSignal(int signal)1765 DoSignal (int signal) 1766 { 1767 Error error; 1768 error.SetErrorStringWithFormat("error: %s does not support sending signals to processes", GetPluginName().GetCString()); 1769 return error; 1770 } 1771 1772 virtual Error WillDestroy()1773 WillDestroy () { return Error(); } 1774 1775 virtual Error 1776 DoDestroy () = 0; 1777 1778 virtual void DidDestroy()1779 DidDestroy () { } 1780 1781 virtual bool DestroyRequiresHalt()1782 DestroyRequiresHalt() { return true; } 1783 1784 1785 //------------------------------------------------------------------ 1786 /// Called after sending a signal to a process. 1787 /// 1788 /// Allow Process plug-ins to execute some code after sending a 1789 /// signal to a process. 1790 //------------------------------------------------------------------ 1791 virtual void DidSignal()1792 DidSignal () {} 1793 1794 //------------------------------------------------------------------ 1795 /// Currently called as part of ShouldStop. 1796 /// FIXME: Should really happen when the target stops before the 1797 /// event is taken from the queue... 1798 /// 1799 /// This callback is called as the event 1800 /// is about to be queued up to allow Process plug-ins to execute 1801 /// some code prior to clients being notified that a process was 1802 /// stopped. Common operations include updating the thread list, 1803 /// invalidating any thread state (registers, stack, etc) prior to 1804 /// letting the notification go out. 1805 /// 1806 //------------------------------------------------------------------ 1807 virtual void 1808 RefreshStateAfterStop () = 0; 1809 1810 //------------------------------------------------------------------ 1811 /// Get the target object pointer for this module. 1812 /// 1813 /// @return 1814 /// A Target object pointer to the target that owns this 1815 /// module. 1816 //------------------------------------------------------------------ 1817 Target & GetTarget()1818 GetTarget () 1819 { 1820 return m_target; 1821 } 1822 1823 //------------------------------------------------------------------ 1824 /// Get the const target object pointer for this module. 1825 /// 1826 /// @return 1827 /// A const Target object pointer to the target that owns this 1828 /// module. 1829 //------------------------------------------------------------------ 1830 const Target & GetTarget()1831 GetTarget () const 1832 { 1833 return m_target; 1834 } 1835 1836 //------------------------------------------------------------------ 1837 /// Flush all data in the process. 1838 /// 1839 /// Flush the memory caches, all threads, and any other cached data 1840 /// in the process. 1841 /// 1842 /// This function can be called after a world changing event like 1843 /// adding a new symbol file, or after the process makes a large 1844 /// context switch (from boot ROM to booted into an OS). 1845 //------------------------------------------------------------------ 1846 void 1847 Flush (); 1848 1849 //------------------------------------------------------------------ 1850 /// Get accessor for the current process state. 1851 /// 1852 /// @return 1853 /// The current state of the process. 1854 /// 1855 /// @see lldb::StateType 1856 //------------------------------------------------------------------ 1857 lldb::StateType 1858 GetState (); 1859 1860 lldb::ExpressionResults 1861 RunThreadPlan (ExecutionContext &exe_ctx, 1862 lldb::ThreadPlanSP &thread_plan_sp, 1863 const EvaluateExpressionOptions &options, 1864 Stream &errors); 1865 1866 static const char * 1867 ExecutionResultAsCString (lldb::ExpressionResults result); 1868 1869 void 1870 GetStatus (Stream &ostrm); 1871 1872 size_t 1873 GetThreadStatus (Stream &ostrm, 1874 bool only_threads_with_stop_reason, 1875 uint32_t start_frame, 1876 uint32_t num_frames, 1877 uint32_t num_frames_with_source); 1878 1879 void 1880 SendAsyncInterrupt (); 1881 1882 //------------------------------------------------------------------ 1883 // Notify this process class that modules got loaded. 1884 // 1885 // If subclasses override this method, they must call this version 1886 // before doing anything in the subclass version of the function. 1887 //------------------------------------------------------------------ 1888 virtual void 1889 ModulesDidLoad (ModuleList &module_list); 1890 1891 1892 //------------------------------------------------------------------ 1893 /// Retrieve the list of shared libraries that are loaded for this process 1894 /// 1895 /// For certain platforms, the time it takes for the DynamicLoader plugin to 1896 /// read all of the shared libraries out of memory over a slow communication 1897 /// channel may be too long. In that instance, the gdb-remote stub may be 1898 /// able to retrieve the necessary information about the solibs out of memory 1899 /// and return a concise summary sufficient for the DynamicLoader plugin. 1900 /// 1901 /// @param [in] image_list_address 1902 /// The address where the table of shared libraries is stored in memory, 1903 /// if that is appropriate for this platform. Else this may be 1904 /// passed as LLDB_INVALID_ADDRESS. 1905 /// 1906 /// @param [in] image_count 1907 /// The number of shared libraries that are present in this process, if 1908 /// that is appropriate for this platofrm Else this may be passed as 1909 /// LLDB_INVALID_ADDRESS. 1910 /// 1911 /// @return 1912 /// A StructureDataSP object which, if non-empty, will contain the 1913 /// information the DynamicLoader needs to get the initial scan of 1914 /// solibs resolved. 1915 //------------------------------------------------------------------ 1916 virtual lldb_private::StructuredData::ObjectSP GetLoadedDynamicLibrariesInfos(lldb::addr_t image_list_address,lldb::addr_t image_count)1917 GetLoadedDynamicLibrariesInfos (lldb::addr_t image_list_address, lldb::addr_t image_count) 1918 { 1919 return StructuredData::ObjectSP(); 1920 } 1921 1922 protected: 1923 1924 void 1925 SetState (lldb::EventSP &event_sp); 1926 1927 lldb::StateType 1928 GetPrivateState (); 1929 1930 //------------------------------------------------------------------ 1931 /// The "private" side of resuming a process. This doesn't alter the 1932 /// state of m_run_lock, but just causes the process to resume. 1933 /// 1934 /// @return 1935 /// An Error object describing the success or failure of the resume. 1936 //------------------------------------------------------------------ 1937 Error 1938 PrivateResume (); 1939 1940 //------------------------------------------------------------------ 1941 // Called internally 1942 //------------------------------------------------------------------ 1943 void 1944 CompleteAttach (); 1945 1946 public: 1947 //------------------------------------------------------------------ 1948 /// Get the exit status for a process. 1949 /// 1950 /// @return 1951 /// The process's return code, or -1 if the current process 1952 /// state is not eStateExited. 1953 //------------------------------------------------------------------ 1954 int 1955 GetExitStatus (); 1956 1957 //------------------------------------------------------------------ 1958 /// Get a textual description of what the process exited. 1959 /// 1960 /// @return 1961 /// The textual description of why the process exited, or NULL 1962 /// if there is no description available. 1963 //------------------------------------------------------------------ 1964 const char * 1965 GetExitDescription (); 1966 1967 1968 virtual void DidExit()1969 DidExit () 1970 { 1971 } 1972 1973 //------------------------------------------------------------------ 1974 /// Get the Modification ID of the process. 1975 /// 1976 /// @return 1977 /// The modification ID of the process. 1978 //------------------------------------------------------------------ 1979 ProcessModID GetModID()1980 GetModID () const 1981 { 1982 return m_mod_id; 1983 } 1984 1985 const ProcessModID & GetModIDRef()1986 GetModIDRef () const 1987 { 1988 return m_mod_id; 1989 } 1990 1991 uint32_t GetStopID()1992 GetStopID () const 1993 { 1994 return m_mod_id.GetStopID(); 1995 } 1996 1997 uint32_t GetResumeID()1998 GetResumeID () const 1999 { 2000 return m_mod_id.GetResumeID(); 2001 } 2002 2003 uint32_t GetLastUserExpressionResumeID()2004 GetLastUserExpressionResumeID () const 2005 { 2006 return m_mod_id.GetLastUserExpressionResumeID(); 2007 } 2008 2009 uint32_t GetLastNaturalStopID()2010 GetLastNaturalStopID() const 2011 { 2012 return m_mod_id.GetLastNaturalStopID(); 2013 } 2014 2015 lldb::EventSP GetStopEventForStopID(uint32_t stop_id)2016 GetStopEventForStopID (uint32_t stop_id) const 2017 { 2018 return m_mod_id.GetStopEventForStopID(stop_id); 2019 } 2020 2021 //------------------------------------------------------------------ 2022 /// Set accessor for the process exit status (return code). 2023 /// 2024 /// Sometimes a child exits and the exit can be detected by global 2025 /// functions (signal handler for SIGCHLD for example). This 2026 /// accessor allows the exit status to be set from an external 2027 /// source. 2028 /// 2029 /// Setting this will cause a eStateExited event to be posted to 2030 /// the process event queue. 2031 /// 2032 /// @param[in] exit_status 2033 /// The value for the process's return code. 2034 /// 2035 /// @see lldb::StateType 2036 //------------------------------------------------------------------ 2037 virtual bool 2038 SetExitStatus (int exit_status, const char *cstr); 2039 2040 //------------------------------------------------------------------ 2041 /// Check if a process is still alive. 2042 /// 2043 /// @return 2044 /// Returns \b true if the process is still valid, \b false 2045 /// otherwise. 2046 //------------------------------------------------------------------ 2047 virtual bool 2048 IsAlive () = 0; 2049 2050 //------------------------------------------------------------------ 2051 /// Before lldb detaches from a process, it warns the user that they are about to lose their debug session. 2052 /// In some cases, this warning doesn't need to be emitted -- for instance, with core file debugging where 2053 /// the user can reconstruct the "state" by simply re-running the debugger on the core file. 2054 /// 2055 /// @return 2056 // true if the user should be warned about detaching from this process. 2057 //------------------------------------------------------------------ 2058 virtual bool WarnBeforeDetach()2059 WarnBeforeDetach () const 2060 { 2061 return true; 2062 } 2063 2064 //------------------------------------------------------------------ 2065 /// Actually do the reading of memory from a process. 2066 /// 2067 /// Subclasses must override this function and can return fewer 2068 /// bytes than requested when memory requests are too large. This 2069 /// class will break up the memory requests and keep advancing the 2070 /// arguments along as needed. 2071 /// 2072 /// @param[in] vm_addr 2073 /// A virtual load address that indicates where to start reading 2074 /// memory from. 2075 /// 2076 /// @param[in] size 2077 /// The number of bytes to read. 2078 /// 2079 /// @param[out] buf 2080 /// A byte buffer that is at least \a size bytes long that 2081 /// will receive the memory bytes. 2082 /// 2083 /// @return 2084 /// The number of bytes that were actually read into \a buf. 2085 //------------------------------------------------------------------ 2086 virtual size_t 2087 DoReadMemory (lldb::addr_t vm_addr, 2088 void *buf, 2089 size_t size, 2090 Error &error) = 0; 2091 2092 //------------------------------------------------------------------ 2093 /// Read of memory from a process. 2094 /// 2095 /// This function will read memory from the current process's 2096 /// address space and remove any traps that may have been inserted 2097 /// into the memory. 2098 /// 2099 /// This function is not meant to be overridden by Process 2100 /// subclasses, the subclasses should implement 2101 /// Process::DoReadMemory (lldb::addr_t, size_t, void *). 2102 /// 2103 /// @param[in] vm_addr 2104 /// A virtual load address that indicates where to start reading 2105 /// memory from. 2106 /// 2107 /// @param[out] buf 2108 /// A byte buffer that is at least \a size bytes long that 2109 /// will receive the memory bytes. 2110 /// 2111 /// @param[in] size 2112 /// The number of bytes to read. 2113 /// 2114 /// @return 2115 /// The number of bytes that were actually read into \a buf. If 2116 /// the returned number is greater than zero, yet less than \a 2117 /// size, then this function will get called again with \a 2118 /// vm_addr, \a buf, and \a size updated appropriately. Zero is 2119 /// returned to indicate an error. 2120 //------------------------------------------------------------------ 2121 virtual size_t 2122 ReadMemory (lldb::addr_t vm_addr, 2123 void *buf, 2124 size_t size, 2125 Error &error); 2126 2127 //------------------------------------------------------------------ 2128 /// Read a NULL terminated string from memory 2129 /// 2130 /// This function will read a cache page at a time until a NULL 2131 /// string terminator is found. It will stop reading if an aligned 2132 /// sequence of NULL termination \a type_width bytes is not found 2133 /// before reading \a cstr_max_len bytes. The results are always 2134 /// guaranteed to be NULL terminated, and that no more than 2135 /// (max_bytes - type_width) bytes will be read. 2136 /// 2137 /// @param[in] vm_addr 2138 /// The virtual load address to start the memory read. 2139 /// 2140 /// @param[in] str 2141 /// A character buffer containing at least max_bytes. 2142 /// 2143 /// @param[in] max_bytes 2144 /// The maximum number of bytes to read. 2145 /// 2146 /// @param[in] error 2147 /// The error status of the read operation. 2148 /// 2149 /// @param[in] type_width 2150 /// The size of the null terminator (1 to 4 bytes per 2151 /// character). Defaults to 1. 2152 /// 2153 /// @return 2154 /// The error status or the number of bytes prior to the null terminator. 2155 //------------------------------------------------------------------ 2156 size_t 2157 ReadStringFromMemory (lldb::addr_t vm_addr, 2158 char *str, 2159 size_t max_bytes, 2160 Error &error, 2161 size_t type_width = 1); 2162 2163 //------------------------------------------------------------------ 2164 /// Read a NULL terminated C string from memory 2165 /// 2166 /// This function will read a cache page at a time until the NULL 2167 /// C string terminator is found. It will stop reading if the NULL 2168 /// termination byte isn't found before reading \a cstr_max_len 2169 /// bytes, and the results are always guaranteed to be NULL 2170 /// terminated (at most cstr_max_len - 1 bytes will be read). 2171 //------------------------------------------------------------------ 2172 size_t 2173 ReadCStringFromMemory (lldb::addr_t vm_addr, 2174 char *cstr, 2175 size_t cstr_max_len, 2176 Error &error); 2177 2178 size_t 2179 ReadCStringFromMemory (lldb::addr_t vm_addr, 2180 std::string &out_str, 2181 Error &error); 2182 2183 size_t 2184 ReadMemoryFromInferior (lldb::addr_t vm_addr, 2185 void *buf, 2186 size_t size, 2187 Error &error); 2188 2189 //------------------------------------------------------------------ 2190 /// Reads an unsigned integer of the specified byte size from 2191 /// process memory. 2192 /// 2193 /// @param[in] load_addr 2194 /// A load address of the integer to read. 2195 /// 2196 /// @param[in] byte_size 2197 /// The size in byte of the integer to read. 2198 /// 2199 /// @param[in] fail_value 2200 /// The value to return if we fail to read an integer. 2201 /// 2202 /// @param[out] error 2203 /// An error that indicates the success or failure of this 2204 /// operation. If error indicates success (error.Success()), 2205 /// then the value returned can be trusted, otherwise zero 2206 /// will be returned. 2207 /// 2208 /// @return 2209 /// The unsigned integer that was read from the process memory 2210 /// space. If the integer was smaller than a uint64_t, any 2211 /// unused upper bytes will be zero filled. If the process 2212 /// byte order differs from the host byte order, the integer 2213 /// value will be appropriately byte swapped into host byte 2214 /// order. 2215 //------------------------------------------------------------------ 2216 uint64_t 2217 ReadUnsignedIntegerFromMemory (lldb::addr_t load_addr, 2218 size_t byte_size, 2219 uint64_t fail_value, 2220 Error &error); 2221 2222 lldb::addr_t 2223 ReadPointerFromMemory (lldb::addr_t vm_addr, 2224 Error &error); 2225 2226 bool 2227 WritePointerToMemory (lldb::addr_t vm_addr, 2228 lldb::addr_t ptr_value, 2229 Error &error); 2230 2231 //------------------------------------------------------------------ 2232 /// Actually do the writing of memory to a process. 2233 /// 2234 /// @param[in] vm_addr 2235 /// A virtual load address that indicates where to start writing 2236 /// memory to. 2237 /// 2238 /// @param[in] buf 2239 /// A byte buffer that is at least \a size bytes long that 2240 /// contains the data to write. 2241 /// 2242 /// @param[in] size 2243 /// The number of bytes to write. 2244 /// 2245 /// @param[out] error 2246 /// An error value in case the memory write fails. 2247 /// 2248 /// @return 2249 /// The number of bytes that were actually written. 2250 //------------------------------------------------------------------ 2251 virtual size_t DoWriteMemory(lldb::addr_t vm_addr,const void * buf,size_t size,Error & error)2252 DoWriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error) 2253 { 2254 error.SetErrorStringWithFormat("error: %s does not support writing to processes", GetPluginName().GetCString()); 2255 return 0; 2256 } 2257 2258 2259 //------------------------------------------------------------------ 2260 /// Write all or part of a scalar value to memory. 2261 /// 2262 /// The value contained in \a scalar will be swapped to match the 2263 /// byte order of the process that is being debugged. If \a size is 2264 /// less than the size of scalar, the least significant \a size bytes 2265 /// from scalar will be written. If \a size is larger than the byte 2266 /// size of scalar, then the extra space will be padded with zeros 2267 /// and the scalar value will be placed in the least significant 2268 /// bytes in memory. 2269 /// 2270 /// @param[in] vm_addr 2271 /// A virtual load address that indicates where to start writing 2272 /// memory to. 2273 /// 2274 /// @param[in] scalar 2275 /// The scalar to write to the debugged process. 2276 /// 2277 /// @param[in] size 2278 /// This value can be smaller or larger than the scalar value 2279 /// itself. If \a size is smaller than the size of \a scalar, 2280 /// the least significant bytes in \a scalar will be used. If 2281 /// \a size is larger than the byte size of \a scalar, then 2282 /// the extra space will be padded with zeros. If \a size is 2283 /// set to UINT32_MAX, then the size of \a scalar will be used. 2284 /// 2285 /// @param[out] error 2286 /// An error value in case the memory write fails. 2287 /// 2288 /// @return 2289 /// The number of bytes that were actually written. 2290 //------------------------------------------------------------------ 2291 size_t 2292 WriteScalarToMemory (lldb::addr_t vm_addr, 2293 const Scalar &scalar, 2294 size_t size, 2295 Error &error); 2296 2297 size_t 2298 ReadScalarIntegerFromMemory (lldb::addr_t addr, 2299 uint32_t byte_size, 2300 bool is_signed, 2301 Scalar &scalar, 2302 Error &error); 2303 2304 //------------------------------------------------------------------ 2305 /// Write memory to a process. 2306 /// 2307 /// This function will write memory to the current process's 2308 /// address space and maintain any traps that might be present due 2309 /// to software breakpoints. 2310 /// 2311 /// This function is not meant to be overridden by Process 2312 /// subclasses, the subclasses should implement 2313 /// Process::DoWriteMemory (lldb::addr_t, size_t, void *). 2314 /// 2315 /// @param[in] vm_addr 2316 /// A virtual load address that indicates where to start writing 2317 /// memory to. 2318 /// 2319 /// @param[in] buf 2320 /// A byte buffer that is at least \a size bytes long that 2321 /// contains the data to write. 2322 /// 2323 /// @param[in] size 2324 /// The number of bytes to write. 2325 /// 2326 /// @return 2327 /// The number of bytes that were actually written. 2328 //------------------------------------------------------------------ 2329 size_t 2330 WriteMemory (lldb::addr_t vm_addr, const void *buf, size_t size, Error &error); 2331 2332 2333 //------------------------------------------------------------------ 2334 /// Actually allocate memory in the process. 2335 /// 2336 /// This function will allocate memory in the process's address 2337 /// space. This can't rely on the generic function calling mechanism, 2338 /// since that requires this function. 2339 /// 2340 /// @param[in] size 2341 /// The size of the allocation requested. 2342 /// 2343 /// @return 2344 /// The address of the allocated buffer in the process, or 2345 /// LLDB_INVALID_ADDRESS if the allocation failed. 2346 //------------------------------------------------------------------ 2347 2348 virtual lldb::addr_t DoAllocateMemory(size_t size,uint32_t permissions,Error & error)2349 DoAllocateMemory (size_t size, uint32_t permissions, Error &error) 2350 { 2351 error.SetErrorStringWithFormat("error: %s does not support allocating in the debug process", GetPluginName().GetCString()); 2352 return LLDB_INVALID_ADDRESS; 2353 } 2354 2355 2356 //------------------------------------------------------------------ 2357 /// The public interface to allocating memory in the process. 2358 /// 2359 /// This function will allocate memory in the process's address 2360 /// space. This can't rely on the generic function calling mechanism, 2361 /// since that requires this function. 2362 /// 2363 /// @param[in] size 2364 /// The size of the allocation requested. 2365 /// 2366 /// @param[in] permissions 2367 /// Or together any of the lldb::Permissions bits. The permissions on 2368 /// a given memory allocation can't be changed after allocation. Note 2369 /// that a block that isn't set writable can still be written on from lldb, 2370 /// just not by the process itself. 2371 /// 2372 /// @param[in/out] error 2373 /// An error object to fill in if things go wrong. 2374 /// @return 2375 /// The address of the allocated buffer in the process, or 2376 /// LLDB_INVALID_ADDRESS if the allocation failed. 2377 //------------------------------------------------------------------ 2378 2379 lldb::addr_t 2380 AllocateMemory (size_t size, uint32_t permissions, Error &error); 2381 2382 2383 //------------------------------------------------------------------ 2384 /// Resolve dynamically loaded indirect functions. 2385 /// 2386 /// @param[in] address 2387 /// The load address of the indirect function to resolve. 2388 /// 2389 /// @param[out] error 2390 /// An error value in case the resolve fails. 2391 /// 2392 /// @return 2393 /// The address of the resolved function. 2394 /// LLDB_INVALID_ADDRESS if the resolution failed. 2395 //------------------------------------------------------------------ 2396 2397 virtual lldb::addr_t 2398 ResolveIndirectFunction(const Address *address, Error &error); 2399 2400 virtual Error GetMemoryRegionInfo(lldb::addr_t load_addr,MemoryRegionInfo & range_info)2401 GetMemoryRegionInfo (lldb::addr_t load_addr, 2402 MemoryRegionInfo &range_info) 2403 { 2404 Error error; 2405 error.SetErrorString ("Process::GetMemoryRegionInfo() not supported"); 2406 return error; 2407 } 2408 2409 virtual Error GetWatchpointSupportInfo(uint32_t & num)2410 GetWatchpointSupportInfo (uint32_t &num) 2411 { 2412 Error error; 2413 num = 0; 2414 error.SetErrorString ("Process::GetWatchpointSupportInfo() not supported"); 2415 return error; 2416 } 2417 2418 virtual Error GetWatchpointSupportInfo(uint32_t & num,bool & after)2419 GetWatchpointSupportInfo (uint32_t &num, bool& after) 2420 { 2421 Error error; 2422 num = 0; 2423 after = true; 2424 error.SetErrorString ("Process::GetWatchpointSupportInfo() not supported"); 2425 return error; 2426 } 2427 2428 lldb::ModuleSP 2429 ReadModuleFromMemory (const FileSpec& file_spec, 2430 lldb::addr_t header_addr, 2431 size_t size_to_read = 512); 2432 2433 //------------------------------------------------------------------ 2434 /// Attempt to get the attributes for a region of memory in the process. 2435 /// 2436 /// It may be possible for the remote debug server to inspect attributes 2437 /// for a region of memory in the process, such as whether there is a 2438 /// valid page of memory at a given address or whether that page is 2439 /// readable/writable/executable by the process. 2440 /// 2441 /// @param[in] load_addr 2442 /// The address of interest in the process. 2443 /// 2444 /// @param[out] permissions 2445 /// If this call returns successfully, this bitmask will have 2446 /// its Permissions bits set to indicate whether the region is 2447 /// readable/writable/executable. If this call fails, the 2448 /// bitmask values are undefined. 2449 /// 2450 /// @return 2451 /// Returns true if it was able to determine the attributes of the 2452 /// memory region. False if not. 2453 //------------------------------------------------------------------ 2454 virtual bool 2455 GetLoadAddressPermissions (lldb::addr_t load_addr, uint32_t &permissions); 2456 2457 //------------------------------------------------------------------ 2458 /// Determines whether executing JIT-compiled code in this process 2459 /// is possible. 2460 /// 2461 /// @return 2462 /// True if execution of JIT code is possible; false otherwise. 2463 //------------------------------------------------------------------ 2464 bool CanJIT (); 2465 2466 //------------------------------------------------------------------ 2467 /// Sets whether executing JIT-compiled code in this process 2468 /// is possible. 2469 /// 2470 /// @param[in] can_jit 2471 /// True if execution of JIT code is possible; false otherwise. 2472 //------------------------------------------------------------------ 2473 void SetCanJIT (bool can_jit); 2474 2475 //------------------------------------------------------------------ 2476 /// Determines whether executing function calls using the interpreter 2477 /// is possible for this process. 2478 /// 2479 /// @return 2480 /// True if possible; false otherwise. 2481 //------------------------------------------------------------------ CanInterpretFunctionCalls()2482 bool CanInterpretFunctionCalls () 2483 { 2484 return m_can_interpret_function_calls; 2485 } 2486 2487 //------------------------------------------------------------------ 2488 /// Sets whether executing function calls using the interpreter 2489 /// is possible for this process. 2490 /// 2491 /// @param[in] can_interpret_function_calls 2492 /// True if possible; false otherwise. 2493 //------------------------------------------------------------------ SetCanInterpretFunctionCalls(bool can_interpret_function_calls)2494 void SetCanInterpretFunctionCalls (bool can_interpret_function_calls) 2495 { 2496 m_can_interpret_function_calls = can_interpret_function_calls; 2497 } 2498 2499 //------------------------------------------------------------------ 2500 /// Sets whether executing code in this process is possible. 2501 /// This could be either through JIT or interpreting. 2502 /// 2503 /// @param[in] can_run_code 2504 /// True if execution of code is possible; false otherwise. 2505 //------------------------------------------------------------------ 2506 void SetCanRunCode (bool can_run_code); 2507 2508 //------------------------------------------------------------------ 2509 /// Actually deallocate memory in the process. 2510 /// 2511 /// This function will deallocate memory in the process's address 2512 /// space that was allocated with AllocateMemory. 2513 /// 2514 /// @param[in] ptr 2515 /// A return value from AllocateMemory, pointing to the memory you 2516 /// want to deallocate. 2517 /// 2518 /// @return 2519 /// \btrue if the memory was deallocated, \bfalse otherwise. 2520 //------------------------------------------------------------------ 2521 2522 virtual Error DoDeallocateMemory(lldb::addr_t ptr)2523 DoDeallocateMemory (lldb::addr_t ptr) 2524 { 2525 Error error; 2526 error.SetErrorStringWithFormat("error: %s does not support deallocating in the debug process", GetPluginName().GetCString()); 2527 return error; 2528 } 2529 2530 2531 //------------------------------------------------------------------ 2532 /// The public interface to deallocating memory in the process. 2533 /// 2534 /// This function will deallocate memory in the process's address 2535 /// space that was allocated with AllocateMemory. 2536 /// 2537 /// @param[in] ptr 2538 /// A return value from AllocateMemory, pointing to the memory you 2539 /// want to deallocate. 2540 /// 2541 /// @return 2542 /// \btrue if the memory was deallocated, \bfalse otherwise. 2543 //------------------------------------------------------------------ 2544 2545 Error 2546 DeallocateMemory (lldb::addr_t ptr); 2547 2548 //------------------------------------------------------------------ 2549 /// Get any available STDOUT. 2550 /// 2551 /// Calling this method is a valid operation only if all of the 2552 /// following conditions are true: 2553 /// 1) The process was launched, and not attached to. 2554 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 2555 /// 3) The process was launched without supplying a valid file path 2556 /// for STDOUT. 2557 /// 2558 /// Note that the implementation will probably need to start a read 2559 /// thread in the background to make sure that the pipe is drained 2560 /// and the STDOUT buffered appropriately, to prevent the process 2561 /// from deadlocking trying to write to a full buffer. 2562 /// 2563 /// Events will be queued indicating that there is STDOUT available 2564 /// that can be retrieved using this function. 2565 /// 2566 /// @param[out] buf 2567 /// A buffer that will receive any STDOUT bytes that are 2568 /// currently available. 2569 /// 2570 /// @param[in] buf_size 2571 /// The size in bytes for the buffer \a buf. 2572 /// 2573 /// @return 2574 /// The number of bytes written into \a buf. If this value is 2575 /// equal to \a buf_size, another call to this function should 2576 /// be made to retrieve more STDOUT data. 2577 //------------------------------------------------------------------ 2578 virtual size_t 2579 GetSTDOUT (char *buf, size_t buf_size, Error &error); 2580 2581 //------------------------------------------------------------------ 2582 /// Get any available STDERR. 2583 /// 2584 /// Calling this method is a valid operation only if all of the 2585 /// following conditions are true: 2586 /// 1) The process was launched, and not attached to. 2587 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 2588 /// 3) The process was launched without supplying a valid file path 2589 /// for STDERR. 2590 /// 2591 /// Note that the implementation will probably need to start a read 2592 /// thread in the background to make sure that the pipe is drained 2593 /// and the STDERR buffered appropriately, to prevent the process 2594 /// from deadlocking trying to write to a full buffer. 2595 /// 2596 /// Events will be queued indicating that there is STDERR available 2597 /// that can be retrieved using this function. 2598 /// 2599 /// @param[in] buf 2600 /// A buffer that will receive any STDERR bytes that are 2601 /// currently available. 2602 /// 2603 /// @param[out] buf_size 2604 /// The size in bytes for the buffer \a buf. 2605 /// 2606 /// @return 2607 /// The number of bytes written into \a buf. If this value is 2608 /// equal to \a buf_size, another call to this function should 2609 /// be made to retrieve more STDERR data. 2610 //------------------------------------------------------------------ 2611 virtual size_t 2612 GetSTDERR (char *buf, size_t buf_size, Error &error); 2613 2614 //------------------------------------------------------------------ 2615 /// Puts data into this process's STDIN. 2616 /// 2617 /// Calling this method is a valid operation only if all of the 2618 /// following conditions are true: 2619 /// 1) The process was launched, and not attached to. 2620 /// 2) The process was not launched with eLaunchFlagDisableSTDIO. 2621 /// 3) The process was launched without supplying a valid file path 2622 /// for STDIN. 2623 /// 2624 /// @param[in] buf 2625 /// A buffer that contains the data to write to the process's STDIN. 2626 /// 2627 /// @param[in] buf_size 2628 /// The size in bytes for the buffer \a buf. 2629 /// 2630 /// @return 2631 /// The number of bytes written into \a buf. If this value is 2632 /// less than \a buf_size, another call to this function should 2633 /// be made to write the rest of the data. 2634 //------------------------------------------------------------------ 2635 virtual size_t PutSTDIN(const char * buf,size_t buf_size,Error & error)2636 PutSTDIN (const char *buf, size_t buf_size, Error &error) 2637 { 2638 error.SetErrorString("stdin unsupported"); 2639 return 0; 2640 } 2641 2642 //------------------------------------------------------------------ 2643 /// Get any available profile data. 2644 /// 2645 /// @param[out] buf 2646 /// A buffer that will receive any profile data bytes that are 2647 /// currently available. 2648 /// 2649 /// @param[out] buf_size 2650 /// The size in bytes for the buffer \a buf. 2651 /// 2652 /// @return 2653 /// The number of bytes written into \a buf. If this value is 2654 /// equal to \a buf_size, another call to this function should 2655 /// be made to retrieve more profile data. 2656 //------------------------------------------------------------------ 2657 virtual size_t 2658 GetAsyncProfileData (char *buf, size_t buf_size, Error &error); 2659 2660 //---------------------------------------------------------------------- 2661 // Process Breakpoints 2662 //---------------------------------------------------------------------- 2663 size_t 2664 GetSoftwareBreakpointTrapOpcode (BreakpointSite* bp_site); 2665 2666 virtual Error EnableBreakpointSite(BreakpointSite * bp_site)2667 EnableBreakpointSite (BreakpointSite *bp_site) 2668 { 2669 Error error; 2670 error.SetErrorStringWithFormat("error: %s does not support enabling breakpoints", GetPluginName().GetCString()); 2671 return error; 2672 } 2673 2674 2675 virtual Error DisableBreakpointSite(BreakpointSite * bp_site)2676 DisableBreakpointSite (BreakpointSite *bp_site) 2677 { 2678 Error error; 2679 error.SetErrorStringWithFormat("error: %s does not support disabling breakpoints", GetPluginName().GetCString()); 2680 return error; 2681 } 2682 2683 2684 // This is implemented completely using the lldb::Process API. Subclasses 2685 // don't need to implement this function unless the standard flow of 2686 // read existing opcode, write breakpoint opcode, verify breakpoint opcode 2687 // doesn't work for a specific process plug-in. 2688 virtual Error 2689 EnableSoftwareBreakpoint (BreakpointSite *bp_site); 2690 2691 // This is implemented completely using the lldb::Process API. Subclasses 2692 // don't need to implement this function unless the standard flow of 2693 // restoring original opcode in memory and verifying the restored opcode 2694 // doesn't work for a specific process plug-in. 2695 virtual Error 2696 DisableSoftwareBreakpoint (BreakpointSite *bp_site); 2697 2698 BreakpointSiteList & 2699 GetBreakpointSiteList(); 2700 2701 const BreakpointSiteList & 2702 GetBreakpointSiteList() const; 2703 2704 void 2705 DisableAllBreakpointSites (); 2706 2707 Error 2708 ClearBreakpointSiteByID (lldb::user_id_t break_id); 2709 2710 lldb::break_id_t 2711 CreateBreakpointSite (const lldb::BreakpointLocationSP &owner, 2712 bool use_hardware); 2713 2714 Error 2715 DisableBreakpointSiteByID (lldb::user_id_t break_id); 2716 2717 Error 2718 EnableBreakpointSiteByID (lldb::user_id_t break_id); 2719 2720 2721 // BreakpointLocations use RemoveOwnerFromBreakpointSite to remove 2722 // themselves from the owner's list of this breakpoint sites. 2723 void 2724 RemoveOwnerFromBreakpointSite (lldb::user_id_t owner_id, 2725 lldb::user_id_t owner_loc_id, 2726 lldb::BreakpointSiteSP &bp_site_sp); 2727 2728 //---------------------------------------------------------------------- 2729 // Process Watchpoints (optional) 2730 //---------------------------------------------------------------------- 2731 virtual Error 2732 EnableWatchpoint (Watchpoint *wp, bool notify = true); 2733 2734 virtual Error 2735 DisableWatchpoint (Watchpoint *wp, bool notify = true); 2736 2737 //------------------------------------------------------------------ 2738 // Thread Queries 2739 //------------------------------------------------------------------ 2740 virtual bool 2741 UpdateThreadList (ThreadList &old_thread_list, ThreadList &new_thread_list) = 0; 2742 2743 void 2744 UpdateThreadListIfNeeded (); 2745 2746 ThreadList & GetThreadList()2747 GetThreadList () 2748 { 2749 return m_thread_list; 2750 } 2751 2752 // When ExtendedBacktraces are requested, the HistoryThreads that are 2753 // created need an owner -- they're saved here in the Process. The 2754 // threads in this list are not iterated over - driver programs need to 2755 // request the extended backtrace calls starting from a root concrete 2756 // thread one by one. 2757 ThreadList & GetExtendedThreadList()2758 GetExtendedThreadList () 2759 { 2760 return m_extended_thread_list; 2761 } 2762 2763 ThreadList::ThreadIterable Threads()2764 Threads () 2765 { 2766 return m_thread_list.Threads(); 2767 } 2768 2769 uint32_t 2770 GetNextThreadIndexID (uint64_t thread_id); 2771 2772 lldb::ThreadSP 2773 CreateOSPluginThread (lldb::tid_t tid, lldb::addr_t context); 2774 2775 // Returns true if an index id has been assigned to a thread. 2776 bool 2777 HasAssignedIndexIDToThread(uint64_t sb_thread_id); 2778 2779 // Given a thread_id, it will assign a more reasonable index id for display to the user. 2780 // If the thread_id has previously been assigned, the same index id will be used. 2781 uint32_t 2782 AssignIndexIDToThread(uint64_t thread_id); 2783 2784 //------------------------------------------------------------------ 2785 // Queue Queries 2786 //------------------------------------------------------------------ 2787 2788 void 2789 UpdateQueueListIfNeeded (); 2790 2791 QueueList & GetQueueList()2792 GetQueueList () 2793 { 2794 UpdateQueueListIfNeeded(); 2795 return m_queue_list; 2796 } 2797 2798 QueueList::QueueIterable Queues()2799 Queues () 2800 { 2801 UpdateQueueListIfNeeded(); 2802 return m_queue_list.Queues(); 2803 } 2804 2805 //------------------------------------------------------------------ 2806 // Event Handling 2807 //------------------------------------------------------------------ 2808 lldb::StateType 2809 GetNextEvent (lldb::EventSP &event_sp); 2810 2811 // Returns the process state when it is stopped. If specified, event_sp_ptr 2812 // is set to the event which triggered the stop. If wait_always = false, 2813 // and the process is already stopped, this function returns immediately. 2814 lldb::StateType 2815 WaitForProcessToStop (const TimeValue *timeout, 2816 lldb::EventSP *event_sp_ptr = NULL, 2817 bool wait_always = true, 2818 Listener *hijack_listener = NULL, 2819 Stream *stream = NULL); 2820 2821 uint32_t GetIOHandlerID()2822 GetIOHandlerID () const 2823 { 2824 return m_iohandler_sync.GetValue(); 2825 } 2826 2827 //-------------------------------------------------------------------------------------- 2828 /// Waits for the process state to be running within a given msec timeout. 2829 /// 2830 /// The main purpose of this is to implement an interlock waiting for HandlePrivateEvent 2831 /// to push an IOHandler. 2832 /// 2833 /// @param[in] timeout_msec 2834 /// The maximum time length to wait for the process to transition to the 2835 /// eStateRunning state, specified in milliseconds. 2836 //-------------------------------------------------------------------------------------- 2837 void 2838 SyncIOHandler (uint32_t iohandler_id, uint64_t timeout_msec); 2839 2840 lldb::StateType 2841 WaitForStateChangedEvents (const TimeValue *timeout, 2842 lldb::EventSP &event_sp, 2843 Listener *hijack_listener); // Pass NULL to use builtin listener 2844 2845 //-------------------------------------------------------------------------------------- 2846 /// Centralize the code that handles and prints descriptions for process state changes. 2847 /// 2848 /// @param[in] event_sp 2849 /// The process state changed event 2850 /// 2851 /// @param[in] stream 2852 /// The output stream to get the state change description 2853 /// 2854 /// @param[inout] pop_process_io_handler 2855 /// If this value comes in set to \b true, then pop the Process IOHandler if needed. 2856 /// Else this variable will be set to \b true or \b false to indicate if the process 2857 /// needs to have its process IOHandler popped. 2858 /// 2859 /// @return 2860 /// \b true if the event describes a process state changed event, \b false otherwise. 2861 //-------------------------------------------------------------------------------------- 2862 static bool 2863 HandleProcessStateChangedEvent (const lldb::EventSP &event_sp, 2864 Stream *stream, 2865 bool &pop_process_io_handler); 2866 Event * 2867 PeekAtStateChangedEvents (); 2868 2869 2870 class 2871 ProcessEventHijacker 2872 { 2873 public: ProcessEventHijacker(Process & process,Listener * listener)2874 ProcessEventHijacker (Process &process, Listener *listener) : 2875 m_process (process) 2876 { 2877 m_process.HijackProcessEvents (listener); 2878 } ~ProcessEventHijacker()2879 ~ProcessEventHijacker () 2880 { 2881 m_process.RestoreProcessEvents(); 2882 } 2883 2884 private: 2885 Process &m_process; 2886 }; 2887 friend class ProcessEventHijacker; 2888 friend class ProcessProperties; 2889 //------------------------------------------------------------------ 2890 /// If you need to ensure that you and only you will hear about some public 2891 /// event, then make a new listener, set to listen to process events, and 2892 /// then call this with that listener. Then you will have to wait on that 2893 /// listener explicitly for events (rather than using the GetNextEvent & WaitFor* 2894 /// calls above. Be sure to call RestoreProcessEvents when you are done. 2895 /// 2896 /// @param[in] listener 2897 /// This is the new listener to whom all process events will be delivered. 2898 /// 2899 /// @return 2900 /// Returns \b true if the new listener could be installed, 2901 /// \b false otherwise. 2902 //------------------------------------------------------------------ 2903 bool 2904 HijackProcessEvents (Listener *listener); 2905 2906 //------------------------------------------------------------------ 2907 /// Restores the process event broadcasting to its normal state. 2908 /// 2909 //------------------------------------------------------------------ 2910 void 2911 RestoreProcessEvents (); 2912 2913 private: 2914 //------------------------------------------------------------------ 2915 /// This is the part of the event handling that for a process event. 2916 /// It decides what to do with the event and returns true if the 2917 /// event needs to be propagated to the user, and false otherwise. 2918 /// If the event is not propagated, this call will most likely set 2919 /// the target to executing again. 2920 /// There is only one place where this call should be called, HandlePrivateEvent. 2921 /// Don't call it from anywhere else... 2922 /// 2923 /// @param[in] event_ptr 2924 /// This is the event we are handling. 2925 /// 2926 /// @return 2927 /// Returns \b true if the event should be reported to the 2928 /// user, \b false otherwise. 2929 //------------------------------------------------------------------ 2930 bool 2931 ShouldBroadcastEvent (Event *event_ptr); 2932 2933 public: 2934 const lldb::ABISP & 2935 GetABI (); 2936 2937 OperatingSystem * GetOperatingSystem()2938 GetOperatingSystem () 2939 { 2940 return m_os_ap.get(); 2941 } 2942 2943 ArchSpec::StopInfoOverrideCallbackType GetStopInfoOverrideCallback()2944 GetStopInfoOverrideCallback () const 2945 { 2946 return m_stop_info_override_callback; 2947 } 2948 2949 virtual LanguageRuntime * 2950 GetLanguageRuntime (lldb::LanguageType language, bool retry_if_null = true); 2951 2952 virtual CPPLanguageRuntime * 2953 GetCPPLanguageRuntime (bool retry_if_null = true); 2954 2955 virtual ObjCLanguageRuntime * 2956 GetObjCLanguageRuntime (bool retry_if_null = true); 2957 2958 bool 2959 IsPossibleDynamicValue (ValueObject& in_value); 2960 2961 bool 2962 IsRunning () const; 2963 GetDynamicCheckers()2964 DynamicCheckerFunctions *GetDynamicCheckers() 2965 { 2966 return m_dynamic_checkers_ap.get(); 2967 } 2968 2969 void SetDynamicCheckers(DynamicCheckerFunctions *dynamic_checkers); 2970 2971 //------------------------------------------------------------------ 2972 /// Call this to set the lldb in the mode where it breaks on new thread 2973 /// creations, and then auto-restarts. This is useful when you are trying 2974 /// to run only one thread, but either that thread or the kernel is creating 2975 /// new threads in the process. If you stop when the thread is created, you 2976 /// can immediately suspend it, and keep executing only the one thread you intend. 2977 /// 2978 /// @return 2979 /// Returns \b true if we were able to start up the notification 2980 /// \b false otherwise. 2981 //------------------------------------------------------------------ 2982 virtual bool StartNoticingNewThreads()2983 StartNoticingNewThreads() 2984 { 2985 return true; 2986 } 2987 2988 //------------------------------------------------------------------ 2989 /// Call this to turn off the stop & notice new threads mode. 2990 /// 2991 /// @return 2992 /// Returns \b true if we were able to start up the notification 2993 /// \b false otherwise. 2994 //------------------------------------------------------------------ 2995 virtual bool StopNoticingNewThreads()2996 StopNoticingNewThreads() 2997 { 2998 return true; 2999 } 3000 3001 void 3002 SetRunningUserExpression (bool on); 3003 3004 //------------------------------------------------------------------ 3005 // lldb::ExecutionContextScope pure virtual functions 3006 //------------------------------------------------------------------ 3007 virtual lldb::TargetSP 3008 CalculateTarget (); 3009 3010 virtual lldb::ProcessSP CalculateProcess()3011 CalculateProcess () 3012 { 3013 return shared_from_this(); 3014 } 3015 3016 virtual lldb::ThreadSP CalculateThread()3017 CalculateThread () 3018 { 3019 return lldb::ThreadSP(); 3020 } 3021 3022 virtual lldb::StackFrameSP CalculateStackFrame()3023 CalculateStackFrame () 3024 { 3025 return lldb::StackFrameSP(); 3026 } 3027 3028 virtual void 3029 CalculateExecutionContext (ExecutionContext &exe_ctx); 3030 3031 void 3032 SetSTDIOFileDescriptor (int file_descriptor); 3033 3034 //------------------------------------------------------------------ 3035 // Add a permanent region of memory that should never be read or 3036 // written to. This can be used to ensure that memory reads or writes 3037 // to certain areas of memory never end up being sent to the 3038 // DoReadMemory or DoWriteMemory functions which can improve 3039 // performance. 3040 //------------------------------------------------------------------ 3041 void 3042 AddInvalidMemoryRegion (const LoadRange ®ion); 3043 3044 //------------------------------------------------------------------ 3045 // Remove a permanent region of memory that should never be read or 3046 // written to that was previously added with AddInvalidMemoryRegion. 3047 //------------------------------------------------------------------ 3048 bool 3049 RemoveInvalidMemoryRange (const LoadRange ®ion); 3050 3051 //------------------------------------------------------------------ 3052 // If the setup code of a thread plan needs to do work that might involve 3053 // calling a function in the target, it should not do that work directly 3054 // in one of the thread plan functions (DidPush/WillResume) because 3055 // such work needs to be handled carefully. Instead, put that work in 3056 // a PreResumeAction callback, and register it with the process. It will 3057 // get done before the actual "DoResume" gets called. 3058 //------------------------------------------------------------------ 3059 3060 typedef bool (PreResumeActionCallback)(void *); 3061 3062 void 3063 AddPreResumeAction (PreResumeActionCallback callback, void *baton); 3064 3065 bool 3066 RunPreResumeActions (); 3067 3068 void 3069 ClearPreResumeActions (); 3070 3071 ProcessRunLock & 3072 GetRunLock (); 3073 3074 virtual Error SendEventData(const char * data)3075 SendEventData(const char *data) 3076 { 3077 Error return_error ("Sending an event is not supported for this process."); 3078 return return_error; 3079 } 3080 3081 lldb::ThreadCollectionSP 3082 GetHistoryThreads(lldb::addr_t addr); 3083 3084 lldb::InstrumentationRuntimeSP 3085 GetInstrumentationRuntime(lldb::InstrumentationRuntimeType type); 3086 3087 //------------------------------------------------------------------ 3088 /// Try to fetch the module specification for a module with the 3089 /// given file name and architecture. Process sub-classes have to 3090 /// override this method if they support platforms where the 3091 /// Platform object can't get the module spec for all module. 3092 /// 3093 /// @param[in] module_file_spec 3094 /// The file name of the module to get specification for. 3095 /// 3096 /// @param[in] arch 3097 /// The architecture of the module to get specification for. 3098 /// 3099 /// @param[out] module_spec 3100 /// The fetched module specification if the return value is 3101 /// \b true, unchanged otherwise. 3102 /// 3103 /// @return 3104 /// Returns \b true if the module spec fetched successfully, 3105 /// \b false otherwise. 3106 //------------------------------------------------------------------ 3107 virtual bool 3108 GetModuleSpec(const FileSpec& module_file_spec, const ArchSpec& arch, ModuleSpec &module_spec); 3109 3110 //------------------------------------------------------------------ 3111 /// Try to find the load address of a file. 3112 /// The load address is defined as the address of the first memory 3113 /// region what contains data mapped from the specified file. 3114 /// 3115 /// @param[in] file 3116 /// The name of the file whose load address we are looking for 3117 /// 3118 /// @param[out] is_loaded 3119 /// \b True if the file is loaded into the memory and false 3120 /// otherwise. 3121 /// 3122 /// @param[out] load_addr 3123 /// The load address of the file if it is loaded into the 3124 /// processes address space, LLDB_INVALID_ADDRESS otherwise. 3125 //------------------------------------------------------------------ 3126 virtual Error GetFileLoadAddress(const FileSpec & file,bool & is_loaded,lldb::addr_t & load_addr)3127 GetFileLoadAddress(const FileSpec& file, bool& is_loaded, lldb::addr_t& load_addr) 3128 { 3129 return Error("Not supported"); 3130 } 3131 3132 protected: 3133 3134 //------------------------------------------------------------------ 3135 // NextEventAction provides a way to register an action on the next 3136 // event that is delivered to this process. There is currently only 3137 // one next event action allowed in the process at one time. If a 3138 // new "NextEventAction" is added while one is already present, the 3139 // old action will be discarded (with HandleBeingUnshipped called 3140 // after it is discarded.) 3141 // 3142 // If you want to resume the process as a result of a resume action, 3143 // call RequestResume, don't call Resume directly. 3144 //------------------------------------------------------------------ 3145 class NextEventAction 3146 { 3147 public: 3148 typedef enum EventActionResult 3149 { 3150 eEventActionSuccess, 3151 eEventActionRetry, 3152 eEventActionExit 3153 } EventActionResult; 3154 NextEventAction(Process * process)3155 NextEventAction (Process *process) : 3156 m_process(process) 3157 { 3158 } 3159 3160 virtual ~NextEventAction()3161 ~NextEventAction() 3162 { 3163 } 3164 3165 virtual EventActionResult PerformAction (lldb::EventSP &event_sp) = 0; HandleBeingUnshipped()3166 virtual void HandleBeingUnshipped () {} 3167 virtual EventActionResult HandleBeingInterrupted () = 0; 3168 virtual const char *GetExitString() = 0; RequestResume()3169 void RequestResume() 3170 { 3171 m_process->m_resume_requested = true; 3172 } 3173 protected: 3174 Process *m_process; 3175 }; 3176 SetNextEventAction(Process::NextEventAction * next_event_action)3177 void SetNextEventAction (Process::NextEventAction *next_event_action) 3178 { 3179 if (m_next_event_action_ap.get()) 3180 m_next_event_action_ap->HandleBeingUnshipped(); 3181 3182 m_next_event_action_ap.reset(next_event_action); 3183 } 3184 3185 // This is the completer for Attaching: 3186 class AttachCompletionHandler : public NextEventAction 3187 { 3188 public: 3189 AttachCompletionHandler (Process *process, uint32_t exec_count); 3190 3191 virtual ~AttachCompletionHandler()3192 ~AttachCompletionHandler() 3193 { 3194 } 3195 3196 virtual EventActionResult PerformAction (lldb::EventSP &event_sp); 3197 virtual EventActionResult HandleBeingInterrupted (); 3198 virtual const char *GetExitString(); 3199 private: 3200 uint32_t m_exec_count; 3201 std::string m_exit_string; 3202 }; 3203 3204 bool 3205 HijackPrivateProcessEvents (Listener *listener); 3206 3207 void 3208 RestorePrivateProcessEvents (); 3209 3210 bool PrivateStateThreadIsValid()3211 PrivateStateThreadIsValid () const 3212 { 3213 return m_private_state_thread.IsJoinable(); 3214 } 3215 3216 void ForceNextEventDelivery()3217 ForceNextEventDelivery() 3218 { 3219 m_force_next_event_delivery = true; 3220 } 3221 3222 //------------------------------------------------------------------ 3223 // Type definitions 3224 //------------------------------------------------------------------ 3225 typedef std::map<lldb::LanguageType, lldb::LanguageRuntimeSP> LanguageRuntimeCollection; 3226 3227 struct PreResumeCallbackAndBaton 3228 { 3229 bool (*callback) (void *); 3230 void *baton; PreResumeCallbackAndBatonPreResumeCallbackAndBaton3231 PreResumeCallbackAndBaton (PreResumeActionCallback in_callback, void *in_baton) : 3232 callback (in_callback), 3233 baton (in_baton) 3234 { 3235 } 3236 }; 3237 3238 //------------------------------------------------------------------ 3239 // Member variables 3240 //------------------------------------------------------------------ 3241 Target & m_target; ///< The target that owns this process. 3242 ThreadSafeValue<lldb::StateType> m_public_state; 3243 ThreadSafeValue<lldb::StateType> m_private_state; // The actual state of our process 3244 Broadcaster m_private_state_broadcaster; // This broadcaster feeds state changed events into the private state thread's listener. 3245 Broadcaster m_private_state_control_broadcaster; // This is the control broadcaster, used to pause, resume & stop the private state thread. 3246 Listener m_private_state_listener; // This is the listener for the private state thread. 3247 Predicate<bool> m_private_state_control_wait; /// This Predicate is used to signal that a control operation is complete. 3248 HostThread m_private_state_thread; ///< Thread ID for the thread that watches internal state events 3249 ProcessModID m_mod_id; ///< Tracks the state of the process over stops and other alterations. 3250 uint32_t m_process_unique_id; ///< Each lldb_private::Process class that is created gets a unique integer ID that increments with each new instance 3251 uint32_t m_thread_index_id; ///< Each thread is created with a 1 based index that won't get re-used. 3252 std::map<uint64_t, uint32_t> m_thread_id_to_index_id_map; 3253 int m_exit_status; ///< The exit status of the process, or -1 if not set. 3254 std::string m_exit_string; ///< A textual description of why a process exited. 3255 Mutex m_exit_status_mutex; ///< Mutex so m_exit_status m_exit_string can be safely accessed from multiple threads 3256 Mutex m_thread_mutex; 3257 ThreadList m_thread_list_real; ///< The threads for this process as are known to the protocol we are debugging with 3258 ThreadList m_thread_list; ///< The threads for this process as the user will see them. This is usually the same as 3259 ///< m_thread_list_real, but might be different if there is an OS plug-in creating memory threads 3260 ThreadList m_extended_thread_list; ///< Owner for extended threads that may be generated, cleared on natural stops 3261 uint32_t m_extended_thread_stop_id; ///< The natural stop id when extended_thread_list was last updated 3262 QueueList m_queue_list; ///< The list of libdispatch queues at a given stop point 3263 uint32_t m_queue_list_stop_id; ///< The natural stop id when queue list was last fetched 3264 std::vector<Notifications> m_notifications; ///< The list of notifications that this process can deliver. 3265 std::vector<lldb::addr_t> m_image_tokens; 3266 Listener &m_listener; 3267 BreakpointSiteList m_breakpoint_site_list; ///< This is the list of breakpoint locations we intend to insert in the target. 3268 lldb::DynamicLoaderUP m_dyld_ap; 3269 lldb::JITLoaderListUP m_jit_loaders_ap; 3270 lldb::DynamicCheckerFunctionsUP m_dynamic_checkers_ap; ///< The functions used by the expression parser to validate data that expressions use. 3271 lldb::OperatingSystemUP m_os_ap; 3272 lldb::SystemRuntimeUP m_system_runtime_ap; 3273 lldb::UnixSignalsSP m_unix_signals_sp; /// This is the current signal set for this process. 3274 lldb::ABISP m_abi_sp; 3275 lldb::IOHandlerSP m_process_input_reader; 3276 Communication m_stdio_communication; 3277 Mutex m_stdio_communication_mutex; 3278 bool m_stdin_forward; /// Remember if stdin must be forwarded to remote debug server 3279 std::string m_stdout_data; 3280 std::string m_stderr_data; 3281 Mutex m_profile_data_comm_mutex; 3282 std::vector<std::string> m_profile_data; 3283 Predicate<uint32_t> m_iohandler_sync; 3284 MemoryCache m_memory_cache; 3285 AllocatedMemoryCache m_allocated_memory_cache; 3286 bool m_should_detach; /// Should we detach if the process object goes away with an explicit call to Kill or Detach? 3287 LanguageRuntimeCollection m_language_runtimes; 3288 InstrumentationRuntimeCollection m_instrumentation_runtimes; 3289 std::unique_ptr<NextEventAction> m_next_event_action_ap; 3290 std::vector<PreResumeCallbackAndBaton> m_pre_resume_actions; 3291 ProcessRunLock m_public_run_lock; 3292 ProcessRunLock m_private_run_lock; 3293 Predicate<bool> m_currently_handling_event; // This predicate is set in HandlePrivateEvent while all its business is being done. 3294 ArchSpec::StopInfoOverrideCallbackType m_stop_info_override_callback; 3295 bool m_currently_handling_do_on_removals; 3296 bool m_resume_requested; // If m_currently_handling_event or m_currently_handling_do_on_removals are true, Resume will only request a resume, using this flag to check. 3297 bool m_finalizing; // This is set at the beginning of Process::Finalize() to stop functions from looking up or creating things during a finalize call 3298 bool m_finalize_called; // This is set at the end of Process::Finalize() 3299 bool m_clear_thread_plans_on_stop; 3300 bool m_force_next_event_delivery; 3301 lldb::StateType m_last_broadcast_state; /// This helps with the Public event coalescing in ShouldBroadcastEvent. 3302 std::map<lldb::addr_t,lldb::addr_t> m_resolved_indirect_addresses; 3303 bool m_destroy_in_process; 3304 bool m_can_interpret_function_calls; // Some targets, e.g the OSX kernel, don't support the ability to modify the stack. 3305 3306 enum { 3307 eCanJITDontKnow= 0, 3308 eCanJITYes, 3309 eCanJITNo 3310 } m_can_jit; 3311 3312 size_t 3313 RemoveBreakpointOpcodesFromBuffer (lldb::addr_t addr, size_t size, uint8_t *buf) const; 3314 3315 void 3316 SynchronouslyNotifyStateChanged (lldb::StateType state); 3317 3318 void 3319 SetPublicState (lldb::StateType new_state, bool restarted); 3320 3321 void 3322 SetPrivateState (lldb::StateType state); 3323 3324 bool 3325 StartPrivateStateThread (bool is_secondary_thread = false); 3326 3327 void 3328 StopPrivateStateThread (); 3329 3330 void 3331 PausePrivateStateThread (); 3332 3333 void 3334 ResumePrivateStateThread (); 3335 3336 struct PrivateStateThreadArgs 3337 { 3338 Process *process; 3339 bool is_secondary_thread; 3340 }; 3341 3342 static lldb::thread_result_t 3343 PrivateStateThread (void *arg); 3344 3345 // The starts up the private state thread that will watch for events from the debugee. 3346 // Pass true for is_secondary_thread in the case where you have to temporarily spin up a 3347 // secondary state thread to handle events from a hand-called function on the primary 3348 // private state thread. 3349 3350 lldb::thread_result_t 3351 RunPrivateStateThread (bool is_secondary_thread); 3352 3353 void 3354 HandlePrivateEvent (lldb::EventSP &event_sp); 3355 3356 lldb::StateType 3357 WaitForProcessStopPrivate (const TimeValue *timeout, lldb::EventSP &event_sp); 3358 3359 // This waits for both the state change broadcaster, and the control broadcaster. 3360 // If control_only, it only waits for the control broadcaster. 3361 3362 bool 3363 WaitForEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp, bool control_only); 3364 3365 lldb::StateType 3366 WaitForStateChangedEventsPrivate (const TimeValue *timeout, lldb::EventSP &event_sp); 3367 3368 lldb::StateType 3369 WaitForState (const TimeValue *timeout, 3370 const lldb::StateType *match_states, 3371 const uint32_t num_match_states); 3372 3373 size_t 3374 WriteMemoryPrivate (lldb::addr_t addr, const void *buf, size_t size, Error &error); 3375 3376 void 3377 AppendSTDOUT (const char *s, size_t len); 3378 3379 void 3380 AppendSTDERR (const char *s, size_t len); 3381 3382 void 3383 BroadcastAsyncProfileData(const std::string &one_profile_data); 3384 3385 static void 3386 STDIOReadThreadBytesReceived (void *baton, const void *src, size_t src_len); 3387 3388 bool 3389 PushProcessIOHandler (); 3390 3391 bool 3392 PopProcessIOHandler (); 3393 3394 bool 3395 ProcessIOHandlerIsActive (); 3396 3397 bool ProcessIOHandlerExists()3398 ProcessIOHandlerExists () const 3399 { 3400 return static_cast<bool>(m_process_input_reader); 3401 } 3402 3403 Error 3404 HaltForDestroyOrDetach(lldb::EventSP &exit_event_sp); 3405 3406 bool 3407 StateChangedIsExternallyHijacked(); 3408 3409 void 3410 LoadOperatingSystemPlugin(bool flush); 3411 private: 3412 //------------------------------------------------------------------ 3413 // For Process only 3414 //------------------------------------------------------------------ 3415 void ControlPrivateStateThread (uint32_t signal); 3416 3417 DISALLOW_COPY_AND_ASSIGN (Process); 3418 3419 }; 3420 3421 } // namespace lldb_private 3422 3423 #endif // liblldb_Process_h_ 3424