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