ProcessMonitor.cpp revision 5e91e379b3be10738ab5aeae87b47001de16cd7c
1//===-- ProcessMonitor.cpp ------------------------------------ -*- 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// C Includes 11#include <errno.h> 12#include <poll.h> 13#include <string.h> 14#include <unistd.h> 15#include <sys/ptrace.h> 16#include <sys/socket.h> 17#include <sys/types.h> 18#include <sys/user.h> 19#include <sys/wait.h> 20 21// C++ Includes 22// Other libraries and framework includes 23#include "lldb/Core/Debugger.h" 24#include "lldb/Core/Error.h" 25#include "lldb/Core/RegisterValue.h" 26#include "lldb/Core/Scalar.h" 27#include "lldb/Host/Host.h" 28#include "lldb/Target/Thread.h" 29#include "lldb/Target/RegisterContext.h" 30#include "lldb/Utility/PseudoTerminal.h" 31 32#include "POSIXThread.h" 33#include "ProcessLinux.h" 34#include "ProcessPOSIXLog.h" 35#include "ProcessMonitor.h" 36 37 38#define DEBUG_PTRACE_MAXBYTES 20 39 40using namespace lldb_private; 41 42// FIXME: this code is host-dependent with respect to types and 43// endianness and needs to be fixed. For example, lldb::addr_t is 44// hard-coded to uint64_t, but on a 32-bit Linux host, ptrace requires 45// 32-bit pointer arguments. This code uses casts to work around the 46// problem. 47 48// We disable the tracing of ptrace calls for integration builds to 49// avoid the additional indirection and checks. 50#ifndef LLDB_CONFIGURATION_BUILDANDINTEGRATION 51 52static void 53DisplayBytes (lldb_private::StreamString &s, void *bytes, uint32_t count) 54{ 55 uint8_t *ptr = (uint8_t *)bytes; 56 const uint32_t loop_count = std::min<uint32_t>(DEBUG_PTRACE_MAXBYTES, count); 57 for(uint32_t i=0; i<loop_count; i++) 58 { 59 s.Printf ("[%x]", *ptr); 60 ptr++; 61 } 62} 63 64static void PtraceDisplayBytes(__ptrace_request &req, void *data) 65{ 66 StreamString buf; 67 LogSP verbose_log (ProcessPOSIXLog::GetLogIfAllCategoriesSet ( 68 POSIX_LOG_PTRACE | POSIX_LOG_VERBOSE)); 69 70 if (verbose_log) 71 { 72 switch(req) 73 { 74 case PTRACE_POKETEXT: 75 { 76 DisplayBytes(buf, &data, 8); 77 verbose_log->Printf("PTRACE_POKETEXT %s", buf.GetData()); 78 break; 79 } 80 case PTRACE_POKEDATA: 81 { 82 DisplayBytes(buf, &data, 8); 83 verbose_log->Printf("PTRACE_POKEDATA %s", buf.GetData()); 84 break; 85 } 86 case PTRACE_POKEUSER: 87 { 88 DisplayBytes(buf, &data, 8); 89 verbose_log->Printf("PTRACE_POKEUSER %s", buf.GetData()); 90 break; 91 } 92 case PTRACE_SETREGS: 93 { 94 DisplayBytes(buf, data, sizeof(user_regs_struct)); 95 verbose_log->Printf("PTRACE_SETREGS %s", buf.GetData()); 96 break; 97 } 98 case PTRACE_SETFPREGS: 99 { 100 DisplayBytes(buf, data, sizeof(user_fpregs_struct)); 101 verbose_log->Printf("PTRACE_SETFPREGS %s", buf.GetData()); 102 break; 103 } 104 case PTRACE_SETSIGINFO: 105 { 106 DisplayBytes(buf, data, sizeof(siginfo_t)); 107 verbose_log->Printf("PTRACE_SETSIGINFO %s", buf.GetData()); 108 break; 109 } 110 default: 111 { 112 } 113 } 114 } 115} 116 117// Wrapper for ptrace to catch errors and log calls. 118extern long 119PtraceWrapper(__ptrace_request req, pid_t pid, void *addr, void *data, 120 const char* reqName, const char* file, int line) 121{ 122 long int result; 123 124 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PTRACE)); 125 126 if (log) 127 log->Printf("ptrace(%s, %u, %p, %p) called from file %s line %d", 128 reqName, pid, addr, data, file, line); 129 130 PtraceDisplayBytes(req, data); 131 132 errno = 0; 133 result = ptrace(req, pid, addr, data); 134 135 PtraceDisplayBytes(req, data); 136 137 if (log && (result == -1 || errno != 0)) 138 { 139 const char* str; 140 switch (errno) 141 { 142 case ESRCH: str = "ESRCH"; break; 143 case EINVAL: str = "EINVAL"; break; 144 case EBUSY: str = "EBUSY"; break; 145 case EPERM: str = "EPERM"; break; 146 default: str = "<unknown>"; 147 } 148 log->Printf("ptrace() failed; errno=%d (%s)", errno, str); 149 } 150 151 return result; 152} 153 154#define PTRACE(req, pid, addr, data) \ 155 PtraceWrapper((req), (pid), (addr), (data), #req, __FILE__, __LINE__) 156#else 157#define PTRACE ptrace 158#endif 159 160//------------------------------------------------------------------------------ 161// Static implementations of ProcessMonitor::ReadMemory and 162// ProcessMonitor::WriteMemory. This enables mutual recursion between these 163// functions without needed to go thru the thread funnel. 164 165static size_t 166DoReadMemory(lldb::pid_t pid, 167 lldb::addr_t vm_addr, void *buf, size_t size, Error &error) 168{ 169 // ptrace word size is determined by the host, not the child 170 static const unsigned word_size = sizeof(void*); 171 unsigned char *dst = static_cast<unsigned char*>(buf); 172 size_t bytes_read; 173 size_t remainder; 174 long data; 175 176 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL)); 177 if (log) 178 ProcessPOSIXLog::IncNestLevel(); 179 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY)) 180 log->Printf ("ProcessMonitor::%s(%d, %d, %p, %p, %d, _)", __FUNCTION__, 181 pid, word_size, (void*)vm_addr, buf, size); 182 183 assert(sizeof(data) >= word_size); 184 for (bytes_read = 0; bytes_read < size; bytes_read += remainder) 185 { 186 errno = 0; 187 data = PTRACE(PTRACE_PEEKDATA, pid, (void*)vm_addr, NULL); 188 if (data == -1L && errno) 189 { 190 error.SetErrorToErrno(); 191 if (log) 192 ProcessPOSIXLog::DecNestLevel(); 193 return bytes_read; 194 } 195 196 remainder = size - bytes_read; 197 remainder = remainder > word_size ? word_size : remainder; 198 199 // Copy the data into our buffer 200 if (log) 201 memset(dst, 0, sizeof(dst)); 202 for (unsigned i = 0; i < remainder; ++i) 203 dst[i] = ((data >> i*8) & 0xFF); 204 205 if (log && ProcessPOSIXLog::AtTopNestLevel() && 206 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 207 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 208 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 209 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 210 (void*)vm_addr, *(unsigned long*)dst, (unsigned long)data); 211 212 vm_addr += word_size; 213 dst += word_size; 214 } 215 216 if (log) 217 ProcessPOSIXLog::DecNestLevel(); 218 return bytes_read; 219} 220 221static size_t 222DoWriteMemory(lldb::pid_t pid, 223 lldb::addr_t vm_addr, const void *buf, size_t size, Error &error) 224{ 225 // ptrace word size is determined by the host, not the child 226 static const unsigned word_size = sizeof(void*); 227 const unsigned char *src = static_cast<const unsigned char*>(buf); 228 size_t bytes_written = 0; 229 size_t remainder; 230 231 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_ALL)); 232 if (log) 233 ProcessPOSIXLog::IncNestLevel(); 234 if (log && ProcessPOSIXLog::AtTopNestLevel() && log->GetMask().Test(POSIX_LOG_MEMORY)) 235 log->Printf ("ProcessMonitor::%s(%d, %d, %p, %p, %d, _)", __FUNCTION__, 236 pid, word_size, (void*)vm_addr, buf, size); 237 238 for (bytes_written = 0; bytes_written < size; bytes_written += remainder) 239 { 240 remainder = size - bytes_written; 241 remainder = remainder > word_size ? word_size : remainder; 242 243 if (remainder == word_size) 244 { 245 unsigned long data = 0; 246 assert(sizeof(data) >= word_size); 247 for (unsigned i = 0; i < word_size; ++i) 248 data |= (unsigned long)src[i] << i*8; 249 250 if (log && ProcessPOSIXLog::AtTopNestLevel() && 251 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 252 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 253 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 254 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 255 (void*)vm_addr, *(unsigned long*)src, data); 256 257 if (PTRACE(PTRACE_POKEDATA, pid, (void*)vm_addr, (void*)data)) 258 { 259 error.SetErrorToErrno(); 260 if (log) 261 ProcessPOSIXLog::DecNestLevel(); 262 return bytes_written; 263 } 264 } 265 else 266 { 267 unsigned char buff[8]; 268 if (DoReadMemory(pid, vm_addr, 269 buff, word_size, error) != word_size) 270 { 271 if (log) 272 ProcessPOSIXLog::DecNestLevel(); 273 return bytes_written; 274 } 275 276 memcpy(buff, src, remainder); 277 278 if (DoWriteMemory(pid, vm_addr, 279 buff, word_size, error) != word_size) 280 { 281 if (log) 282 ProcessPOSIXLog::DecNestLevel(); 283 return bytes_written; 284 } 285 286 if (log && ProcessPOSIXLog::AtTopNestLevel() && 287 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_LONG) || 288 (log->GetMask().Test(POSIX_LOG_MEMORY_DATA_SHORT) && 289 size <= POSIX_LOG_MEMORY_SHORT_BYTES))) 290 log->Printf ("ProcessMonitor::%s() [%p]:0x%lx (0x%lx)", __FUNCTION__, 291 (void*)vm_addr, *(unsigned long*)src, *(unsigned long*)buff); 292 } 293 294 vm_addr += word_size; 295 src += word_size; 296 } 297 if (log) 298 ProcessPOSIXLog::DecNestLevel(); 299 return bytes_written; 300} 301 302// Simple helper function to ensure flags are enabled on the given file 303// descriptor. 304static bool 305EnsureFDFlags(int fd, int flags, Error &error) 306{ 307 int status; 308 309 if ((status = fcntl(fd, F_GETFL)) == -1) 310 { 311 error.SetErrorToErrno(); 312 return false; 313 } 314 315 if (fcntl(fd, F_SETFL, status | flags) == -1) 316 { 317 error.SetErrorToErrno(); 318 return false; 319 } 320 321 return true; 322} 323 324//------------------------------------------------------------------------------ 325/// @class Operation 326/// @brief Represents a ProcessMonitor operation. 327/// 328/// Under Linux, it is not possible to ptrace() from any other thread but the 329/// one that spawned or attached to the process from the start. Therefore, when 330/// a ProcessMonitor is asked to deliver or change the state of an inferior 331/// process the operation must be "funneled" to a specific thread to perform the 332/// task. The Operation class provides an abstract base for all services the 333/// ProcessMonitor must perform via the single virtual function Execute, thus 334/// encapsulating the code that needs to run in the privileged context. 335class Operation 336{ 337public: 338 virtual void Execute(ProcessMonitor *monitor) = 0; 339}; 340 341//------------------------------------------------------------------------------ 342/// @class ReadOperation 343/// @brief Implements ProcessMonitor::ReadMemory. 344class ReadOperation : public Operation 345{ 346public: 347 ReadOperation(lldb::addr_t addr, void *buff, size_t size, 348 Error &error, size_t &result) 349 : m_addr(addr), m_buff(buff), m_size(size), 350 m_error(error), m_result(result) 351 { } 352 353 void Execute(ProcessMonitor *monitor); 354 355private: 356 lldb::addr_t m_addr; 357 void *m_buff; 358 size_t m_size; 359 Error &m_error; 360 size_t &m_result; 361}; 362 363void 364ReadOperation::Execute(ProcessMonitor *monitor) 365{ 366 lldb::pid_t pid = monitor->GetPID(); 367 368 m_result = DoReadMemory(pid, m_addr, m_buff, m_size, m_error); 369} 370 371//------------------------------------------------------------------------------ 372/// @class ReadOperation 373/// @brief Implements ProcessMonitor::WriteMemory. 374class WriteOperation : public Operation 375{ 376public: 377 WriteOperation(lldb::addr_t addr, const void *buff, size_t size, 378 Error &error, size_t &result) 379 : m_addr(addr), m_buff(buff), m_size(size), 380 m_error(error), m_result(result) 381 { } 382 383 void Execute(ProcessMonitor *monitor); 384 385private: 386 lldb::addr_t m_addr; 387 const void *m_buff; 388 size_t m_size; 389 Error &m_error; 390 size_t &m_result; 391}; 392 393void 394WriteOperation::Execute(ProcessMonitor *monitor) 395{ 396 lldb::pid_t pid = monitor->GetPID(); 397 398 m_result = DoWriteMemory(pid, m_addr, m_buff, m_size, m_error); 399} 400 401 402//------------------------------------------------------------------------------ 403/// @class ReadRegOperation 404/// @brief Implements ProcessMonitor::ReadRegisterValue. 405class ReadRegOperation : public Operation 406{ 407public: 408 ReadRegOperation(unsigned offset, RegisterValue &value, bool &result) 409 : m_offset(offset), m_value(value), m_result(result) 410 { } 411 412 void Execute(ProcessMonitor *monitor); 413 414private: 415 unsigned m_offset; 416 RegisterValue &m_value; 417 bool &m_result; 418}; 419 420void 421ReadRegOperation::Execute(ProcessMonitor *monitor) 422{ 423 lldb::pid_t pid = monitor->GetPID(); 424 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS)); 425 426 // Set errno to zero so that we can detect a failed peek. 427 errno = 0; 428 lldb::addr_t data = PTRACE(PTRACE_PEEKUSER, pid, (void*)m_offset, NULL); 429 if (data == -1UL && errno) 430 m_result = false; 431 else 432 { 433 m_value = data; 434 m_result = true; 435 } 436 if (log) 437 log->Printf ("ProcessMonitor::%s() reg %s: 0x%x", __FUNCTION__, 438 POSIXThread::GetRegisterNameFromOffset(m_offset), data); 439} 440 441//------------------------------------------------------------------------------ 442/// @class WriteRegOperation 443/// @brief Implements ProcessMonitor::WriteRegisterValue. 444class WriteRegOperation : public Operation 445{ 446public: 447 WriteRegOperation(unsigned offset, const RegisterValue &value, bool &result) 448 : m_offset(offset), m_value(value), m_result(result) 449 { } 450 451 void Execute(ProcessMonitor *monitor); 452 453private: 454 unsigned m_offset; 455 const RegisterValue &m_value; 456 bool &m_result; 457}; 458 459void 460WriteRegOperation::Execute(ProcessMonitor *monitor) 461{ 462 void* buf; 463 lldb::pid_t pid = monitor->GetPID(); 464 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_REGISTERS)); 465 466 if (sizeof(void*) == sizeof(uint64_t)) 467 buf = (void*) m_value.GetAsUInt64(); 468 else 469 { 470 assert(sizeof(void*) == sizeof(uint32_t)); 471 buf = (void*) m_value.GetAsUInt32(); 472 } 473 474 if (log) 475 log->Printf ("ProcessMonitor::%s() reg %s: %p", __FUNCTION__, 476 POSIXThread::GetRegisterNameFromOffset(m_offset), buf); 477 if (PTRACE(PTRACE_POKEUSER, pid, (void*)m_offset, buf)) 478 m_result = false; 479 else 480 m_result = true; 481} 482 483//------------------------------------------------------------------------------ 484/// @class ReadGPROperation 485/// @brief Implements ProcessMonitor::ReadGPR. 486class ReadGPROperation : public Operation 487{ 488public: 489 ReadGPROperation(void *buf, bool &result) 490 : m_buf(buf), m_result(result) 491 { } 492 493 void Execute(ProcessMonitor *monitor); 494 495private: 496 void *m_buf; 497 bool &m_result; 498}; 499 500void 501ReadGPROperation::Execute(ProcessMonitor *monitor) 502{ 503 if (PTRACE(PTRACE_GETREGS, monitor->GetPID(), NULL, m_buf) < 0) 504 m_result = false; 505 else 506 m_result = true; 507} 508 509//------------------------------------------------------------------------------ 510/// @class ReadFPROperation 511/// @brief Implements ProcessMonitor::ReadFPR. 512class ReadFPROperation : public Operation 513{ 514public: 515 ReadFPROperation(void *buf, bool &result) 516 : m_buf(buf), m_result(result) 517 { } 518 519 void Execute(ProcessMonitor *monitor); 520 521private: 522 void *m_buf; 523 bool &m_result; 524}; 525 526void 527ReadFPROperation::Execute(ProcessMonitor *monitor) 528{ 529 if (PTRACE(PTRACE_GETFPREGS, monitor->GetPID(), NULL, m_buf) < 0) 530 m_result = false; 531 else 532 m_result = true; 533} 534 535//------------------------------------------------------------------------------ 536/// @class WriteGPROperation 537/// @brief Implements ProcessMonitor::WriteGPR. 538class WriteGPROperation : public Operation 539{ 540public: 541 WriteGPROperation(void *buf, bool &result) 542 : m_buf(buf), m_result(result) 543 { } 544 545 void Execute(ProcessMonitor *monitor); 546 547private: 548 void *m_buf; 549 bool &m_result; 550}; 551 552void 553WriteGPROperation::Execute(ProcessMonitor *monitor) 554{ 555 if (PTRACE(PTRACE_SETREGS, monitor->GetPID(), NULL, m_buf) < 0) 556 m_result = false; 557 else 558 m_result = true; 559} 560 561//------------------------------------------------------------------------------ 562/// @class WriteFPROperation 563/// @brief Implements ProcessMonitor::WriteFPR. 564class WriteFPROperation : public Operation 565{ 566public: 567 WriteFPROperation(void *buf, bool &result) 568 : m_buf(buf), m_result(result) 569 { } 570 571 void Execute(ProcessMonitor *monitor); 572 573private: 574 void *m_buf; 575 bool &m_result; 576}; 577 578void 579WriteFPROperation::Execute(ProcessMonitor *monitor) 580{ 581 if (PTRACE(PTRACE_SETFPREGS, monitor->GetPID(), NULL, m_buf) < 0) 582 m_result = false; 583 else 584 m_result = true; 585} 586 587//------------------------------------------------------------------------------ 588/// @class ResumeOperation 589/// @brief Implements ProcessMonitor::Resume. 590class ResumeOperation : public Operation 591{ 592public: 593 ResumeOperation(lldb::tid_t tid, uint32_t signo, bool &result) : 594 m_tid(tid), m_signo(signo), m_result(result) { } 595 596 void Execute(ProcessMonitor *monitor); 597 598private: 599 lldb::tid_t m_tid; 600 uint32_t m_signo; 601 bool &m_result; 602}; 603 604void 605ResumeOperation::Execute(ProcessMonitor *monitor) 606{ 607 int data = 0; 608 609 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER) 610 data = m_signo; 611 612 if (PTRACE(PTRACE_CONT, m_tid, NULL, (void*)data)) 613 m_result = false; 614 else 615 m_result = true; 616} 617 618//------------------------------------------------------------------------------ 619/// @class ResumeOperation 620/// @brief Implements ProcessMonitor::SingleStep. 621class SingleStepOperation : public Operation 622{ 623public: 624 SingleStepOperation(lldb::tid_t tid, uint32_t signo, bool &result) 625 : m_tid(tid), m_signo(signo), m_result(result) { } 626 627 void Execute(ProcessMonitor *monitor); 628 629private: 630 lldb::tid_t m_tid; 631 uint32_t m_signo; 632 bool &m_result; 633}; 634 635void 636SingleStepOperation::Execute(ProcessMonitor *monitor) 637{ 638 int data = 0; 639 640 if (m_signo != LLDB_INVALID_SIGNAL_NUMBER) 641 data = m_signo; 642 643 if (PTRACE(PTRACE_SINGLESTEP, m_tid, NULL, (void*)data)) 644 m_result = false; 645 else 646 m_result = true; 647} 648 649//------------------------------------------------------------------------------ 650/// @class SiginfoOperation 651/// @brief Implements ProcessMonitor::GetSignalInfo. 652class SiginfoOperation : public Operation 653{ 654public: 655 SiginfoOperation(lldb::tid_t tid, void *info, bool &result) 656 : m_tid(tid), m_info(info), m_result(result) { } 657 658 void Execute(ProcessMonitor *monitor); 659 660private: 661 lldb::tid_t m_tid; 662 void *m_info; 663 bool &m_result; 664}; 665 666void 667SiginfoOperation::Execute(ProcessMonitor *monitor) 668{ 669 if (PTRACE(PTRACE_GETSIGINFO, m_tid, NULL, m_info)) 670 m_result = false; 671 else 672 m_result = true; 673} 674 675//------------------------------------------------------------------------------ 676/// @class EventMessageOperation 677/// @brief Implements ProcessMonitor::GetEventMessage. 678class EventMessageOperation : public Operation 679{ 680public: 681 EventMessageOperation(lldb::tid_t tid, unsigned long *message, bool &result) 682 : m_tid(tid), m_message(message), m_result(result) { } 683 684 void Execute(ProcessMonitor *monitor); 685 686private: 687 lldb::tid_t m_tid; 688 unsigned long *m_message; 689 bool &m_result; 690}; 691 692void 693EventMessageOperation::Execute(ProcessMonitor *monitor) 694{ 695 if (PTRACE(PTRACE_GETEVENTMSG, m_tid, NULL, m_message)) 696 m_result = false; 697 else 698 m_result = true; 699} 700 701//------------------------------------------------------------------------------ 702/// @class KillOperation 703/// @brief Implements ProcessMonitor::BringProcessIntoLimbo. 704class KillOperation : public Operation 705{ 706public: 707 KillOperation(bool &result) : m_result(result) { } 708 709 void Execute(ProcessMonitor *monitor); 710 711private: 712 bool &m_result; 713}; 714 715void 716KillOperation::Execute(ProcessMonitor *monitor) 717{ 718 lldb::pid_t pid = monitor->GetPID(); 719 720 if (PTRACE(PTRACE_KILL, pid, NULL, NULL)) 721 m_result = false; 722 else 723 m_result = true; 724} 725 726//------------------------------------------------------------------------------ 727/// @class KillOperation 728/// @brief Implements ProcessMonitor::BringProcessIntoLimbo. 729class DetachOperation : public Operation 730{ 731public: 732 DetachOperation(Error &result) : m_error(result) { } 733 734 void Execute(ProcessMonitor *monitor); 735 736private: 737 Error &m_error; 738}; 739 740void 741DetachOperation::Execute(ProcessMonitor *monitor) 742{ 743 lldb::pid_t pid = monitor->GetPID(); 744 745 if (ptrace(PT_DETACH, pid, NULL, 0) < 0) 746 m_error.SetErrorToErrno(); 747 748} 749 750ProcessMonitor::OperationArgs::OperationArgs(ProcessMonitor *monitor) 751 : m_monitor(monitor) 752{ 753 sem_init(&m_semaphore, 0, 0); 754} 755 756ProcessMonitor::OperationArgs::~OperationArgs() 757{ 758 sem_destroy(&m_semaphore); 759} 760 761ProcessMonitor::LaunchArgs::LaunchArgs(ProcessMonitor *monitor, 762 lldb_private::Module *module, 763 char const **argv, 764 char const **envp, 765 const char *stdin_path, 766 const char *stdout_path, 767 const char *stderr_path) 768 : OperationArgs(monitor), 769 m_module(module), 770 m_argv(argv), 771 m_envp(envp), 772 m_stdin_path(stdin_path), 773 m_stdout_path(stdout_path), 774 m_stderr_path(stderr_path) { } 775 776ProcessMonitor::LaunchArgs::~LaunchArgs() 777{ } 778 779ProcessMonitor::AttachArgs::AttachArgs(ProcessMonitor *monitor, 780 lldb::pid_t pid) 781 : OperationArgs(monitor), m_pid(pid) { } 782 783ProcessMonitor::AttachArgs::~AttachArgs() 784{ } 785 786//------------------------------------------------------------------------------ 787/// The basic design of the ProcessMonitor is built around two threads. 788/// 789/// One thread (@see SignalThread) simply blocks on a call to waitpid() looking 790/// for changes in the debugee state. When a change is detected a 791/// ProcessMessage is sent to the associated ProcessLinux instance. This thread 792/// "drives" state changes in the debugger. 793/// 794/// The second thread (@see OperationThread) is responsible for two things 1) 795/// launching or attaching to the inferior process, and then 2) servicing 796/// operations such as register reads/writes, stepping, etc. See the comments 797/// on the Operation class for more info as to why this is needed. 798ProcessMonitor::ProcessMonitor(ProcessPOSIX *process, 799 Module *module, 800 const char *argv[], 801 const char *envp[], 802 const char *stdin_path, 803 const char *stdout_path, 804 const char *stderr_path, 805 lldb_private::Error &error) 806 : m_process(static_cast<ProcessLinux *>(process)), 807 m_operation_thread(LLDB_INVALID_HOST_THREAD), 808 m_pid(LLDB_INVALID_PROCESS_ID), 809 m_terminal_fd(-1), 810 m_monitor_thread(LLDB_INVALID_HOST_THREAD), 811 m_client_fd(-1), 812 m_server_fd(-1) 813{ 814 std::auto_ptr<LaunchArgs> args; 815 816 args.reset(new LaunchArgs(this, module, argv, envp, 817 stdin_path, stdout_path, stderr_path)); 818 819 // Server/client descriptors. 820 if (!EnableIPC()) 821 { 822 error.SetErrorToGenericError(); 823 error.SetErrorString("Monitor failed to initialize."); 824 } 825 826 StartLaunchOpThread(args.get(), error); 827 if (!error.Success()) 828 return; 829 830WAIT_AGAIN: 831 // Wait for the operation thread to initialize. 832 if (sem_wait(&args->m_semaphore)) 833 { 834 if (errno == EINTR) 835 goto WAIT_AGAIN; 836 else 837 { 838 error.SetErrorToErrno(); 839 return; 840 } 841 } 842 843 // Check that the launch was a success. 844 if (!args->m_error.Success()) 845 { 846 StopLaunchOpThread(); 847 error = args->m_error; 848 return; 849 } 850 851 // Finally, start monitoring the child process for change in state. 852 m_monitor_thread = Host::StartMonitoringChildProcess( 853 ProcessMonitor::MonitorCallback, this, GetPID(), true); 854 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread)) 855 { 856 error.SetErrorToGenericError(); 857 error.SetErrorString("Process launch failed."); 858 return; 859 } 860} 861 862ProcessMonitor::ProcessMonitor(ProcessPOSIX *process, 863 lldb::pid_t pid, 864 lldb_private::Error &error) 865 : m_process(static_cast<ProcessLinux *>(process)), 866 m_operation_thread(LLDB_INVALID_HOST_THREAD), 867 m_pid(LLDB_INVALID_PROCESS_ID), 868 m_terminal_fd(-1), 869 m_monitor_thread(LLDB_INVALID_HOST_THREAD), 870 m_client_fd(-1), 871 m_server_fd(-1) 872{ 873 std::auto_ptr<AttachArgs> args; 874 875 args.reset(new AttachArgs(this, pid)); 876 877 // Server/client descriptors. 878 if (!EnableIPC()) 879 { 880 error.SetErrorToGenericError(); 881 error.SetErrorString("Monitor failed to initialize."); 882 } 883 884 StartAttachOpThread(args.get(), error); 885 if (!error.Success()) 886 return; 887 888WAIT_AGAIN: 889 // Wait for the operation thread to initialize. 890 if (sem_wait(&args->m_semaphore)) 891 { 892 if (errno == EINTR) 893 goto WAIT_AGAIN; 894 else 895 { 896 error.SetErrorToErrno(); 897 return; 898 } 899 } 900 901 // Check that the launch was a success. 902 if (!args->m_error.Success()) 903 { 904 StopAttachOpThread(); 905 error = args->m_error; 906 return; 907 } 908 909 // Finally, start monitoring the child process for change in state. 910 m_monitor_thread = Host::StartMonitoringChildProcess( 911 ProcessMonitor::MonitorCallback, this, GetPID(), true); 912 if (!IS_VALID_LLDB_HOST_THREAD(m_monitor_thread)) 913 { 914 error.SetErrorToGenericError(); 915 error.SetErrorString("Process attach failed."); 916 return; 917 } 918} 919 920ProcessMonitor::~ProcessMonitor() 921{ 922 StopMonitor(); 923} 924 925//------------------------------------------------------------------------------ 926// Thread setup and tear down. 927void 928ProcessMonitor::StartLaunchOpThread(LaunchArgs *args, Error &error) 929{ 930 static const char *g_thread_name = "lldb.process.linux.operation"; 931 932 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread)) 933 return; 934 935 m_operation_thread = 936 Host::ThreadCreate(g_thread_name, LaunchOpThread, args, &error); 937} 938 939void 940ProcessMonitor::StopLaunchOpThread() 941{ 942 lldb::thread_result_t result; 943 944 if (!IS_VALID_LLDB_HOST_THREAD(m_operation_thread)) 945 return; 946 947 Host::ThreadCancel(m_operation_thread, NULL); 948 Host::ThreadJoin(m_operation_thread, &result, NULL); 949} 950 951void * 952ProcessMonitor::LaunchOpThread(void *arg) 953{ 954 LaunchArgs *args = static_cast<LaunchArgs*>(arg); 955 956 if (!Launch(args)) { 957 sem_post(&args->m_semaphore); 958 return NULL; 959 } 960 961 ServeOperation(args); 962 return NULL; 963} 964 965bool 966ProcessMonitor::Launch(LaunchArgs *args) 967{ 968 ProcessMonitor *monitor = args->m_monitor; 969 ProcessLinux &process = monitor->GetProcess(); 970 const char **argv = args->m_argv; 971 const char **envp = args->m_envp; 972 const char *stdin_path = args->m_stdin_path; 973 const char *stdout_path = args->m_stdout_path; 974 const char *stderr_path = args->m_stderr_path; 975 976 lldb_utility::PseudoTerminal terminal; 977 const size_t err_len = 1024; 978 char err_str[err_len]; 979 lldb::pid_t pid; 980 981 lldb::ThreadSP inferior; 982 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS)); 983 984 // Propagate the environment if one is not supplied. 985 if (envp == NULL || envp[0] == NULL) 986 envp = const_cast<const char **>(environ); 987 988 // Pseudo terminal setup. 989 if (!terminal.OpenFirstAvailableMaster(O_RDWR | O_NOCTTY, err_str, err_len)) 990 { 991 args->m_error.SetErrorToGenericError(); 992 args->m_error.SetErrorString("Could not open controlling TTY."); 993 goto FINISH; 994 } 995 996 if ((pid = terminal.Fork(err_str, err_len)) < 0) 997 { 998 args->m_error.SetErrorToGenericError(); 999 args->m_error.SetErrorString("Process fork failed."); 1000 goto FINISH; 1001 } 1002 1003 // Recognized child exit status codes. 1004 enum { 1005 ePtraceFailed = 1, 1006 eDupStdinFailed, 1007 eDupStdoutFailed, 1008 eDupStderrFailed, 1009 eExecFailed 1010 }; 1011 1012 // Child process. 1013 if (pid == 0) 1014 { 1015 // Trace this process. 1016 if (PTRACE(PTRACE_TRACEME, 0, NULL, NULL) < 0) 1017 exit(ePtraceFailed); 1018 1019 // Do not inherit setgid powers. 1020 setgid(getgid()); 1021 1022 // Let us have our own process group. 1023 setpgid(0, 0); 1024 1025 // Dup file descriptors if needed. 1026 // 1027 // FIXME: If two or more of the paths are the same we needlessly open 1028 // the same file multiple times. 1029 if (stdin_path != NULL && stdin_path[0]) 1030 if (!DupDescriptor(stdin_path, STDIN_FILENO, O_RDONLY)) 1031 exit(eDupStdinFailed); 1032 1033 if (stdout_path != NULL && stdout_path[0]) 1034 if (!DupDescriptor(stdout_path, STDOUT_FILENO, O_WRONLY | O_CREAT)) 1035 exit(eDupStdoutFailed); 1036 1037 if (stderr_path != NULL && stderr_path[0]) 1038 if (!DupDescriptor(stderr_path, STDERR_FILENO, O_WRONLY | O_CREAT)) 1039 exit(eDupStderrFailed); 1040 1041 // Execute. We should never return. 1042 execve(argv[0], 1043 const_cast<char *const *>(argv), 1044 const_cast<char *const *>(envp)); 1045 exit(eExecFailed); 1046 } 1047 1048 // Wait for the child process to to trap on its call to execve. 1049 pid_t wpid; 1050 int status; 1051 if ((wpid = waitpid(pid, &status, 0)) < 0) 1052 { 1053 args->m_error.SetErrorToErrno(); 1054 goto FINISH; 1055 } 1056 else if (WIFEXITED(status)) 1057 { 1058 // open, dup or execve likely failed for some reason. 1059 args->m_error.SetErrorToGenericError(); 1060 switch (WEXITSTATUS(status)) 1061 { 1062 case ePtraceFailed: 1063 args->m_error.SetErrorString("Child ptrace failed."); 1064 break; 1065 case eDupStdinFailed: 1066 args->m_error.SetErrorString("Child open stdin failed."); 1067 break; 1068 case eDupStdoutFailed: 1069 args->m_error.SetErrorString("Child open stdout failed."); 1070 break; 1071 case eDupStderrFailed: 1072 args->m_error.SetErrorString("Child open stderr failed."); 1073 break; 1074 case eExecFailed: 1075 args->m_error.SetErrorString("Child exec failed."); 1076 break; 1077 default: 1078 args->m_error.SetErrorString("Child returned unknown exit status."); 1079 break; 1080 } 1081 goto FINISH; 1082 } 1083 assert(WIFSTOPPED(status) && wpid == pid && 1084 "Could not sync with inferior process."); 1085 1086 // Have the child raise an event on exit. This is used to keep the child in 1087 // limbo until it is destroyed. 1088 if (PTRACE(PTRACE_SETOPTIONS, pid, NULL, (void*)PTRACE_O_TRACEEXIT) < 0) 1089 { 1090 args->m_error.SetErrorToErrno(); 1091 goto FINISH; 1092 } 1093 1094 // Release the master terminal descriptor and pass it off to the 1095 // ProcessMonitor instance. Similarly stash the inferior pid. 1096 monitor->m_terminal_fd = terminal.ReleaseMasterFileDescriptor(); 1097 monitor->m_pid = pid; 1098 1099 // Set the terminal fd to be in non blocking mode (it simplifies the 1100 // implementation of ProcessLinux::GetSTDOUT to have a non-blocking 1101 // descriptor to read from). 1102 if (!EnsureFDFlags(monitor->m_terminal_fd, O_NONBLOCK, args->m_error)) 1103 goto FINISH; 1104 1105 // Update the process thread list with this new thread. 1106 // FIXME: should we be letting UpdateThreadList handle this? 1107 // FIXME: by using pids instead of tids, we can only support one thread. 1108 inferior.reset(new POSIXThread(process, pid)); 1109 if (log) 1110 log->Printf ("ProcessMonitor::%s() adding pid = %i", __FUNCTION__, pid); 1111 process.GetThreadList().AddThread(inferior); 1112 1113 // Let our process instance know the thread has stopped. 1114 process.SendMessage(ProcessMessage::Trace(pid)); 1115 1116FINISH: 1117 return args->m_error.Success(); 1118} 1119 1120bool 1121ProcessMonitor::EnableIPC() 1122{ 1123 int fd[2]; 1124 1125 if (socketpair(AF_UNIX, SOCK_STREAM, 0, fd)) 1126 return false; 1127 1128 m_client_fd = fd[0]; 1129 m_server_fd = fd[1]; 1130 return true; 1131} 1132 1133void 1134ProcessMonitor::StartAttachOpThread(AttachArgs *args, lldb_private::Error &error) 1135{ 1136 static const char *g_thread_name = "lldb.process.linux.operation"; 1137 1138 if (IS_VALID_LLDB_HOST_THREAD(m_operation_thread)) 1139 return; 1140 1141 m_operation_thread = 1142 Host::ThreadCreate(g_thread_name, AttachOpThread, args, &error); 1143} 1144 1145void 1146ProcessMonitor::StopAttachOpThread() 1147{ 1148 assert(!"Not implemented yet!!!"); 1149} 1150 1151void * 1152ProcessMonitor::AttachOpThread(void *arg) 1153{ 1154 AttachArgs *args = static_cast<AttachArgs*>(arg); 1155 1156 if (!Attach(args)) 1157 return NULL; 1158 1159 ServeOperation(args); 1160 return NULL; 1161} 1162 1163bool 1164ProcessMonitor::Attach(AttachArgs *args) 1165{ 1166 lldb::pid_t pid = args->m_pid; 1167 1168 ProcessMonitor *monitor = args->m_monitor; 1169 ProcessLinux &process = monitor->GetProcess(); 1170 lldb::ThreadSP inferior; 1171 LogSP log (ProcessPOSIXLog::GetLogIfAllCategoriesSet (POSIX_LOG_PROCESS)); 1172 1173 if (pid <= 1) 1174 { 1175 args->m_error.SetErrorToGenericError(); 1176 args->m_error.SetErrorString("Attaching to process 1 is not allowed."); 1177 goto FINISH; 1178 } 1179 1180 // Attach to the requested process. 1181 if (PTRACE(PTRACE_ATTACH, pid, NULL, NULL) < 0) 1182 { 1183 args->m_error.SetErrorToErrno(); 1184 goto FINISH; 1185 } 1186 1187 int status; 1188 if ((status = waitpid(pid, NULL, 0)) < 0) 1189 { 1190 args->m_error.SetErrorToErrno(); 1191 goto FINISH; 1192 } 1193 1194 monitor->m_pid = pid; 1195 1196 // Update the process thread list with the attached thread. 1197 inferior.reset(new POSIXThread(process, pid)); 1198 if (log) 1199 log->Printf ("ProcessMonitor::%s() adding tid = %i", __FUNCTION__, pid); 1200 process.GetThreadList().AddThread(inferior); 1201 1202 // Let our process instance know the thread has stopped. 1203 process.SendMessage(ProcessMessage::Trace(pid)); 1204 1205 FINISH: 1206 return args->m_error.Success(); 1207} 1208 1209bool 1210ProcessMonitor::MonitorCallback(void *callback_baton, 1211 lldb::pid_t pid, 1212 bool exited, 1213 int signal, 1214 int status) 1215{ 1216 ProcessMessage message; 1217 ProcessMonitor *monitor = static_cast<ProcessMonitor*>(callback_baton); 1218 ProcessLinux *process = monitor->m_process; 1219 assert(process); 1220 bool stop_monitoring; 1221 siginfo_t info; 1222 1223 if (!monitor->GetSignalInfo(pid, &info)) 1224 stop_monitoring = true; // pid is gone. Bail. 1225 else { 1226 switch (info.si_signo) 1227 { 1228 case SIGTRAP: 1229 message = MonitorSIGTRAP(monitor, &info, pid); 1230 break; 1231 1232 default: 1233 message = MonitorSignal(monitor, &info, pid); 1234 break; 1235 } 1236 1237 process->SendMessage(message); 1238 stop_monitoring = message.GetKind() == ProcessMessage::eExitMessage; 1239 } 1240 1241 return stop_monitoring; 1242} 1243 1244ProcessMessage 1245ProcessMonitor::MonitorSIGTRAP(ProcessMonitor *monitor, 1246 const siginfo_t *info, lldb::pid_t pid) 1247{ 1248 ProcessMessage message; 1249 1250 assert(monitor); 1251 assert(info && info->si_signo == SIGTRAP && "Unexpected child signal!"); 1252 1253 switch (info->si_code) 1254 { 1255 default: 1256 assert(false && "Unexpected SIGTRAP code!"); 1257 break; 1258 1259 case (SIGTRAP | (PTRACE_EVENT_EXIT << 8)): 1260 { 1261 // The inferior process is about to exit. Maintain the process in a 1262 // state of "limbo" until we are explicitly commanded to detach, 1263 // destroy, resume, etc. 1264 unsigned long data = 0; 1265 if (!monitor->GetEventMessage(pid, &data)) 1266 data = -1; 1267 message = ProcessMessage::Limbo(pid, (data >> 8)); 1268 break; 1269 } 1270 1271 case 0: 1272 case TRAP_TRACE: 1273 message = ProcessMessage::Trace(pid); 1274 break; 1275 1276 case SI_KERNEL: 1277 case TRAP_BRKPT: 1278 message = ProcessMessage::Break(pid); 1279 break; 1280 } 1281 1282 return message; 1283} 1284 1285ProcessMessage 1286ProcessMonitor::MonitorSignal(ProcessMonitor *monitor, 1287 const siginfo_t *info, lldb::pid_t pid) 1288{ 1289 ProcessMessage message; 1290 int signo = info->si_signo; 1291 1292 // POSIX says that process behaviour is undefined after it ignores a SIGFPE, 1293 // SIGILL, SIGSEGV, or SIGBUS *unless* that signal was generated by a 1294 // kill(2) or raise(3). Similarly for tgkill(2) on Linux. 1295 // 1296 // IOW, user generated signals never generate what we consider to be a 1297 // "crash". 1298 // 1299 // Similarly, ACK signals generated by this monitor. 1300 if (info->si_code == SI_TKILL || info->si_code == SI_USER) 1301 { 1302 if (info->si_pid == getpid()) 1303 return ProcessMessage::SignalDelivered(pid, signo); 1304 else 1305 return ProcessMessage::Signal(pid, signo); 1306 } 1307 1308 if (signo == SIGSEGV) { 1309 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr); 1310 ProcessMessage::CrashReason reason = GetCrashReasonForSIGSEGV(info); 1311 return ProcessMessage::Crash(pid, reason, signo, fault_addr); 1312 } 1313 1314 if (signo == SIGILL) { 1315 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr); 1316 ProcessMessage::CrashReason reason = GetCrashReasonForSIGILL(info); 1317 return ProcessMessage::Crash(pid, reason, signo, fault_addr); 1318 } 1319 1320 if (signo == SIGFPE) { 1321 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr); 1322 ProcessMessage::CrashReason reason = GetCrashReasonForSIGFPE(info); 1323 return ProcessMessage::Crash(pid, reason, signo, fault_addr); 1324 } 1325 1326 if (signo == SIGBUS) { 1327 lldb::addr_t fault_addr = reinterpret_cast<lldb::addr_t>(info->si_addr); 1328 ProcessMessage::CrashReason reason = GetCrashReasonForSIGBUS(info); 1329 return ProcessMessage::Crash(pid, reason, signo, fault_addr); 1330 } 1331 1332 // Everything else is "normal" and does not require any special action on 1333 // our part. 1334 return ProcessMessage::Signal(pid, signo); 1335} 1336 1337ProcessMessage::CrashReason 1338ProcessMonitor::GetCrashReasonForSIGSEGV(const siginfo_t *info) 1339{ 1340 ProcessMessage::CrashReason reason; 1341 assert(info->si_signo == SIGSEGV); 1342 1343 reason = ProcessMessage::eInvalidCrashReason; 1344 1345 switch (info->si_code) 1346 { 1347 default: 1348 assert(false && "unexpected si_code for SIGSEGV"); 1349 break; 1350 case SEGV_MAPERR: 1351 reason = ProcessMessage::eInvalidAddress; 1352 break; 1353 case SEGV_ACCERR: 1354 reason = ProcessMessage::ePrivilegedAddress; 1355 break; 1356 } 1357 1358 return reason; 1359} 1360 1361ProcessMessage::CrashReason 1362ProcessMonitor::GetCrashReasonForSIGILL(const siginfo_t *info) 1363{ 1364 ProcessMessage::CrashReason reason; 1365 assert(info->si_signo == SIGILL); 1366 1367 reason = ProcessMessage::eInvalidCrashReason; 1368 1369 switch (info->si_code) 1370 { 1371 default: 1372 assert(false && "unexpected si_code for SIGILL"); 1373 break; 1374 case ILL_ILLOPC: 1375 reason = ProcessMessage::eIllegalOpcode; 1376 break; 1377 case ILL_ILLOPN: 1378 reason = ProcessMessage::eIllegalOperand; 1379 break; 1380 case ILL_ILLADR: 1381 reason = ProcessMessage::eIllegalAddressingMode; 1382 break; 1383 case ILL_ILLTRP: 1384 reason = ProcessMessage::eIllegalTrap; 1385 break; 1386 case ILL_PRVOPC: 1387 reason = ProcessMessage::ePrivilegedOpcode; 1388 break; 1389 case ILL_PRVREG: 1390 reason = ProcessMessage::ePrivilegedRegister; 1391 break; 1392 case ILL_COPROC: 1393 reason = ProcessMessage::eCoprocessorError; 1394 break; 1395 case ILL_BADSTK: 1396 reason = ProcessMessage::eInternalStackError; 1397 break; 1398 } 1399 1400 return reason; 1401} 1402 1403ProcessMessage::CrashReason 1404ProcessMonitor::GetCrashReasonForSIGFPE(const siginfo_t *info) 1405{ 1406 ProcessMessage::CrashReason reason; 1407 assert(info->si_signo == SIGFPE); 1408 1409 reason = ProcessMessage::eInvalidCrashReason; 1410 1411 switch (info->si_code) 1412 { 1413 default: 1414 assert(false && "unexpected si_code for SIGFPE"); 1415 break; 1416 case FPE_INTDIV: 1417 reason = ProcessMessage::eIntegerDivideByZero; 1418 break; 1419 case FPE_INTOVF: 1420 reason = ProcessMessage::eIntegerOverflow; 1421 break; 1422 case FPE_FLTDIV: 1423 reason = ProcessMessage::eFloatDivideByZero; 1424 break; 1425 case FPE_FLTOVF: 1426 reason = ProcessMessage::eFloatOverflow; 1427 break; 1428 case FPE_FLTUND: 1429 reason = ProcessMessage::eFloatUnderflow; 1430 break; 1431 case FPE_FLTRES: 1432 reason = ProcessMessage::eFloatInexactResult; 1433 break; 1434 case FPE_FLTINV: 1435 reason = ProcessMessage::eFloatInvalidOperation; 1436 break; 1437 case FPE_FLTSUB: 1438 reason = ProcessMessage::eFloatSubscriptRange; 1439 break; 1440 } 1441 1442 return reason; 1443} 1444 1445ProcessMessage::CrashReason 1446ProcessMonitor::GetCrashReasonForSIGBUS(const siginfo_t *info) 1447{ 1448 ProcessMessage::CrashReason reason; 1449 assert(info->si_signo == SIGBUS); 1450 1451 reason = ProcessMessage::eInvalidCrashReason; 1452 1453 switch (info->si_code) 1454 { 1455 default: 1456 assert(false && "unexpected si_code for SIGBUS"); 1457 break; 1458 case BUS_ADRALN: 1459 reason = ProcessMessage::eIllegalAlignment; 1460 break; 1461 case BUS_ADRERR: 1462 reason = ProcessMessage::eIllegalAddress; 1463 break; 1464 case BUS_OBJERR: 1465 reason = ProcessMessage::eHardwareError; 1466 break; 1467 } 1468 1469 return reason; 1470} 1471 1472void 1473ProcessMonitor::ServeOperation(OperationArgs *args) 1474{ 1475 int status; 1476 pollfd fdset; 1477 1478 ProcessMonitor *monitor = args->m_monitor; 1479 1480 fdset.fd = monitor->m_server_fd; 1481 fdset.events = POLLIN | POLLPRI; 1482 fdset.revents = 0; 1483 1484 // We are finised with the arguments and are ready to go. Sync with the 1485 // parent thread and start serving operations on the inferior. 1486 sem_post(&args->m_semaphore); 1487 1488 for (;;) 1489 { 1490 if ((status = poll(&fdset, 1, -1)) < 0) 1491 { 1492 switch (errno) 1493 { 1494 default: 1495 assert(false && "Unexpected poll() failure!"); 1496 continue; 1497 1498 case EINTR: continue; // Just poll again. 1499 case EBADF: return; // Connection terminated. 1500 } 1501 } 1502 1503 assert(status == 1 && "Too many descriptors!"); 1504 1505 if (fdset.revents & POLLIN) 1506 { 1507 Operation *op = NULL; 1508 1509 READ_AGAIN: 1510 if ((status = read(fdset.fd, &op, sizeof(op))) < 0) 1511 { 1512 // There is only one acceptable failure. 1513 assert(errno == EINTR); 1514 goto READ_AGAIN; 1515 } 1516 1517 assert(status == sizeof(op)); 1518 op->Execute(monitor); 1519 write(fdset.fd, &op, sizeof(op)); 1520 } 1521 } 1522} 1523 1524void 1525ProcessMonitor::DoOperation(Operation *op) 1526{ 1527 int status; 1528 Operation *ack = NULL; 1529 Mutex::Locker lock(m_server_mutex); 1530 1531 // FIXME: Do proper error checking here. 1532 write(m_client_fd, &op, sizeof(op)); 1533 1534READ_AGAIN: 1535 if ((status = read(m_client_fd, &ack, sizeof(ack))) < 0) 1536 { 1537 // If interrupted by a signal handler try again. Otherwise the monitor 1538 // thread probably died and we have a stale file descriptor -- abort the 1539 // operation. 1540 if (errno == EINTR) 1541 goto READ_AGAIN; 1542 return; 1543 } 1544 1545 assert(status == sizeof(ack)); 1546 assert(ack == op && "Invalid monitor thread response!"); 1547} 1548 1549size_t 1550ProcessMonitor::ReadMemory(lldb::addr_t vm_addr, void *buf, size_t size, 1551 Error &error) 1552{ 1553 size_t result; 1554 ReadOperation op(vm_addr, buf, size, error, result); 1555 DoOperation(&op); 1556 return result; 1557} 1558 1559size_t 1560ProcessMonitor::WriteMemory(lldb::addr_t vm_addr, const void *buf, size_t size, 1561 lldb_private::Error &error) 1562{ 1563 size_t result; 1564 WriteOperation op(vm_addr, buf, size, error, result); 1565 DoOperation(&op); 1566 return result; 1567} 1568 1569bool 1570ProcessMonitor::ReadRegisterValue(unsigned offset, unsigned size, RegisterValue &value) 1571{ 1572 bool result; 1573 ReadRegOperation op(offset, value, result); 1574 DoOperation(&op); 1575 return result; 1576} 1577 1578bool 1579ProcessMonitor::WriteRegisterValue(unsigned offset, const RegisterValue &value) 1580{ 1581 bool result; 1582 WriteRegOperation op(offset, value, result); 1583 DoOperation(&op); 1584 return result; 1585} 1586 1587bool 1588ProcessMonitor::ReadGPR(void *buf) 1589{ 1590 bool result; 1591 ReadGPROperation op(buf, result); 1592 DoOperation(&op); 1593 return result; 1594} 1595 1596bool 1597ProcessMonitor::ReadFPR(void *buf) 1598{ 1599 bool result; 1600 ReadFPROperation op(buf, result); 1601 DoOperation(&op); 1602 return result; 1603} 1604 1605bool 1606ProcessMonitor::WriteGPR(void *buf) 1607{ 1608 bool result; 1609 WriteGPROperation op(buf, result); 1610 DoOperation(&op); 1611 return result; 1612} 1613 1614bool 1615ProcessMonitor::WriteFPR(void *buf) 1616{ 1617 bool result; 1618 WriteFPROperation op(buf, result); 1619 DoOperation(&op); 1620 return result; 1621} 1622 1623bool 1624ProcessMonitor::Resume(lldb::tid_t tid, uint32_t signo) 1625{ 1626 bool result; 1627 ResumeOperation op(tid, signo, result); 1628 DoOperation(&op); 1629 return result; 1630} 1631 1632bool 1633ProcessMonitor::SingleStep(lldb::tid_t tid, uint32_t signo) 1634{ 1635 bool result; 1636 SingleStepOperation op(tid, signo, result); 1637 DoOperation(&op); 1638 return result; 1639} 1640 1641bool 1642ProcessMonitor::BringProcessIntoLimbo() 1643{ 1644 bool result; 1645 KillOperation op(result); 1646 DoOperation(&op); 1647 return result; 1648} 1649 1650bool 1651ProcessMonitor::GetSignalInfo(lldb::tid_t tid, void *siginfo) 1652{ 1653 bool result; 1654 SiginfoOperation op(tid, siginfo, result); 1655 DoOperation(&op); 1656 return result; 1657} 1658 1659bool 1660ProcessMonitor::GetEventMessage(lldb::tid_t tid, unsigned long *message) 1661{ 1662 bool result; 1663 EventMessageOperation op(tid, message, result); 1664 DoOperation(&op); 1665 return result; 1666} 1667 1668bool 1669ProcessMonitor::Detach() 1670{ 1671 bool result; 1672 lldb_private::Error error; 1673 DetachOperation op(error); 1674 result = error.Success(); 1675 DoOperation(&op); 1676 StopMonitor(); 1677 return result; 1678} 1679 1680bool 1681ProcessMonitor::DupDescriptor(const char *path, int fd, int flags) 1682{ 1683 int target_fd = open(path, flags, 0666); 1684 1685 if (target_fd == -1) 1686 return false; 1687 1688 return (dup2(target_fd, fd) == -1) ? false : true; 1689} 1690 1691void 1692ProcessMonitor::StopMonitoringChildProcess() 1693{ 1694 lldb::thread_result_t thread_result; 1695 1696 if (IS_VALID_LLDB_HOST_THREAD(m_monitor_thread)) 1697 { 1698 Host::ThreadCancel(m_monitor_thread, NULL); 1699 Host::ThreadJoin(m_monitor_thread, &thread_result, NULL); 1700 m_monitor_thread = LLDB_INVALID_HOST_THREAD; 1701 } 1702} 1703 1704void 1705ProcessMonitor::StopMonitor() 1706{ 1707 StopMonitoringChildProcess(); 1708 StopLaunchOpThread(); 1709 CloseFD(m_terminal_fd); 1710 CloseFD(m_client_fd); 1711 CloseFD(m_server_fd); 1712} 1713 1714void 1715ProcessMonitor::CloseFD(int &fd) 1716{ 1717 if (fd != -1) 1718 { 1719 close(fd); 1720 fd = -1; 1721 } 1722} 1723