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