229/// Target setpgid() handler. 230SyscallReturn setpgidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 231 232/// Target fchown() handler. 233SyscallReturn fchownFunc(SyscallDesc *desc, int num, ThreadContext *tc); 234 235/// Target dup() handler. 236SyscallReturn dupFunc(SyscallDesc *desc, int num, ThreadContext *tc); 237 238/// Target dup2() handler. 239SyscallReturn dup2Func(SyscallDesc *desc, int num, ThreadContext *tc); 240 241/// Target fcntl() handler. 242SyscallReturn fcntlFunc(SyscallDesc *desc, int num, ThreadContext *tc); 243 244/// Target fcntl64() handler. 245SyscallReturn fcntl64Func(SyscallDesc *desc, int num, ThreadContext *tc); 246 247/// Target setuid() handler. 248SyscallReturn setuidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 249 250/// Target pipe() handler. 251SyscallReturn pipeFunc(SyscallDesc *desc, int num, ThreadContext *tc); 252 253/// Internal pipe() handler. 254SyscallReturn pipeImpl(SyscallDesc *desc, int num, ThreadContext *tc, 255 bool pseudo_pipe, bool is_pipe2=false); 256 257/// Target pipe() handler. 258SyscallReturn pipe2Func(SyscallDesc *desc, int num, ThreadContext *tc); 259 260/// Target getpid() handler. 261SyscallReturn getpidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 262 263// Target getpeername() handler. 264SyscallReturn getpeernameFunc(SyscallDesc *desc, int num, ThreadContext *tc); 265 266// Target bind() handler. 267SyscallReturn bindFunc(SyscallDesc *desc, int num, ThreadContext *tc); 268 269// Target listen() handler. 270SyscallReturn listenFunc(SyscallDesc *desc, int num, ThreadContext *tc); 271 272// Target connect() handler. 273SyscallReturn connectFunc(SyscallDesc *desc, int num, ThreadContext *tc); 274 275#if defined(SYS_getdents) 276// Target getdents() handler. 277SyscallReturn getdentsFunc(SyscallDesc *desc, int num, ThreadContext *tc); 278#endif 279 280#if defined(SYS_getdents64) 281// Target getdents() handler. 282SyscallReturn getdents64Func(SyscallDesc *desc, int num, ThreadContext *tc); 283#endif 284 285// Target sendto() handler. 286SyscallReturn sendtoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 287 288// Target recvfrom() handler. 289SyscallReturn recvfromFunc(SyscallDesc *desc, int num, ThreadContext *tc); 290 291// Target recvmsg() handler. 292SyscallReturn recvmsgFunc(SyscallDesc *desc, int num, ThreadContext *tc); 293 294// Target sendmsg() handler. 295SyscallReturn sendmsgFunc(SyscallDesc *desc, int num, ThreadContext *tc); 296 297// Target getuid() handler. 298SyscallReturn getuidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 299 300/// Target getgid() handler. 301SyscallReturn getgidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 302 303/// Target getppid() handler. 304SyscallReturn getppidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 305 306/// Target geteuid() handler. 307SyscallReturn geteuidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 308 309/// Target getegid() handler. 310SyscallReturn getegidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 311 312/// Target access() handler 313SyscallReturn accessFunc(SyscallDesc *desc, int num, ThreadContext *tc); 314SyscallReturn accessFunc(SyscallDesc *desc, int num, ThreadContext *tc, 315 int index); 316 317// Target getsockopt() handler. 318SyscallReturn getsockoptFunc(SyscallDesc *desc, int num, ThreadContext *tc); 319 320// Target setsockopt() handler. 321SyscallReturn setsockoptFunc(SyscallDesc *desc, int num, ThreadContext *tc); 322 323// Target getsockname() handler. 324SyscallReturn getsocknameFunc(SyscallDesc *desc, int num, ThreadContext *tc); 325 326/// Futex system call 327/// Implemented by Daniel Sanchez 328/// Used by printf's in multi-threaded apps 329template <class OS> 330SyscallReturn 331futexFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 332{ 333 using namespace std; 334 335 int index = 0; 336 auto process = tc->getProcessPtr(); 337 338 Addr uaddr = process->getSyscallArg(tc, index); 339 int op = process->getSyscallArg(tc, index); 340 int val = process->getSyscallArg(tc, index); 341 int timeout M5_VAR_USED = process->getSyscallArg(tc, index); 342 Addr uaddr2 M5_VAR_USED = process->getSyscallArg(tc, index); 343 int val3 = process->getSyscallArg(tc, index); 344 345 /* 346 * Unsupported option that does not affect the correctness of the 347 * application. This is a performance optimization utilized by Linux. 348 */ 349 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG; 350 op &= ~OS::TGT_FUTEX_CLOCK_REALTIME_FLAG; 351 352 FutexMap &futex_map = tc->getSystemPtr()->futexMap; 353 354 if (OS::TGT_FUTEX_WAIT == op || OS::TGT_FUTEX_WAIT_BITSET == op) { 355 // Ensure futex system call accessed atomically. 356 BufferArg buf(uaddr, sizeof(int)); 357 buf.copyIn(tc->getVirtProxy()); 358 int mem_val = *(int*)buf.bufferPtr(); 359 360 /* 361 * The value in memory at uaddr is not equal with the expected val 362 * (a different thread must have changed it before the system call was 363 * invoked). In this case, we need to throw an error. 364 */ 365 if (val != mem_val) 366 return -OS::TGT_EWOULDBLOCK; 367 368 if (OS::TGT_FUTEX_WAIT) { 369 futex_map.suspend(uaddr, process->tgid(), tc); 370 } else { 371 futex_map.suspend_bitset(uaddr, process->tgid(), tc, val3); 372 } 373 374 return 0; 375 } else if (OS::TGT_FUTEX_WAKE == op) { 376 return futex_map.wakeup(uaddr, process->tgid(), val); 377 } else if (OS::TGT_FUTEX_WAKE_BITSET == op) { 378 return futex_map.wakeup_bitset(uaddr, process->tgid(), val3); 379 } else if (OS::TGT_FUTEX_REQUEUE == op || 380 OS::TGT_FUTEX_CMP_REQUEUE == op) { 381 382 // Ensure futex system call accessed atomically. 383 BufferArg buf(uaddr, sizeof(int)); 384 buf.copyIn(tc->getVirtProxy()); 385 int mem_val = *(int*)buf.bufferPtr(); 386 /* 387 * For CMP_REQUEUE, the whole operation is only started only if 388 * val3 is still the value of the futex pointed to by uaddr. 389 */ 390 if (OS::TGT_FUTEX_CMP_REQUEUE && val3 != mem_val) 391 return -OS::TGT_EWOULDBLOCK; 392 return futex_map.requeue(uaddr, process->tgid(), val, timeout, uaddr2); 393 } else if (OS::TGT_FUTEX_WAKE_OP == op) { 394 /* 395 * The FUTEX_WAKE_OP operation is equivalent to executing the 396 * following code atomically and totally ordered with respect to 397 * other futex operations on any of the two supplied futex words: 398 * 399 * int oldval = *(int *) addr2; 400 * *(int *) addr2 = oldval op oparg; 401 * futex(addr1, FUTEX_WAKE, val, 0, 0, 0); 402 * if (oldval cmp cmparg) 403 * futex(addr2, FUTEX_WAKE, val2, 0, 0, 0); 404 * 405 * (op, oparg, cmp, cmparg are encoded in val3) 406 * 407 * +---+---+-----------+-----------+ 408 * |op |cmp| oparg | cmparg | 409 * +---+---+-----------+-----------+ 410 * 4 4 12 12 <== # of bits 411 * 412 * reference: http://man7.org/linux/man-pages/man2/futex.2.html 413 * 414 */ 415 // get value from simulated-space 416 BufferArg buf(uaddr2, sizeof(int)); 417 buf.copyIn(tc->getVirtProxy()); 418 int oldval = *(int*)buf.bufferPtr(); 419 int newval = oldval; 420 // extract op, oparg, cmp, cmparg from val3 421 int wake_cmparg = val3 & 0xfff; 422 int wake_oparg = (val3 & 0xfff000) >> 12; 423 int wake_cmp = (val3 & 0xf000000) >> 24; 424 int wake_op = (val3 & 0xf0000000) >> 28; 425 if ((wake_op & OS::TGT_FUTEX_OP_ARG_SHIFT) >> 3 == 1) 426 wake_oparg = (1 << wake_oparg); 427 wake_op &= ~OS::TGT_FUTEX_OP_ARG_SHIFT; 428 // perform operation on the value of the second futex 429 if (wake_op == OS::TGT_FUTEX_OP_SET) 430 newval = wake_oparg; 431 else if (wake_op == OS::TGT_FUTEX_OP_ADD) 432 newval += wake_oparg; 433 else if (wake_op == OS::TGT_FUTEX_OP_OR) 434 newval |= wake_oparg; 435 else if (wake_op == OS::TGT_FUTEX_OP_ANDN) 436 newval &= ~wake_oparg; 437 else if (wake_op == OS::TGT_FUTEX_OP_XOR) 438 newval ^= wake_oparg; 439 // copy updated value back to simulated-space 440 *(int*)buf.bufferPtr() = newval; 441 buf.copyOut(tc->getVirtProxy()); 442 // perform the first wake-up 443 int woken1 = futex_map.wakeup(uaddr, process->tgid(), val); 444 int woken2 = 0; 445 // calculate the condition of the second wake-up 446 bool is_wake2 = false; 447 if (wake_cmp == OS::TGT_FUTEX_OP_CMP_EQ) 448 is_wake2 = oldval == wake_cmparg; 449 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_NE) 450 is_wake2 = oldval != wake_cmparg; 451 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LT) 452 is_wake2 = oldval < wake_cmparg; 453 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LE) 454 is_wake2 = oldval <= wake_cmparg; 455 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GT) 456 is_wake2 = oldval > wake_cmparg; 457 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GE) 458 is_wake2 = oldval >= wake_cmparg; 459 // perform the second wake-up 460 if (is_wake2) 461 woken2 = futex_map.wakeup(uaddr2, process->tgid(), timeout); 462 463 return woken1 + woken2; 464 } 465 warn("futex: op %d not implemented; ignoring.", op); 466 return -ENOSYS; 467} 468 469 470/// Pseudo Funcs - These functions use a different return convension, 471/// returning a second value in a register other than the normal return register 472SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 473 474/// Target getpidPseudo() handler. 475SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 476 477/// Target getuidPseudo() handler. 478SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 479 480/// Target getgidPseudo() handler. 481SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 482 483 484/// A readable name for 1,000,000, for converting microseconds to seconds. 485const int one_million = 1000000; 486/// A readable name for 1,000,000,000, for converting nanoseconds to seconds. 487const int one_billion = 1000000000; 488 489/// Approximate seconds since the epoch (1/1/1970). About a billion, 490/// by my reckoning. We want to keep this a constant (not use the 491/// real-world time) to keep simulations repeatable. 492const unsigned seconds_since_epoch = 1000000000; 493 494/// Helper function to convert current elapsed time to seconds and 495/// microseconds. 496template <class T1, class T2> 497void 498getElapsedTimeMicro(T1 &sec, T2 &usec) 499{ 500 uint64_t elapsed_usecs = curTick() / SimClock::Int::us; 501 sec = elapsed_usecs / one_million; 502 usec = elapsed_usecs % one_million; 503} 504 505/// Helper function to convert current elapsed time to seconds and 506/// nanoseconds. 507template <class T1, class T2> 508void 509getElapsedTimeNano(T1 &sec, T2 &nsec) 510{ 511 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns; 512 sec = elapsed_nsecs / one_billion; 513 nsec = elapsed_nsecs % one_billion; 514} 515 516////////////////////////////////////////////////////////////////////// 517// 518// The following emulation functions are generic, but need to be 519// templated to account for differences in types, constants, etc. 520// 521////////////////////////////////////////////////////////////////////// 522 523 typedef struct statfs hst_statfs; 524#if NO_STAT64 525 typedef struct stat hst_stat; 526 typedef struct stat hst_stat64; 527#else 528 typedef struct stat hst_stat; 529 typedef struct stat64 hst_stat64; 530#endif 531 532//// Helper function to convert a host stat buffer to a target stat 533//// buffer. Also copies the target buffer out to the simulated 534//// memory space. Used by stat(), fstat(), and lstat(). 535 536template <typename target_stat, typename host_stat> 537void 538convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false) 539{ 540 using namespace TheISA; 541 542 if (fakeTTY) 543 tgt->st_dev = 0xA; 544 else 545 tgt->st_dev = host->st_dev; 546 tgt->st_dev = TheISA::htog(tgt->st_dev); 547 tgt->st_ino = host->st_ino; 548 tgt->st_ino = TheISA::htog(tgt->st_ino); 549 tgt->st_mode = host->st_mode; 550 if (fakeTTY) { 551 // Claim to be a character device 552 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT 553 tgt->st_mode |= S_IFCHR; // Set S_IFCHR 554 } 555 tgt->st_mode = TheISA::htog(tgt->st_mode); 556 tgt->st_nlink = host->st_nlink; 557 tgt->st_nlink = TheISA::htog(tgt->st_nlink); 558 tgt->st_uid = host->st_uid; 559 tgt->st_uid = TheISA::htog(tgt->st_uid); 560 tgt->st_gid = host->st_gid; 561 tgt->st_gid = TheISA::htog(tgt->st_gid); 562 if (fakeTTY) 563 tgt->st_rdev = 0x880d; 564 else 565 tgt->st_rdev = host->st_rdev; 566 tgt->st_rdev = TheISA::htog(tgt->st_rdev); 567 tgt->st_size = host->st_size; 568 tgt->st_size = TheISA::htog(tgt->st_size); 569 tgt->st_atimeX = host->st_atime; 570 tgt->st_atimeX = TheISA::htog(tgt->st_atimeX); 571 tgt->st_mtimeX = host->st_mtime; 572 tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX); 573 tgt->st_ctimeX = host->st_ctime; 574 tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX); 575 // Force the block size to be 8KB. This helps to ensure buffered io works 576 // consistently across different hosts. 577 tgt->st_blksize = 0x2000; 578 tgt->st_blksize = TheISA::htog(tgt->st_blksize); 579 tgt->st_blocks = host->st_blocks; 580 tgt->st_blocks = TheISA::htog(tgt->st_blocks); 581} 582 583// Same for stat64 584 585template <typename target_stat, typename host_stat64> 586void 587convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false) 588{ 589 using namespace TheISA; 590 591 convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY); 592#if defined(STAT_HAVE_NSEC) 593 tgt->st_atime_nsec = host->st_atime_nsec; 594 tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec); 595 tgt->st_mtime_nsec = host->st_mtime_nsec; 596 tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec); 597 tgt->st_ctime_nsec = host->st_ctime_nsec; 598 tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec); 599#else 600 tgt->st_atime_nsec = 0; 601 tgt->st_mtime_nsec = 0; 602 tgt->st_ctime_nsec = 0; 603#endif 604} 605 606// Here are a couple of convenience functions 607template<class OS> 608void 609copyOutStatBuf(PortProxy &mem, Addr addr, 610 hst_stat *host, bool fakeTTY = false) 611{ 612 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf; 613 tgt_stat_buf tgt(addr); 614 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY); 615 tgt.copyOut(mem); 616} 617 618template<class OS> 619void 620copyOutStat64Buf(PortProxy &mem, Addr addr, 621 hst_stat64 *host, bool fakeTTY = false) 622{ 623 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf; 624 tgt_stat_buf tgt(addr); 625 convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY); 626 tgt.copyOut(mem); 627} 628 629template <class OS> 630void 631copyOutStatfsBuf(PortProxy &mem, Addr addr, 632 hst_statfs *host) 633{ 634 TypedBufferArg<typename OS::tgt_statfs> tgt(addr); 635 636 tgt->f_type = TheISA::htog(host->f_type); 637#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) 638 tgt->f_bsize = TheISA::htog(host->f_iosize); 639#else 640 tgt->f_bsize = TheISA::htog(host->f_bsize); 641#endif 642 tgt->f_blocks = TheISA::htog(host->f_blocks); 643 tgt->f_bfree = TheISA::htog(host->f_bfree); 644 tgt->f_bavail = TheISA::htog(host->f_bavail); 645 tgt->f_files = TheISA::htog(host->f_files); 646 tgt->f_ffree = TheISA::htog(host->f_ffree); 647 memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid)); 648#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) 649 tgt->f_namelen = TheISA::htog(host->f_namemax); 650 tgt->f_frsize = TheISA::htog(host->f_bsize); 651#elif defined(__APPLE__) 652 tgt->f_namelen = 0; 653 tgt->f_frsize = 0; 654#else 655 tgt->f_namelen = TheISA::htog(host->f_namelen); 656 tgt->f_frsize = TheISA::htog(host->f_frsize); 657#endif 658#if defined(__linux__) 659 memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare)); 660#else 661 /* 662 * The fields are different sizes per OS. Don't bother with 663 * f_spare or f_reserved on non-Linux for now. 664 */ 665 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare)); 666#endif 667 668 tgt.copyOut(mem); 669} 670 671/// Target ioctl() handler. For the most part, programs call ioctl() 672/// only to find out if their stdout is a tty, to determine whether to 673/// do line or block buffering. We always claim that output fds are 674/// not TTYs to provide repeatable results. 675template <class OS> 676SyscallReturn 677ioctlFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 678{ 679 int index = 0; 680 auto p = tc->getProcessPtr(); 681 682 int tgt_fd = p->getSyscallArg(tc, index); 683 unsigned req = p->getSyscallArg(tc, index); 684 685 DPRINTF_SYSCALL(Verbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req); 686 687 if (OS::isTtyReq(req)) 688 return -ENOTTY; 689 690 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]); 691 if (dfdp) { 692 EmulatedDriver *emul_driver = dfdp->getDriver(); 693 if (emul_driver) 694 return emul_driver->ioctl(tc, req); 695 } 696 697 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]); 698 if (sfdp) { 699 int status; 700 701 switch (req) { 702 case SIOCGIFCONF: { 703 Addr conf_addr = p->getSyscallArg(tc, index); 704 BufferArg conf_arg(conf_addr, sizeof(ifconf)); 705 conf_arg.copyIn(tc->getVirtProxy()); 706 707 ifconf *conf = (ifconf*)conf_arg.bufferPtr(); 708 Addr ifc_buf_addr = (Addr)conf->ifc_buf; 709 BufferArg ifc_buf_arg(ifc_buf_addr, conf->ifc_len); 710 ifc_buf_arg.copyIn(tc->getVirtProxy()); 711 712 conf->ifc_buf = (char*)ifc_buf_arg.bufferPtr(); 713 714 status = ioctl(sfdp->getSimFD(), req, conf_arg.bufferPtr()); 715 if (status != -1) { 716 conf->ifc_buf = (char*)ifc_buf_addr; 717 ifc_buf_arg.copyOut(tc->getVirtProxy()); 718 conf_arg.copyOut(tc->getVirtProxy()); 719 } 720 721 return status; 722 } 723 case SIOCGIFFLAGS: 724#if defined(__linux__) 725 case SIOCGIFINDEX: 726#endif 727 case SIOCGIFNETMASK: 728 case SIOCGIFADDR: 729#if defined(__linux__) 730 case SIOCGIFHWADDR: 731#endif 732 case SIOCGIFMTU: { 733 Addr req_addr = p->getSyscallArg(tc, index); 734 BufferArg req_arg(req_addr, sizeof(ifreq)); 735 req_arg.copyIn(tc->getVirtProxy()); 736 737 status = ioctl(sfdp->getSimFD(), req, req_arg.bufferPtr()); 738 if (status != -1) 739 req_arg.copyOut(tc->getVirtProxy()); 740 return status; 741 } 742 } 743 } 744 745 /** 746 * For lack of a better return code, return ENOTTY. Ideally, we should 747 * return something better here, but at least we issue the warning. 748 */ 749 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n", 750 tgt_fd, req, tc->pcState()); 751 return -ENOTTY; 752} 753 754template <class OS> 755SyscallReturn 756openImpl(SyscallDesc *desc, int callnum, ThreadContext *tc, bool isopenat) 757{ 758 int index = 0; 759 auto p = tc->getProcessPtr(); 760 int tgt_dirfd = -1; 761 762 /** 763 * If using the openat variant, read in the target directory file 764 * descriptor from the simulated process. 765 */ 766 if (isopenat) 767 tgt_dirfd = p->getSyscallArg(tc, index); 768 769 /** 770 * Retrieve the simulated process' memory proxy and then read in the path 771 * string from that memory space into the host's working memory space. 772 */ 773 std::string path; 774 if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index))) 775 return -EFAULT; 776 777#ifdef __CYGWIN32__ 778 int host_flags = O_BINARY; 779#else 780 int host_flags = 0; 781#endif 782 /** 783 * Translate target flags into host flags. Flags exist which are not 784 * ported between architectures which can cause check failures. 785 */ 786 int tgt_flags = p->getSyscallArg(tc, index); 787 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) { 788 if (tgt_flags & OS::openFlagTable[i].tgtFlag) { 789 tgt_flags &= ~OS::openFlagTable[i].tgtFlag; 790 host_flags |= OS::openFlagTable[i].hostFlag; 791 } 792 } 793 if (tgt_flags) { 794 warn("open%s: cannot decode flags 0x%x", 795 isopenat ? "at" : "", tgt_flags); 796 } 797#ifdef __CYGWIN32__ 798 host_flags |= O_BINARY; 799#endif 800 801 int mode = p->getSyscallArg(tc, index); 802 803 /** 804 * If the simulated process called open or openat with AT_FDCWD specified, 805 * take the current working directory value which was passed into the 806 * process class as a Python parameter and append the current path to 807 * create a full path. 808 * Otherwise, openat with a valid target directory file descriptor has 809 * been called. If the path option, which was passed in as a parameter, 810 * is not absolute, retrieve the directory file descriptor's path and 811 * prepend it to the path passed in as a parameter. 812 * In every case, we should have a full path (which is relevant to the 813 * host) to work with after this block has been passed. 814 */ 815 std::string redir_path = path; 816 std::string abs_path = path; 817 if (!isopenat || tgt_dirfd == OS::TGT_AT_FDCWD) { 818 abs_path = p->absolutePath(path, true); 819 redir_path = p->checkPathRedirect(path); 820 } else if (!startswith(path, "/")) { 821 std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]); 822 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep); 823 if (!ffdp) 824 return -EBADF; 825 abs_path = ffdp->getFileName() + path; 826 redir_path = p->checkPathRedirect(abs_path); 827 } 828 829 /** 830 * Since this is an emulated environment, we create pseudo file 831 * descriptors for device requests that have been registered with 832 * the process class through Python; this allows us to create a file 833 * descriptor for subsequent ioctl or mmap calls. 834 */ 835 if (startswith(abs_path, "/dev/")) { 836 std::string filename = abs_path.substr(strlen("/dev/")); 837 EmulatedDriver *drv = p->findDriver(filename); 838 if (drv) { 839 DPRINTF_SYSCALL(Verbose, "open%s: passing call to " 840 "driver open with path[%s]\n", 841 isopenat ? "at" : "", abs_path.c_str()); 842 return drv->open(tc, mode, host_flags); 843 } 844 /** 845 * Fall through here for pass through to host devices, such 846 * as /dev/zero 847 */ 848 } 849 850 /** 851 * We make several attempts resolve a call to open. 852 * 853 * 1) Resolve any path redirection before hand. This will set the path 854 * up with variable 'redir_path' which may contain a modified path or 855 * the original path value. This should already be done in prior code. 856 * 2) Try to handle the access using 'special_paths'. Some special_paths 857 * and files cannot be called on the host and need to be handled as 858 * special cases inside the simulator. These special_paths are handled by 859 * C++ routines to provide output back to userspace. 860 * 3) If the full path that was created above does not match any of the 861 * special cases, pass it through to the open call on the __HOST__ to let 862 * the host open the file on our behalf. Again, the openImpl tries to 863 * USE_THE_HOST_FILESYSTEM_OPEN (with a possible redirection to the 864 * faux-filesystem files). The faux-filesystem is dynamically created 865 * during simulator configuration using Python functions. 866 * 4) If the host cannot open the file, the open attempt failed in "3)". 867 * Return the host's error code back through the system call to the 868 * simulated process. If running a debug trace, also notify the user that 869 * the open call failed. 870 * 871 * Any success will set sim_fd to something other than -1 and skip the 872 * next conditions effectively bypassing them. 873 */ 874 int sim_fd = -1; 875 std::string used_path; 876 std::vector<std::string> special_paths = 877 { "/proc/meminfo/", "/system/", "/platform/", "/etc/passwd" }; 878 for (auto entry : special_paths) { 879 if (startswith(path, entry)) { 880 sim_fd = OS::openSpecialFile(abs_path, p, tc); 881 used_path = abs_path; 882 } 883 } 884 if (sim_fd == -1) { 885 sim_fd = open(redir_path.c_str(), host_flags, mode); 886 used_path = redir_path; 887 } 888 if (sim_fd == -1) { 889 int local = -errno; 890 DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s " 891 "(inferred from:%s)\n", isopenat ? "at" : "", 892 used_path.c_str(), path.c_str()); 893 return local; 894 } 895 896 /** 897 * The file was opened successfully and needs to be recorded in the 898 * process' file descriptor array so that it can be retrieved later. 899 * The target file descriptor that is chosen will be the lowest unused 900 * file descriptor. 901 * Return the indirect target file descriptor back to the simulated 902 * process to act as a handle for the opened file. 903 */ 904 auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0); 905 int tgt_fd = p->fds->allocFD(ffdp); 906 DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n" 907 "(inferred from:%s)\n", isopenat ? "at" : "", 908 sim_fd, tgt_fd, used_path.c_str(), path.c_str()); 909 return tgt_fd; 910} 911 912/// Target open() handler. 913template <class OS> 914SyscallReturn 915openFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 916{ 917 return openImpl<OS>(desc, callnum, tc, false); 918} 919 920/// Target openat() handler. 921template <class OS> 922SyscallReturn 923openatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 924{ 925 return openImpl<OS>(desc, callnum, tc, true); 926} 927 928/// Target unlinkat() handler. 929template <class OS> 930SyscallReturn 931unlinkatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 932{ 933 int index = 0; 934 auto process = tc->getProcessPtr(); 935 int dirfd = process->getSyscallArg(tc, index); 936 if (dirfd != OS::TGT_AT_FDCWD) 937 warn("unlinkat: first argument not AT_FDCWD; unlikely to work"); 938 939 return unlinkHelper(desc, callnum, tc, 1); 940} 941 942/// Target facessat() handler 943template <class OS> 944SyscallReturn 945faccessatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 946{ 947 int index = 0; 948 auto process = tc->getProcessPtr(); 949 int dirfd = process->getSyscallArg(tc, index); 950 if (dirfd != OS::TGT_AT_FDCWD) 951 warn("faccessat: first argument not AT_FDCWD; unlikely to work"); 952 return accessFunc(desc, callnum, tc, 1); 953} 954 955/// Target readlinkat() handler 956template <class OS> 957SyscallReturn 958readlinkatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 959{ 960 int index = 0; 961 auto process = tc->getProcessPtr(); 962 int dirfd = process->getSyscallArg(tc, index); 963 if (dirfd != OS::TGT_AT_FDCWD) 964 warn("openat: first argument not AT_FDCWD; unlikely to work"); 965 return readlinkFunc(desc, callnum, tc, 1); 966} 967 968/// Target renameat() handler. 969template <class OS> 970SyscallReturn 971renameatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 972{ 973 int index = 0; 974 auto process = tc->getProcessPtr(); 975 976 int olddirfd = process->getSyscallArg(tc, index); 977 if (olddirfd != OS::TGT_AT_FDCWD) 978 warn("renameat: first argument not AT_FDCWD; unlikely to work"); 979 980 std::string old_name; 981 982 if (!tc->getVirtProxy().tryReadString(old_name, 983 process->getSyscallArg(tc, index))) 984 return -EFAULT; 985 986 int newdirfd = process->getSyscallArg(tc, index); 987 if (newdirfd != OS::TGT_AT_FDCWD) 988 warn("renameat: third argument not AT_FDCWD; unlikely to work"); 989 990 std::string new_name; 991 992 if (!tc->getVirtProxy().tryReadString(new_name, 993 process->getSyscallArg(tc, index))) 994 return -EFAULT; 995 996 // Adjust path for cwd and redirection 997 old_name = process->checkPathRedirect(old_name); 998 new_name = process->checkPathRedirect(new_name); 999 1000 int result = rename(old_name.c_str(), new_name.c_str()); 1001 return (result == -1) ? -errno : result; 1002} 1003 1004/// Target sysinfo() handler. 1005template <class OS> 1006SyscallReturn 1007sysinfoFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1008{ 1009 int index = 0; 1010 auto process = tc->getProcessPtr(); 1011 1012 TypedBufferArg<typename OS::tgt_sysinfo> 1013 sysinfo(process->getSyscallArg(tc, index)); 1014 1015 sysinfo->uptime = seconds_since_epoch; 1016 sysinfo->totalram = process->system->memSize(); 1017 sysinfo->mem_unit = 1; 1018 1019 sysinfo.copyOut(tc->getVirtProxy()); 1020 1021 return 0; 1022} 1023 1024/// Target chmod() handler. 1025template <class OS> 1026SyscallReturn 1027chmodFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1028{ 1029 std::string path; 1030 auto process = tc->getProcessPtr(); 1031 1032 int index = 0; 1033 if (!tc->getVirtProxy().tryReadString(path, 1034 process->getSyscallArg(tc, index))) { 1035 return -EFAULT; 1036 } 1037 1038 uint32_t mode = process->getSyscallArg(tc, index); 1039 mode_t hostMode = 0; 1040 1041 // XXX translate mode flags via OS::something??? 1042 hostMode = mode; 1043 1044 // Adjust path for cwd and redirection 1045 path = process->checkPathRedirect(path); 1046 1047 // do the chmod 1048 int result = chmod(path.c_str(), hostMode); 1049 if (result < 0) 1050 return -errno; 1051 1052 return 0; 1053} 1054 1055template <class OS> 1056SyscallReturn 1057pollFunc(SyscallDesc *desc, int num, ThreadContext *tc) 1058{ 1059 int index = 0; 1060 auto p = tc->getProcessPtr(); 1061 Addr fdsPtr = p->getSyscallArg(tc, index); 1062 int nfds = p->getSyscallArg(tc, index); 1063 int tmout = p->getSyscallArg(tc, index); 1064 1065 BufferArg fdsBuf(fdsPtr, sizeof(struct pollfd) * nfds); 1066 fdsBuf.copyIn(tc->getVirtProxy()); 1067 1068 /** 1069 * Record the target file descriptors in a local variable. We need to 1070 * replace them with host file descriptors but we need a temporary copy 1071 * for later. Afterwards, replace each target file descriptor in the 1072 * poll_fd array with its host_fd. 1073 */ 1074 int temp_tgt_fds[nfds]; 1075 for (index = 0; index < nfds; index++) { 1076 temp_tgt_fds[index] = ((struct pollfd *)fdsBuf.bufferPtr())[index].fd; 1077 auto tgt_fd = temp_tgt_fds[index]; 1078 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 1079 if (!hbfdp) 1080 return -EBADF; 1081 auto host_fd = hbfdp->getSimFD(); 1082 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = host_fd; 1083 } 1084 1085 /** 1086 * We cannot allow an infinite poll to occur or it will inevitably cause 1087 * a deadlock in the gem5 simulator with clone. We must pass in tmout with 1088 * a non-negative value, however it also makes no sense to poll on the 1089 * underlying host for any other time than tmout a zero timeout. 1090 */ 1091 int status; 1092 if (tmout < 0) { 1093 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0); 1094 if (status == 0) { 1095 /** 1096 * If blocking indefinitely, check the signal list to see if a 1097 * signal would break the poll out of the retry cycle and try 1098 * to return the signal interrupt instead. 1099 */ 1100 System *sysh = tc->getSystemPtr(); 1101 std::list<BasicSignal>::iterator it; 1102 for (it=sysh->signalList.begin(); it!=sysh->signalList.end(); it++) 1103 if (it->receiver == p) 1104 return -EINTR; 1105 return SyscallReturn::retry(); 1106 } 1107 } else 1108 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0); 1109 1110 if (status == -1) 1111 return -errno; 1112 1113 /** 1114 * Replace each host_fd in the returned poll_fd array with its original 1115 * target file descriptor. 1116 */ 1117 for (index = 0; index < nfds; index++) { 1118 auto tgt_fd = temp_tgt_fds[index]; 1119 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = tgt_fd; 1120 } 1121 1122 /** 1123 * Copy out the pollfd struct because the host may have updated fields 1124 * in the structure. 1125 */ 1126 fdsBuf.copyOut(tc->getVirtProxy()); 1127 1128 return status; 1129} 1130 1131/// Target fchmod() handler. 1132template <class OS> 1133SyscallReturn 1134fchmodFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1135{ 1136 int index = 0; 1137 auto p = tc->getProcessPtr(); 1138 int tgt_fd = p->getSyscallArg(tc, index); 1139 uint32_t mode = p->getSyscallArg(tc, index); 1140 1141 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1142 if (!ffdp) 1143 return -EBADF; 1144 int sim_fd = ffdp->getSimFD(); 1145 1146 mode_t hostMode = mode; 1147 1148 int result = fchmod(sim_fd, hostMode); 1149 1150 return (result < 0) ? -errno : 0; 1151} 1152 1153/// Target mremap() handler. 1154template <class OS> 1155SyscallReturn 1156mremapFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1157{ 1158 int index = 0; 1159 auto process = tc->getProcessPtr(); 1160 Addr start = process->getSyscallArg(tc, index); 1161 uint64_t old_length = process->getSyscallArg(tc, index); 1162 uint64_t new_length = process->getSyscallArg(tc, index); 1163 uint64_t flags = process->getSyscallArg(tc, index); 1164 uint64_t provided_address = 0; 1165 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED; 1166 1167 if (use_provided_address) 1168 provided_address = process->getSyscallArg(tc, index); 1169 1170 if ((start % TheISA::PageBytes != 0) || 1171 (provided_address % TheISA::PageBytes != 0)) { 1172 warn("mremap failing: arguments not page aligned"); 1173 return -EINVAL; 1174 } 1175 1176 new_length = roundUp(new_length, TheISA::PageBytes); 1177 1178 if (new_length > old_length) { 1179 std::shared_ptr<MemState> mem_state = process->memState; 1180 Addr mmap_end = mem_state->getMmapEnd(); 1181 1182 if ((start + old_length) == mmap_end && 1183 (!use_provided_address || provided_address == start)) { 1184 // This case cannot occur when growing downward, as 1185 // start is greater than or equal to mmap_end. 1186 uint64_t diff = new_length - old_length; 1187 process->allocateMem(mmap_end, diff); 1188 mem_state->setMmapEnd(mmap_end + diff); 1189 return start; 1190 } else { 1191 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) { 1192 warn("can't remap here and MREMAP_MAYMOVE flag not set\n"); 1193 return -ENOMEM; 1194 } else { 1195 uint64_t new_start = provided_address; 1196 if (!use_provided_address) { 1197 new_start = process->mmapGrowsDown() ? 1198 mmap_end - new_length : mmap_end; 1199 mmap_end = process->mmapGrowsDown() ? 1200 new_start : mmap_end + new_length; 1201 mem_state->setMmapEnd(mmap_end); 1202 } 1203 1204 process->pTable->remap(start, old_length, new_start); 1205 warn("mremapping to new vaddr %08p-%08p, adding %d\n", 1206 new_start, new_start + new_length, 1207 new_length - old_length); 1208 // add on the remaining unallocated pages 1209 process->allocateMem(new_start + old_length, 1210 new_length - old_length, 1211 use_provided_address /* clobber */); 1212 if (use_provided_address && 1213 ((new_start + new_length > mem_state->getMmapEnd() && 1214 !process->mmapGrowsDown()) || 1215 (new_start < mem_state->getMmapEnd() && 1216 process->mmapGrowsDown()))) { 1217 // something fishy going on here, at least notify the user 1218 // @todo: increase mmap_end? 1219 warn("mmap region limit exceeded with MREMAP_FIXED\n"); 1220 } 1221 warn("returning %08p as start\n", new_start); 1222 return new_start; 1223 } 1224 } 1225 } else { 1226 if (use_provided_address && provided_address != start) 1227 process->pTable->remap(start, new_length, provided_address); 1228 process->pTable->unmap(start + new_length, old_length - new_length); 1229 return use_provided_address ? provided_address : start; 1230 } 1231} 1232 1233/// Target stat() handler. 1234template <class OS> 1235SyscallReturn 1236statFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1237{ 1238 std::string path; 1239 auto process = tc->getProcessPtr(); 1240 1241 int index = 0; 1242 if (!tc->getVirtProxy().tryReadString(path, 1243 process->getSyscallArg(tc, index))) { 1244 return -EFAULT; 1245 } 1246 Addr bufPtr = process->getSyscallArg(tc, index); 1247 1248 // Adjust path for cwd and redirection 1249 path = process->checkPathRedirect(path); 1250 1251 struct stat hostBuf; 1252 int result = stat(path.c_str(), &hostBuf); 1253 1254 if (result < 0) 1255 return -errno; 1256 1257 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1258 1259 return 0; 1260} 1261 1262 1263/// Target stat64() handler. 1264template <class OS> 1265SyscallReturn 1266stat64Func(SyscallDesc *desc, int callnum, ThreadContext *tc) 1267{ 1268 std::string path; 1269 auto process = tc->getProcessPtr(); 1270 1271 int index = 0; 1272 if (!tc->getVirtProxy().tryReadString(path, 1273 process->getSyscallArg(tc, index))) 1274 return -EFAULT; 1275 Addr bufPtr = process->getSyscallArg(tc, index); 1276 1277 // Adjust path for cwd and redirection 1278 path = process->checkPathRedirect(path); 1279 1280#if NO_STAT64 1281 struct stat hostBuf; 1282 int result = stat(path.c_str(), &hostBuf); 1283#else 1284 struct stat64 hostBuf; 1285 int result = stat64(path.c_str(), &hostBuf); 1286#endif 1287 1288 if (result < 0) 1289 return -errno; 1290 1291 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1292 1293 return 0; 1294} 1295 1296 1297/// Target fstatat64() handler. 1298template <class OS> 1299SyscallReturn 1300fstatat64Func(SyscallDesc *desc, int callnum, ThreadContext *tc) 1301{ 1302 int index = 0; 1303 auto process = tc->getProcessPtr(); 1304 int dirfd = process->getSyscallArg(tc, index); 1305 if (dirfd != OS::TGT_AT_FDCWD) 1306 warn("fstatat64: first argument not AT_FDCWD; unlikely to work"); 1307 1308 std::string path; 1309 if (!tc->getVirtProxy().tryReadString(path, 1310 process->getSyscallArg(tc, index))) 1311 return -EFAULT; 1312 Addr bufPtr = process->getSyscallArg(tc, index); 1313 1314 // Adjust path for cwd and redirection 1315 path = process->checkPathRedirect(path); 1316 1317#if NO_STAT64 1318 struct stat hostBuf; 1319 int result = stat(path.c_str(), &hostBuf); 1320#else 1321 struct stat64 hostBuf; 1322 int result = stat64(path.c_str(), &hostBuf); 1323#endif 1324 1325 if (result < 0) 1326 return -errno; 1327 1328 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1329 1330 return 0; 1331} 1332 1333 1334/// Target fstat64() handler. 1335template <class OS> 1336SyscallReturn 1337fstat64Func(SyscallDesc *desc, int callnum, ThreadContext *tc) 1338{ 1339 int index = 0; 1340 auto p = tc->getProcessPtr(); 1341 int tgt_fd = p->getSyscallArg(tc, index); 1342 Addr bufPtr = p->getSyscallArg(tc, index); 1343 1344 auto ffdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 1345 if (!ffdp) 1346 return -EBADF; 1347 int sim_fd = ffdp->getSimFD(); 1348 1349#if NO_STAT64 1350 struct stat hostBuf; 1351 int result = fstat(sim_fd, &hostBuf); 1352#else 1353 struct stat64 hostBuf; 1354 int result = fstat64(sim_fd, &hostBuf); 1355#endif 1356 1357 if (result < 0) 1358 return -errno; 1359 1360 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf, (sim_fd == 1)); 1361 1362 return 0; 1363} 1364 1365 1366/// Target lstat() handler. 1367template <class OS> 1368SyscallReturn 1369lstatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1370{ 1371 std::string path; 1372 auto process = tc->getProcessPtr(); 1373 1374 int index = 0; 1375 if (!tc->getVirtProxy().tryReadString(path, 1376 process->getSyscallArg(tc, index))) { 1377 return -EFAULT; 1378 } 1379 Addr bufPtr = process->getSyscallArg(tc, index); 1380 1381 // Adjust path for cwd and redirection 1382 path = process->checkPathRedirect(path); 1383 1384 struct stat hostBuf; 1385 int result = lstat(path.c_str(), &hostBuf); 1386 1387 if (result < 0) 1388 return -errno; 1389 1390 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1391 1392 return 0; 1393} 1394 1395/// Target lstat64() handler. 1396template <class OS> 1397SyscallReturn 1398lstat64Func(SyscallDesc *desc, int callnum, ThreadContext *tc) 1399{ 1400 std::string path; 1401 auto process = tc->getProcessPtr(); 1402 1403 int index = 0; 1404 if (!tc->getVirtProxy().tryReadString(path, 1405 process->getSyscallArg(tc, index))) { 1406 return -EFAULT; 1407 } 1408 Addr bufPtr = process->getSyscallArg(tc, index); 1409 1410 // Adjust path for cwd and redirection 1411 path = process->checkPathRedirect(path); 1412 1413#if NO_STAT64 1414 struct stat hostBuf; 1415 int result = lstat(path.c_str(), &hostBuf); 1416#else 1417 struct stat64 hostBuf; 1418 int result = lstat64(path.c_str(), &hostBuf); 1419#endif 1420 1421 if (result < 0) 1422 return -errno; 1423 1424 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1425 1426 return 0; 1427} 1428 1429/// Target fstat() handler. 1430template <class OS> 1431SyscallReturn 1432fstatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1433{ 1434 int index = 0; 1435 auto p = tc->getProcessPtr(); 1436 int tgt_fd = p->getSyscallArg(tc, index); 1437 Addr bufPtr = p->getSyscallArg(tc, index); 1438 1439 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd); 1440 1441 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1442 if (!ffdp) 1443 return -EBADF; 1444 int sim_fd = ffdp->getSimFD(); 1445 1446 struct stat hostBuf; 1447 int result = fstat(sim_fd, &hostBuf); 1448 1449 if (result < 0) 1450 return -errno; 1451 1452 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf, (sim_fd == 1)); 1453 1454 return 0; 1455} 1456 1457/// Target statfs() handler. 1458template <class OS> 1459SyscallReturn 1460statfsFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1461{ 1462#if defined(__linux__) 1463 std::string path; 1464 auto process = tc->getProcessPtr(); 1465 1466 int index = 0; 1467 if (!tc->getVirtProxy().tryReadString(path, 1468 process->getSyscallArg(tc, index))) { 1469 return -EFAULT; 1470 } 1471 Addr bufPtr = process->getSyscallArg(tc, index); 1472 1473 // Adjust path for cwd and redirection 1474 path = process->checkPathRedirect(path); 1475 1476 struct statfs hostBuf; 1477 int result = statfs(path.c_str(), &hostBuf); 1478 1479 if (result < 0) 1480 return -errno; 1481 1482 copyOutStatfsBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1483 return 0; 1484#else 1485 warnUnsupportedOS("statfs"); 1486 return -1; 1487#endif 1488} 1489 1490template <class OS> 1491SyscallReturn 1492cloneFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1493{ 1494 int index = 0; 1495 1496 auto p = tc->getProcessPtr(); 1497 RegVal flags = p->getSyscallArg(tc, index); 1498 RegVal newStack = p->getSyscallArg(tc, index); 1499 Addr ptidPtr = p->getSyscallArg(tc, index); 1500 1501#if THE_ISA == RISCV_ISA or THE_ISA == ARM_ISA 1502 /** 1503 * Linux sets CLONE_BACKWARDS flag for RISC-V and Arm. 1504 * The flag defines the list of clone() arguments in the following 1505 * order: flags -> newStack -> ptidPtr -> tlsPtr -> ctidPtr 1506 */ 1507 Addr tlsPtr = p->getSyscallArg(tc, index); 1508 Addr ctidPtr = p->getSyscallArg(tc, index); 1509#else 1510 Addr ctidPtr = p->getSyscallArg(tc, index); 1511 Addr tlsPtr = p->getSyscallArg(tc, index); 1512#endif 1513 1514 if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) || 1515 ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) || 1516 ((flags & OS::TGT_CLONE_FS) && (flags & OS::TGT_CLONE_NEWNS)) || 1517 ((flags & OS::TGT_CLONE_NEWIPC) && (flags & OS::TGT_CLONE_SYSVSEM)) || 1518 ((flags & OS::TGT_CLONE_NEWPID) && (flags & OS::TGT_CLONE_THREAD)) || 1519 ((flags & OS::TGT_CLONE_VM) && !(newStack))) 1520 return -EINVAL; 1521 1522 ThreadContext *ctc; 1523 if (!(ctc = p->findFreeContext())) { 1524 DPRINTF_SYSCALL(Verbose, "clone: no spare thread context in system" 1525 "[cpu %d, thread %d]", tc->cpuId(), tc->threadId()); 1526 return -EAGAIN; 1527 } 1528 1529 /** 1530 * Note that ProcessParams is generated by swig and there are no other 1531 * examples of how to create anything but this default constructor. The 1532 * fields are manually initialized instead of passing parameters to the 1533 * constructor. 1534 */ 1535 ProcessParams *pp = new ProcessParams(); 1536 pp->executable.assign(*(new std::string(p->progName()))); 1537 pp->cmd.push_back(*(new std::string(p->progName()))); 1538 pp->system = p->system; 1539 pp->cwd.assign(p->tgtCwd); 1540 pp->input.assign("stdin"); 1541 pp->output.assign("stdout"); 1542 pp->errout.assign("stderr"); 1543 pp->uid = p->uid(); 1544 pp->euid = p->euid(); 1545 pp->gid = p->gid(); 1546 pp->egid = p->egid(); 1547 1548 /* Find the first free PID that's less than the maximum */ 1549 std::set<int> const& pids = p->system->PIDs; 1550 int temp_pid = *pids.begin(); 1551 do { 1552 temp_pid++; 1553 } while (pids.find(temp_pid) != pids.end()); 1554 if (temp_pid >= System::maxPID) 1555 fatal("temp_pid is too large: %d", temp_pid); 1556 1557 pp->pid = temp_pid; 1558 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid(); 1559 pp->useArchPT = p->useArchPT; 1560 pp->kvmInSE = p->kvmInSE; 1561 Process *cp = pp->create(); 1562 delete pp; 1563 1564 Process *owner = ctc->getProcessPtr(); 1565 ctc->setProcessPtr(cp); 1566 cp->assignThreadContext(ctc->contextId()); 1567 owner->revokeThreadContext(ctc->contextId()); 1568 1569 if (flags & OS::TGT_CLONE_PARENT_SETTID) { 1570 BufferArg ptidBuf(ptidPtr, sizeof(long)); 1571 long *ptid = (long *)ptidBuf.bufferPtr(); 1572 *ptid = cp->pid(); 1573 ptidBuf.copyOut(tc->getVirtProxy()); 1574 } 1575 1576 if (flags & OS::TGT_CLONE_THREAD) { 1577 cp->pTable->shared = true; 1578 cp->useForClone = true; 1579 } 1580 cp->initState(); 1581 p->clone(tc, ctc, cp, flags); 1582 1583 if (flags & OS::TGT_CLONE_THREAD) { 1584 delete cp->sigchld; 1585 cp->sigchld = p->sigchld; 1586 } else if (flags & OS::TGT_SIGCHLD) { 1587 *cp->sigchld = true; 1588 } 1589 1590 if (flags & OS::TGT_CLONE_CHILD_SETTID) { 1591 BufferArg ctidBuf(ctidPtr, sizeof(long)); 1592 long *ctid = (long *)ctidBuf.bufferPtr(); 1593 *ctid = cp->pid(); 1594 ctidBuf.copyOut(ctc->getVirtProxy()); 1595 } 1596 1597 if (flags & OS::TGT_CLONE_CHILD_CLEARTID) 1598 cp->childClearTID = (uint64_t)ctidPtr; 1599 1600 ctc->clearArchRegs(); 1601 1602 OS::archClone(flags, p, cp, tc, ctc, newStack, tlsPtr); 1603 1604 cp->setSyscallReturn(ctc, 0); 1605 1606#if THE_ISA == ALPHA_ISA 1607 ctc->setIntReg(TheISA::SyscallSuccessReg, 0); 1608#elif THE_ISA == SPARC_ISA 1609 tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0); 1610 ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1); 1611#endif 1612 1613 if (p->kvmInSE) { 1614#if THE_ISA == X86_ISA 1615 ctc->pcState(tc->readIntReg(TheISA::INTREG_RCX)); 1616#else 1617 panic("KVM CPU model is not supported for this ISA"); 1618#endif 1619 } else { 1620 TheISA::PCState cpc = tc->pcState(); 1621 cpc.advance(); 1622 ctc->pcState(cpc); 1623 } 1624 ctc->activate(); 1625 1626 return cp->pid(); 1627} 1628 1629/// Target fstatfs() handler. 1630template <class OS> 1631SyscallReturn 1632fstatfsFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1633{ 1634 int index = 0; 1635 auto p = tc->getProcessPtr(); 1636 int tgt_fd = p->getSyscallArg(tc, index); 1637 Addr bufPtr = p->getSyscallArg(tc, index); 1638 1639 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1640 if (!ffdp) 1641 return -EBADF; 1642 int sim_fd = ffdp->getSimFD(); 1643 1644 struct statfs hostBuf; 1645 int result = fstatfs(sim_fd, &hostBuf); 1646 1647 if (result < 0) 1648 return -errno; 1649 1650 copyOutStatfsBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1651 1652 return 0; 1653} 1654 1655/// Target readv() handler. 1656template <class OS> 1657SyscallReturn 1658readvFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1659{ 1660 int index = 0; 1661 auto p = tc->getProcessPtr(); 1662 int tgt_fd = p->getSyscallArg(tc, index); 1663 1664 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1665 if (!ffdp) 1666 return -EBADF; 1667 int sim_fd = ffdp->getSimFD(); 1668 1669 PortProxy &prox = tc->getVirtProxy(); 1670 uint64_t tiov_base = p->getSyscallArg(tc, index); 1671 size_t count = p->getSyscallArg(tc, index); 1672 typename OS::tgt_iovec tiov[count]; 1673 struct iovec hiov[count]; 1674 for (size_t i = 0; i < count; ++i) { 1675 prox.readBlob(tiov_base + (i * sizeof(typename OS::tgt_iovec)), 1676 &tiov[i], sizeof(typename OS::tgt_iovec)); 1677 hiov[i].iov_len = TheISA::gtoh(tiov[i].iov_len); 1678 hiov[i].iov_base = new char [hiov[i].iov_len]; 1679 } 1680 1681 int result = readv(sim_fd, hiov, count); 1682 int local_errno = errno; 1683 1684 for (size_t i = 0; i < count; ++i) { 1685 if (result != -1) { 1686 prox.writeBlob(TheISA::htog(tiov[i].iov_base), 1687 hiov[i].iov_base, hiov[i].iov_len); 1688 } 1689 delete [] (char *)hiov[i].iov_base; 1690 } 1691 1692 return (result == -1) ? -local_errno : result; 1693} 1694 1695/// Target writev() handler. 1696template <class OS> 1697SyscallReturn 1698writevFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1699{ 1700 int index = 0; 1701 auto p = tc->getProcessPtr(); 1702 int tgt_fd = p->getSyscallArg(tc, index); 1703 1704 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 1705 if (!hbfdp) 1706 return -EBADF; 1707 int sim_fd = hbfdp->getSimFD(); 1708 1709 PortProxy &prox = tc->getVirtProxy(); 1710 uint64_t tiov_base = p->getSyscallArg(tc, index); 1711 size_t count = p->getSyscallArg(tc, index); 1712 struct iovec hiov[count]; 1713 for (size_t i = 0; i < count; ++i) { 1714 typename OS::tgt_iovec tiov; 1715 1716 prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec), 1717 &tiov, sizeof(typename OS::tgt_iovec)); 1718 hiov[i].iov_len = TheISA::gtoh(tiov.iov_len); 1719 hiov[i].iov_base = new char [hiov[i].iov_len]; 1720 prox.readBlob(TheISA::gtoh(tiov.iov_base), hiov[i].iov_base, 1721 hiov[i].iov_len); 1722 } 1723 1724 int result = writev(sim_fd, hiov, count); 1725 1726 for (size_t i = 0; i < count; ++i) 1727 delete [] (char *)hiov[i].iov_base; 1728 1729 return (result == -1) ? -errno : result; 1730} 1731 1732/// Real mmap handler. 1733template <class OS> 1734SyscallReturn 1735mmapImpl(SyscallDesc *desc, int num, ThreadContext *tc, bool is_mmap2) 1736{ 1737 int index = 0; 1738 auto p = tc->getProcessPtr(); 1739 Addr start = p->getSyscallArg(tc, index); 1740 uint64_t length = p->getSyscallArg(tc, index); 1741 int prot = p->getSyscallArg(tc, index); 1742 int tgt_flags = p->getSyscallArg(tc, index); 1743 int tgt_fd = p->getSyscallArg(tc, index); 1744 int offset = p->getSyscallArg(tc, index); 1745 1746 if (is_mmap2) 1747 offset *= TheISA::PageBytes; 1748 1749 if (start & (TheISA::PageBytes - 1) || 1750 offset & (TheISA::PageBytes - 1) || 1751 (tgt_flags & OS::TGT_MAP_PRIVATE && 1752 tgt_flags & OS::TGT_MAP_SHARED) || 1753 (!(tgt_flags & OS::TGT_MAP_PRIVATE) && 1754 !(tgt_flags & OS::TGT_MAP_SHARED)) || 1755 !length) { 1756 return -EINVAL; 1757 } 1758 1759 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) { 1760 // With shared mmaps, there are two cases to consider: 1761 // 1) anonymous: writes should modify the mapping and this should be 1762 // visible to observers who share the mapping. Currently, it's 1763 // difficult to update the shared mapping because there's no 1764 // structure which maintains information about the which virtual 1765 // memory areas are shared. If that structure existed, it would be 1766 // possible to make the translations point to the same frames. 1767 // 2) file-backed: writes should modify the mapping and the file 1768 // which is backed by the mapping. The shared mapping problem is the 1769 // same as what was mentioned about the anonymous mappings. For 1770 // file-backed mappings, the writes to the file are difficult 1771 // because it requires syncing what the mapping holds with the file 1772 // that resides on the host system. So, any write on a real system 1773 // would cause the change to be propagated to the file mapping at 1774 // some point in the future (the inode is tracked along with the 1775 // mapping). This isn't guaranteed to always happen, but it usually 1776 // works well enough. The guarantee is provided by the msync system 1777 // call. We could force the change through with shared mappings with 1778 // a call to msync, but that again would require more information 1779 // than we currently maintain. 1780 warn("mmap: writing to shared mmap region is currently " 1781 "unsupported. The write succeeds on the target, but it " 1782 "will not be propagated to the host or shared mappings"); 1783 } 1784 1785 length = roundUp(length, TheISA::PageBytes); 1786 1787 int sim_fd = -1; 1788 uint8_t *pmap = nullptr; 1789 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) { 1790 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd]; 1791 1792 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep); 1793 if (dfdp) { 1794 EmulatedDriver *emul_driver = dfdp->getDriver(); 1795 return emul_driver->mmap(tc, start, length, prot, tgt_flags, 1796 tgt_fd, offset); 1797 } 1798 1799 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep); 1800 if (!ffdp) 1801 return -EBADF; 1802 sim_fd = ffdp->getSimFD(); 1803 1804 pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE, 1805 sim_fd, offset); 1806 1807 if (pmap == (decltype(pmap))-1) { 1808 warn("mmap: failed to map file into host address space"); 1809 return -errno; 1810 } 1811 } 1812 1813 // Extend global mmap region if necessary. Note that we ignore the 1814 // start address unless MAP_FIXED is specified. 1815 if (!(tgt_flags & OS::TGT_MAP_FIXED)) { 1816 std::shared_ptr<MemState> mem_state = p->memState; 1817 Addr mmap_end = mem_state->getMmapEnd(); 1818 1819 start = p->mmapGrowsDown() ? mmap_end - length : mmap_end; 1820 mmap_end = p->mmapGrowsDown() ? start : mmap_end + length; 1821 1822 mem_state->setMmapEnd(mmap_end); 1823 } 1824 1825 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n", 1826 start, start + length - 1); 1827 1828 // We only allow mappings to overwrite existing mappings if 1829 // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem 1830 // because we ignore the start hint if TGT_MAP_FIXED is not set. 1831 int clobber = tgt_flags & OS::TGT_MAP_FIXED; 1832 if (clobber) { 1833 for (auto tc : p->system->threadContexts) { 1834 // If we might be overwriting old mappings, we need to 1835 // invalidate potentially stale mappings out of the TLBs. 1836 tc->getDTBPtr()->flushAll(); 1837 tc->getITBPtr()->flushAll(); 1838 } 1839 } 1840 1841 // Allocate physical memory and map it in. If the page table is already 1842 // mapped and clobber is not set, the simulator will issue throw a 1843 // fatal and bail out of the simulation. 1844 p->allocateMem(start, length, clobber); 1845 1846 // Transfer content into target address space. 1847 PortProxy &tp = tc->getVirtProxy(); 1848 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) { 1849 // In general, we should zero the mapped area for anonymous mappings, 1850 // with something like: 1851 // tp.memsetBlob(start, 0, length); 1852 // However, given that we don't support sparse mappings, and 1853 // some applications can map a couple of gigabytes of space 1854 // (intending sparse usage), that can get painfully expensive. 1855 // Fortunately, since we don't properly implement munmap either, 1856 // there's no danger of remapping used memory, so for now all 1857 // newly mapped memory should already be zeroed so we can skip it. 1858 } else { 1859 // It is possible to mmap an area larger than a file, however 1860 // accessing unmapped portions the system triggers a "Bus error" 1861 // on the host. We must know when to stop copying the file from 1862 // the host into the target address space. 1863 struct stat file_stat; 1864 if (fstat(sim_fd, &file_stat) > 0) 1865 fatal("mmap: cannot stat file"); 1866 1867 // Copy the portion of the file that is resident. This requires 1868 // checking both the mmap size and the filesize that we are 1869 // trying to mmap into this space; the mmap size also depends 1870 // on the specified offset into the file. 1871 uint64_t size = std::min((uint64_t)file_stat.st_size - offset, 1872 length); 1873 tp.writeBlob(start, pmap, size); 1874 1875 // Cleanup the mmap region before exiting this function. 1876 munmap(pmap, length); 1877 1878 // Maintain the symbol table for dynamic executables. 1879 // The loader will call mmap to map the images into its address 1880 // space and we intercept that here. We can verify that we are 1881 // executing inside the loader by checking the program counter value. 1882 // XXX: with multiprogrammed workloads or multi-node configurations, 1883 // this will not work since there is a single global symbol table. 1884 ObjectFile *interpreter = p->getInterpreter(); 1885 if (interpreter) { 1886 Addr text_start = interpreter->textBase(); 1887 Addr text_end = text_start + interpreter->textSize(); 1888 1889 Addr pc = tc->pcState().pc(); 1890 1891 if (pc >= text_start && pc < text_end) { 1892 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd]; 1893 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep); 1894 ObjectFile *lib = createObjectFile(ffdp->getFileName()); 1895 1896 if (lib) { 1897 lib->loadAllSymbols(debugSymbolTable, 1898 lib->textBase(), start); 1899 } 1900 } 1901 } 1902 1903 // Note that we do not zero out the remainder of the mapping. This 1904 // is done by a real system, but it probably will not affect 1905 // execution (hopefully). 1906 } 1907 1908 return start; 1909} 1910 1911template <class OS> 1912SyscallReturn 1913pwrite64Func(SyscallDesc *desc, int num, ThreadContext *tc) 1914{ 1915 int index = 0; 1916 auto p = tc->getProcessPtr(); 1917 int tgt_fd = p->getSyscallArg(tc, index); 1918 Addr bufPtr = p->getSyscallArg(tc, index); 1919 int nbytes = p->getSyscallArg(tc, index); 1920 int offset = p->getSyscallArg(tc, index); 1921 1922 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1923 if (!ffdp) 1924 return -EBADF; 1925 int sim_fd = ffdp->getSimFD(); 1926 1927 BufferArg bufArg(bufPtr, nbytes); 1928 bufArg.copyIn(tc->getVirtProxy()); 1929 1930 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset); 1931 1932 return (bytes_written == -1) ? -errno : bytes_written; 1933} 1934 1935/// Target mmap() handler. 1936template <class OS> 1937SyscallReturn 1938mmapFunc(SyscallDesc *desc, int num, ThreadContext *tc) 1939{ 1940 return mmapImpl<OS>(desc, num, tc, false); 1941} 1942 1943/// Target mmap2() handler. 1944template <class OS> 1945SyscallReturn 1946mmap2Func(SyscallDesc *desc, int num, ThreadContext *tc) 1947{ 1948 return mmapImpl<OS>(desc, num, tc, true); 1949} 1950 1951/// Target getrlimit() handler. 1952template <class OS> 1953SyscallReturn 1954getrlimitFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1955{ 1956 int index = 0; 1957 auto process = tc->getProcessPtr(); 1958 unsigned resource = process->getSyscallArg(tc, index); 1959 TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index)); 1960 1961 switch (resource) { 1962 case OS::TGT_RLIMIT_STACK: 1963 // max stack size in bytes: make up a number (8MB for now) 1964 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024; 1965 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 1966 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 1967 break; 1968 1969 case OS::TGT_RLIMIT_DATA: 1970 // max data segment size in bytes: make up a number 1971 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024; 1972 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 1973 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 1974 break; 1975 1976 case OS::TGT_RLIMIT_NPROC: 1977 rlp->rlim_cur = rlp->rlim_max = tc->getSystemPtr()->numContexts(); 1978 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 1979 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 1980 break; 1981 1982 default: 1983 warn("getrlimit: unimplemented resource %d", resource); 1984 return -EINVAL; 1985 break; 1986 } 1987 1988 rlp.copyOut(tc->getVirtProxy()); 1989 return 0; 1990} 1991 1992template <class OS> 1993SyscallReturn 1994prlimitFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1995{ 1996 int index = 0; 1997 auto process = tc->getProcessPtr(); 1998 if (process->getSyscallArg(tc, index) != 0) 1999 { 2000 warn("prlimit: ignoring rlimits for nonzero pid"); 2001 return -EPERM; 2002 } 2003 int resource = process->getSyscallArg(tc, index); 2004 Addr n = process->getSyscallArg(tc, index); 2005 if (n != 0) 2006 warn("prlimit: ignoring new rlimit"); 2007 Addr o = process->getSyscallArg(tc, index); 2008 if (o != 0) 2009 { 2010 TypedBufferArg<typename OS::rlimit> rlp(o); 2011 switch (resource) { 2012 case OS::TGT_RLIMIT_STACK: 2013 // max stack size in bytes: make up a number (8MB for now) 2014 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024; 2015 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 2016 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 2017 break; 2018 case OS::TGT_RLIMIT_DATA: 2019 // max data segment size in bytes: make up a number 2020 rlp->rlim_cur = rlp->rlim_max = 256*1024*1024; 2021 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 2022 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 2023 break; 2024 default: 2025 warn("prlimit: unimplemented resource %d", resource); 2026 return -EINVAL; 2027 break; 2028 } 2029 rlp.copyOut(tc->getVirtProxy()); 2030 } 2031 return 0; 2032} 2033 2034/// Target clock_gettime() function. 2035template <class OS> 2036SyscallReturn 2037clock_gettimeFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2038{ 2039 int index = 1; 2040 auto p = tc->getProcessPtr(); 2041 //int clk_id = p->getSyscallArg(tc, index); 2042 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index)); 2043 2044 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec); 2045 tp->tv_sec += seconds_since_epoch; 2046 tp->tv_sec = TheISA::htog(tp->tv_sec); 2047 tp->tv_nsec = TheISA::htog(tp->tv_nsec); 2048 2049 tp.copyOut(tc->getVirtProxy()); 2050 2051 return 0; 2052} 2053 2054/// Target clock_getres() function. 2055template <class OS> 2056SyscallReturn 2057clock_getresFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2058{ 2059 int index = 1; 2060 auto p = tc->getProcessPtr(); 2061 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index)); 2062 2063 // Set resolution at ns, which is what clock_gettime() returns 2064 tp->tv_sec = 0; 2065 tp->tv_nsec = 1; 2066 2067 tp.copyOut(tc->getVirtProxy()); 2068 2069 return 0; 2070} 2071 2072/// Target gettimeofday() handler. 2073template <class OS> 2074SyscallReturn 2075gettimeofdayFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2076{ 2077 int index = 0; 2078 auto process = tc->getProcessPtr(); 2079 TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index)); 2080 2081 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec); 2082 tp->tv_sec += seconds_since_epoch; 2083 tp->tv_sec = TheISA::htog(tp->tv_sec); 2084 tp->tv_usec = TheISA::htog(tp->tv_usec); 2085 2086 tp.copyOut(tc->getVirtProxy()); 2087 2088 return 0; 2089} 2090 2091 2092/// Target utimes() handler. 2093template <class OS> 2094SyscallReturn 2095utimesFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2096{ 2097 std::string path; 2098 auto process = tc->getProcessPtr(); 2099 2100 int index = 0; 2101 if (!tc->getVirtProxy().tryReadString(path, 2102 process->getSyscallArg(tc, index))) { 2103 return -EFAULT; 2104 } 2105 2106 TypedBufferArg<typename OS::timeval [2]> 2107 tp(process->getSyscallArg(tc, index)); 2108 tp.copyIn(tc->getVirtProxy()); 2109 2110 struct timeval hostTimeval[2]; 2111 for (int i = 0; i < 2; ++i) { 2112 hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec); 2113 hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec); 2114 } 2115 2116 // Adjust path for cwd and redirection 2117 path = process->checkPathRedirect(path); 2118 2119 int result = utimes(path.c_str(), hostTimeval); 2120 2121 if (result < 0) 2122 return -errno; 2123 2124 return 0; 2125} 2126 2127template <class OS> 2128SyscallReturn 2129execveFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2130{ 2131 desc->setFlags(0); 2132 auto p = tc->getProcessPtr(); 2133 2134 int index = 0; 2135 std::string path; 2136 PortProxy & mem_proxy = tc->getVirtProxy(); 2137 if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index))) 2138 return -EFAULT; 2139 2140 if (access(path.c_str(), F_OK) == -1) 2141 return -EACCES; 2142 2143 auto read_in = [](std::vector<std::string> &vect, 2144 PortProxy &mem_proxy, Addr mem_loc) 2145 { 2146 for (int inc = 0; ; inc++) { 2147 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr)); 2148 b.copyIn(mem_proxy); 2149 2150 if (!*(Addr*)b.bufferPtr()) 2151 break; 2152 2153 vect.push_back(std::string()); 2154 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr()); 2155 } 2156 }; 2157 2158 /** 2159 * Note that ProcessParams is generated by swig and there are no other 2160 * examples of how to create anything but this default constructor. The 2161 * fields are manually initialized instead of passing parameters to the 2162 * constructor. 2163 */ 2164 ProcessParams *pp = new ProcessParams(); 2165 pp->executable = path; 2166 Addr argv_mem_loc = p->getSyscallArg(tc, index); 2167 read_in(pp->cmd, mem_proxy, argv_mem_loc); 2168 Addr envp_mem_loc = p->getSyscallArg(tc, index); 2169 read_in(pp->env, mem_proxy, envp_mem_loc); 2170 pp->uid = p->uid(); 2171 pp->egid = p->egid(); 2172 pp->euid = p->euid(); 2173 pp->gid = p->gid(); 2174 pp->ppid = p->ppid(); 2175 pp->pid = p->pid(); 2176 pp->input.assign("cin"); 2177 pp->output.assign("cout"); 2178 pp->errout.assign("cerr"); 2179 pp->cwd.assign(p->tgtCwd); 2180 pp->system = p->system; 2181 /** 2182 * Prevent process object creation with identical PIDs (which will trip 2183 * a fatal check in Process constructor). The execve call is supposed to 2184 * take over the currently executing process' identity but replace 2185 * whatever it is doing with a new process image. Instead of hijacking 2186 * the process object in the simulator, we create a new process object 2187 * and bind to the previous process' thread below (hijacking the thread). 2188 */ 2189 p->system->PIDs.erase(p->pid()); 2190 Process *new_p = pp->create(); 2191 delete pp; 2192 2193 /** 2194 * Work through the file descriptor array and close any files marked 2195 * close-on-exec. 2196 */ 2197 new_p->fds = p->fds; 2198 for (int i = 0; i < new_p->fds->getSize(); i++) { 2199 std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i]; 2200 if (fdep && fdep->getCOE()) 2201 new_p->fds->closeFDEntry(i); 2202 } 2203 2204 *new_p->sigchld = true; 2205 2206 delete p; 2207 tc->clearArchRegs(); 2208 tc->setProcessPtr(new_p); 2209 new_p->assignThreadContext(tc->contextId()); 2210 new_p->initState(); 2211 tc->activate(); 2212 TheISA::PCState pcState = tc->pcState(); 2213 tc->setNPC(pcState.instAddr()); 2214 2215 desc->setFlags(SyscallDesc::SuppressReturnValue); 2216 return 0; 2217} 2218 2219/// Target getrusage() function. 2220template <class OS> 2221SyscallReturn 2222getrusageFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2223{ 2224 int index = 0; 2225 auto process = tc->getProcessPtr(); 2226 int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN 2227 TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index)); 2228 2229 rup->ru_utime.tv_sec = 0; 2230 rup->ru_utime.tv_usec = 0; 2231 rup->ru_stime.tv_sec = 0; 2232 rup->ru_stime.tv_usec = 0; 2233 rup->ru_maxrss = 0; 2234 rup->ru_ixrss = 0; 2235 rup->ru_idrss = 0; 2236 rup->ru_isrss = 0; 2237 rup->ru_minflt = 0; 2238 rup->ru_majflt = 0; 2239 rup->ru_nswap = 0; 2240 rup->ru_inblock = 0; 2241 rup->ru_oublock = 0; 2242 rup->ru_msgsnd = 0; 2243 rup->ru_msgrcv = 0; 2244 rup->ru_nsignals = 0; 2245 rup->ru_nvcsw = 0; 2246 rup->ru_nivcsw = 0; 2247 2248 switch (who) { 2249 case OS::TGT_RUSAGE_SELF: 2250 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec); 2251 rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec); 2252 rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec); 2253 break; 2254 2255 case OS::TGT_RUSAGE_CHILDREN: 2256 // do nothing. We have no child processes, so they take no time. 2257 break; 2258 2259 default: 2260 // don't really handle THREAD or CHILDREN, but just warn and 2261 // plow ahead 2262 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.", 2263 who); 2264 } 2265 2266 rup.copyOut(tc->getVirtProxy()); 2267 2268 return 0; 2269} 2270 2271/// Target times() function. 2272template <class OS> 2273SyscallReturn 2274timesFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2275{ 2276 int index = 0; 2277 auto process = tc->getProcessPtr(); 2278 TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index)); 2279 2280 // Fill in the time structure (in clocks) 2281 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s; 2282 bufp->tms_utime = clocks; 2283 bufp->tms_stime = 0; 2284 bufp->tms_cutime = 0; 2285 bufp->tms_cstime = 0; 2286 2287 // Convert to host endianness 2288 bufp->tms_utime = TheISA::htog(bufp->tms_utime); 2289 2290 // Write back 2291 bufp.copyOut(tc->getVirtProxy()); 2292 2293 // Return clock ticks since system boot 2294 return clocks; 2295} 2296 2297/// Target time() function. 2298template <class OS> 2299SyscallReturn 2300timeFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2301{ 2302 typename OS::time_t sec, usec; 2303 getElapsedTimeMicro(sec, usec); 2304 sec += seconds_since_epoch; 2305 2306 int index = 0; 2307 auto process = tc->getProcessPtr(); 2308 Addr taddr = (Addr)process->getSyscallArg(tc, index); 2309 if (taddr != 0) { 2310 typename OS::time_t t = sec; 2311 t = TheISA::htog(t); 2312 PortProxy &p = tc->getVirtProxy(); 2313 p.writeBlob(taddr, &t, (int)sizeof(typename OS::time_t)); 2314 } 2315 return sec; 2316} 2317 2318template <class OS> 2319SyscallReturn 2320tgkillFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2321{ 2322 int index = 0; 2323 auto process = tc->getProcessPtr(); 2324 int tgid = process->getSyscallArg(tc, index); 2325 int tid = process->getSyscallArg(tc, index); 2326 int sig = process->getSyscallArg(tc, index); 2327 2328 /** 2329 * This system call is intended to allow killing a specific thread 2330 * within an arbitrary thread group if sanctioned with permission checks. 2331 * It's usually true that threads share the termination signal as pointed 2332 * out by the pthread_kill man page and this seems to be the intended 2333 * usage. Due to this being an emulated environment, assume the following: 2334 * Threads are allowed to call tgkill because the EUID for all threads 2335 * should be the same. There is no signal handling mechanism for kernel 2336 * registration of signal handlers since signals are poorly supported in 2337 * emulation mode. Since signal handlers cannot be registered, all 2338 * threads within in a thread group must share the termination signal. 2339 * We never exhaust PIDs so there's no chance of finding the wrong one 2340 * due to PID rollover. 2341 */ 2342 2343 System *sys = tc->getSystemPtr(); 2344 Process *tgt_proc = nullptr; 2345 for (int i = 0; i < sys->numContexts(); i++) { 2346 Process *temp = sys->threadContexts[i]->getProcessPtr(); 2347 if (temp->pid() == tid) { 2348 tgt_proc = temp; 2349 break; 2350 } 2351 } 2352 2353 if (sig != 0 || sig != OS::TGT_SIGABRT) 2354 return -EINVAL; 2355 2356 if (tgt_proc == nullptr) 2357 return -ESRCH; 2358 2359 if (tgid != -1 && tgt_proc->tgid() != tgid) 2360 return -ESRCH; 2361 2362 if (sig == OS::TGT_SIGABRT) 2363 exitGroupFunc(desc, 252, tc); 2364 2365 return 0; 2366} 2367 2368template <class OS> 2369SyscallReturn 2370socketFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2371{ 2372 int index = 0; 2373 auto p = tc->getProcessPtr(); 2374 int domain = p->getSyscallArg(tc, index); 2375 int type = p->getSyscallArg(tc, index); 2376 int prot = p->getSyscallArg(tc, index); 2377 2378 int sim_fd = socket(domain, type, prot); 2379 if (sim_fd == -1) 2380 return -errno; 2381 2382 auto sfdp = std::make_shared<SocketFDEntry>(sim_fd, domain, type, prot); 2383 int tgt_fd = p->fds->allocFD(sfdp); 2384 2385 return tgt_fd; 2386} 2387 2388template <class OS> 2389SyscallReturn 2390socketpairFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2391{ 2392 int index = 0; 2393 auto p = tc->getProcessPtr(); 2394 int domain = p->getSyscallArg(tc, index); 2395 int type = p->getSyscallArg(tc, index); 2396 int prot = p->getSyscallArg(tc, index); 2397 Addr svPtr = p->getSyscallArg(tc, index); 2398 2399 BufferArg svBuf((Addr)svPtr, 2 * sizeof(int)); 2400 int status = socketpair(domain, type, prot, (int *)svBuf.bufferPtr()); 2401 if (status == -1) 2402 return -errno; 2403 2404 int *fds = (int *)svBuf.bufferPtr(); 2405 2406 auto sfdp1 = std::make_shared<SocketFDEntry>(fds[0], domain, type, prot); 2407 fds[0] = p->fds->allocFD(sfdp1); 2408 auto sfdp2 = std::make_shared<SocketFDEntry>(fds[1], domain, type, prot); 2409 fds[1] = p->fds->allocFD(sfdp2); 2410 svBuf.copyOut(tc->getVirtProxy()); 2411 2412 return status; 2413} 2414 2415template <class OS> 2416SyscallReturn 2417selectFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2418{ 2419 int retval; 2420 2421 int index = 0; 2422 auto p = tc->getProcessPtr(); 2423 int nfds_t = p->getSyscallArg(tc, index); 2424 Addr fds_read_ptr = p->getSyscallArg(tc, index); 2425 Addr fds_writ_ptr = p->getSyscallArg(tc, index); 2426 Addr fds_excp_ptr = p->getSyscallArg(tc, index); 2427 Addr time_val_ptr = p->getSyscallArg(tc, index); 2428 2429 TypedBufferArg<typename OS::fd_set> rd_t(fds_read_ptr); 2430 TypedBufferArg<typename OS::fd_set> wr_t(fds_writ_ptr); 2431 TypedBufferArg<typename OS::fd_set> ex_t(fds_excp_ptr); 2432 TypedBufferArg<typename OS::timeval> tp(time_val_ptr); 2433 2434 /** 2435 * Host fields. Notice that these use the definitions from the system 2436 * headers instead of the gem5 headers and libraries. If the host and 2437 * target have different header file definitions, this will not work. 2438 */ 2439 fd_set rd_h; 2440 FD_ZERO(&rd_h); 2441 fd_set wr_h; 2442 FD_ZERO(&wr_h); 2443 fd_set ex_h; 2444 FD_ZERO(&ex_h); 2445 2446 /** 2447 * Copy in the fd_set from the target. 2448 */ 2449 if (fds_read_ptr) 2450 rd_t.copyIn(tc->getVirtProxy()); 2451 if (fds_writ_ptr) 2452 wr_t.copyIn(tc->getVirtProxy()); 2453 if (fds_excp_ptr) 2454 ex_t.copyIn(tc->getVirtProxy()); 2455 2456 /** 2457 * We need to translate the target file descriptor set into a host file 2458 * descriptor set. This involves both our internal process fd array 2459 * and the fd_set defined in Linux header files. The nfds field also 2460 * needs to be updated as it will be only target specific after 2461 * retrieving it from the target; the nfds value is expected to be the 2462 * highest file descriptor that needs to be checked, so we need to extend 2463 * it out for nfds_h when we do the update. 2464 */ 2465 int nfds_h = 0; 2466 std::map<int, int> trans_map; 2467 auto try_add_host_set = [&](fd_set *tgt_set_entry, 2468 fd_set *hst_set_entry, 2469 int iter) -> bool 2470 { 2471 /** 2472 * By this point, we know that we are looking at a valid file 2473 * descriptor set on the target. We need to check if the target file 2474 * descriptor value passed in as iter is part of the set. 2475 */ 2476 if (FD_ISSET(iter, tgt_set_entry)) { 2477 /** 2478 * We know that the target file descriptor belongs to the set, 2479 * but we do not yet know if the file descriptor is valid or 2480 * that we have a host mapping. Check that now. 2481 */ 2482 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[iter]); 2483 if (!hbfdp) 2484 return true; 2485 auto sim_fd = hbfdp->getSimFD(); 2486 2487 /** 2488 * Add the sim_fd to tgt_fd translation into trans_map for use 2489 * later when we need to zero the target fd_set structures and 2490 * then update them with hits returned from the host select call. 2491 */ 2492 trans_map[sim_fd] = iter; 2493 2494 /** 2495 * We know that the host file descriptor exists so now we check 2496 * if we need to update the max count for nfds_h before passing 2497 * the duplicated structure into the host. 2498 */ 2499 nfds_h = std::max(nfds_h - 1, sim_fd + 1); 2500 2501 /** 2502 * Add the host file descriptor to the set that we are going to 2503 * pass into the host. 2504 */ 2505 FD_SET(sim_fd, hst_set_entry); 2506 } 2507 return false; 2508 }; 2509 2510 for (int i = 0; i < nfds_t; i++) { 2511 if (fds_read_ptr) { 2512 bool ebadf = try_add_host_set((fd_set*)&*rd_t, &rd_h, i); 2513 if (ebadf) return -EBADF; 2514 } 2515 if (fds_writ_ptr) { 2516 bool ebadf = try_add_host_set((fd_set*)&*wr_t, &wr_h, i); 2517 if (ebadf) return -EBADF; 2518 } 2519 if (fds_excp_ptr) { 2520 bool ebadf = try_add_host_set((fd_set*)&*ex_t, &ex_h, i); 2521 if (ebadf) return -EBADF; 2522 } 2523 } 2524 2525 if (time_val_ptr) { 2526 /** 2527 * It might be possible to decrement the timeval based on some 2528 * derivation of wall clock determined from elapsed simulator ticks 2529 * but that seems like overkill. Rather, we just set the timeval with 2530 * zero timeout. (There is no reason to block during the simulation 2531 * as it only decreases simulator performance.) 2532 */ 2533 tp->tv_sec = 0; 2534 tp->tv_usec = 0; 2535 2536 retval = select(nfds_h, 2537 fds_read_ptr ? &rd_h : nullptr, 2538 fds_writ_ptr ? &wr_h : nullptr, 2539 fds_excp_ptr ? &ex_h : nullptr, 2540 (timeval*)&*tp); 2541 } else { 2542 /** 2543 * If the timeval pointer is null, setup a new timeval structure to 2544 * pass into the host select call. Unfortunately, we will need to 2545 * manually check the return value and throw a retry fault if the 2546 * return value is zero. Allowing the system call to block will 2547 * likely deadlock the event queue. 2548 */ 2549 struct timeval tv = { 0, 0 }; 2550 2551 retval = select(nfds_h, 2552 fds_read_ptr ? &rd_h : nullptr, 2553 fds_writ_ptr ? &wr_h : nullptr, 2554 fds_excp_ptr ? &ex_h : nullptr, 2555 &tv); 2556 2557 if (retval == 0) { 2558 /** 2559 * If blocking indefinitely, check the signal list to see if a 2560 * signal would break the poll out of the retry cycle and try to 2561 * return the signal interrupt instead. 2562 */ 2563 for (auto sig : tc->getSystemPtr()->signalList) 2564 if (sig.receiver == p) 2565 return -EINTR; 2566 return SyscallReturn::retry(); 2567 } 2568 } 2569 2570 if (retval == -1) 2571 return -errno; 2572 2573 FD_ZERO((fd_set*)&*rd_t); 2574 FD_ZERO((fd_set*)&*wr_t); 2575 FD_ZERO((fd_set*)&*ex_t); 2576 2577 /** 2578 * We need to translate the host file descriptor set into a target file 2579 * descriptor set. This involves both our internal process fd array 2580 * and the fd_set defined in header files. 2581 */ 2582 for (int i = 0; i < nfds_h; i++) { 2583 if (fds_read_ptr) { 2584 if (FD_ISSET(i, &rd_h)) 2585 FD_SET(trans_map[i], (fd_set*)&*rd_t); 2586 } 2587 2588 if (fds_writ_ptr) { 2589 if (FD_ISSET(i, &wr_h)) 2590 FD_SET(trans_map[i], (fd_set*)&*wr_t); 2591 } 2592 2593 if (fds_excp_ptr) { 2594 if (FD_ISSET(i, &ex_h)) 2595 FD_SET(trans_map[i], (fd_set*)&*ex_t); 2596 } 2597 } 2598 2599 if (fds_read_ptr) 2600 rd_t.copyOut(tc->getVirtProxy()); 2601 if (fds_writ_ptr) 2602 wr_t.copyOut(tc->getVirtProxy()); 2603 if (fds_excp_ptr) 2604 ex_t.copyOut(tc->getVirtProxy()); 2605 if (time_val_ptr) 2606 tp.copyOut(tc->getVirtProxy()); 2607 2608 return retval; 2609} 2610 2611template <class OS> 2612SyscallReturn 2613readFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2614{ 2615 int index = 0; 2616 auto p = tc->getProcessPtr(); 2617 int tgt_fd = p->getSyscallArg(tc, index); 2618 Addr buf_ptr = p->getSyscallArg(tc, index); 2619 int nbytes = p->getSyscallArg(tc, index); 2620 2621 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 2622 if (!hbfdp) 2623 return -EBADF; 2624 int sim_fd = hbfdp->getSimFD(); 2625 2626 struct pollfd pfd; 2627 pfd.fd = sim_fd; 2628 pfd.events = POLLIN | POLLPRI; 2629 if ((poll(&pfd, 1, 0) == 0) 2630 && !(hbfdp->getFlags() & OS::TGT_O_NONBLOCK)) 2631 return SyscallReturn::retry(); 2632 2633 BufferArg buf_arg(buf_ptr, nbytes); 2634 int bytes_read = read(sim_fd, buf_arg.bufferPtr(), nbytes); 2635 2636 if (bytes_read > 0) 2637 buf_arg.copyOut(tc->getVirtProxy()); 2638 2639 return (bytes_read == -1) ? -errno : bytes_read; 2640} 2641 2642template <class OS> 2643SyscallReturn 2644writeFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2645{ 2646 int index = 0; 2647 auto p = tc->getProcessPtr(); 2648 int tgt_fd = p->getSyscallArg(tc, index); 2649 Addr buf_ptr = p->getSyscallArg(tc, index); 2650 int nbytes = p->getSyscallArg(tc, index); 2651 2652 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 2653 if (!hbfdp) 2654 return -EBADF; 2655 int sim_fd = hbfdp->getSimFD(); 2656 2657 BufferArg buf_arg(buf_ptr, nbytes); 2658 buf_arg.copyIn(tc->getVirtProxy()); 2659 2660 struct pollfd pfd; 2661 pfd.fd = sim_fd; 2662 pfd.events = POLLOUT; 2663 2664 /** 2665 * We don't want to poll on /dev/random. The kernel will not enable the 2666 * file descriptor for writing unless the entropy in the system falls 2667 * below write_wakeup_threshold. This is not guaranteed to happen 2668 * depending on host settings. 2669 */ 2670 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(hbfdp); 2671 if (ffdp && (ffdp->getFileName() != "/dev/random")) { 2672 if (!poll(&pfd, 1, 0) && !(ffdp->getFlags() & OS::TGT_O_NONBLOCK)) 2673 return SyscallReturn::retry(); 2674 } 2675 2676 int bytes_written = write(sim_fd, buf_arg.bufferPtr(), nbytes); 2677 2678 if (bytes_written != -1) 2679 fsync(sim_fd); 2680 2681 return (bytes_written == -1) ? -errno : bytes_written; 2682} 2683 2684template <class OS> 2685SyscallReturn 2686wait4Func(SyscallDesc *desc, int num, ThreadContext *tc) 2687{ 2688 int index = 0; 2689 auto p = tc->getProcessPtr(); 2690 pid_t pid = p->getSyscallArg(tc, index); 2691 Addr statPtr = p->getSyscallArg(tc, index); 2692 int options = p->getSyscallArg(tc, index); 2693 Addr rusagePtr = p->getSyscallArg(tc, index); 2694 2695 if (rusagePtr) 2696 DPRINTF_SYSCALL(Verbose, "wait4: rusage pointer provided %lx, however " 2697 "functionality not supported. Ignoring rusage pointer.\n", 2698 rusagePtr); 2699 2700 /** 2701 * Currently, wait4 is only implemented so that it will wait for children 2702 * exit conditions which are denoted by a SIGCHLD signals posted into the 2703 * system signal list. We return no additional information via any of the 2704 * parameters supplied to wait4. If nothing is found in the system signal 2705 * list, we will wait indefinitely for SIGCHLD to post by retrying the 2706 * call. 2707 */ 2708 System *sysh = tc->getSystemPtr(); 2709 std::list<BasicSignal>::iterator iter; 2710 for (iter=sysh->signalList.begin(); iter!=sysh->signalList.end(); iter++) { 2711 if (iter->receiver == p) { 2712 if (pid < -1) { 2713 if ((iter->sender->pgid() == -pid) 2714 && (iter->signalValue == OS::TGT_SIGCHLD)) 2715 goto success; 2716 } else if (pid == -1) { 2717 if (iter->signalValue == OS::TGT_SIGCHLD) 2718 goto success; 2719 } else if (pid == 0) { 2720 if ((iter->sender->pgid() == p->pgid()) 2721 && (iter->signalValue == OS::TGT_SIGCHLD)) 2722 goto success; 2723 } else { 2724 if ((iter->sender->pid() == pid) 2725 && (iter->signalValue == OS::TGT_SIGCHLD)) 2726 goto success; 2727 } 2728 } 2729 } 2730 2731 return (options & OS::TGT_WNOHANG) ? 0 : SyscallReturn::retry(); 2732 2733success: 2734 // Set status to EXITED for WIFEXITED evaluations. 2735 const int EXITED = 0; 2736 BufferArg statusBuf(statPtr, sizeof(int)); 2737 *(int *)statusBuf.bufferPtr() = EXITED; 2738 statusBuf.copyOut(tc->getVirtProxy()); 2739 2740 // Return the child PID. 2741 pid_t retval = iter->sender->pid(); 2742 sysh->signalList.erase(iter); 2743 return retval; 2744} 2745 2746template <class OS> 2747SyscallReturn 2748acceptFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2749{ 2750 struct sockaddr sa; 2751 socklen_t addrLen; 2752 int host_fd; 2753 int index = 0; 2754 auto p = tc->getProcessPtr(); 2755 int tgt_fd = p->getSyscallArg(tc, index); 2756 Addr addrPtr = p->getSyscallArg(tc, index); 2757 Addr lenPtr = p->getSyscallArg(tc, index); 2758 2759 BufferArg *lenBufPtr = nullptr; 2760 BufferArg *addrBufPtr = nullptr; 2761 2762 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]); 2763 if (!sfdp) 2764 return -EBADF; 2765 int sim_fd = sfdp->getSimFD(); 2766 2767 /** 2768 * We poll the socket file descriptor first to guarantee that we do not 2769 * block on our accept call. The socket can be opened without the 2770 * non-blocking flag (it blocks). This will cause deadlocks between 2771 * communicating processes. 2772 */ 2773 struct pollfd pfd; 2774 pfd.fd = sim_fd; 2775 pfd.events = POLLIN | POLLPRI; 2776 if ((poll(&pfd, 1, 0) == 0) 2777 && !(sfdp->getFlags() & OS::TGT_O_NONBLOCK)) 2778 return SyscallReturn::retry(); 2779 2780 if (lenPtr) { 2781 lenBufPtr = new BufferArg(lenPtr, sizeof(socklen_t)); 2782 lenBufPtr->copyIn(tc->getVirtProxy()); 2783 memcpy(&addrLen, (socklen_t *)lenBufPtr->bufferPtr(), 2784 sizeof(socklen_t)); 2785 } 2786 2787 if (addrPtr) { 2788 addrBufPtr = new BufferArg(addrPtr, sizeof(struct sockaddr)); 2789 addrBufPtr->copyIn(tc->getVirtProxy()); 2790 memcpy(&sa, (struct sockaddr *)addrBufPtr->bufferPtr(), 2791 sizeof(struct sockaddr)); 2792 } 2793 2794 host_fd = accept(sim_fd, &sa, &addrLen); 2795 2796 if (host_fd == -1) 2797 return -errno; 2798 2799 if (addrPtr) { 2800 memcpy(addrBufPtr->bufferPtr(), &sa, sizeof(sa)); 2801 addrBufPtr->copyOut(tc->getVirtProxy()); 2802 delete(addrBufPtr); 2803 } 2804 2805 if (lenPtr) { 2806 *(socklen_t *)lenBufPtr->bufferPtr() = addrLen; 2807 lenBufPtr->copyOut(tc->getVirtProxy()); 2808 delete(lenBufPtr); 2809 } 2810 2811 auto afdp = std::make_shared<SocketFDEntry>(host_fd, sfdp->_domain, 2812 sfdp->_type, sfdp->_protocol); 2813 return p->fds->allocFD(afdp); 2814} 2815 2816/// Target eventfd() function. 2817template <class OS> 2818SyscallReturn 2819eventfdFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2820{ 2821#if defined(__linux__) 2822 int index = 0; 2823 auto p = tc->getProcessPtr(); 2824 unsigned initval = p->getSyscallArg(tc, index); 2825 int in_flags = p->getSyscallArg(tc, index); 2826 2827 int sim_fd = eventfd(initval, in_flags); 2828 if (sim_fd == -1) 2829 return -errno; 2830 2831 bool cloexec = in_flags & OS::TGT_O_CLOEXEC; 2832 2833 int flags = cloexec ? OS::TGT_O_CLOEXEC : 0; 2834 flags |= (in_flags & OS::TGT_O_NONBLOCK) ? OS::TGT_O_NONBLOCK : 0; 2835 2836 auto hbfdp = std::make_shared<HBFDEntry>(flags, sim_fd, cloexec); 2837 int tgt_fd = p->fds->allocFD(hbfdp); 2838 return tgt_fd; 2839#else 2840 warnUnsupportedOS("eventfd"); 2841 return -1; 2842#endif 2843} 2844 2845#endif // __SIM_SYSCALL_EMUL_HH__
| 232/// Target setpgid() handler. 233SyscallReturn setpgidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 234 235/// Target fchown() handler. 236SyscallReturn fchownFunc(SyscallDesc *desc, int num, ThreadContext *tc); 237 238/// Target dup() handler. 239SyscallReturn dupFunc(SyscallDesc *desc, int num, ThreadContext *tc); 240 241/// Target dup2() handler. 242SyscallReturn dup2Func(SyscallDesc *desc, int num, ThreadContext *tc); 243 244/// Target fcntl() handler. 245SyscallReturn fcntlFunc(SyscallDesc *desc, int num, ThreadContext *tc); 246 247/// Target fcntl64() handler. 248SyscallReturn fcntl64Func(SyscallDesc *desc, int num, ThreadContext *tc); 249 250/// Target setuid() handler. 251SyscallReturn setuidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 252 253/// Target pipe() handler. 254SyscallReturn pipeFunc(SyscallDesc *desc, int num, ThreadContext *tc); 255 256/// Internal pipe() handler. 257SyscallReturn pipeImpl(SyscallDesc *desc, int num, ThreadContext *tc, 258 bool pseudo_pipe, bool is_pipe2=false); 259 260/// Target pipe() handler. 261SyscallReturn pipe2Func(SyscallDesc *desc, int num, ThreadContext *tc); 262 263/// Target getpid() handler. 264SyscallReturn getpidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 265 266// Target getpeername() handler. 267SyscallReturn getpeernameFunc(SyscallDesc *desc, int num, ThreadContext *tc); 268 269// Target bind() handler. 270SyscallReturn bindFunc(SyscallDesc *desc, int num, ThreadContext *tc); 271 272// Target listen() handler. 273SyscallReturn listenFunc(SyscallDesc *desc, int num, ThreadContext *tc); 274 275// Target connect() handler. 276SyscallReturn connectFunc(SyscallDesc *desc, int num, ThreadContext *tc); 277 278#if defined(SYS_getdents) 279// Target getdents() handler. 280SyscallReturn getdentsFunc(SyscallDesc *desc, int num, ThreadContext *tc); 281#endif 282 283#if defined(SYS_getdents64) 284// Target getdents() handler. 285SyscallReturn getdents64Func(SyscallDesc *desc, int num, ThreadContext *tc); 286#endif 287 288// Target sendto() handler. 289SyscallReturn sendtoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 290 291// Target recvfrom() handler. 292SyscallReturn recvfromFunc(SyscallDesc *desc, int num, ThreadContext *tc); 293 294// Target recvmsg() handler. 295SyscallReturn recvmsgFunc(SyscallDesc *desc, int num, ThreadContext *tc); 296 297// Target sendmsg() handler. 298SyscallReturn sendmsgFunc(SyscallDesc *desc, int num, ThreadContext *tc); 299 300// Target getuid() handler. 301SyscallReturn getuidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 302 303/// Target getgid() handler. 304SyscallReturn getgidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 305 306/// Target getppid() handler. 307SyscallReturn getppidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 308 309/// Target geteuid() handler. 310SyscallReturn geteuidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 311 312/// Target getegid() handler. 313SyscallReturn getegidFunc(SyscallDesc *desc, int num, ThreadContext *tc); 314 315/// Target access() handler 316SyscallReturn accessFunc(SyscallDesc *desc, int num, ThreadContext *tc); 317SyscallReturn accessFunc(SyscallDesc *desc, int num, ThreadContext *tc, 318 int index); 319 320// Target getsockopt() handler. 321SyscallReturn getsockoptFunc(SyscallDesc *desc, int num, ThreadContext *tc); 322 323// Target setsockopt() handler. 324SyscallReturn setsockoptFunc(SyscallDesc *desc, int num, ThreadContext *tc); 325 326// Target getsockname() handler. 327SyscallReturn getsocknameFunc(SyscallDesc *desc, int num, ThreadContext *tc); 328 329/// Futex system call 330/// Implemented by Daniel Sanchez 331/// Used by printf's in multi-threaded apps 332template <class OS> 333SyscallReturn 334futexFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 335{ 336 using namespace std; 337 338 int index = 0; 339 auto process = tc->getProcessPtr(); 340 341 Addr uaddr = process->getSyscallArg(tc, index); 342 int op = process->getSyscallArg(tc, index); 343 int val = process->getSyscallArg(tc, index); 344 int timeout M5_VAR_USED = process->getSyscallArg(tc, index); 345 Addr uaddr2 M5_VAR_USED = process->getSyscallArg(tc, index); 346 int val3 = process->getSyscallArg(tc, index); 347 348 /* 349 * Unsupported option that does not affect the correctness of the 350 * application. This is a performance optimization utilized by Linux. 351 */ 352 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG; 353 op &= ~OS::TGT_FUTEX_CLOCK_REALTIME_FLAG; 354 355 FutexMap &futex_map = tc->getSystemPtr()->futexMap; 356 357 if (OS::TGT_FUTEX_WAIT == op || OS::TGT_FUTEX_WAIT_BITSET == op) { 358 // Ensure futex system call accessed atomically. 359 BufferArg buf(uaddr, sizeof(int)); 360 buf.copyIn(tc->getVirtProxy()); 361 int mem_val = *(int*)buf.bufferPtr(); 362 363 /* 364 * The value in memory at uaddr is not equal with the expected val 365 * (a different thread must have changed it before the system call was 366 * invoked). In this case, we need to throw an error. 367 */ 368 if (val != mem_val) 369 return -OS::TGT_EWOULDBLOCK; 370 371 if (OS::TGT_FUTEX_WAIT) { 372 futex_map.suspend(uaddr, process->tgid(), tc); 373 } else { 374 futex_map.suspend_bitset(uaddr, process->tgid(), tc, val3); 375 } 376 377 return 0; 378 } else if (OS::TGT_FUTEX_WAKE == op) { 379 return futex_map.wakeup(uaddr, process->tgid(), val); 380 } else if (OS::TGT_FUTEX_WAKE_BITSET == op) { 381 return futex_map.wakeup_bitset(uaddr, process->tgid(), val3); 382 } else if (OS::TGT_FUTEX_REQUEUE == op || 383 OS::TGT_FUTEX_CMP_REQUEUE == op) { 384 385 // Ensure futex system call accessed atomically. 386 BufferArg buf(uaddr, sizeof(int)); 387 buf.copyIn(tc->getVirtProxy()); 388 int mem_val = *(int*)buf.bufferPtr(); 389 /* 390 * For CMP_REQUEUE, the whole operation is only started only if 391 * val3 is still the value of the futex pointed to by uaddr. 392 */ 393 if (OS::TGT_FUTEX_CMP_REQUEUE && val3 != mem_val) 394 return -OS::TGT_EWOULDBLOCK; 395 return futex_map.requeue(uaddr, process->tgid(), val, timeout, uaddr2); 396 } else if (OS::TGT_FUTEX_WAKE_OP == op) { 397 /* 398 * The FUTEX_WAKE_OP operation is equivalent to executing the 399 * following code atomically and totally ordered with respect to 400 * other futex operations on any of the two supplied futex words: 401 * 402 * int oldval = *(int *) addr2; 403 * *(int *) addr2 = oldval op oparg; 404 * futex(addr1, FUTEX_WAKE, val, 0, 0, 0); 405 * if (oldval cmp cmparg) 406 * futex(addr2, FUTEX_WAKE, val2, 0, 0, 0); 407 * 408 * (op, oparg, cmp, cmparg are encoded in val3) 409 * 410 * +---+---+-----------+-----------+ 411 * |op |cmp| oparg | cmparg | 412 * +---+---+-----------+-----------+ 413 * 4 4 12 12 <== # of bits 414 * 415 * reference: http://man7.org/linux/man-pages/man2/futex.2.html 416 * 417 */ 418 // get value from simulated-space 419 BufferArg buf(uaddr2, sizeof(int)); 420 buf.copyIn(tc->getVirtProxy()); 421 int oldval = *(int*)buf.bufferPtr(); 422 int newval = oldval; 423 // extract op, oparg, cmp, cmparg from val3 424 int wake_cmparg = val3 & 0xfff; 425 int wake_oparg = (val3 & 0xfff000) >> 12; 426 int wake_cmp = (val3 & 0xf000000) >> 24; 427 int wake_op = (val3 & 0xf0000000) >> 28; 428 if ((wake_op & OS::TGT_FUTEX_OP_ARG_SHIFT) >> 3 == 1) 429 wake_oparg = (1 << wake_oparg); 430 wake_op &= ~OS::TGT_FUTEX_OP_ARG_SHIFT; 431 // perform operation on the value of the second futex 432 if (wake_op == OS::TGT_FUTEX_OP_SET) 433 newval = wake_oparg; 434 else if (wake_op == OS::TGT_FUTEX_OP_ADD) 435 newval += wake_oparg; 436 else if (wake_op == OS::TGT_FUTEX_OP_OR) 437 newval |= wake_oparg; 438 else if (wake_op == OS::TGT_FUTEX_OP_ANDN) 439 newval &= ~wake_oparg; 440 else if (wake_op == OS::TGT_FUTEX_OP_XOR) 441 newval ^= wake_oparg; 442 // copy updated value back to simulated-space 443 *(int*)buf.bufferPtr() = newval; 444 buf.copyOut(tc->getVirtProxy()); 445 // perform the first wake-up 446 int woken1 = futex_map.wakeup(uaddr, process->tgid(), val); 447 int woken2 = 0; 448 // calculate the condition of the second wake-up 449 bool is_wake2 = false; 450 if (wake_cmp == OS::TGT_FUTEX_OP_CMP_EQ) 451 is_wake2 = oldval == wake_cmparg; 452 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_NE) 453 is_wake2 = oldval != wake_cmparg; 454 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LT) 455 is_wake2 = oldval < wake_cmparg; 456 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LE) 457 is_wake2 = oldval <= wake_cmparg; 458 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GT) 459 is_wake2 = oldval > wake_cmparg; 460 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GE) 461 is_wake2 = oldval >= wake_cmparg; 462 // perform the second wake-up 463 if (is_wake2) 464 woken2 = futex_map.wakeup(uaddr2, process->tgid(), timeout); 465 466 return woken1 + woken2; 467 } 468 warn("futex: op %d not implemented; ignoring.", op); 469 return -ENOSYS; 470} 471 472 473/// Pseudo Funcs - These functions use a different return convension, 474/// returning a second value in a register other than the normal return register 475SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 476 477/// Target getpidPseudo() handler. 478SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 479 480/// Target getuidPseudo() handler. 481SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 482 483/// Target getgidPseudo() handler. 484SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc); 485 486 487/// A readable name for 1,000,000, for converting microseconds to seconds. 488const int one_million = 1000000; 489/// A readable name for 1,000,000,000, for converting nanoseconds to seconds. 490const int one_billion = 1000000000; 491 492/// Approximate seconds since the epoch (1/1/1970). About a billion, 493/// by my reckoning. We want to keep this a constant (not use the 494/// real-world time) to keep simulations repeatable. 495const unsigned seconds_since_epoch = 1000000000; 496 497/// Helper function to convert current elapsed time to seconds and 498/// microseconds. 499template <class T1, class T2> 500void 501getElapsedTimeMicro(T1 &sec, T2 &usec) 502{ 503 uint64_t elapsed_usecs = curTick() / SimClock::Int::us; 504 sec = elapsed_usecs / one_million; 505 usec = elapsed_usecs % one_million; 506} 507 508/// Helper function to convert current elapsed time to seconds and 509/// nanoseconds. 510template <class T1, class T2> 511void 512getElapsedTimeNano(T1 &sec, T2 &nsec) 513{ 514 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns; 515 sec = elapsed_nsecs / one_billion; 516 nsec = elapsed_nsecs % one_billion; 517} 518 519////////////////////////////////////////////////////////////////////// 520// 521// The following emulation functions are generic, but need to be 522// templated to account for differences in types, constants, etc. 523// 524////////////////////////////////////////////////////////////////////// 525 526 typedef struct statfs hst_statfs; 527#if NO_STAT64 528 typedef struct stat hst_stat; 529 typedef struct stat hst_stat64; 530#else 531 typedef struct stat hst_stat; 532 typedef struct stat64 hst_stat64; 533#endif 534 535//// Helper function to convert a host stat buffer to a target stat 536//// buffer. Also copies the target buffer out to the simulated 537//// memory space. Used by stat(), fstat(), and lstat(). 538 539template <typename target_stat, typename host_stat> 540void 541convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false) 542{ 543 using namespace TheISA; 544 545 if (fakeTTY) 546 tgt->st_dev = 0xA; 547 else 548 tgt->st_dev = host->st_dev; 549 tgt->st_dev = TheISA::htog(tgt->st_dev); 550 tgt->st_ino = host->st_ino; 551 tgt->st_ino = TheISA::htog(tgt->st_ino); 552 tgt->st_mode = host->st_mode; 553 if (fakeTTY) { 554 // Claim to be a character device 555 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT 556 tgt->st_mode |= S_IFCHR; // Set S_IFCHR 557 } 558 tgt->st_mode = TheISA::htog(tgt->st_mode); 559 tgt->st_nlink = host->st_nlink; 560 tgt->st_nlink = TheISA::htog(tgt->st_nlink); 561 tgt->st_uid = host->st_uid; 562 tgt->st_uid = TheISA::htog(tgt->st_uid); 563 tgt->st_gid = host->st_gid; 564 tgt->st_gid = TheISA::htog(tgt->st_gid); 565 if (fakeTTY) 566 tgt->st_rdev = 0x880d; 567 else 568 tgt->st_rdev = host->st_rdev; 569 tgt->st_rdev = TheISA::htog(tgt->st_rdev); 570 tgt->st_size = host->st_size; 571 tgt->st_size = TheISA::htog(tgt->st_size); 572 tgt->st_atimeX = host->st_atime; 573 tgt->st_atimeX = TheISA::htog(tgt->st_atimeX); 574 tgt->st_mtimeX = host->st_mtime; 575 tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX); 576 tgt->st_ctimeX = host->st_ctime; 577 tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX); 578 // Force the block size to be 8KB. This helps to ensure buffered io works 579 // consistently across different hosts. 580 tgt->st_blksize = 0x2000; 581 tgt->st_blksize = TheISA::htog(tgt->st_blksize); 582 tgt->st_blocks = host->st_blocks; 583 tgt->st_blocks = TheISA::htog(tgt->st_blocks); 584} 585 586// Same for stat64 587 588template <typename target_stat, typename host_stat64> 589void 590convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false) 591{ 592 using namespace TheISA; 593 594 convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY); 595#if defined(STAT_HAVE_NSEC) 596 tgt->st_atime_nsec = host->st_atime_nsec; 597 tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec); 598 tgt->st_mtime_nsec = host->st_mtime_nsec; 599 tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec); 600 tgt->st_ctime_nsec = host->st_ctime_nsec; 601 tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec); 602#else 603 tgt->st_atime_nsec = 0; 604 tgt->st_mtime_nsec = 0; 605 tgt->st_ctime_nsec = 0; 606#endif 607} 608 609// Here are a couple of convenience functions 610template<class OS> 611void 612copyOutStatBuf(PortProxy &mem, Addr addr, 613 hst_stat *host, bool fakeTTY = false) 614{ 615 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf; 616 tgt_stat_buf tgt(addr); 617 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY); 618 tgt.copyOut(mem); 619} 620 621template<class OS> 622void 623copyOutStat64Buf(PortProxy &mem, Addr addr, 624 hst_stat64 *host, bool fakeTTY = false) 625{ 626 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf; 627 tgt_stat_buf tgt(addr); 628 convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY); 629 tgt.copyOut(mem); 630} 631 632template <class OS> 633void 634copyOutStatfsBuf(PortProxy &mem, Addr addr, 635 hst_statfs *host) 636{ 637 TypedBufferArg<typename OS::tgt_statfs> tgt(addr); 638 639 tgt->f_type = TheISA::htog(host->f_type); 640#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) 641 tgt->f_bsize = TheISA::htog(host->f_iosize); 642#else 643 tgt->f_bsize = TheISA::htog(host->f_bsize); 644#endif 645 tgt->f_blocks = TheISA::htog(host->f_blocks); 646 tgt->f_bfree = TheISA::htog(host->f_bfree); 647 tgt->f_bavail = TheISA::htog(host->f_bavail); 648 tgt->f_files = TheISA::htog(host->f_files); 649 tgt->f_ffree = TheISA::htog(host->f_ffree); 650 memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid)); 651#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__) 652 tgt->f_namelen = TheISA::htog(host->f_namemax); 653 tgt->f_frsize = TheISA::htog(host->f_bsize); 654#elif defined(__APPLE__) 655 tgt->f_namelen = 0; 656 tgt->f_frsize = 0; 657#else 658 tgt->f_namelen = TheISA::htog(host->f_namelen); 659 tgt->f_frsize = TheISA::htog(host->f_frsize); 660#endif 661#if defined(__linux__) 662 memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare)); 663#else 664 /* 665 * The fields are different sizes per OS. Don't bother with 666 * f_spare or f_reserved on non-Linux for now. 667 */ 668 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare)); 669#endif 670 671 tgt.copyOut(mem); 672} 673 674/// Target ioctl() handler. For the most part, programs call ioctl() 675/// only to find out if their stdout is a tty, to determine whether to 676/// do line or block buffering. We always claim that output fds are 677/// not TTYs to provide repeatable results. 678template <class OS> 679SyscallReturn 680ioctlFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 681{ 682 int index = 0; 683 auto p = tc->getProcessPtr(); 684 685 int tgt_fd = p->getSyscallArg(tc, index); 686 unsigned req = p->getSyscallArg(tc, index); 687 688 DPRINTF_SYSCALL(Verbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req); 689 690 if (OS::isTtyReq(req)) 691 return -ENOTTY; 692 693 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]); 694 if (dfdp) { 695 EmulatedDriver *emul_driver = dfdp->getDriver(); 696 if (emul_driver) 697 return emul_driver->ioctl(tc, req); 698 } 699 700 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]); 701 if (sfdp) { 702 int status; 703 704 switch (req) { 705 case SIOCGIFCONF: { 706 Addr conf_addr = p->getSyscallArg(tc, index); 707 BufferArg conf_arg(conf_addr, sizeof(ifconf)); 708 conf_arg.copyIn(tc->getVirtProxy()); 709 710 ifconf *conf = (ifconf*)conf_arg.bufferPtr(); 711 Addr ifc_buf_addr = (Addr)conf->ifc_buf; 712 BufferArg ifc_buf_arg(ifc_buf_addr, conf->ifc_len); 713 ifc_buf_arg.copyIn(tc->getVirtProxy()); 714 715 conf->ifc_buf = (char*)ifc_buf_arg.bufferPtr(); 716 717 status = ioctl(sfdp->getSimFD(), req, conf_arg.bufferPtr()); 718 if (status != -1) { 719 conf->ifc_buf = (char*)ifc_buf_addr; 720 ifc_buf_arg.copyOut(tc->getVirtProxy()); 721 conf_arg.copyOut(tc->getVirtProxy()); 722 } 723 724 return status; 725 } 726 case SIOCGIFFLAGS: 727#if defined(__linux__) 728 case SIOCGIFINDEX: 729#endif 730 case SIOCGIFNETMASK: 731 case SIOCGIFADDR: 732#if defined(__linux__) 733 case SIOCGIFHWADDR: 734#endif 735 case SIOCGIFMTU: { 736 Addr req_addr = p->getSyscallArg(tc, index); 737 BufferArg req_arg(req_addr, sizeof(ifreq)); 738 req_arg.copyIn(tc->getVirtProxy()); 739 740 status = ioctl(sfdp->getSimFD(), req, req_arg.bufferPtr()); 741 if (status != -1) 742 req_arg.copyOut(tc->getVirtProxy()); 743 return status; 744 } 745 } 746 } 747 748 /** 749 * For lack of a better return code, return ENOTTY. Ideally, we should 750 * return something better here, but at least we issue the warning. 751 */ 752 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n", 753 tgt_fd, req, tc->pcState()); 754 return -ENOTTY; 755} 756 757template <class OS> 758SyscallReturn 759openImpl(SyscallDesc *desc, int callnum, ThreadContext *tc, bool isopenat) 760{ 761 int index = 0; 762 auto p = tc->getProcessPtr(); 763 int tgt_dirfd = -1; 764 765 /** 766 * If using the openat variant, read in the target directory file 767 * descriptor from the simulated process. 768 */ 769 if (isopenat) 770 tgt_dirfd = p->getSyscallArg(tc, index); 771 772 /** 773 * Retrieve the simulated process' memory proxy and then read in the path 774 * string from that memory space into the host's working memory space. 775 */ 776 std::string path; 777 if (!tc->getVirtProxy().tryReadString(path, p->getSyscallArg(tc, index))) 778 return -EFAULT; 779 780#ifdef __CYGWIN32__ 781 int host_flags = O_BINARY; 782#else 783 int host_flags = 0; 784#endif 785 /** 786 * Translate target flags into host flags. Flags exist which are not 787 * ported between architectures which can cause check failures. 788 */ 789 int tgt_flags = p->getSyscallArg(tc, index); 790 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) { 791 if (tgt_flags & OS::openFlagTable[i].tgtFlag) { 792 tgt_flags &= ~OS::openFlagTable[i].tgtFlag; 793 host_flags |= OS::openFlagTable[i].hostFlag; 794 } 795 } 796 if (tgt_flags) { 797 warn("open%s: cannot decode flags 0x%x", 798 isopenat ? "at" : "", tgt_flags); 799 } 800#ifdef __CYGWIN32__ 801 host_flags |= O_BINARY; 802#endif 803 804 int mode = p->getSyscallArg(tc, index); 805 806 /** 807 * If the simulated process called open or openat with AT_FDCWD specified, 808 * take the current working directory value which was passed into the 809 * process class as a Python parameter and append the current path to 810 * create a full path. 811 * Otherwise, openat with a valid target directory file descriptor has 812 * been called. If the path option, which was passed in as a parameter, 813 * is not absolute, retrieve the directory file descriptor's path and 814 * prepend it to the path passed in as a parameter. 815 * In every case, we should have a full path (which is relevant to the 816 * host) to work with after this block has been passed. 817 */ 818 std::string redir_path = path; 819 std::string abs_path = path; 820 if (!isopenat || tgt_dirfd == OS::TGT_AT_FDCWD) { 821 abs_path = p->absolutePath(path, true); 822 redir_path = p->checkPathRedirect(path); 823 } else if (!startswith(path, "/")) { 824 std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]); 825 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep); 826 if (!ffdp) 827 return -EBADF; 828 abs_path = ffdp->getFileName() + path; 829 redir_path = p->checkPathRedirect(abs_path); 830 } 831 832 /** 833 * Since this is an emulated environment, we create pseudo file 834 * descriptors for device requests that have been registered with 835 * the process class through Python; this allows us to create a file 836 * descriptor for subsequent ioctl or mmap calls. 837 */ 838 if (startswith(abs_path, "/dev/")) { 839 std::string filename = abs_path.substr(strlen("/dev/")); 840 EmulatedDriver *drv = p->findDriver(filename); 841 if (drv) { 842 DPRINTF_SYSCALL(Verbose, "open%s: passing call to " 843 "driver open with path[%s]\n", 844 isopenat ? "at" : "", abs_path.c_str()); 845 return drv->open(tc, mode, host_flags); 846 } 847 /** 848 * Fall through here for pass through to host devices, such 849 * as /dev/zero 850 */ 851 } 852 853 /** 854 * We make several attempts resolve a call to open. 855 * 856 * 1) Resolve any path redirection before hand. This will set the path 857 * up with variable 'redir_path' which may contain a modified path or 858 * the original path value. This should already be done in prior code. 859 * 2) Try to handle the access using 'special_paths'. Some special_paths 860 * and files cannot be called on the host and need to be handled as 861 * special cases inside the simulator. These special_paths are handled by 862 * C++ routines to provide output back to userspace. 863 * 3) If the full path that was created above does not match any of the 864 * special cases, pass it through to the open call on the __HOST__ to let 865 * the host open the file on our behalf. Again, the openImpl tries to 866 * USE_THE_HOST_FILESYSTEM_OPEN (with a possible redirection to the 867 * faux-filesystem files). The faux-filesystem is dynamically created 868 * during simulator configuration using Python functions. 869 * 4) If the host cannot open the file, the open attempt failed in "3)". 870 * Return the host's error code back through the system call to the 871 * simulated process. If running a debug trace, also notify the user that 872 * the open call failed. 873 * 874 * Any success will set sim_fd to something other than -1 and skip the 875 * next conditions effectively bypassing them. 876 */ 877 int sim_fd = -1; 878 std::string used_path; 879 std::vector<std::string> special_paths = 880 { "/proc/meminfo/", "/system/", "/platform/", "/etc/passwd" }; 881 for (auto entry : special_paths) { 882 if (startswith(path, entry)) { 883 sim_fd = OS::openSpecialFile(abs_path, p, tc); 884 used_path = abs_path; 885 } 886 } 887 if (sim_fd == -1) { 888 sim_fd = open(redir_path.c_str(), host_flags, mode); 889 used_path = redir_path; 890 } 891 if (sim_fd == -1) { 892 int local = -errno; 893 DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s " 894 "(inferred from:%s)\n", isopenat ? "at" : "", 895 used_path.c_str(), path.c_str()); 896 return local; 897 } 898 899 /** 900 * The file was opened successfully and needs to be recorded in the 901 * process' file descriptor array so that it can be retrieved later. 902 * The target file descriptor that is chosen will be the lowest unused 903 * file descriptor. 904 * Return the indirect target file descriptor back to the simulated 905 * process to act as a handle for the opened file. 906 */ 907 auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0); 908 int tgt_fd = p->fds->allocFD(ffdp); 909 DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n" 910 "(inferred from:%s)\n", isopenat ? "at" : "", 911 sim_fd, tgt_fd, used_path.c_str(), path.c_str()); 912 return tgt_fd; 913} 914 915/// Target open() handler. 916template <class OS> 917SyscallReturn 918openFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 919{ 920 return openImpl<OS>(desc, callnum, tc, false); 921} 922 923/// Target openat() handler. 924template <class OS> 925SyscallReturn 926openatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 927{ 928 return openImpl<OS>(desc, callnum, tc, true); 929} 930 931/// Target unlinkat() handler. 932template <class OS> 933SyscallReturn 934unlinkatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 935{ 936 int index = 0; 937 auto process = tc->getProcessPtr(); 938 int dirfd = process->getSyscallArg(tc, index); 939 if (dirfd != OS::TGT_AT_FDCWD) 940 warn("unlinkat: first argument not AT_FDCWD; unlikely to work"); 941 942 return unlinkHelper(desc, callnum, tc, 1); 943} 944 945/// Target facessat() handler 946template <class OS> 947SyscallReturn 948faccessatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 949{ 950 int index = 0; 951 auto process = tc->getProcessPtr(); 952 int dirfd = process->getSyscallArg(tc, index); 953 if (dirfd != OS::TGT_AT_FDCWD) 954 warn("faccessat: first argument not AT_FDCWD; unlikely to work"); 955 return accessFunc(desc, callnum, tc, 1); 956} 957 958/// Target readlinkat() handler 959template <class OS> 960SyscallReturn 961readlinkatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 962{ 963 int index = 0; 964 auto process = tc->getProcessPtr(); 965 int dirfd = process->getSyscallArg(tc, index); 966 if (dirfd != OS::TGT_AT_FDCWD) 967 warn("openat: first argument not AT_FDCWD; unlikely to work"); 968 return readlinkFunc(desc, callnum, tc, 1); 969} 970 971/// Target renameat() handler. 972template <class OS> 973SyscallReturn 974renameatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 975{ 976 int index = 0; 977 auto process = tc->getProcessPtr(); 978 979 int olddirfd = process->getSyscallArg(tc, index); 980 if (olddirfd != OS::TGT_AT_FDCWD) 981 warn("renameat: first argument not AT_FDCWD; unlikely to work"); 982 983 std::string old_name; 984 985 if (!tc->getVirtProxy().tryReadString(old_name, 986 process->getSyscallArg(tc, index))) 987 return -EFAULT; 988 989 int newdirfd = process->getSyscallArg(tc, index); 990 if (newdirfd != OS::TGT_AT_FDCWD) 991 warn("renameat: third argument not AT_FDCWD; unlikely to work"); 992 993 std::string new_name; 994 995 if (!tc->getVirtProxy().tryReadString(new_name, 996 process->getSyscallArg(tc, index))) 997 return -EFAULT; 998 999 // Adjust path for cwd and redirection 1000 old_name = process->checkPathRedirect(old_name); 1001 new_name = process->checkPathRedirect(new_name); 1002 1003 int result = rename(old_name.c_str(), new_name.c_str()); 1004 return (result == -1) ? -errno : result; 1005} 1006 1007/// Target sysinfo() handler. 1008template <class OS> 1009SyscallReturn 1010sysinfoFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1011{ 1012 int index = 0; 1013 auto process = tc->getProcessPtr(); 1014 1015 TypedBufferArg<typename OS::tgt_sysinfo> 1016 sysinfo(process->getSyscallArg(tc, index)); 1017 1018 sysinfo->uptime = seconds_since_epoch; 1019 sysinfo->totalram = process->system->memSize(); 1020 sysinfo->mem_unit = 1; 1021 1022 sysinfo.copyOut(tc->getVirtProxy()); 1023 1024 return 0; 1025} 1026 1027/// Target chmod() handler. 1028template <class OS> 1029SyscallReturn 1030chmodFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1031{ 1032 std::string path; 1033 auto process = tc->getProcessPtr(); 1034 1035 int index = 0; 1036 if (!tc->getVirtProxy().tryReadString(path, 1037 process->getSyscallArg(tc, index))) { 1038 return -EFAULT; 1039 } 1040 1041 uint32_t mode = process->getSyscallArg(tc, index); 1042 mode_t hostMode = 0; 1043 1044 // XXX translate mode flags via OS::something??? 1045 hostMode = mode; 1046 1047 // Adjust path for cwd and redirection 1048 path = process->checkPathRedirect(path); 1049 1050 // do the chmod 1051 int result = chmod(path.c_str(), hostMode); 1052 if (result < 0) 1053 return -errno; 1054 1055 return 0; 1056} 1057 1058template <class OS> 1059SyscallReturn 1060pollFunc(SyscallDesc *desc, int num, ThreadContext *tc) 1061{ 1062 int index = 0; 1063 auto p = tc->getProcessPtr(); 1064 Addr fdsPtr = p->getSyscallArg(tc, index); 1065 int nfds = p->getSyscallArg(tc, index); 1066 int tmout = p->getSyscallArg(tc, index); 1067 1068 BufferArg fdsBuf(fdsPtr, sizeof(struct pollfd) * nfds); 1069 fdsBuf.copyIn(tc->getVirtProxy()); 1070 1071 /** 1072 * Record the target file descriptors in a local variable. We need to 1073 * replace them with host file descriptors but we need a temporary copy 1074 * for later. Afterwards, replace each target file descriptor in the 1075 * poll_fd array with its host_fd. 1076 */ 1077 int temp_tgt_fds[nfds]; 1078 for (index = 0; index < nfds; index++) { 1079 temp_tgt_fds[index] = ((struct pollfd *)fdsBuf.bufferPtr())[index].fd; 1080 auto tgt_fd = temp_tgt_fds[index]; 1081 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 1082 if (!hbfdp) 1083 return -EBADF; 1084 auto host_fd = hbfdp->getSimFD(); 1085 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = host_fd; 1086 } 1087 1088 /** 1089 * We cannot allow an infinite poll to occur or it will inevitably cause 1090 * a deadlock in the gem5 simulator with clone. We must pass in tmout with 1091 * a non-negative value, however it also makes no sense to poll on the 1092 * underlying host for any other time than tmout a zero timeout. 1093 */ 1094 int status; 1095 if (tmout < 0) { 1096 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0); 1097 if (status == 0) { 1098 /** 1099 * If blocking indefinitely, check the signal list to see if a 1100 * signal would break the poll out of the retry cycle and try 1101 * to return the signal interrupt instead. 1102 */ 1103 System *sysh = tc->getSystemPtr(); 1104 std::list<BasicSignal>::iterator it; 1105 for (it=sysh->signalList.begin(); it!=sysh->signalList.end(); it++) 1106 if (it->receiver == p) 1107 return -EINTR; 1108 return SyscallReturn::retry(); 1109 } 1110 } else 1111 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0); 1112 1113 if (status == -1) 1114 return -errno; 1115 1116 /** 1117 * Replace each host_fd in the returned poll_fd array with its original 1118 * target file descriptor. 1119 */ 1120 for (index = 0; index < nfds; index++) { 1121 auto tgt_fd = temp_tgt_fds[index]; 1122 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = tgt_fd; 1123 } 1124 1125 /** 1126 * Copy out the pollfd struct because the host may have updated fields 1127 * in the structure. 1128 */ 1129 fdsBuf.copyOut(tc->getVirtProxy()); 1130 1131 return status; 1132} 1133 1134/// Target fchmod() handler. 1135template <class OS> 1136SyscallReturn 1137fchmodFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1138{ 1139 int index = 0; 1140 auto p = tc->getProcessPtr(); 1141 int tgt_fd = p->getSyscallArg(tc, index); 1142 uint32_t mode = p->getSyscallArg(tc, index); 1143 1144 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1145 if (!ffdp) 1146 return -EBADF; 1147 int sim_fd = ffdp->getSimFD(); 1148 1149 mode_t hostMode = mode; 1150 1151 int result = fchmod(sim_fd, hostMode); 1152 1153 return (result < 0) ? -errno : 0; 1154} 1155 1156/// Target mremap() handler. 1157template <class OS> 1158SyscallReturn 1159mremapFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1160{ 1161 int index = 0; 1162 auto process = tc->getProcessPtr(); 1163 Addr start = process->getSyscallArg(tc, index); 1164 uint64_t old_length = process->getSyscallArg(tc, index); 1165 uint64_t new_length = process->getSyscallArg(tc, index); 1166 uint64_t flags = process->getSyscallArg(tc, index); 1167 uint64_t provided_address = 0; 1168 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED; 1169 1170 if (use_provided_address) 1171 provided_address = process->getSyscallArg(tc, index); 1172 1173 if ((start % TheISA::PageBytes != 0) || 1174 (provided_address % TheISA::PageBytes != 0)) { 1175 warn("mremap failing: arguments not page aligned"); 1176 return -EINVAL; 1177 } 1178 1179 new_length = roundUp(new_length, TheISA::PageBytes); 1180 1181 if (new_length > old_length) { 1182 std::shared_ptr<MemState> mem_state = process->memState; 1183 Addr mmap_end = mem_state->getMmapEnd(); 1184 1185 if ((start + old_length) == mmap_end && 1186 (!use_provided_address || provided_address == start)) { 1187 // This case cannot occur when growing downward, as 1188 // start is greater than or equal to mmap_end. 1189 uint64_t diff = new_length - old_length; 1190 process->allocateMem(mmap_end, diff); 1191 mem_state->setMmapEnd(mmap_end + diff); 1192 return start; 1193 } else { 1194 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) { 1195 warn("can't remap here and MREMAP_MAYMOVE flag not set\n"); 1196 return -ENOMEM; 1197 } else { 1198 uint64_t new_start = provided_address; 1199 if (!use_provided_address) { 1200 new_start = process->mmapGrowsDown() ? 1201 mmap_end - new_length : mmap_end; 1202 mmap_end = process->mmapGrowsDown() ? 1203 new_start : mmap_end + new_length; 1204 mem_state->setMmapEnd(mmap_end); 1205 } 1206 1207 process->pTable->remap(start, old_length, new_start); 1208 warn("mremapping to new vaddr %08p-%08p, adding %d\n", 1209 new_start, new_start + new_length, 1210 new_length - old_length); 1211 // add on the remaining unallocated pages 1212 process->allocateMem(new_start + old_length, 1213 new_length - old_length, 1214 use_provided_address /* clobber */); 1215 if (use_provided_address && 1216 ((new_start + new_length > mem_state->getMmapEnd() && 1217 !process->mmapGrowsDown()) || 1218 (new_start < mem_state->getMmapEnd() && 1219 process->mmapGrowsDown()))) { 1220 // something fishy going on here, at least notify the user 1221 // @todo: increase mmap_end? 1222 warn("mmap region limit exceeded with MREMAP_FIXED\n"); 1223 } 1224 warn("returning %08p as start\n", new_start); 1225 return new_start; 1226 } 1227 } 1228 } else { 1229 if (use_provided_address && provided_address != start) 1230 process->pTable->remap(start, new_length, provided_address); 1231 process->pTable->unmap(start + new_length, old_length - new_length); 1232 return use_provided_address ? provided_address : start; 1233 } 1234} 1235 1236/// Target stat() handler. 1237template <class OS> 1238SyscallReturn 1239statFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1240{ 1241 std::string path; 1242 auto process = tc->getProcessPtr(); 1243 1244 int index = 0; 1245 if (!tc->getVirtProxy().tryReadString(path, 1246 process->getSyscallArg(tc, index))) { 1247 return -EFAULT; 1248 } 1249 Addr bufPtr = process->getSyscallArg(tc, index); 1250 1251 // Adjust path for cwd and redirection 1252 path = process->checkPathRedirect(path); 1253 1254 struct stat hostBuf; 1255 int result = stat(path.c_str(), &hostBuf); 1256 1257 if (result < 0) 1258 return -errno; 1259 1260 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1261 1262 return 0; 1263} 1264 1265 1266/// Target stat64() handler. 1267template <class OS> 1268SyscallReturn 1269stat64Func(SyscallDesc *desc, int callnum, ThreadContext *tc) 1270{ 1271 std::string path; 1272 auto process = tc->getProcessPtr(); 1273 1274 int index = 0; 1275 if (!tc->getVirtProxy().tryReadString(path, 1276 process->getSyscallArg(tc, index))) 1277 return -EFAULT; 1278 Addr bufPtr = process->getSyscallArg(tc, index); 1279 1280 // Adjust path for cwd and redirection 1281 path = process->checkPathRedirect(path); 1282 1283#if NO_STAT64 1284 struct stat hostBuf; 1285 int result = stat(path.c_str(), &hostBuf); 1286#else 1287 struct stat64 hostBuf; 1288 int result = stat64(path.c_str(), &hostBuf); 1289#endif 1290 1291 if (result < 0) 1292 return -errno; 1293 1294 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1295 1296 return 0; 1297} 1298 1299 1300/// Target fstatat64() handler. 1301template <class OS> 1302SyscallReturn 1303fstatat64Func(SyscallDesc *desc, int callnum, ThreadContext *tc) 1304{ 1305 int index = 0; 1306 auto process = tc->getProcessPtr(); 1307 int dirfd = process->getSyscallArg(tc, index); 1308 if (dirfd != OS::TGT_AT_FDCWD) 1309 warn("fstatat64: first argument not AT_FDCWD; unlikely to work"); 1310 1311 std::string path; 1312 if (!tc->getVirtProxy().tryReadString(path, 1313 process->getSyscallArg(tc, index))) 1314 return -EFAULT; 1315 Addr bufPtr = process->getSyscallArg(tc, index); 1316 1317 // Adjust path for cwd and redirection 1318 path = process->checkPathRedirect(path); 1319 1320#if NO_STAT64 1321 struct stat hostBuf; 1322 int result = stat(path.c_str(), &hostBuf); 1323#else 1324 struct stat64 hostBuf; 1325 int result = stat64(path.c_str(), &hostBuf); 1326#endif 1327 1328 if (result < 0) 1329 return -errno; 1330 1331 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1332 1333 return 0; 1334} 1335 1336 1337/// Target fstat64() handler. 1338template <class OS> 1339SyscallReturn 1340fstat64Func(SyscallDesc *desc, int callnum, ThreadContext *tc) 1341{ 1342 int index = 0; 1343 auto p = tc->getProcessPtr(); 1344 int tgt_fd = p->getSyscallArg(tc, index); 1345 Addr bufPtr = p->getSyscallArg(tc, index); 1346 1347 auto ffdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 1348 if (!ffdp) 1349 return -EBADF; 1350 int sim_fd = ffdp->getSimFD(); 1351 1352#if NO_STAT64 1353 struct stat hostBuf; 1354 int result = fstat(sim_fd, &hostBuf); 1355#else 1356 struct stat64 hostBuf; 1357 int result = fstat64(sim_fd, &hostBuf); 1358#endif 1359 1360 if (result < 0) 1361 return -errno; 1362 1363 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf, (sim_fd == 1)); 1364 1365 return 0; 1366} 1367 1368 1369/// Target lstat() handler. 1370template <class OS> 1371SyscallReturn 1372lstatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1373{ 1374 std::string path; 1375 auto process = tc->getProcessPtr(); 1376 1377 int index = 0; 1378 if (!tc->getVirtProxy().tryReadString(path, 1379 process->getSyscallArg(tc, index))) { 1380 return -EFAULT; 1381 } 1382 Addr bufPtr = process->getSyscallArg(tc, index); 1383 1384 // Adjust path for cwd and redirection 1385 path = process->checkPathRedirect(path); 1386 1387 struct stat hostBuf; 1388 int result = lstat(path.c_str(), &hostBuf); 1389 1390 if (result < 0) 1391 return -errno; 1392 1393 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1394 1395 return 0; 1396} 1397 1398/// Target lstat64() handler. 1399template <class OS> 1400SyscallReturn 1401lstat64Func(SyscallDesc *desc, int callnum, ThreadContext *tc) 1402{ 1403 std::string path; 1404 auto process = tc->getProcessPtr(); 1405 1406 int index = 0; 1407 if (!tc->getVirtProxy().tryReadString(path, 1408 process->getSyscallArg(tc, index))) { 1409 return -EFAULT; 1410 } 1411 Addr bufPtr = process->getSyscallArg(tc, index); 1412 1413 // Adjust path for cwd and redirection 1414 path = process->checkPathRedirect(path); 1415 1416#if NO_STAT64 1417 struct stat hostBuf; 1418 int result = lstat(path.c_str(), &hostBuf); 1419#else 1420 struct stat64 hostBuf; 1421 int result = lstat64(path.c_str(), &hostBuf); 1422#endif 1423 1424 if (result < 0) 1425 return -errno; 1426 1427 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1428 1429 return 0; 1430} 1431 1432/// Target fstat() handler. 1433template <class OS> 1434SyscallReturn 1435fstatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1436{ 1437 int index = 0; 1438 auto p = tc->getProcessPtr(); 1439 int tgt_fd = p->getSyscallArg(tc, index); 1440 Addr bufPtr = p->getSyscallArg(tc, index); 1441 1442 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd); 1443 1444 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1445 if (!ffdp) 1446 return -EBADF; 1447 int sim_fd = ffdp->getSimFD(); 1448 1449 struct stat hostBuf; 1450 int result = fstat(sim_fd, &hostBuf); 1451 1452 if (result < 0) 1453 return -errno; 1454 1455 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf, (sim_fd == 1)); 1456 1457 return 0; 1458} 1459 1460/// Target statfs() handler. 1461template <class OS> 1462SyscallReturn 1463statfsFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1464{ 1465#if defined(__linux__) 1466 std::string path; 1467 auto process = tc->getProcessPtr(); 1468 1469 int index = 0; 1470 if (!tc->getVirtProxy().tryReadString(path, 1471 process->getSyscallArg(tc, index))) { 1472 return -EFAULT; 1473 } 1474 Addr bufPtr = process->getSyscallArg(tc, index); 1475 1476 // Adjust path for cwd and redirection 1477 path = process->checkPathRedirect(path); 1478 1479 struct statfs hostBuf; 1480 int result = statfs(path.c_str(), &hostBuf); 1481 1482 if (result < 0) 1483 return -errno; 1484 1485 copyOutStatfsBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1486 return 0; 1487#else 1488 warnUnsupportedOS("statfs"); 1489 return -1; 1490#endif 1491} 1492 1493template <class OS> 1494SyscallReturn 1495cloneFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1496{ 1497 int index = 0; 1498 1499 auto p = tc->getProcessPtr(); 1500 RegVal flags = p->getSyscallArg(tc, index); 1501 RegVal newStack = p->getSyscallArg(tc, index); 1502 Addr ptidPtr = p->getSyscallArg(tc, index); 1503 1504#if THE_ISA == RISCV_ISA or THE_ISA == ARM_ISA 1505 /** 1506 * Linux sets CLONE_BACKWARDS flag for RISC-V and Arm. 1507 * The flag defines the list of clone() arguments in the following 1508 * order: flags -> newStack -> ptidPtr -> tlsPtr -> ctidPtr 1509 */ 1510 Addr tlsPtr = p->getSyscallArg(tc, index); 1511 Addr ctidPtr = p->getSyscallArg(tc, index); 1512#else 1513 Addr ctidPtr = p->getSyscallArg(tc, index); 1514 Addr tlsPtr = p->getSyscallArg(tc, index); 1515#endif 1516 1517 if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) || 1518 ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) || 1519 ((flags & OS::TGT_CLONE_FS) && (flags & OS::TGT_CLONE_NEWNS)) || 1520 ((flags & OS::TGT_CLONE_NEWIPC) && (flags & OS::TGT_CLONE_SYSVSEM)) || 1521 ((flags & OS::TGT_CLONE_NEWPID) && (flags & OS::TGT_CLONE_THREAD)) || 1522 ((flags & OS::TGT_CLONE_VM) && !(newStack))) 1523 return -EINVAL; 1524 1525 ThreadContext *ctc; 1526 if (!(ctc = p->findFreeContext())) { 1527 DPRINTF_SYSCALL(Verbose, "clone: no spare thread context in system" 1528 "[cpu %d, thread %d]", tc->cpuId(), tc->threadId()); 1529 return -EAGAIN; 1530 } 1531 1532 /** 1533 * Note that ProcessParams is generated by swig and there are no other 1534 * examples of how to create anything but this default constructor. The 1535 * fields are manually initialized instead of passing parameters to the 1536 * constructor. 1537 */ 1538 ProcessParams *pp = new ProcessParams(); 1539 pp->executable.assign(*(new std::string(p->progName()))); 1540 pp->cmd.push_back(*(new std::string(p->progName()))); 1541 pp->system = p->system; 1542 pp->cwd.assign(p->tgtCwd); 1543 pp->input.assign("stdin"); 1544 pp->output.assign("stdout"); 1545 pp->errout.assign("stderr"); 1546 pp->uid = p->uid(); 1547 pp->euid = p->euid(); 1548 pp->gid = p->gid(); 1549 pp->egid = p->egid(); 1550 1551 /* Find the first free PID that's less than the maximum */ 1552 std::set<int> const& pids = p->system->PIDs; 1553 int temp_pid = *pids.begin(); 1554 do { 1555 temp_pid++; 1556 } while (pids.find(temp_pid) != pids.end()); 1557 if (temp_pid >= System::maxPID) 1558 fatal("temp_pid is too large: %d", temp_pid); 1559 1560 pp->pid = temp_pid; 1561 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid(); 1562 pp->useArchPT = p->useArchPT; 1563 pp->kvmInSE = p->kvmInSE; 1564 Process *cp = pp->create(); 1565 delete pp; 1566 1567 Process *owner = ctc->getProcessPtr(); 1568 ctc->setProcessPtr(cp); 1569 cp->assignThreadContext(ctc->contextId()); 1570 owner->revokeThreadContext(ctc->contextId()); 1571 1572 if (flags & OS::TGT_CLONE_PARENT_SETTID) { 1573 BufferArg ptidBuf(ptidPtr, sizeof(long)); 1574 long *ptid = (long *)ptidBuf.bufferPtr(); 1575 *ptid = cp->pid(); 1576 ptidBuf.copyOut(tc->getVirtProxy()); 1577 } 1578 1579 if (flags & OS::TGT_CLONE_THREAD) { 1580 cp->pTable->shared = true; 1581 cp->useForClone = true; 1582 } 1583 cp->initState(); 1584 p->clone(tc, ctc, cp, flags); 1585 1586 if (flags & OS::TGT_CLONE_THREAD) { 1587 delete cp->sigchld; 1588 cp->sigchld = p->sigchld; 1589 } else if (flags & OS::TGT_SIGCHLD) { 1590 *cp->sigchld = true; 1591 } 1592 1593 if (flags & OS::TGT_CLONE_CHILD_SETTID) { 1594 BufferArg ctidBuf(ctidPtr, sizeof(long)); 1595 long *ctid = (long *)ctidBuf.bufferPtr(); 1596 *ctid = cp->pid(); 1597 ctidBuf.copyOut(ctc->getVirtProxy()); 1598 } 1599 1600 if (flags & OS::TGT_CLONE_CHILD_CLEARTID) 1601 cp->childClearTID = (uint64_t)ctidPtr; 1602 1603 ctc->clearArchRegs(); 1604 1605 OS::archClone(flags, p, cp, tc, ctc, newStack, tlsPtr); 1606 1607 cp->setSyscallReturn(ctc, 0); 1608 1609#if THE_ISA == ALPHA_ISA 1610 ctc->setIntReg(TheISA::SyscallSuccessReg, 0); 1611#elif THE_ISA == SPARC_ISA 1612 tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0); 1613 ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1); 1614#endif 1615 1616 if (p->kvmInSE) { 1617#if THE_ISA == X86_ISA 1618 ctc->pcState(tc->readIntReg(TheISA::INTREG_RCX)); 1619#else 1620 panic("KVM CPU model is not supported for this ISA"); 1621#endif 1622 } else { 1623 TheISA::PCState cpc = tc->pcState(); 1624 cpc.advance(); 1625 ctc->pcState(cpc); 1626 } 1627 ctc->activate(); 1628 1629 return cp->pid(); 1630} 1631 1632/// Target fstatfs() handler. 1633template <class OS> 1634SyscallReturn 1635fstatfsFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1636{ 1637 int index = 0; 1638 auto p = tc->getProcessPtr(); 1639 int tgt_fd = p->getSyscallArg(tc, index); 1640 Addr bufPtr = p->getSyscallArg(tc, index); 1641 1642 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1643 if (!ffdp) 1644 return -EBADF; 1645 int sim_fd = ffdp->getSimFD(); 1646 1647 struct statfs hostBuf; 1648 int result = fstatfs(sim_fd, &hostBuf); 1649 1650 if (result < 0) 1651 return -errno; 1652 1653 copyOutStatfsBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf); 1654 1655 return 0; 1656} 1657 1658/// Target readv() handler. 1659template <class OS> 1660SyscallReturn 1661readvFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1662{ 1663 int index = 0; 1664 auto p = tc->getProcessPtr(); 1665 int tgt_fd = p->getSyscallArg(tc, index); 1666 1667 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1668 if (!ffdp) 1669 return -EBADF; 1670 int sim_fd = ffdp->getSimFD(); 1671 1672 PortProxy &prox = tc->getVirtProxy(); 1673 uint64_t tiov_base = p->getSyscallArg(tc, index); 1674 size_t count = p->getSyscallArg(tc, index); 1675 typename OS::tgt_iovec tiov[count]; 1676 struct iovec hiov[count]; 1677 for (size_t i = 0; i < count; ++i) { 1678 prox.readBlob(tiov_base + (i * sizeof(typename OS::tgt_iovec)), 1679 &tiov[i], sizeof(typename OS::tgt_iovec)); 1680 hiov[i].iov_len = TheISA::gtoh(tiov[i].iov_len); 1681 hiov[i].iov_base = new char [hiov[i].iov_len]; 1682 } 1683 1684 int result = readv(sim_fd, hiov, count); 1685 int local_errno = errno; 1686 1687 for (size_t i = 0; i < count; ++i) { 1688 if (result != -1) { 1689 prox.writeBlob(TheISA::htog(tiov[i].iov_base), 1690 hiov[i].iov_base, hiov[i].iov_len); 1691 } 1692 delete [] (char *)hiov[i].iov_base; 1693 } 1694 1695 return (result == -1) ? -local_errno : result; 1696} 1697 1698/// Target writev() handler. 1699template <class OS> 1700SyscallReturn 1701writevFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1702{ 1703 int index = 0; 1704 auto p = tc->getProcessPtr(); 1705 int tgt_fd = p->getSyscallArg(tc, index); 1706 1707 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 1708 if (!hbfdp) 1709 return -EBADF; 1710 int sim_fd = hbfdp->getSimFD(); 1711 1712 PortProxy &prox = tc->getVirtProxy(); 1713 uint64_t tiov_base = p->getSyscallArg(tc, index); 1714 size_t count = p->getSyscallArg(tc, index); 1715 struct iovec hiov[count]; 1716 for (size_t i = 0; i < count; ++i) { 1717 typename OS::tgt_iovec tiov; 1718 1719 prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec), 1720 &tiov, sizeof(typename OS::tgt_iovec)); 1721 hiov[i].iov_len = TheISA::gtoh(tiov.iov_len); 1722 hiov[i].iov_base = new char [hiov[i].iov_len]; 1723 prox.readBlob(TheISA::gtoh(tiov.iov_base), hiov[i].iov_base, 1724 hiov[i].iov_len); 1725 } 1726 1727 int result = writev(sim_fd, hiov, count); 1728 1729 for (size_t i = 0; i < count; ++i) 1730 delete [] (char *)hiov[i].iov_base; 1731 1732 return (result == -1) ? -errno : result; 1733} 1734 1735/// Real mmap handler. 1736template <class OS> 1737SyscallReturn 1738mmapImpl(SyscallDesc *desc, int num, ThreadContext *tc, bool is_mmap2) 1739{ 1740 int index = 0; 1741 auto p = tc->getProcessPtr(); 1742 Addr start = p->getSyscallArg(tc, index); 1743 uint64_t length = p->getSyscallArg(tc, index); 1744 int prot = p->getSyscallArg(tc, index); 1745 int tgt_flags = p->getSyscallArg(tc, index); 1746 int tgt_fd = p->getSyscallArg(tc, index); 1747 int offset = p->getSyscallArg(tc, index); 1748 1749 if (is_mmap2) 1750 offset *= TheISA::PageBytes; 1751 1752 if (start & (TheISA::PageBytes - 1) || 1753 offset & (TheISA::PageBytes - 1) || 1754 (tgt_flags & OS::TGT_MAP_PRIVATE && 1755 tgt_flags & OS::TGT_MAP_SHARED) || 1756 (!(tgt_flags & OS::TGT_MAP_PRIVATE) && 1757 !(tgt_flags & OS::TGT_MAP_SHARED)) || 1758 !length) { 1759 return -EINVAL; 1760 } 1761 1762 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) { 1763 // With shared mmaps, there are two cases to consider: 1764 // 1) anonymous: writes should modify the mapping and this should be 1765 // visible to observers who share the mapping. Currently, it's 1766 // difficult to update the shared mapping because there's no 1767 // structure which maintains information about the which virtual 1768 // memory areas are shared. If that structure existed, it would be 1769 // possible to make the translations point to the same frames. 1770 // 2) file-backed: writes should modify the mapping and the file 1771 // which is backed by the mapping. The shared mapping problem is the 1772 // same as what was mentioned about the anonymous mappings. For 1773 // file-backed mappings, the writes to the file are difficult 1774 // because it requires syncing what the mapping holds with the file 1775 // that resides on the host system. So, any write on a real system 1776 // would cause the change to be propagated to the file mapping at 1777 // some point in the future (the inode is tracked along with the 1778 // mapping). This isn't guaranteed to always happen, but it usually 1779 // works well enough. The guarantee is provided by the msync system 1780 // call. We could force the change through with shared mappings with 1781 // a call to msync, but that again would require more information 1782 // than we currently maintain. 1783 warn("mmap: writing to shared mmap region is currently " 1784 "unsupported. The write succeeds on the target, but it " 1785 "will not be propagated to the host or shared mappings"); 1786 } 1787 1788 length = roundUp(length, TheISA::PageBytes); 1789 1790 int sim_fd = -1; 1791 uint8_t *pmap = nullptr; 1792 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) { 1793 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd]; 1794 1795 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep); 1796 if (dfdp) { 1797 EmulatedDriver *emul_driver = dfdp->getDriver(); 1798 return emul_driver->mmap(tc, start, length, prot, tgt_flags, 1799 tgt_fd, offset); 1800 } 1801 1802 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep); 1803 if (!ffdp) 1804 return -EBADF; 1805 sim_fd = ffdp->getSimFD(); 1806 1807 pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE, 1808 sim_fd, offset); 1809 1810 if (pmap == (decltype(pmap))-1) { 1811 warn("mmap: failed to map file into host address space"); 1812 return -errno; 1813 } 1814 } 1815 1816 // Extend global mmap region if necessary. Note that we ignore the 1817 // start address unless MAP_FIXED is specified. 1818 if (!(tgt_flags & OS::TGT_MAP_FIXED)) { 1819 std::shared_ptr<MemState> mem_state = p->memState; 1820 Addr mmap_end = mem_state->getMmapEnd(); 1821 1822 start = p->mmapGrowsDown() ? mmap_end - length : mmap_end; 1823 mmap_end = p->mmapGrowsDown() ? start : mmap_end + length; 1824 1825 mem_state->setMmapEnd(mmap_end); 1826 } 1827 1828 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n", 1829 start, start + length - 1); 1830 1831 // We only allow mappings to overwrite existing mappings if 1832 // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem 1833 // because we ignore the start hint if TGT_MAP_FIXED is not set. 1834 int clobber = tgt_flags & OS::TGT_MAP_FIXED; 1835 if (clobber) { 1836 for (auto tc : p->system->threadContexts) { 1837 // If we might be overwriting old mappings, we need to 1838 // invalidate potentially stale mappings out of the TLBs. 1839 tc->getDTBPtr()->flushAll(); 1840 tc->getITBPtr()->flushAll(); 1841 } 1842 } 1843 1844 // Allocate physical memory and map it in. If the page table is already 1845 // mapped and clobber is not set, the simulator will issue throw a 1846 // fatal and bail out of the simulation. 1847 p->allocateMem(start, length, clobber); 1848 1849 // Transfer content into target address space. 1850 PortProxy &tp = tc->getVirtProxy(); 1851 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) { 1852 // In general, we should zero the mapped area for anonymous mappings, 1853 // with something like: 1854 // tp.memsetBlob(start, 0, length); 1855 // However, given that we don't support sparse mappings, and 1856 // some applications can map a couple of gigabytes of space 1857 // (intending sparse usage), that can get painfully expensive. 1858 // Fortunately, since we don't properly implement munmap either, 1859 // there's no danger of remapping used memory, so for now all 1860 // newly mapped memory should already be zeroed so we can skip it. 1861 } else { 1862 // It is possible to mmap an area larger than a file, however 1863 // accessing unmapped portions the system triggers a "Bus error" 1864 // on the host. We must know when to stop copying the file from 1865 // the host into the target address space. 1866 struct stat file_stat; 1867 if (fstat(sim_fd, &file_stat) > 0) 1868 fatal("mmap: cannot stat file"); 1869 1870 // Copy the portion of the file that is resident. This requires 1871 // checking both the mmap size and the filesize that we are 1872 // trying to mmap into this space; the mmap size also depends 1873 // on the specified offset into the file. 1874 uint64_t size = std::min((uint64_t)file_stat.st_size - offset, 1875 length); 1876 tp.writeBlob(start, pmap, size); 1877 1878 // Cleanup the mmap region before exiting this function. 1879 munmap(pmap, length); 1880 1881 // Maintain the symbol table for dynamic executables. 1882 // The loader will call mmap to map the images into its address 1883 // space and we intercept that here. We can verify that we are 1884 // executing inside the loader by checking the program counter value. 1885 // XXX: with multiprogrammed workloads or multi-node configurations, 1886 // this will not work since there is a single global symbol table. 1887 ObjectFile *interpreter = p->getInterpreter(); 1888 if (interpreter) { 1889 Addr text_start = interpreter->textBase(); 1890 Addr text_end = text_start + interpreter->textSize(); 1891 1892 Addr pc = tc->pcState().pc(); 1893 1894 if (pc >= text_start && pc < text_end) { 1895 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd]; 1896 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep); 1897 ObjectFile *lib = createObjectFile(ffdp->getFileName()); 1898 1899 if (lib) { 1900 lib->loadAllSymbols(debugSymbolTable, 1901 lib->textBase(), start); 1902 } 1903 } 1904 } 1905 1906 // Note that we do not zero out the remainder of the mapping. This 1907 // is done by a real system, but it probably will not affect 1908 // execution (hopefully). 1909 } 1910 1911 return start; 1912} 1913 1914template <class OS> 1915SyscallReturn 1916pwrite64Func(SyscallDesc *desc, int num, ThreadContext *tc) 1917{ 1918 int index = 0; 1919 auto p = tc->getProcessPtr(); 1920 int tgt_fd = p->getSyscallArg(tc, index); 1921 Addr bufPtr = p->getSyscallArg(tc, index); 1922 int nbytes = p->getSyscallArg(tc, index); 1923 int offset = p->getSyscallArg(tc, index); 1924 1925 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]); 1926 if (!ffdp) 1927 return -EBADF; 1928 int sim_fd = ffdp->getSimFD(); 1929 1930 BufferArg bufArg(bufPtr, nbytes); 1931 bufArg.copyIn(tc->getVirtProxy()); 1932 1933 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset); 1934 1935 return (bytes_written == -1) ? -errno : bytes_written; 1936} 1937 1938/// Target mmap() handler. 1939template <class OS> 1940SyscallReturn 1941mmapFunc(SyscallDesc *desc, int num, ThreadContext *tc) 1942{ 1943 return mmapImpl<OS>(desc, num, tc, false); 1944} 1945 1946/// Target mmap2() handler. 1947template <class OS> 1948SyscallReturn 1949mmap2Func(SyscallDesc *desc, int num, ThreadContext *tc) 1950{ 1951 return mmapImpl<OS>(desc, num, tc, true); 1952} 1953 1954/// Target getrlimit() handler. 1955template <class OS> 1956SyscallReturn 1957getrlimitFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1958{ 1959 int index = 0; 1960 auto process = tc->getProcessPtr(); 1961 unsigned resource = process->getSyscallArg(tc, index); 1962 TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index)); 1963 1964 switch (resource) { 1965 case OS::TGT_RLIMIT_STACK: 1966 // max stack size in bytes: make up a number (8MB for now) 1967 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024; 1968 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 1969 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 1970 break; 1971 1972 case OS::TGT_RLIMIT_DATA: 1973 // max data segment size in bytes: make up a number 1974 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024; 1975 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 1976 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 1977 break; 1978 1979 case OS::TGT_RLIMIT_NPROC: 1980 rlp->rlim_cur = rlp->rlim_max = tc->getSystemPtr()->numContexts(); 1981 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 1982 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 1983 break; 1984 1985 default: 1986 warn("getrlimit: unimplemented resource %d", resource); 1987 return -EINVAL; 1988 break; 1989 } 1990 1991 rlp.copyOut(tc->getVirtProxy()); 1992 return 0; 1993} 1994 1995template <class OS> 1996SyscallReturn 1997prlimitFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 1998{ 1999 int index = 0; 2000 auto process = tc->getProcessPtr(); 2001 if (process->getSyscallArg(tc, index) != 0) 2002 { 2003 warn("prlimit: ignoring rlimits for nonzero pid"); 2004 return -EPERM; 2005 } 2006 int resource = process->getSyscallArg(tc, index); 2007 Addr n = process->getSyscallArg(tc, index); 2008 if (n != 0) 2009 warn("prlimit: ignoring new rlimit"); 2010 Addr o = process->getSyscallArg(tc, index); 2011 if (o != 0) 2012 { 2013 TypedBufferArg<typename OS::rlimit> rlp(o); 2014 switch (resource) { 2015 case OS::TGT_RLIMIT_STACK: 2016 // max stack size in bytes: make up a number (8MB for now) 2017 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024; 2018 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 2019 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 2020 break; 2021 case OS::TGT_RLIMIT_DATA: 2022 // max data segment size in bytes: make up a number 2023 rlp->rlim_cur = rlp->rlim_max = 256*1024*1024; 2024 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur); 2025 rlp->rlim_max = TheISA::htog(rlp->rlim_max); 2026 break; 2027 default: 2028 warn("prlimit: unimplemented resource %d", resource); 2029 return -EINVAL; 2030 break; 2031 } 2032 rlp.copyOut(tc->getVirtProxy()); 2033 } 2034 return 0; 2035} 2036 2037/// Target clock_gettime() function. 2038template <class OS> 2039SyscallReturn 2040clock_gettimeFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2041{ 2042 int index = 1; 2043 auto p = tc->getProcessPtr(); 2044 //int clk_id = p->getSyscallArg(tc, index); 2045 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index)); 2046 2047 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec); 2048 tp->tv_sec += seconds_since_epoch; 2049 tp->tv_sec = TheISA::htog(tp->tv_sec); 2050 tp->tv_nsec = TheISA::htog(tp->tv_nsec); 2051 2052 tp.copyOut(tc->getVirtProxy()); 2053 2054 return 0; 2055} 2056 2057/// Target clock_getres() function. 2058template <class OS> 2059SyscallReturn 2060clock_getresFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2061{ 2062 int index = 1; 2063 auto p = tc->getProcessPtr(); 2064 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index)); 2065 2066 // Set resolution at ns, which is what clock_gettime() returns 2067 tp->tv_sec = 0; 2068 tp->tv_nsec = 1; 2069 2070 tp.copyOut(tc->getVirtProxy()); 2071 2072 return 0; 2073} 2074 2075/// Target gettimeofday() handler. 2076template <class OS> 2077SyscallReturn 2078gettimeofdayFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2079{ 2080 int index = 0; 2081 auto process = tc->getProcessPtr(); 2082 TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index)); 2083 2084 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec); 2085 tp->tv_sec += seconds_since_epoch; 2086 tp->tv_sec = TheISA::htog(tp->tv_sec); 2087 tp->tv_usec = TheISA::htog(tp->tv_usec); 2088 2089 tp.copyOut(tc->getVirtProxy()); 2090 2091 return 0; 2092} 2093 2094 2095/// Target utimes() handler. 2096template <class OS> 2097SyscallReturn 2098utimesFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2099{ 2100 std::string path; 2101 auto process = tc->getProcessPtr(); 2102 2103 int index = 0; 2104 if (!tc->getVirtProxy().tryReadString(path, 2105 process->getSyscallArg(tc, index))) { 2106 return -EFAULT; 2107 } 2108 2109 TypedBufferArg<typename OS::timeval [2]> 2110 tp(process->getSyscallArg(tc, index)); 2111 tp.copyIn(tc->getVirtProxy()); 2112 2113 struct timeval hostTimeval[2]; 2114 for (int i = 0; i < 2; ++i) { 2115 hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec); 2116 hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec); 2117 } 2118 2119 // Adjust path for cwd and redirection 2120 path = process->checkPathRedirect(path); 2121 2122 int result = utimes(path.c_str(), hostTimeval); 2123 2124 if (result < 0) 2125 return -errno; 2126 2127 return 0; 2128} 2129 2130template <class OS> 2131SyscallReturn 2132execveFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2133{ 2134 desc->setFlags(0); 2135 auto p = tc->getProcessPtr(); 2136 2137 int index = 0; 2138 std::string path; 2139 PortProxy & mem_proxy = tc->getVirtProxy(); 2140 if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index))) 2141 return -EFAULT; 2142 2143 if (access(path.c_str(), F_OK) == -1) 2144 return -EACCES; 2145 2146 auto read_in = [](std::vector<std::string> &vect, 2147 PortProxy &mem_proxy, Addr mem_loc) 2148 { 2149 for (int inc = 0; ; inc++) { 2150 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr)); 2151 b.copyIn(mem_proxy); 2152 2153 if (!*(Addr*)b.bufferPtr()) 2154 break; 2155 2156 vect.push_back(std::string()); 2157 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr()); 2158 } 2159 }; 2160 2161 /** 2162 * Note that ProcessParams is generated by swig and there are no other 2163 * examples of how to create anything but this default constructor. The 2164 * fields are manually initialized instead of passing parameters to the 2165 * constructor. 2166 */ 2167 ProcessParams *pp = new ProcessParams(); 2168 pp->executable = path; 2169 Addr argv_mem_loc = p->getSyscallArg(tc, index); 2170 read_in(pp->cmd, mem_proxy, argv_mem_loc); 2171 Addr envp_mem_loc = p->getSyscallArg(tc, index); 2172 read_in(pp->env, mem_proxy, envp_mem_loc); 2173 pp->uid = p->uid(); 2174 pp->egid = p->egid(); 2175 pp->euid = p->euid(); 2176 pp->gid = p->gid(); 2177 pp->ppid = p->ppid(); 2178 pp->pid = p->pid(); 2179 pp->input.assign("cin"); 2180 pp->output.assign("cout"); 2181 pp->errout.assign("cerr"); 2182 pp->cwd.assign(p->tgtCwd); 2183 pp->system = p->system; 2184 /** 2185 * Prevent process object creation with identical PIDs (which will trip 2186 * a fatal check in Process constructor). The execve call is supposed to 2187 * take over the currently executing process' identity but replace 2188 * whatever it is doing with a new process image. Instead of hijacking 2189 * the process object in the simulator, we create a new process object 2190 * and bind to the previous process' thread below (hijacking the thread). 2191 */ 2192 p->system->PIDs.erase(p->pid()); 2193 Process *new_p = pp->create(); 2194 delete pp; 2195 2196 /** 2197 * Work through the file descriptor array and close any files marked 2198 * close-on-exec. 2199 */ 2200 new_p->fds = p->fds; 2201 for (int i = 0; i < new_p->fds->getSize(); i++) { 2202 std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i]; 2203 if (fdep && fdep->getCOE()) 2204 new_p->fds->closeFDEntry(i); 2205 } 2206 2207 *new_p->sigchld = true; 2208 2209 delete p; 2210 tc->clearArchRegs(); 2211 tc->setProcessPtr(new_p); 2212 new_p->assignThreadContext(tc->contextId()); 2213 new_p->initState(); 2214 tc->activate(); 2215 TheISA::PCState pcState = tc->pcState(); 2216 tc->setNPC(pcState.instAddr()); 2217 2218 desc->setFlags(SyscallDesc::SuppressReturnValue); 2219 return 0; 2220} 2221 2222/// Target getrusage() function. 2223template <class OS> 2224SyscallReturn 2225getrusageFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2226{ 2227 int index = 0; 2228 auto process = tc->getProcessPtr(); 2229 int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN 2230 TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index)); 2231 2232 rup->ru_utime.tv_sec = 0; 2233 rup->ru_utime.tv_usec = 0; 2234 rup->ru_stime.tv_sec = 0; 2235 rup->ru_stime.tv_usec = 0; 2236 rup->ru_maxrss = 0; 2237 rup->ru_ixrss = 0; 2238 rup->ru_idrss = 0; 2239 rup->ru_isrss = 0; 2240 rup->ru_minflt = 0; 2241 rup->ru_majflt = 0; 2242 rup->ru_nswap = 0; 2243 rup->ru_inblock = 0; 2244 rup->ru_oublock = 0; 2245 rup->ru_msgsnd = 0; 2246 rup->ru_msgrcv = 0; 2247 rup->ru_nsignals = 0; 2248 rup->ru_nvcsw = 0; 2249 rup->ru_nivcsw = 0; 2250 2251 switch (who) { 2252 case OS::TGT_RUSAGE_SELF: 2253 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec); 2254 rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec); 2255 rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec); 2256 break; 2257 2258 case OS::TGT_RUSAGE_CHILDREN: 2259 // do nothing. We have no child processes, so they take no time. 2260 break; 2261 2262 default: 2263 // don't really handle THREAD or CHILDREN, but just warn and 2264 // plow ahead 2265 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.", 2266 who); 2267 } 2268 2269 rup.copyOut(tc->getVirtProxy()); 2270 2271 return 0; 2272} 2273 2274/// Target times() function. 2275template <class OS> 2276SyscallReturn 2277timesFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2278{ 2279 int index = 0; 2280 auto process = tc->getProcessPtr(); 2281 TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index)); 2282 2283 // Fill in the time structure (in clocks) 2284 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s; 2285 bufp->tms_utime = clocks; 2286 bufp->tms_stime = 0; 2287 bufp->tms_cutime = 0; 2288 bufp->tms_cstime = 0; 2289 2290 // Convert to host endianness 2291 bufp->tms_utime = TheISA::htog(bufp->tms_utime); 2292 2293 // Write back 2294 bufp.copyOut(tc->getVirtProxy()); 2295 2296 // Return clock ticks since system boot 2297 return clocks; 2298} 2299 2300/// Target time() function. 2301template <class OS> 2302SyscallReturn 2303timeFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2304{ 2305 typename OS::time_t sec, usec; 2306 getElapsedTimeMicro(sec, usec); 2307 sec += seconds_since_epoch; 2308 2309 int index = 0; 2310 auto process = tc->getProcessPtr(); 2311 Addr taddr = (Addr)process->getSyscallArg(tc, index); 2312 if (taddr != 0) { 2313 typename OS::time_t t = sec; 2314 t = TheISA::htog(t); 2315 PortProxy &p = tc->getVirtProxy(); 2316 p.writeBlob(taddr, &t, (int)sizeof(typename OS::time_t)); 2317 } 2318 return sec; 2319} 2320 2321template <class OS> 2322SyscallReturn 2323tgkillFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2324{ 2325 int index = 0; 2326 auto process = tc->getProcessPtr(); 2327 int tgid = process->getSyscallArg(tc, index); 2328 int tid = process->getSyscallArg(tc, index); 2329 int sig = process->getSyscallArg(tc, index); 2330 2331 /** 2332 * This system call is intended to allow killing a specific thread 2333 * within an arbitrary thread group if sanctioned with permission checks. 2334 * It's usually true that threads share the termination signal as pointed 2335 * out by the pthread_kill man page and this seems to be the intended 2336 * usage. Due to this being an emulated environment, assume the following: 2337 * Threads are allowed to call tgkill because the EUID for all threads 2338 * should be the same. There is no signal handling mechanism for kernel 2339 * registration of signal handlers since signals are poorly supported in 2340 * emulation mode. Since signal handlers cannot be registered, all 2341 * threads within in a thread group must share the termination signal. 2342 * We never exhaust PIDs so there's no chance of finding the wrong one 2343 * due to PID rollover. 2344 */ 2345 2346 System *sys = tc->getSystemPtr(); 2347 Process *tgt_proc = nullptr; 2348 for (int i = 0; i < sys->numContexts(); i++) { 2349 Process *temp = sys->threadContexts[i]->getProcessPtr(); 2350 if (temp->pid() == tid) { 2351 tgt_proc = temp; 2352 break; 2353 } 2354 } 2355 2356 if (sig != 0 || sig != OS::TGT_SIGABRT) 2357 return -EINVAL; 2358 2359 if (tgt_proc == nullptr) 2360 return -ESRCH; 2361 2362 if (tgid != -1 && tgt_proc->tgid() != tgid) 2363 return -ESRCH; 2364 2365 if (sig == OS::TGT_SIGABRT) 2366 exitGroupFunc(desc, 252, tc); 2367 2368 return 0; 2369} 2370 2371template <class OS> 2372SyscallReturn 2373socketFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2374{ 2375 int index = 0; 2376 auto p = tc->getProcessPtr(); 2377 int domain = p->getSyscallArg(tc, index); 2378 int type = p->getSyscallArg(tc, index); 2379 int prot = p->getSyscallArg(tc, index); 2380 2381 int sim_fd = socket(domain, type, prot); 2382 if (sim_fd == -1) 2383 return -errno; 2384 2385 auto sfdp = std::make_shared<SocketFDEntry>(sim_fd, domain, type, prot); 2386 int tgt_fd = p->fds->allocFD(sfdp); 2387 2388 return tgt_fd; 2389} 2390 2391template <class OS> 2392SyscallReturn 2393socketpairFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2394{ 2395 int index = 0; 2396 auto p = tc->getProcessPtr(); 2397 int domain = p->getSyscallArg(tc, index); 2398 int type = p->getSyscallArg(tc, index); 2399 int prot = p->getSyscallArg(tc, index); 2400 Addr svPtr = p->getSyscallArg(tc, index); 2401 2402 BufferArg svBuf((Addr)svPtr, 2 * sizeof(int)); 2403 int status = socketpair(domain, type, prot, (int *)svBuf.bufferPtr()); 2404 if (status == -1) 2405 return -errno; 2406 2407 int *fds = (int *)svBuf.bufferPtr(); 2408 2409 auto sfdp1 = std::make_shared<SocketFDEntry>(fds[0], domain, type, prot); 2410 fds[0] = p->fds->allocFD(sfdp1); 2411 auto sfdp2 = std::make_shared<SocketFDEntry>(fds[1], domain, type, prot); 2412 fds[1] = p->fds->allocFD(sfdp2); 2413 svBuf.copyOut(tc->getVirtProxy()); 2414 2415 return status; 2416} 2417 2418template <class OS> 2419SyscallReturn 2420selectFunc(SyscallDesc *desc, int callnum, ThreadContext *tc) 2421{ 2422 int retval; 2423 2424 int index = 0; 2425 auto p = tc->getProcessPtr(); 2426 int nfds_t = p->getSyscallArg(tc, index); 2427 Addr fds_read_ptr = p->getSyscallArg(tc, index); 2428 Addr fds_writ_ptr = p->getSyscallArg(tc, index); 2429 Addr fds_excp_ptr = p->getSyscallArg(tc, index); 2430 Addr time_val_ptr = p->getSyscallArg(tc, index); 2431 2432 TypedBufferArg<typename OS::fd_set> rd_t(fds_read_ptr); 2433 TypedBufferArg<typename OS::fd_set> wr_t(fds_writ_ptr); 2434 TypedBufferArg<typename OS::fd_set> ex_t(fds_excp_ptr); 2435 TypedBufferArg<typename OS::timeval> tp(time_val_ptr); 2436 2437 /** 2438 * Host fields. Notice that these use the definitions from the system 2439 * headers instead of the gem5 headers and libraries. If the host and 2440 * target have different header file definitions, this will not work. 2441 */ 2442 fd_set rd_h; 2443 FD_ZERO(&rd_h); 2444 fd_set wr_h; 2445 FD_ZERO(&wr_h); 2446 fd_set ex_h; 2447 FD_ZERO(&ex_h); 2448 2449 /** 2450 * Copy in the fd_set from the target. 2451 */ 2452 if (fds_read_ptr) 2453 rd_t.copyIn(tc->getVirtProxy()); 2454 if (fds_writ_ptr) 2455 wr_t.copyIn(tc->getVirtProxy()); 2456 if (fds_excp_ptr) 2457 ex_t.copyIn(tc->getVirtProxy()); 2458 2459 /** 2460 * We need to translate the target file descriptor set into a host file 2461 * descriptor set. This involves both our internal process fd array 2462 * and the fd_set defined in Linux header files. The nfds field also 2463 * needs to be updated as it will be only target specific after 2464 * retrieving it from the target; the nfds value is expected to be the 2465 * highest file descriptor that needs to be checked, so we need to extend 2466 * it out for nfds_h when we do the update. 2467 */ 2468 int nfds_h = 0; 2469 std::map<int, int> trans_map; 2470 auto try_add_host_set = [&](fd_set *tgt_set_entry, 2471 fd_set *hst_set_entry, 2472 int iter) -> bool 2473 { 2474 /** 2475 * By this point, we know that we are looking at a valid file 2476 * descriptor set on the target. We need to check if the target file 2477 * descriptor value passed in as iter is part of the set. 2478 */ 2479 if (FD_ISSET(iter, tgt_set_entry)) { 2480 /** 2481 * We know that the target file descriptor belongs to the set, 2482 * but we do not yet know if the file descriptor is valid or 2483 * that we have a host mapping. Check that now. 2484 */ 2485 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[iter]); 2486 if (!hbfdp) 2487 return true; 2488 auto sim_fd = hbfdp->getSimFD(); 2489 2490 /** 2491 * Add the sim_fd to tgt_fd translation into trans_map for use 2492 * later when we need to zero the target fd_set structures and 2493 * then update them with hits returned from the host select call. 2494 */ 2495 trans_map[sim_fd] = iter; 2496 2497 /** 2498 * We know that the host file descriptor exists so now we check 2499 * if we need to update the max count for nfds_h before passing 2500 * the duplicated structure into the host. 2501 */ 2502 nfds_h = std::max(nfds_h - 1, sim_fd + 1); 2503 2504 /** 2505 * Add the host file descriptor to the set that we are going to 2506 * pass into the host. 2507 */ 2508 FD_SET(sim_fd, hst_set_entry); 2509 } 2510 return false; 2511 }; 2512 2513 for (int i = 0; i < nfds_t; i++) { 2514 if (fds_read_ptr) { 2515 bool ebadf = try_add_host_set((fd_set*)&*rd_t, &rd_h, i); 2516 if (ebadf) return -EBADF; 2517 } 2518 if (fds_writ_ptr) { 2519 bool ebadf = try_add_host_set((fd_set*)&*wr_t, &wr_h, i); 2520 if (ebadf) return -EBADF; 2521 } 2522 if (fds_excp_ptr) { 2523 bool ebadf = try_add_host_set((fd_set*)&*ex_t, &ex_h, i); 2524 if (ebadf) return -EBADF; 2525 } 2526 } 2527 2528 if (time_val_ptr) { 2529 /** 2530 * It might be possible to decrement the timeval based on some 2531 * derivation of wall clock determined from elapsed simulator ticks 2532 * but that seems like overkill. Rather, we just set the timeval with 2533 * zero timeout. (There is no reason to block during the simulation 2534 * as it only decreases simulator performance.) 2535 */ 2536 tp->tv_sec = 0; 2537 tp->tv_usec = 0; 2538 2539 retval = select(nfds_h, 2540 fds_read_ptr ? &rd_h : nullptr, 2541 fds_writ_ptr ? &wr_h : nullptr, 2542 fds_excp_ptr ? &ex_h : nullptr, 2543 (timeval*)&*tp); 2544 } else { 2545 /** 2546 * If the timeval pointer is null, setup a new timeval structure to 2547 * pass into the host select call. Unfortunately, we will need to 2548 * manually check the return value and throw a retry fault if the 2549 * return value is zero. Allowing the system call to block will 2550 * likely deadlock the event queue. 2551 */ 2552 struct timeval tv = { 0, 0 }; 2553 2554 retval = select(nfds_h, 2555 fds_read_ptr ? &rd_h : nullptr, 2556 fds_writ_ptr ? &wr_h : nullptr, 2557 fds_excp_ptr ? &ex_h : nullptr, 2558 &tv); 2559 2560 if (retval == 0) { 2561 /** 2562 * If blocking indefinitely, check the signal list to see if a 2563 * signal would break the poll out of the retry cycle and try to 2564 * return the signal interrupt instead. 2565 */ 2566 for (auto sig : tc->getSystemPtr()->signalList) 2567 if (sig.receiver == p) 2568 return -EINTR; 2569 return SyscallReturn::retry(); 2570 } 2571 } 2572 2573 if (retval == -1) 2574 return -errno; 2575 2576 FD_ZERO((fd_set*)&*rd_t); 2577 FD_ZERO((fd_set*)&*wr_t); 2578 FD_ZERO((fd_set*)&*ex_t); 2579 2580 /** 2581 * We need to translate the host file descriptor set into a target file 2582 * descriptor set. This involves both our internal process fd array 2583 * and the fd_set defined in header files. 2584 */ 2585 for (int i = 0; i < nfds_h; i++) { 2586 if (fds_read_ptr) { 2587 if (FD_ISSET(i, &rd_h)) 2588 FD_SET(trans_map[i], (fd_set*)&*rd_t); 2589 } 2590 2591 if (fds_writ_ptr) { 2592 if (FD_ISSET(i, &wr_h)) 2593 FD_SET(trans_map[i], (fd_set*)&*wr_t); 2594 } 2595 2596 if (fds_excp_ptr) { 2597 if (FD_ISSET(i, &ex_h)) 2598 FD_SET(trans_map[i], (fd_set*)&*ex_t); 2599 } 2600 } 2601 2602 if (fds_read_ptr) 2603 rd_t.copyOut(tc->getVirtProxy()); 2604 if (fds_writ_ptr) 2605 wr_t.copyOut(tc->getVirtProxy()); 2606 if (fds_excp_ptr) 2607 ex_t.copyOut(tc->getVirtProxy()); 2608 if (time_val_ptr) 2609 tp.copyOut(tc->getVirtProxy()); 2610 2611 return retval; 2612} 2613 2614template <class OS> 2615SyscallReturn 2616readFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2617{ 2618 int index = 0; 2619 auto p = tc->getProcessPtr(); 2620 int tgt_fd = p->getSyscallArg(tc, index); 2621 Addr buf_ptr = p->getSyscallArg(tc, index); 2622 int nbytes = p->getSyscallArg(tc, index); 2623 2624 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 2625 if (!hbfdp) 2626 return -EBADF; 2627 int sim_fd = hbfdp->getSimFD(); 2628 2629 struct pollfd pfd; 2630 pfd.fd = sim_fd; 2631 pfd.events = POLLIN | POLLPRI; 2632 if ((poll(&pfd, 1, 0) == 0) 2633 && !(hbfdp->getFlags() & OS::TGT_O_NONBLOCK)) 2634 return SyscallReturn::retry(); 2635 2636 BufferArg buf_arg(buf_ptr, nbytes); 2637 int bytes_read = read(sim_fd, buf_arg.bufferPtr(), nbytes); 2638 2639 if (bytes_read > 0) 2640 buf_arg.copyOut(tc->getVirtProxy()); 2641 2642 return (bytes_read == -1) ? -errno : bytes_read; 2643} 2644 2645template <class OS> 2646SyscallReturn 2647writeFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2648{ 2649 int index = 0; 2650 auto p = tc->getProcessPtr(); 2651 int tgt_fd = p->getSyscallArg(tc, index); 2652 Addr buf_ptr = p->getSyscallArg(tc, index); 2653 int nbytes = p->getSyscallArg(tc, index); 2654 2655 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]); 2656 if (!hbfdp) 2657 return -EBADF; 2658 int sim_fd = hbfdp->getSimFD(); 2659 2660 BufferArg buf_arg(buf_ptr, nbytes); 2661 buf_arg.copyIn(tc->getVirtProxy()); 2662 2663 struct pollfd pfd; 2664 pfd.fd = sim_fd; 2665 pfd.events = POLLOUT; 2666 2667 /** 2668 * We don't want to poll on /dev/random. The kernel will not enable the 2669 * file descriptor for writing unless the entropy in the system falls 2670 * below write_wakeup_threshold. This is not guaranteed to happen 2671 * depending on host settings. 2672 */ 2673 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(hbfdp); 2674 if (ffdp && (ffdp->getFileName() != "/dev/random")) { 2675 if (!poll(&pfd, 1, 0) && !(ffdp->getFlags() & OS::TGT_O_NONBLOCK)) 2676 return SyscallReturn::retry(); 2677 } 2678 2679 int bytes_written = write(sim_fd, buf_arg.bufferPtr(), nbytes); 2680 2681 if (bytes_written != -1) 2682 fsync(sim_fd); 2683 2684 return (bytes_written == -1) ? -errno : bytes_written; 2685} 2686 2687template <class OS> 2688SyscallReturn 2689wait4Func(SyscallDesc *desc, int num, ThreadContext *tc) 2690{ 2691 int index = 0; 2692 auto p = tc->getProcessPtr(); 2693 pid_t pid = p->getSyscallArg(tc, index); 2694 Addr statPtr = p->getSyscallArg(tc, index); 2695 int options = p->getSyscallArg(tc, index); 2696 Addr rusagePtr = p->getSyscallArg(tc, index); 2697 2698 if (rusagePtr) 2699 DPRINTF_SYSCALL(Verbose, "wait4: rusage pointer provided %lx, however " 2700 "functionality not supported. Ignoring rusage pointer.\n", 2701 rusagePtr); 2702 2703 /** 2704 * Currently, wait4 is only implemented so that it will wait for children 2705 * exit conditions which are denoted by a SIGCHLD signals posted into the 2706 * system signal list. We return no additional information via any of the 2707 * parameters supplied to wait4. If nothing is found in the system signal 2708 * list, we will wait indefinitely for SIGCHLD to post by retrying the 2709 * call. 2710 */ 2711 System *sysh = tc->getSystemPtr(); 2712 std::list<BasicSignal>::iterator iter; 2713 for (iter=sysh->signalList.begin(); iter!=sysh->signalList.end(); iter++) { 2714 if (iter->receiver == p) { 2715 if (pid < -1) { 2716 if ((iter->sender->pgid() == -pid) 2717 && (iter->signalValue == OS::TGT_SIGCHLD)) 2718 goto success; 2719 } else if (pid == -1) { 2720 if (iter->signalValue == OS::TGT_SIGCHLD) 2721 goto success; 2722 } else if (pid == 0) { 2723 if ((iter->sender->pgid() == p->pgid()) 2724 && (iter->signalValue == OS::TGT_SIGCHLD)) 2725 goto success; 2726 } else { 2727 if ((iter->sender->pid() == pid) 2728 && (iter->signalValue == OS::TGT_SIGCHLD)) 2729 goto success; 2730 } 2731 } 2732 } 2733 2734 return (options & OS::TGT_WNOHANG) ? 0 : SyscallReturn::retry(); 2735 2736success: 2737 // Set status to EXITED for WIFEXITED evaluations. 2738 const int EXITED = 0; 2739 BufferArg statusBuf(statPtr, sizeof(int)); 2740 *(int *)statusBuf.bufferPtr() = EXITED; 2741 statusBuf.copyOut(tc->getVirtProxy()); 2742 2743 // Return the child PID. 2744 pid_t retval = iter->sender->pid(); 2745 sysh->signalList.erase(iter); 2746 return retval; 2747} 2748 2749template <class OS> 2750SyscallReturn 2751acceptFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2752{ 2753 struct sockaddr sa; 2754 socklen_t addrLen; 2755 int host_fd; 2756 int index = 0; 2757 auto p = tc->getProcessPtr(); 2758 int tgt_fd = p->getSyscallArg(tc, index); 2759 Addr addrPtr = p->getSyscallArg(tc, index); 2760 Addr lenPtr = p->getSyscallArg(tc, index); 2761 2762 BufferArg *lenBufPtr = nullptr; 2763 BufferArg *addrBufPtr = nullptr; 2764 2765 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]); 2766 if (!sfdp) 2767 return -EBADF; 2768 int sim_fd = sfdp->getSimFD(); 2769 2770 /** 2771 * We poll the socket file descriptor first to guarantee that we do not 2772 * block on our accept call. The socket can be opened without the 2773 * non-blocking flag (it blocks). This will cause deadlocks between 2774 * communicating processes. 2775 */ 2776 struct pollfd pfd; 2777 pfd.fd = sim_fd; 2778 pfd.events = POLLIN | POLLPRI; 2779 if ((poll(&pfd, 1, 0) == 0) 2780 && !(sfdp->getFlags() & OS::TGT_O_NONBLOCK)) 2781 return SyscallReturn::retry(); 2782 2783 if (lenPtr) { 2784 lenBufPtr = new BufferArg(lenPtr, sizeof(socklen_t)); 2785 lenBufPtr->copyIn(tc->getVirtProxy()); 2786 memcpy(&addrLen, (socklen_t *)lenBufPtr->bufferPtr(), 2787 sizeof(socklen_t)); 2788 } 2789 2790 if (addrPtr) { 2791 addrBufPtr = new BufferArg(addrPtr, sizeof(struct sockaddr)); 2792 addrBufPtr->copyIn(tc->getVirtProxy()); 2793 memcpy(&sa, (struct sockaddr *)addrBufPtr->bufferPtr(), 2794 sizeof(struct sockaddr)); 2795 } 2796 2797 host_fd = accept(sim_fd, &sa, &addrLen); 2798 2799 if (host_fd == -1) 2800 return -errno; 2801 2802 if (addrPtr) { 2803 memcpy(addrBufPtr->bufferPtr(), &sa, sizeof(sa)); 2804 addrBufPtr->copyOut(tc->getVirtProxy()); 2805 delete(addrBufPtr); 2806 } 2807 2808 if (lenPtr) { 2809 *(socklen_t *)lenBufPtr->bufferPtr() = addrLen; 2810 lenBufPtr->copyOut(tc->getVirtProxy()); 2811 delete(lenBufPtr); 2812 } 2813 2814 auto afdp = std::make_shared<SocketFDEntry>(host_fd, sfdp->_domain, 2815 sfdp->_type, sfdp->_protocol); 2816 return p->fds->allocFD(afdp); 2817} 2818 2819/// Target eventfd() function. 2820template <class OS> 2821SyscallReturn 2822eventfdFunc(SyscallDesc *desc, int num, ThreadContext *tc) 2823{ 2824#if defined(__linux__) 2825 int index = 0; 2826 auto p = tc->getProcessPtr(); 2827 unsigned initval = p->getSyscallArg(tc, index); 2828 int in_flags = p->getSyscallArg(tc, index); 2829 2830 int sim_fd = eventfd(initval, in_flags); 2831 if (sim_fd == -1) 2832 return -errno; 2833 2834 bool cloexec = in_flags & OS::TGT_O_CLOEXEC; 2835 2836 int flags = cloexec ? OS::TGT_O_CLOEXEC : 0; 2837 flags |= (in_flags & OS::TGT_O_NONBLOCK) ? OS::TGT_O_NONBLOCK : 0; 2838 2839 auto hbfdp = std::make_shared<HBFDEntry>(flags, sim_fd, cloexec); 2840 int tgt_fd = p->fds->allocFD(hbfdp); 2841 return tgt_fd; 2842#else 2843 warnUnsupportedOS("eventfd"); 2844 return -1; 2845#endif 2846} 2847 2848#endif // __SIM_SYSCALL_EMUL_HH__
|