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