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