2 * Copyright (c) 2012-2013, 2015, 2019 ARM Limited
3 * Copyright (c) 2015 Advanced Micro Devices, Inc.
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.
15 * Copyright (c) 2003-2005 The Regents of The University of Michigan
16 * All rights reserved.
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.
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.
42 #ifndef __SIM_SYSCALL_EMUL_HH__
43 #define __SIM_SYSCALL_EMUL_HH__
45 #if (defined(__APPLE__) || defined(__OpenBSD__) || \
46 defined(__FreeBSD__) || defined(__CYGWIN__) || \
54 /// @file syscall_emul.hh
56 /// This file defines objects used to emulate syscalls from the target
57 /// application on the host machine.
59 #if defined(__linux__)
60 #include <sys/eventfd.h>
61 #include <sys/statfs.h>
64 #include <sys/mount.h>
69 #include <sys/fcntl.h>
75 #include <sys/ioctl.h>
77 #include <sys/socket.h>
80 #include <sys/types.h>
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/guest_abi.hh"
103 #include "sim/process.hh"
104 #include "sim/syscall_debug_macros.hh"
105 #include "sim/syscall_desc.hh"
106 #include "sim/syscall_emul_buf.hh"
107 #include "sim/syscall_return.hh"
109 #if defined(__APPLE__) && defined(__MACH__) && !defined(CMSG_ALIGN)
110 #define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & ~(sizeof(size_t) - 1))
113 //////////////////////////////////////////////////////////////////////
115 // The following emulation functions are generic enough that they
116 // don't need to be recompiled for different emulated OS's. They are
117 // defined in sim/syscall_emul.cc.
119 //////////////////////////////////////////////////////////////////////
121 void warnUnsupportedOS(std::string syscall_name);
123 /// Handler for unimplemented syscalls that we haven't thought about.
124 SyscallReturn unimplementedFunc(SyscallDesc *desc, ThreadContext *tc);
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. Prints a warning. Return success to the target
130 SyscallReturn ignoreFunc(SyscallDesc *desc, ThreadContext *tc);
131 /// Like above, but only prints a warning once per syscall desc it's used with.
133 ignoreWarnOnceFunc(SyscallDesc *desc, ThreadContext *tc);
135 // Target fallocateFunc() handler.
136 SyscallReturn fallocateFunc(SyscallDesc *desc, ThreadContext *tc,
137 int tgt_fd, int mode, off_t offset, off_t len);
139 /// Target exit() handler: terminate current context.
140 SyscallReturn exitFunc(SyscallDesc *desc, ThreadContext *tc, int status);
142 /// Target exit_group() handler: terminate simulation. (exit all threads)
143 SyscallReturn exitGroupFunc(SyscallDesc *desc, ThreadContext *tc, int status);
145 /// Target set_tid_address() handler.
146 SyscallReturn setTidAddressFunc(SyscallDesc *desc, ThreadContext *tc,
149 /// Target getpagesize() handler.
150 SyscallReturn getpagesizeFunc(SyscallDesc *desc, ThreadContext *tc);
152 /// Target brk() handler: set brk address.
153 SyscallReturn brkFunc(SyscallDesc *desc, ThreadContext *tc, Addr new_brk);
155 /// Target close() handler.
156 SyscallReturn closeFunc(SyscallDesc *desc, ThreadContext *tc, int tgt_fd);
158 /// Target lseek() handler.
159 SyscallReturn lseekFunc(SyscallDesc *desc, ThreadContext *tc,
160 int tgt_fd, uint64_t offs, int whence);
162 /// Target _llseek() handler.
163 SyscallReturn _llseekFunc(SyscallDesc *desc, ThreadContext *tc,
164 int tgt_fd, uint64_t offset_high,
165 uint32_t offset_low, Addr result_ptr, int whence);
167 /// Target munmap() handler.
168 SyscallReturn munmapFunc(SyscallDesc *desc, ThreadContext *tc, Addr start,
171 /// Target shutdown() handler.
172 SyscallReturn shutdownFunc(SyscallDesc *desc, ThreadContext *tc,
173 int tgt_fd, int how);
175 /// Target gethostname() handler.
176 SyscallReturn gethostnameFunc(SyscallDesc *desc, ThreadContext *tc,
177 Addr buf_ptr, int name_len);
179 /// Target getcwd() handler.
180 SyscallReturn getcwdFunc(SyscallDesc *desc, ThreadContext *tc,
181 Addr buf_ptr, unsigned long size);
183 /// Target readlink() handler.
184 SyscallReturn readlinkFunc(SyscallDesc *desc, ThreadContext *tc,
185 Addr pathname, Addr buf, size_t bufsiz);
187 /// Target unlink() handler.
188 SyscallReturn unlinkFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname);
190 /// Target link() handler
191 SyscallReturn linkFunc(SyscallDesc *desc, ThreadContext *tc,
192 Addr pathname, Addr new_pathname);
194 /// Target symlink() handler.
195 SyscallReturn symlinkFunc(SyscallDesc *desc, ThreadContext *tc,
196 Addr pathname, Addr new_pathname);
198 /// Target mkdir() handler.
199 SyscallReturn mkdirFunc(SyscallDesc *desc, ThreadContext *tc,
200 Addr pathname, mode_t mode);
202 /// Target mknod() handler.
203 SyscallReturn mknodFunc(SyscallDesc *desc, ThreadContext *tc,
204 Addr pathname, mode_t mode, dev_t dev);
206 /// Target chdir() handler.
207 SyscallReturn chdirFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname);
209 // Target rmdir() handler.
210 SyscallReturn rmdirFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname);
212 /// Target rename() handler.
213 SyscallReturn renameFunc(SyscallDesc *desc, ThreadContext *tc,
214 Addr oldpath, Addr newpath);
217 /// Target truncate() handler.
218 SyscallReturn truncateFunc(SyscallDesc *desc, ThreadContext *tc,
219 Addr pathname, off_t length);
222 /// Target ftruncate() handler.
223 SyscallReturn ftruncateFunc(SyscallDesc *desc, ThreadContext *tc,
224 int tgt_fd, off_t length);
227 /// Target truncate64() handler.
228 SyscallReturn truncate64Func(SyscallDesc *desc, ThreadContext *tc,
229 Addr pathname, int64_t length);
231 /// Target ftruncate64() handler.
232 SyscallReturn ftruncate64Func(SyscallDesc *desc, ThreadContext *tc,
233 int tgt_fd, int64_t length);
235 /// Target umask() handler.
236 SyscallReturn umaskFunc(SyscallDesc *desc, ThreadContext *tc);
238 /// Target gettid() handler.
239 SyscallReturn gettidFunc(SyscallDesc *desc, ThreadContext *tc);
241 /// Target chown() handler.
242 SyscallReturn chownFunc(SyscallDesc *desc, ThreadContext *tc,
243 Addr pathname, uint32_t owner, uint32_t group);
245 /// Target getpgrpFunc() handler.
246 SyscallReturn getpgrpFunc(SyscallDesc *desc, ThreadContext *tc);
248 /// Target setpgid() handler.
249 SyscallReturn setpgidFunc(SyscallDesc *desc, ThreadContext *tc,
252 /// Target fchown() handler.
253 SyscallReturn fchownFunc(SyscallDesc *desc, ThreadContext *tc,
254 int tgt_fd, uint32_t owner, uint32_t group);
256 /// Target dup() handler.
257 SyscallReturn dupFunc(SyscallDesc *desc, ThreadContext *tc,
260 /// Target dup2() handler.
261 SyscallReturn dup2Func(SyscallDesc *desc, ThreadContext *tc,
262 int old_tgt_fd, int new_tgt_fd);
264 /// Target fcntl() handler.
265 SyscallReturn fcntlFunc(SyscallDesc *desc, ThreadContext *tc,
266 int tgt_fd, int cmd, GuestABI::VarArgs<int> varargs);
268 /// Target fcntl64() handler.
269 SyscallReturn fcntl64Func(SyscallDesc *desc, ThreadContext *tc,
270 int tgt_fd, int cmd);
272 /// Target pipe() handler.
273 SyscallReturn pipeFunc(SyscallDesc *desc, ThreadContext *tc, Addr tgt_addr);
275 /// Target pipe() handler.
276 SyscallReturn pipe2Func(SyscallDesc *desc, ThreadContext *tc,
277 Addr tgt_addr, int flags);
279 /// Target getpid() handler.
280 SyscallReturn getpidFunc(SyscallDesc *desc, ThreadContext *tc);
282 // Target getpeername() handler.
283 SyscallReturn getpeernameFunc(SyscallDesc *desc, ThreadContext *tc,
284 int tgt_fd, Addr sockAddrPtr, Addr addrlenPtr);
286 // Target bind() handler.
287 SyscallReturn bindFunc(SyscallDesc *desc, ThreadContext *tc,
288 int tgt_fd, Addr buf_ptr, int addrlen);
290 // Target listen() handler.
291 SyscallReturn listenFunc(SyscallDesc *desc, ThreadContext *tc,
292 int tgt_fd, int backlog);
294 // Target connect() handler.
295 SyscallReturn connectFunc(SyscallDesc *desc, ThreadContext *tc,
296 int tgt_fd, Addr buf_ptr, int addrlen);
298 #if defined(SYS_getdents)
299 // Target getdents() handler.
300 SyscallReturn getdentsFunc(SyscallDesc *desc, ThreadContext *tc,
301 int tgt_fd, Addr buf_ptr, unsigned count);
304 #if defined(SYS_getdents64)
305 // Target getdents() handler.
306 SyscallReturn getdents64Func(SyscallDesc *desc, ThreadContext *tc,
307 int tgt_fd, Addr buf_ptr, unsigned count);
310 // Target sendto() handler.
311 SyscallReturn sendtoFunc(SyscallDesc *desc, ThreadContext *tc,
312 int tgt_fd, Addr bufrPtr, size_t bufrLen, int flags,
313 Addr addrPtr, socklen_t addrLen);
315 // Target recvfrom() handler.
316 SyscallReturn recvfromFunc(SyscallDesc *desc, ThreadContext *tc,
317 int tgt_fd, Addr bufrPtr, size_t bufrLen,
318 int flags, Addr addrPtr, Addr addrlenPtr);
320 // Target recvmsg() handler.
321 SyscallReturn recvmsgFunc(SyscallDesc *desc, ThreadContext *tc,
322 int tgt_fd, Addr msgPtr, int flags);
324 // Target sendmsg() handler.
325 SyscallReturn sendmsgFunc(SyscallDesc *desc, ThreadContext *tc,
326 int tgt_fd, Addr msgPtr, int flags);
328 // Target getuid() handler.
329 SyscallReturn getuidFunc(SyscallDesc *desc, ThreadContext *tc);
331 /// Target getgid() handler.
332 SyscallReturn getgidFunc(SyscallDesc *desc, ThreadContext *tc);
334 /// Target getppid() handler.
335 SyscallReturn getppidFunc(SyscallDesc *desc, ThreadContext *tc);
337 /// Target geteuid() handler.
338 SyscallReturn geteuidFunc(SyscallDesc *desc, ThreadContext *tc);
340 /// Target getegid() handler.
341 SyscallReturn getegidFunc(SyscallDesc *desc, ThreadContext *tc);
343 /// Target access() handler
344 SyscallReturn accessFunc(SyscallDesc *desc, ThreadContext *tc,
345 Addr pathname, mode_t mode);
347 // Target getsockopt() handler.
348 SyscallReturn getsockoptFunc(SyscallDesc *desc, ThreadContext *tc,
349 int tgt_fd, int level, int optname,
350 Addr valPtr, Addr lenPtr);
352 // Target setsockopt() handler.
353 SyscallReturn setsockoptFunc(SyscallDesc *desc, ThreadContext *tc,
354 int tgt_fd, int level, int optname,
355 Addr valPtr, socklen_t len);
357 // Target getsockname() handler.
358 SyscallReturn getsocknameFunc(SyscallDesc *desc, ThreadContext *tc,
359 int tgt_fd, Addr addrPtr, Addr lenPtr);
361 /// Futex system call
362 /// Implemented by Daniel Sanchez
363 /// Used by printf's in multi-threaded apps
366 futexFunc(SyscallDesc *desc, ThreadContext *tc,
367 Addr uaddr, int op, int val, int timeout, Addr uaddr2, int val3)
371 auto process = tc->getProcessPtr();
374 * Unsupported option that does not affect the correctness of the
375 * application. This is a performance optimization utilized by Linux.
377 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
378 op &= ~OS::TGT_FUTEX_CLOCK_REALTIME_FLAG;
380 FutexMap &futex_map = tc->getSystemPtr()->futexMap;
382 if (OS::TGT_FUTEX_WAIT == op || OS::TGT_FUTEX_WAIT_BITSET == op) {
383 // Ensure futex system call accessed atomically.
384 BufferArg buf(uaddr, sizeof(int));
385 buf.copyIn(tc->getVirtProxy());
386 int mem_val = *(int*)buf.bufferPtr();
389 * The value in memory at uaddr is not equal with the expected val
390 * (a different thread must have changed it before the system call was
391 * invoked). In this case, we need to throw an error.
394 return -OS::TGT_EWOULDBLOCK;
396 if (OS::TGT_FUTEX_WAIT == op) {
397 futex_map.suspend(uaddr, process->tgid(), tc);
399 futex_map.suspend_bitset(uaddr, process->tgid(), tc, val3);
403 } else if (OS::TGT_FUTEX_WAKE == op) {
404 return futex_map.wakeup(uaddr, process->tgid(), val);
405 } else if (OS::TGT_FUTEX_WAKE_BITSET == op) {
406 return futex_map.wakeup_bitset(uaddr, process->tgid(), val3);
407 } else if (OS::TGT_FUTEX_REQUEUE == op ||
408 OS::TGT_FUTEX_CMP_REQUEUE == op) {
410 // Ensure futex system call accessed atomically.
411 BufferArg buf(uaddr, sizeof(int));
412 buf.copyIn(tc->getVirtProxy());
413 int mem_val = *(int*)buf.bufferPtr();
415 * For CMP_REQUEUE, the whole operation is only started only if
416 * val3 is still the value of the futex pointed to by uaddr.
418 if (OS::TGT_FUTEX_CMP_REQUEUE && val3 != mem_val)
419 return -OS::TGT_EWOULDBLOCK;
420 return futex_map.requeue(uaddr, process->tgid(), val, timeout, uaddr2);
421 } else if (OS::TGT_FUTEX_WAKE_OP == op) {
423 * The FUTEX_WAKE_OP operation is equivalent to executing the
424 * following code atomically and totally ordered with respect to
425 * other futex operations on any of the two supplied futex words:
427 * int oldval = *(int *) addr2;
428 * *(int *) addr2 = oldval op oparg;
429 * futex(addr1, FUTEX_WAKE, val, 0, 0, 0);
430 * if (oldval cmp cmparg)
431 * futex(addr2, FUTEX_WAKE, val2, 0, 0, 0);
433 * (op, oparg, cmp, cmparg are encoded in val3)
435 * +---+---+-----------+-----------+
436 * |op |cmp| oparg | cmparg |
437 * +---+---+-----------+-----------+
438 * 4 4 12 12 <== # of bits
440 * reference: http://man7.org/linux/man-pages/man2/futex.2.html
443 // get value from simulated-space
444 BufferArg buf(uaddr2, sizeof(int));
445 buf.copyIn(tc->getVirtProxy());
446 int oldval = *(int*)buf.bufferPtr();
448 // extract op, oparg, cmp, cmparg from val3
449 int wake_cmparg = val3 & 0xfff;
450 int wake_oparg = (val3 & 0xfff000) >> 12;
451 int wake_cmp = (val3 & 0xf000000) >> 24;
452 int wake_op = (val3 & 0xf0000000) >> 28;
453 if ((wake_op & OS::TGT_FUTEX_OP_ARG_SHIFT) >> 3 == 1)
454 wake_oparg = (1 << wake_oparg);
455 wake_op &= ~OS::TGT_FUTEX_OP_ARG_SHIFT;
456 // perform operation on the value of the second futex
457 if (wake_op == OS::TGT_FUTEX_OP_SET)
459 else if (wake_op == OS::TGT_FUTEX_OP_ADD)
460 newval += wake_oparg;
461 else if (wake_op == OS::TGT_FUTEX_OP_OR)
462 newval |= wake_oparg;
463 else if (wake_op == OS::TGT_FUTEX_OP_ANDN)
464 newval &= ~wake_oparg;
465 else if (wake_op == OS::TGT_FUTEX_OP_XOR)
466 newval ^= wake_oparg;
467 // copy updated value back to simulated-space
468 *(int*)buf.bufferPtr() = newval;
469 buf.copyOut(tc->getVirtProxy());
470 // perform the first wake-up
471 int woken1 = futex_map.wakeup(uaddr, process->tgid(), val);
473 // calculate the condition of the second wake-up
474 bool is_wake2 = false;
475 if (wake_cmp == OS::TGT_FUTEX_OP_CMP_EQ)
476 is_wake2 = oldval == wake_cmparg;
477 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_NE)
478 is_wake2 = oldval != wake_cmparg;
479 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LT)
480 is_wake2 = oldval < wake_cmparg;
481 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LE)
482 is_wake2 = oldval <= wake_cmparg;
483 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GT)
484 is_wake2 = oldval > wake_cmparg;
485 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GE)
486 is_wake2 = oldval >= wake_cmparg;
487 // perform the second wake-up
489 woken2 = futex_map.wakeup(uaddr2, process->tgid(), timeout);
491 return woken1 + woken2;
493 warn("futex: op %d not implemented; ignoring.", op);
497 /// Pseudo Funcs - These functions use a different return convension,
498 /// returning a second value in a register other than the normal return register
499 SyscallReturn pipePseudoFunc(SyscallDesc *desc, ThreadContext *tc);
502 /// Approximate seconds since the epoch (1/1/1970). About a billion,
503 /// by my reckoning. We want to keep this a constant (not use the
504 /// real-world time) to keep simulations repeatable.
505 const unsigned seconds_since_epoch = 1000 * 1000 * 1000;
507 /// Helper function to convert current elapsed time to seconds and
509 template <class T1, class T2>
511 getElapsedTimeMicro(T1 &sec, T2 &usec)
513 static const int OneMillion = 1000 * 1000;
515 uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
516 sec = elapsed_usecs / OneMillion;
517 usec = elapsed_usecs % OneMillion;
520 /// Helper function to convert current elapsed time to seconds and
522 template <class T1, class T2>
524 getElapsedTimeNano(T1 &sec, T2 &nsec)
526 static const int OneBillion = 1000 * 1000 * 1000;
528 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
529 sec = elapsed_nsecs / OneBillion;
530 nsec = elapsed_nsecs % OneBillion;
533 //////////////////////////////////////////////////////////////////////
535 // The following emulation functions are generic, but need to be
536 // templated to account for differences in types, constants, etc.
538 //////////////////////////////////////////////////////////////////////
540 typedef struct statfs hst_statfs;
542 typedef struct stat hst_stat;
543 typedef struct stat hst_stat64;
545 typedef struct stat hst_stat;
546 typedef struct stat64 hst_stat64;
549 //// Helper function to convert a host stat buffer to a target stat
550 //// buffer. Also copies the target buffer out to the simulated
551 //// memory space. Used by stat(), fstat(), and lstat().
553 template <typename target_stat, typename host_stat>
555 convertStatBuf(target_stat &tgt, host_stat *host,
556 ByteOrder bo, bool fakeTTY=false)
561 tgt->st_dev = host->st_dev;
562 tgt->st_dev = htog(tgt->st_dev, bo);
563 tgt->st_ino = host->st_ino;
564 tgt->st_ino = htog(tgt->st_ino, bo);
565 tgt->st_mode = host->st_mode;
567 // Claim to be a character device
568 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT
569 tgt->st_mode |= S_IFCHR; // Set S_IFCHR
571 tgt->st_mode = htog(tgt->st_mode, bo);
572 tgt->st_nlink = host->st_nlink;
573 tgt->st_nlink = htog(tgt->st_nlink, bo);
574 tgt->st_uid = host->st_uid;
575 tgt->st_uid = htog(tgt->st_uid, bo);
576 tgt->st_gid = host->st_gid;
577 tgt->st_gid = htog(tgt->st_gid, bo);
579 tgt->st_rdev = 0x880d;
581 tgt->st_rdev = host->st_rdev;
582 tgt->st_rdev = htog(tgt->st_rdev, bo);
583 tgt->st_size = host->st_size;
584 tgt->st_size = htog(tgt->st_size, bo);
585 tgt->st_atimeX = host->st_atime;
586 tgt->st_atimeX = htog(tgt->st_atimeX, bo);
587 tgt->st_mtimeX = host->st_mtime;
588 tgt->st_mtimeX = htog(tgt->st_mtimeX, bo);
589 tgt->st_ctimeX = host->st_ctime;
590 tgt->st_ctimeX = htog(tgt->st_ctimeX, bo);
591 // Force the block size to be 8KB. This helps to ensure buffered io works
592 // consistently across different hosts.
593 tgt->st_blksize = 0x2000;
594 tgt->st_blksize = htog(tgt->st_blksize, bo);
595 tgt->st_blocks = host->st_blocks;
596 tgt->st_blocks = htog(tgt->st_blocks, bo);
601 template <typename target_stat, typename host_stat64>
603 convertStat64Buf(target_stat &tgt, host_stat64 *host,
604 ByteOrder bo, bool fakeTTY=false)
606 convertStatBuf<target_stat, host_stat64>(tgt, host, bo, fakeTTY);
607 #if defined(STAT_HAVE_NSEC)
608 tgt->st_atime_nsec = host->st_atime_nsec;
609 tgt->st_atime_nsec = htog(tgt->st_atime_nsec, bo);
610 tgt->st_mtime_nsec = host->st_mtime_nsec;
611 tgt->st_mtime_nsec = htog(tgt->st_mtime_nsec, bo);
612 tgt->st_ctime_nsec = host->st_ctime_nsec;
613 tgt->st_ctime_nsec = htog(tgt->st_ctime_nsec, bo);
615 tgt->st_atime_nsec = 0;
616 tgt->st_mtime_nsec = 0;
617 tgt->st_ctime_nsec = 0;
621 // Here are a couple of convenience functions
624 copyOutStatBuf(PortProxy &mem, Addr addr,
625 hst_stat *host, bool fakeTTY = false)
627 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
628 tgt_stat_buf tgt(addr);
629 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, OS::byteOrder, fakeTTY);
635 copyOutStat64Buf(PortProxy &mem, Addr addr,
636 hst_stat64 *host, bool fakeTTY = false)
638 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
639 tgt_stat_buf tgt(addr);
640 convertStat64Buf<tgt_stat_buf, hst_stat64>(
641 tgt, host, OS::byteOrder, fakeTTY);
647 copyOutStatfsBuf(PortProxy &mem, Addr addr,
650 TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
652 const ByteOrder bo = OS::byteOrder;
654 tgt->f_type = htog(host->f_type, bo);
655 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
656 tgt->f_bsize = htog(host->f_iosize, bo);
658 tgt->f_bsize = htog(host->f_bsize, bo);
660 tgt->f_blocks = htog(host->f_blocks, bo);
661 tgt->f_bfree = htog(host->f_bfree, bo);
662 tgt->f_bavail = htog(host->f_bavail, bo);
663 tgt->f_files = htog(host->f_files, bo);
664 tgt->f_ffree = htog(host->f_ffree, bo);
665 memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
666 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
667 tgt->f_namelen = htog(host->f_namemax, bo);
668 tgt->f_frsize = htog(host->f_bsize, bo);
669 #elif defined(__APPLE__)
673 tgt->f_namelen = htog(host->f_namelen, bo);
674 tgt->f_frsize = htog(host->f_frsize, bo);
676 #if defined(__linux__)
677 memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
680 * The fields are different sizes per OS. Don't bother with
681 * f_spare or f_reserved on non-Linux for now.
683 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
689 /// Target ioctl() handler. For the most part, programs call ioctl()
690 /// only to find out if their stdout is a tty, to determine whether to
691 /// do line or block buffering. We always claim that output fds are
692 /// not TTYs to provide repeatable results.
695 ioctlFunc(SyscallDesc *desc, ThreadContext *tc,
696 int tgt_fd, unsigned req, Addr addr)
698 auto p = tc->getProcessPtr();
700 DPRINTF_SYSCALL(Verbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
702 if (OS::isTtyReq(req))
705 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
707 EmulatedDriver *emul_driver = dfdp->getDriver();
709 return emul_driver->ioctl(tc, req, addr);
712 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
718 BufferArg conf_arg(addr, sizeof(ifconf));
719 conf_arg.copyIn(tc->getVirtProxy());
721 ifconf *conf = (ifconf*)conf_arg.bufferPtr();
722 Addr ifc_buf_addr = (Addr)conf->ifc_buf;
723 BufferArg ifc_buf_arg(ifc_buf_addr, conf->ifc_len);
724 ifc_buf_arg.copyIn(tc->getVirtProxy());
726 conf->ifc_buf = (char*)ifc_buf_arg.bufferPtr();
728 status = ioctl(sfdp->getSimFD(), req, conf_arg.bufferPtr());
730 conf->ifc_buf = (char*)ifc_buf_addr;
731 ifc_buf_arg.copyOut(tc->getVirtProxy());
732 conf_arg.copyOut(tc->getVirtProxy());
738 #if defined(__linux__)
743 #if defined(__linux__)
747 BufferArg req_arg(addr, sizeof(ifreq));
748 req_arg.copyIn(tc->getVirtProxy());
750 status = ioctl(sfdp->getSimFD(), req, req_arg.bufferPtr());
752 req_arg.copyOut(tc->getVirtProxy());
759 * For lack of a better return code, return ENOTTY. Ideally, we should
760 * return something better here, but at least we issue the warning.
762 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
763 tgt_fd, req, tc->pcState());
767 /// Target open() handler.
770 openatFunc(SyscallDesc *desc, ThreadContext *tc,
771 int tgt_dirfd, Addr pathname, int tgt_flags, int mode)
773 auto p = tc->getProcessPtr();
776 * Retrieve the simulated process' memory proxy and then read in the path
777 * string from that memory space into the host's working memory space.
780 if (!tc->getVirtProxy().tryReadString(path, pathname))
784 int host_flags = O_BINARY;
789 * Translate target flags into host flags. Flags exist which are not
790 * ported between architectures which can cause check failures.
792 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
793 if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
794 tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
795 host_flags |= OS::openFlagTable[i].hostFlag;
799 warn("%s: cannot decode flags %#x", desc->name(), tgt_flags);
802 host_flags |= O_BINARY;
806 * If the simulated process called open or openat with AT_FDCWD specified,
807 * take the current working directory value which was passed into the
808 * process class as a Python parameter and append the current path to
809 * create a full path.
810 * Otherwise, openat with a valid target directory file descriptor has
811 * been called. If the path option, which was passed in as a parameter,
812 * is not absolute, retrieve the directory file descriptor's path and
813 * prepend it to the path passed in as a parameter.
814 * In every case, we should have a full path (which is relevant to the
815 * host) to work with after this block has been passed.
817 std::string redir_path = path;
818 std::string abs_path = path;
819 if (tgt_dirfd == OS::TGT_AT_FDCWD) {
820 abs_path = p->absolutePath(path, true);
821 redir_path = p->checkPathRedirect(path);
822 } else if (!startswith(path, "/")) {
823 std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
824 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
827 abs_path = ffdp->getFileName() + path;
828 redir_path = p->checkPathRedirect(abs_path);
832 * Since this is an emulated environment, we create pseudo file
833 * descriptors for device requests that have been registered with
834 * the process class through Python; this allows us to create a file
835 * descriptor for subsequent ioctl or mmap calls.
837 if (startswith(abs_path, "/dev/")) {
838 std::string filename = abs_path.substr(strlen("/dev/"));
839 EmulatedDriver *drv = p->findDriver(filename);
841 DPRINTF_SYSCALL(Verbose, "%s: passing call to "
842 "driver open with path[%s]\n",
843 desc->name(), abs_path.c_str());
844 return drv->open(tc, mode, host_flags);
847 * Fall through here for pass through to host devices, such
853 * We make several attempts resolve a call to open.
855 * 1) Resolve any path redirection before hand. This will set the path
856 * up with variable 'redir_path' which may contain a modified path or
857 * the original path value. This should already be done in prior code.
858 * 2) Try to handle the access using 'special_paths'. Some special_paths
859 * and files cannot be called on the host and need to be handled as
860 * special cases inside the simulator. These special_paths are handled by
861 * C++ routines to provide output back to userspace.
862 * 3) If the full path that was created above does not match any of the
863 * special cases, pass it through to the open call on the __HOST__ to let
864 * the host open the file on our behalf. Again, the openImpl tries to
865 * USE_THE_HOST_FILESYSTEM_OPEN (with a possible redirection to the
866 * faux-filesystem files). The faux-filesystem is dynamically created
867 * during simulator configuration using Python functions.
868 * 4) If the host cannot open the file, the open attempt failed in "3)".
869 * Return the host's error code back through the system call to the
870 * simulated process. If running a debug trace, also notify the user that
871 * the open call failed.
873 * Any success will set sim_fd to something other than -1 and skip the
874 * next conditions effectively bypassing them.
877 std::string used_path;
878 std::vector<std::string> special_paths =
879 { "/proc/meminfo/", "/system/", "/platform/", "/etc/passwd",
880 "/proc/self/maps", "/dev/urandom",
881 "/sys/devices/system/cpu/online" };
882 for (auto entry : special_paths) {
883 if (startswith(path, entry)) {
884 sim_fd = OS::openSpecialFile(abs_path, p, tc);
885 used_path = abs_path;
889 sim_fd = open(redir_path.c_str(), host_flags, mode);
890 used_path = redir_path;
894 DPRINTF_SYSCALL(Verbose, "%s: failed -> path:%s "
895 "(inferred from:%s)\n", desc->name(),
896 used_path.c_str(), path.c_str());
901 * The file was opened successfully and needs to be recorded in the
902 * process' file descriptor array so that it can be retrieved later.
903 * The target file descriptor that is chosen will be the lowest unused
905 * Return the indirect target file descriptor back to the simulated
906 * process to act as a handle for the opened file.
908 auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
909 int tgt_fd = p->fds->allocFD(ffdp);
910 DPRINTF_SYSCALL(Verbose, "%s: sim_fd[%d], target_fd[%d] -> path:%s\n"
911 "(inferred from:%s)\n", desc->name(),
912 sim_fd, tgt_fd, used_path.c_str(), path.c_str());
916 /// Target open() handler.
919 openFunc(SyscallDesc *desc, ThreadContext *tc,
920 Addr pathname, int tgt_flags, int mode)
922 return openatFunc<OS>(
923 desc, tc, OS::TGT_AT_FDCWD, pathname, tgt_flags, mode);
926 /// Target unlinkat() handler.
929 unlinkatFunc(SyscallDesc *desc, ThreadContext *tc, int dirfd, Addr pathname)
931 if (dirfd != OS::TGT_AT_FDCWD)
932 warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
934 return unlinkFunc(desc, tc, pathname);
937 /// Target facessat() handler
940 faccessatFunc(SyscallDesc *desc, ThreadContext *tc,
941 int dirfd, Addr pathname, int mode)
943 if (dirfd != OS::TGT_AT_FDCWD)
944 warn("faccessat: first argument not AT_FDCWD; unlikely to work");
945 return accessFunc(desc, tc, pathname, mode);
948 /// Target readlinkat() handler
951 readlinkatFunc(SyscallDesc *desc, ThreadContext *tc,
952 int dirfd, Addr pathname, Addr buf, size_t bufsiz)
954 if (dirfd != OS::TGT_AT_FDCWD)
955 warn("openat: first argument not AT_FDCWD; unlikely to work");
956 return readlinkFunc(desc, tc, pathname, buf, bufsiz);
959 /// Target renameat() handler.
962 renameatFunc(SyscallDesc *desc, ThreadContext *tc,
963 int olddirfd, Addr oldpath, int newdirfd, Addr newpath)
965 if (olddirfd != OS::TGT_AT_FDCWD)
966 warn("renameat: first argument not AT_FDCWD; unlikely to work");
968 if (newdirfd != OS::TGT_AT_FDCWD)
969 warn("renameat: third argument not AT_FDCWD; unlikely to work");
971 return renameFunc(desc, tc, oldpath, newpath);
974 /// Target sysinfo() handler.
977 sysinfoFunc(SyscallDesc *desc, ThreadContext *tc, Addr info)
979 auto process = tc->getProcessPtr();
981 TypedBufferArg<typename OS::tgt_sysinfo> sysinfo(info);
983 sysinfo->uptime = seconds_since_epoch;
984 sysinfo->totalram = process->system->memSize();
985 sysinfo->mem_unit = 1;
987 sysinfo.copyOut(tc->getVirtProxy());
992 /// Target chmod() handler.
995 chmodFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, mode_t mode)
998 auto process = tc->getProcessPtr();
1000 if (!tc->getVirtProxy().tryReadString(path, pathname))
1003 mode_t hostMode = 0;
1005 // XXX translate mode flags via OS::something???
1008 // Adjust path for cwd and redirection
1009 path = process->checkPathRedirect(path);
1012 int result = chmod(path.c_str(), hostMode);
1021 pollFunc(SyscallDesc *desc, ThreadContext *tc,
1022 Addr fdsPtr, int nfds, int tmout)
1024 auto p = tc->getProcessPtr();
1026 BufferArg fdsBuf(fdsPtr, sizeof(struct pollfd) * nfds);
1027 fdsBuf.copyIn(tc->getVirtProxy());
1030 * Record the target file descriptors in a local variable. We need to
1031 * replace them with host file descriptors but we need a temporary copy
1032 * for later. Afterwards, replace each target file descriptor in the
1033 * poll_fd array with its host_fd.
1035 int temp_tgt_fds[nfds];
1036 for (int index = 0; index < nfds; index++) {
1037 temp_tgt_fds[index] = ((struct pollfd *)fdsBuf.bufferPtr())[index].fd;
1038 auto tgt_fd = temp_tgt_fds[index];
1039 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1042 auto host_fd = hbfdp->getSimFD();
1043 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = host_fd;
1047 * We cannot allow an infinite poll to occur or it will inevitably cause
1048 * a deadlock in the gem5 simulator with clone. We must pass in tmout with
1049 * a non-negative value, however it also makes no sense to poll on the
1050 * underlying host for any other time than tmout a zero timeout.
1054 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1057 * If blocking indefinitely, check the signal list to see if a
1058 * signal would break the poll out of the retry cycle and try
1059 * to return the signal interrupt instead.
1061 System *sysh = tc->getSystemPtr();
1062 std::list<BasicSignal>::iterator it;
1063 for (it=sysh->signalList.begin(); it!=sysh->signalList.end(); it++)
1064 if (it->receiver == p)
1066 return SyscallReturn::retry();
1069 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1075 * Replace each host_fd in the returned poll_fd array with its original
1076 * target file descriptor.
1078 for (int index = 0; index < nfds; index++) {
1079 auto tgt_fd = temp_tgt_fds[index];
1080 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = tgt_fd;
1084 * Copy out the pollfd struct because the host may have updated fields
1087 fdsBuf.copyOut(tc->getVirtProxy());
1092 /// Target fchmod() handler.
1095 fchmodFunc(SyscallDesc *desc, ThreadContext *tc, int tgt_fd, uint32_t mode)
1097 auto p = tc->getProcessPtr();
1099 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1102 int sim_fd = ffdp->getSimFD();
1104 mode_t hostMode = mode;
1106 int result = fchmod(sim_fd, hostMode);
1108 return (result < 0) ? -errno : 0;
1111 /// Target mremap() handler.
1114 mremapFunc(SyscallDesc *desc, ThreadContext *tc,
1115 Addr start, uint64_t old_length, uint64_t new_length, uint64_t flags,
1116 GuestABI::VarArgs<uint64_t> varargs)
1118 auto p = tc->getProcessPtr();
1119 Addr page_bytes = tc->getSystemPtr()->getPageBytes();
1120 uint64_t provided_address = 0;
1121 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
1123 if (use_provided_address)
1124 provided_address = varargs.get<uint64_t>();
1126 if ((start % page_bytes != 0) ||
1127 (provided_address % page_bytes != 0)) {
1128 warn("mremap failing: arguments not page aligned");
1132 new_length = roundUp(new_length, page_bytes);
1134 if (new_length > old_length) {
1135 Addr mmap_end = p->memState->getMmapEnd();
1137 if ((start + old_length) == mmap_end &&
1138 (!use_provided_address || provided_address == start)) {
1139 // This case cannot occur when growing downward, as
1140 // start is greater than or equal to mmap_end.
1141 uint64_t diff = new_length - old_length;
1142 p->memState->mapRegion(mmap_end, diff, "remapped");
1143 p->memState->setMmapEnd(mmap_end + diff);
1146 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
1147 warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
1150 uint64_t new_start = provided_address;
1151 if (!use_provided_address) {
1152 new_start = p->mmapGrowsDown() ?
1153 mmap_end - new_length : mmap_end;
1154 mmap_end = p->mmapGrowsDown() ?
1155 new_start : mmap_end + new_length;
1156 p->memState->setMmapEnd(mmap_end);
1159 warn("mremapping to new vaddr %08p-%08p, adding %d\n",
1160 new_start, new_start + new_length,
1161 new_length - old_length);
1163 // add on the remaining unallocated pages
1164 p->allocateMem(new_start + old_length,
1165 new_length - old_length,
1166 use_provided_address /* clobber */);
1168 if (use_provided_address &&
1169 ((new_start + new_length > p->memState->getMmapEnd() &&
1170 !p->mmapGrowsDown()) ||
1171 (new_start < p->memState->getMmapEnd() &&
1172 p->mmapGrowsDown()))) {
1173 // something fishy going on here, at least notify the user
1174 // @todo: increase mmap_end?
1175 warn("mmap region limit exceeded with MREMAP_FIXED\n");
1178 warn("returning %08p as start\n", new_start);
1179 p->memState->remapRegion(start, new_start, old_length);
1180 p->memState->mapRegion(new_start, new_length, "remapped");
1186 if (use_provided_address && provided_address != start)
1187 p->memState->remapRegion(start, provided_address, new_length);
1188 if (new_length != old_length)
1189 p->memState->unmapRegion(start + new_length,
1190 old_length - new_length);
1191 return use_provided_address ? provided_address : start;
1195 /// Target stat() handler.
1198 statFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1201 auto process = tc->getProcessPtr();
1203 if (!tc->getVirtProxy().tryReadString(path, pathname))
1206 // Adjust path for cwd and redirection
1207 path = process->checkPathRedirect(path);
1209 struct stat hostBuf;
1210 int result = stat(path.c_str(), &hostBuf);
1215 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1221 /// Target stat64() handler.
1224 stat64Func(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1227 auto process = tc->getProcessPtr();
1229 if (!tc->getVirtProxy().tryReadString(path, pathname))
1232 // Adjust path for cwd and redirection
1233 path = process->checkPathRedirect(path);
1236 struct stat hostBuf;
1237 int result = stat(path.c_str(), &hostBuf);
1239 struct stat64 hostBuf;
1240 int result = stat64(path.c_str(), &hostBuf);
1246 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1252 /// Target fstatat64() handler.
1255 fstatat64Func(SyscallDesc *desc, ThreadContext *tc,
1256 int dirfd, Addr pathname, Addr bufPtr)
1258 auto process = tc->getProcessPtr();
1259 if (dirfd != OS::TGT_AT_FDCWD)
1260 warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1263 if (!tc->getVirtProxy().tryReadString(path, pathname))
1266 // Adjust path for cwd and redirection
1267 path = process->checkPathRedirect(path);
1270 struct stat hostBuf;
1271 int result = stat(path.c_str(), &hostBuf);
1273 struct stat64 hostBuf;
1274 int result = stat64(path.c_str(), &hostBuf);
1280 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1286 /// Target fstat64() handler.
1289 fstat64Func(SyscallDesc *desc, ThreadContext *tc, int tgt_fd, Addr bufPtr)
1291 auto p = tc->getProcessPtr();
1293 auto ffdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1296 int sim_fd = ffdp->getSimFD();
1299 struct stat hostBuf;
1300 int result = fstat(sim_fd, &hostBuf);
1302 struct stat64 hostBuf;
1303 int result = fstat64(sim_fd, &hostBuf);
1309 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1315 /// Target lstat() handler.
1318 lstatFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1321 auto process = tc->getProcessPtr();
1323 if (!tc->getVirtProxy().tryReadString(path, pathname))
1326 // Adjust path for cwd and redirection
1327 path = process->checkPathRedirect(path);
1329 struct stat hostBuf;
1330 int result = lstat(path.c_str(), &hostBuf);
1335 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1340 /// Target lstat64() handler.
1343 lstat64Func(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1346 auto process = tc->getProcessPtr();
1348 if (!tc->getVirtProxy().tryReadString(path, pathname))
1351 // Adjust path for cwd and redirection
1352 path = process->checkPathRedirect(path);
1355 struct stat hostBuf;
1356 int result = lstat(path.c_str(), &hostBuf);
1358 struct stat64 hostBuf;
1359 int result = lstat64(path.c_str(), &hostBuf);
1365 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1370 /// Target fstat() handler.
1373 fstatFunc(SyscallDesc *desc, ThreadContext *tc, int tgt_fd, Addr bufPtr)
1375 auto p = tc->getProcessPtr();
1377 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1379 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1382 int sim_fd = ffdp->getSimFD();
1384 struct stat hostBuf;
1385 int result = fstat(sim_fd, &hostBuf);
1390 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1395 /// Target statfs() handler.
1398 statfsFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1400 #if defined(__linux__)
1402 auto process = tc->getProcessPtr();
1404 if (!tc->getVirtProxy().tryReadString(path, pathname))
1407 // Adjust path for cwd and redirection
1408 path = process->checkPathRedirect(path);
1410 struct statfs hostBuf;
1411 int result = statfs(path.c_str(), &hostBuf);
1416 copyOutStatfsBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1419 warnUnsupportedOS("statfs");
1426 cloneFunc(SyscallDesc *desc, ThreadContext *tc, RegVal flags, RegVal newStack,
1427 Addr ptidPtr, Addr ctidPtr, Addr tlsPtr)
1429 auto p = tc->getProcessPtr();
1431 if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1432 ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1433 ((flags & OS::TGT_CLONE_FS) && (flags & OS::TGT_CLONE_NEWNS)) ||
1434 ((flags & OS::TGT_CLONE_NEWIPC) && (flags & OS::TGT_CLONE_SYSVSEM)) ||
1435 ((flags & OS::TGT_CLONE_NEWPID) && (flags & OS::TGT_CLONE_THREAD)) ||
1436 ((flags & OS::TGT_CLONE_VM) && !(newStack)))
1440 if (!(ctc = tc->getSystemPtr()->findFreeContext())) {
1441 DPRINTF_SYSCALL(Verbose, "clone: no spare thread context in system"
1442 "[cpu %d, thread %d]", tc->cpuId(), tc->threadId());
1447 * Note that ProcessParams is generated by swig and there are no other
1448 * examples of how to create anything but this default constructor. The
1449 * fields are manually initialized instead of passing parameters to the
1452 ProcessParams *pp = new ProcessParams();
1453 pp->executable.assign(*(new std::string(p->progName())));
1454 pp->cmd.push_back(*(new std::string(p->progName())));
1455 pp->system = p->system;
1456 pp->cwd.assign(p->tgtCwd);
1457 pp->input.assign("stdin");
1458 pp->output.assign("stdout");
1459 pp->errout.assign("stderr");
1461 pp->euid = p->euid();
1463 pp->egid = p->egid();
1465 /* Find the first free PID that's less than the maximum */
1466 std::set<int> const& pids = p->system->PIDs;
1467 int temp_pid = *pids.begin();
1470 } while (pids.find(temp_pid) != pids.end());
1471 if (temp_pid >= System::maxPID)
1472 fatal("temp_pid is too large: %d", temp_pid);
1475 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1476 pp->useArchPT = p->useArchPT;
1477 pp->kvmInSE = p->kvmInSE;
1478 Process *cp = pp->create();
1479 // TODO: there is no way to know when the Process SimObject is done with
1480 // the params pointer. Both the params pointer (pp) and the process
1481 // pointer (cp) are normally managed in python and are never cleaned up.
1483 Process *owner = ctc->getProcessPtr();
1484 ctc->setProcessPtr(cp);
1485 cp->assignThreadContext(ctc->contextId());
1486 owner->revokeThreadContext(ctc->contextId());
1488 if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1489 BufferArg ptidBuf(ptidPtr, sizeof(long));
1490 long *ptid = (long *)ptidBuf.bufferPtr();
1492 ptidBuf.copyOut(tc->getVirtProxy());
1495 if (flags & OS::TGT_CLONE_THREAD) {
1496 cp->pTable->shared = true;
1497 cp->useForClone = true;
1500 p->clone(tc, ctc, cp, flags);
1502 if (flags & OS::TGT_CLONE_THREAD) {
1504 cp->sigchld = p->sigchld;
1505 } else if (flags & OS::TGT_SIGCHLD) {
1506 *cp->sigchld = true;
1509 if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1510 BufferArg ctidBuf(ctidPtr, sizeof(long));
1511 long *ctid = (long *)ctidBuf.bufferPtr();
1513 ctidBuf.copyOut(ctc->getVirtProxy());
1516 if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1517 cp->childClearTID = (uint64_t)ctidPtr;
1519 ctc->clearArchRegs();
1521 OS::archClone(flags, p, cp, tc, ctc, newStack, tlsPtr);
1523 desc->returnInto(ctc, 0);
1525 #if THE_ISA == SPARC_ISA
1526 tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1527 ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1530 TheISA::PCState cpc = tc->pcState();
1541 cloneBackwardsFunc(SyscallDesc *desc, ThreadContext *tc, RegVal flags,
1542 RegVal newStack, Addr ptidPtr, Addr tlsPtr, Addr ctidPtr)
1544 return cloneFunc<OS>(desc, tc, flags, newStack, ptidPtr, ctidPtr, tlsPtr);
1547 /// Target fstatfs() handler.
1550 fstatfsFunc(SyscallDesc *desc, ThreadContext *tc, int tgt_fd, Addr bufPtr)
1552 auto p = tc->getProcessPtr();
1554 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1557 int sim_fd = ffdp->getSimFD();
1559 struct statfs hostBuf;
1560 int result = fstatfs(sim_fd, &hostBuf);
1565 copyOutStatfsBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1570 /// Target readv() handler.
1573 readvFunc(SyscallDesc *desc, ThreadContext *tc,
1574 int tgt_fd, uint64_t tiov_base, size_t count)
1576 auto p = tc->getProcessPtr();
1578 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1581 int sim_fd = ffdp->getSimFD();
1583 PortProxy &prox = tc->getVirtProxy();
1584 typename OS::tgt_iovec tiov[count];
1585 struct iovec hiov[count];
1586 for (size_t i = 0; i < count; ++i) {
1587 prox.readBlob(tiov_base + (i * sizeof(typename OS::tgt_iovec)),
1588 &tiov[i], sizeof(typename OS::tgt_iovec));
1589 hiov[i].iov_len = gtoh(tiov[i].iov_len, OS::byteOrder);
1590 hiov[i].iov_base = new char [hiov[i].iov_len];
1593 int result = readv(sim_fd, hiov, count);
1594 int local_errno = errno;
1596 for (size_t i = 0; i < count; ++i) {
1598 prox.writeBlob(htog(tiov[i].iov_base, OS::byteOrder),
1599 hiov[i].iov_base, hiov[i].iov_len);
1601 delete [] (char *)hiov[i].iov_base;
1604 return (result == -1) ? -local_errno : result;
1607 /// Target writev() handler.
1610 writevFunc(SyscallDesc *desc, ThreadContext *tc,
1611 int tgt_fd, uint64_t tiov_base, size_t count)
1613 auto p = tc->getProcessPtr();
1615 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1618 int sim_fd = hbfdp->getSimFD();
1620 PortProxy &prox = tc->getVirtProxy();
1621 struct iovec hiov[count];
1622 for (size_t i = 0; i < count; ++i) {
1623 typename OS::tgt_iovec tiov;
1625 prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1626 &tiov, sizeof(typename OS::tgt_iovec));
1627 hiov[i].iov_len = gtoh(tiov.iov_len, OS::byteOrder);
1628 hiov[i].iov_base = new char [hiov[i].iov_len];
1629 prox.readBlob(gtoh(tiov.iov_base, OS::byteOrder), hiov[i].iov_base,
1633 int result = writev(sim_fd, hiov, count);
1635 for (size_t i = 0; i < count; ++i)
1636 delete [] (char *)hiov[i].iov_base;
1638 return (result == -1) ? -errno : result;
1641 /// Target mmap() handler.
1644 mmapFunc(SyscallDesc *desc, ThreadContext *tc,
1645 Addr start, uint64_t length, int prot, int tgt_flags,
1646 int tgt_fd, int offset)
1648 auto p = tc->getProcessPtr();
1649 Addr page_bytes = tc->getSystemPtr()->getPageBytes();
1651 if (start & (page_bytes - 1) ||
1652 offset & (page_bytes - 1) ||
1653 (tgt_flags & OS::TGT_MAP_PRIVATE &&
1654 tgt_flags & OS::TGT_MAP_SHARED) ||
1655 (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1656 !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1661 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1662 // With shared mmaps, there are two cases to consider:
1663 // 1) anonymous: writes should modify the mapping and this should be
1664 // visible to observers who share the mapping. Currently, it's
1665 // difficult to update the shared mapping because there's no
1666 // structure which maintains information about the which virtual
1667 // memory areas are shared. If that structure existed, it would be
1668 // possible to make the translations point to the same frames.
1669 // 2) file-backed: writes should modify the mapping and the file
1670 // which is backed by the mapping. The shared mapping problem is the
1671 // same as what was mentioned about the anonymous mappings. For
1672 // file-backed mappings, the writes to the file are difficult
1673 // because it requires syncing what the mapping holds with the file
1674 // that resides on the host system. So, any write on a real system
1675 // would cause the change to be propagated to the file mapping at
1676 // some point in the future (the inode is tracked along with the
1677 // mapping). This isn't guaranteed to always happen, but it usually
1678 // works well enough. The guarantee is provided by the msync system
1679 // call. We could force the change through with shared mappings with
1680 // a call to msync, but that again would require more information
1681 // than we currently maintain.
1682 warn_once("mmap: writing to shared mmap region is currently "
1683 "unsupported. The write succeeds on the target, but it "
1684 "will not be propagated to the host or shared mappings");
1687 length = roundUp(length, page_bytes);
1690 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1691 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1693 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1695 EmulatedDriver *emul_driver = dfdp->getDriver();
1696 return emul_driver->mmap(tc, start, length, prot, tgt_flags,
1700 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1703 sim_fd = ffdp->getSimFD();
1706 * Maintain the symbol table for dynamic executables.
1707 * The loader will call mmap to map the images into its address
1708 * space and we intercept that here. We can verify that we are
1709 * executing inside the loader by checking the program counter value.
1710 * XXX: with multiprogrammed workloads or multi-node configurations,
1711 * this will not work since there is a single global symbol table.
1713 if (p->interpImage.contains(tc->pcState().instAddr())) {
1714 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1715 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1716 ObjectFile *lib = createObjectFile(ffdp->getFileName());
1717 DPRINTF_SYSCALL(Verbose, "Loading symbols from %s\n",
1718 ffdp->getFileName());
1721 lib->loadAllSymbols(debugSymbolTable,
1722 lib->buildImage().minAddr(), start);
1728 * Not TGT_MAP_FIXED means we can start wherever we want.
1730 if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1732 * If the application provides us with a hint, we should make some
1733 * small amount of effort to accomodate it. Basically, we check if
1734 * every single VA within the requested range is unused. If it is,
1735 * we give the application the range. If not, we fall back to
1736 * extending the global mmap region.
1738 if (!(start && p->memState->isUnmapped(start, length))) {
1740 * Extend global mmap region to give us some room for the app.
1742 start = p->memState->extendMmap(length);
1746 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1747 start, start + length - 1);
1750 * We only allow mappings to overwrite existing mappings if
1751 * TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1752 * because we ignore the start hint if TGT_MAP_FIXED is not set.
1754 if (tgt_flags & OS::TGT_MAP_FIXED) {
1756 * We might already have some old VMAs mapped to this region, so
1757 * make sure to clear em out!
1759 p->memState->unmapRegion(start, length);
1763 * Figure out a human-readable name for the mapping.
1765 std::string region_name;
1766 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1767 region_name = "anon";
1769 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1770 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1771 region_name = ffdp->getFileName();
1775 * Setup the correct VMA for this region. The physical pages will be
1778 p->memState->mapRegion(start, length, region_name, sim_fd, offset);
1785 pread64Func(SyscallDesc *desc, ThreadContext *tc,
1786 int tgt_fd, Addr bufPtr, int nbytes, int offset)
1788 auto p = tc->getProcessPtr();
1790 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1793 int sim_fd = ffdp->getSimFD();
1795 BufferArg bufArg(bufPtr, nbytes);
1797 int bytes_read = pread(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1799 bufArg.copyOut(tc->getVirtProxy());
1801 return (bytes_read == -1) ? -errno : bytes_read;
1806 pwrite64Func(SyscallDesc *desc, ThreadContext *tc,
1807 int tgt_fd, Addr bufPtr, int nbytes, int offset)
1809 auto p = tc->getProcessPtr();
1811 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1814 int sim_fd = ffdp->getSimFD();
1816 BufferArg bufArg(bufPtr, nbytes);
1817 bufArg.copyIn(tc->getVirtProxy());
1819 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1821 return (bytes_written == -1) ? -errno : bytes_written;
1824 /// Target mmap2() handler.
1827 mmap2Func(SyscallDesc *desc, ThreadContext *tc,
1828 Addr start, uint64_t length, int prot, int tgt_flags,
1829 int tgt_fd, int offset)
1831 return mmapFunc<OS>(desc, tc, start, length, prot, tgt_flags,
1832 tgt_fd, offset * tc->getSystemPtr()->getPageBytes());
1835 /// Target getrlimit() handler.
1838 getrlimitFunc(SyscallDesc *desc, ThreadContext *tc,
1839 unsigned resource, Addr rlim)
1841 TypedBufferArg<typename OS::rlimit> rlp(rlim);
1843 const ByteOrder bo = OS::byteOrder;
1845 case OS::TGT_RLIMIT_STACK:
1846 // max stack size in bytes: make up a number (8MB for now)
1847 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1848 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1849 rlp->rlim_max = htog(rlp->rlim_max, bo);
1852 case OS::TGT_RLIMIT_DATA:
1853 // max data segment size in bytes: make up a number
1854 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1855 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1856 rlp->rlim_max = htog(rlp->rlim_max, bo);
1859 case OS::TGT_RLIMIT_NPROC:
1860 rlp->rlim_cur = rlp->rlim_max = tc->getSystemPtr()->numContexts();
1861 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1862 rlp->rlim_max = htog(rlp->rlim_max, bo);
1866 warn("getrlimit: unimplemented resource %d", resource);
1871 rlp.copyOut(tc->getVirtProxy());
1877 prlimitFunc(SyscallDesc *desc, ThreadContext *tc,
1878 int pid, int resource, Addr n, Addr o)
1881 warn("prlimit: ignoring rlimits for nonzero pid");
1885 warn("prlimit: ignoring new rlimit");
1887 const ByteOrder bo = OS::byteOrder;
1888 TypedBufferArg<typename OS::rlimit> rlp(o);
1890 case OS::TGT_RLIMIT_STACK:
1891 // max stack size in bytes: make up a number (8MB for now)
1892 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1893 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1894 rlp->rlim_max = htog(rlp->rlim_max, bo);
1896 case OS::TGT_RLIMIT_DATA:
1897 // max data segment size in bytes: make up a number
1898 rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
1899 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1900 rlp->rlim_max = htog(rlp->rlim_max, bo);
1903 warn("prlimit: unimplemented resource %d", resource);
1907 rlp.copyOut(tc->getVirtProxy());
1912 /// Target clock_gettime() function.
1915 clock_gettimeFunc(SyscallDesc *desc, ThreadContext *tc,
1916 int clk_id, Addr tp_ptr)
1918 TypedBufferArg<typename OS::timespec> tp(tp_ptr);
1920 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1921 tp->tv_sec += seconds_since_epoch;
1922 tp->tv_sec = htog(tp->tv_sec, OS::byteOrder);
1923 tp->tv_nsec = htog(tp->tv_nsec, OS::byteOrder);
1925 tp.copyOut(tc->getVirtProxy());
1930 /// Target clock_getres() function.
1933 clock_getresFunc(SyscallDesc *desc, ThreadContext *tc, int clk_id, Addr tp_ptr)
1935 TypedBufferArg<typename OS::timespec> tp(tp_ptr);
1937 // Set resolution at ns, which is what clock_gettime() returns
1941 tp.copyOut(tc->getVirtProxy());
1946 /// Target gettimeofday() handler.
1949 gettimeofdayFunc(SyscallDesc *desc, ThreadContext *tc,
1950 Addr tv_ptr, Addr tz_ptr)
1952 TypedBufferArg<typename OS::timeval> tp(tv_ptr);
1954 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1955 tp->tv_sec += seconds_since_epoch;
1956 tp->tv_sec = htog(tp->tv_sec, OS::byteOrder);
1957 tp->tv_usec = htog(tp->tv_usec, OS::byteOrder);
1959 tp.copyOut(tc->getVirtProxy());
1965 /// Target utimes() handler.
1968 utimesFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr times)
1971 auto process = tc->getProcessPtr();
1973 if (!tc->getVirtProxy().tryReadString(path, pathname))
1976 TypedBufferArg<typename OS::timeval [2]> tp(times);
1977 tp.copyIn(tc->getVirtProxy());
1979 struct timeval hostTimeval[2];
1980 for (int i = 0; i < 2; ++i) {
1981 hostTimeval[i].tv_sec = gtoh((*tp)[i].tv_sec, OS::byteOrder);
1982 hostTimeval[i].tv_usec = gtoh((*tp)[i].tv_usec, OS::byteOrder);
1985 // Adjust path for cwd and redirection
1986 path = process->checkPathRedirect(path);
1988 int result = utimes(path.c_str(), hostTimeval);
1998 execveFunc(SyscallDesc *desc, ThreadContext *tc,
1999 Addr pathname, Addr argv_mem_loc, Addr envp_mem_loc)
2001 auto p = tc->getProcessPtr();
2004 PortProxy & mem_proxy = tc->getVirtProxy();
2005 if (!mem_proxy.tryReadString(path, pathname))
2008 if (access(path.c_str(), F_OK) == -1)
2011 auto read_in = [](std::vector<std::string> &vect,
2012 PortProxy &mem_proxy, Addr mem_loc)
2014 for (int inc = 0; ; inc++) {
2015 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
2016 b.copyIn(mem_proxy);
2018 if (!*(Addr*)b.bufferPtr())
2021 vect.push_back(std::string());
2022 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
2027 * Note that ProcessParams is generated by swig and there are no other
2028 * examples of how to create anything but this default constructor. The
2029 * fields are manually initialized instead of passing parameters to the
2032 ProcessParams *pp = new ProcessParams();
2033 pp->executable = path;
2034 read_in(pp->cmd, mem_proxy, argv_mem_loc);
2035 read_in(pp->env, mem_proxy, envp_mem_loc);
2037 pp->egid = p->egid();
2038 pp->euid = p->euid();
2040 pp->ppid = p->ppid();
2042 pp->input.assign("cin");
2043 pp->output.assign("cout");
2044 pp->errout.assign("cerr");
2045 pp->cwd.assign(p->tgtCwd);
2046 pp->system = p->system;
2048 * Prevent process object creation with identical PIDs (which will trip
2049 * a fatal check in Process constructor). The execve call is supposed to
2050 * take over the currently executing process' identity but replace
2051 * whatever it is doing with a new process image. Instead of hijacking
2052 * the process object in the simulator, we create a new process object
2053 * and bind to the previous process' thread below (hijacking the thread).
2055 p->system->PIDs.erase(p->pid());
2056 Process *new_p = pp->create();
2060 * Work through the file descriptor array and close any files marked
2063 new_p->fds = p->fds;
2064 for (int i = 0; i < new_p->fds->getSize(); i++) {
2065 std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
2066 if (fdep && fdep->getCOE())
2067 new_p->fds->closeFDEntry(i);
2070 *new_p->sigchld = true;
2073 tc->clearArchRegs();
2074 tc->setProcessPtr(new_p);
2075 new_p->assignThreadContext(tc->contextId());
2078 TheISA::PCState pcState = tc->pcState();
2079 tc->setNPC(pcState.instAddr());
2081 return SyscallReturn();
2084 /// Target getrusage() function.
2087 getrusageFunc(SyscallDesc *desc, ThreadContext *tc,
2088 int who /* THREAD, SELF, or CHILDREN */, Addr usage)
2090 TypedBufferArg<typename OS::rusage> rup(usage);
2092 rup->ru_utime.tv_sec = 0;
2093 rup->ru_utime.tv_usec = 0;
2094 rup->ru_stime.tv_sec = 0;
2095 rup->ru_stime.tv_usec = 0;
2103 rup->ru_inblock = 0;
2104 rup->ru_oublock = 0;
2107 rup->ru_nsignals = 0;
2112 case OS::TGT_RUSAGE_SELF:
2113 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
2114 rup->ru_utime.tv_sec = htog(rup->ru_utime.tv_sec, OS::byteOrder);
2115 rup->ru_utime.tv_usec = htog(rup->ru_utime.tv_usec, OS::byteOrder);
2118 case OS::TGT_RUSAGE_CHILDREN:
2119 // do nothing. We have no child processes, so they take no time.
2123 // don't really handle THREAD or CHILDREN, but just warn and
2125 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
2129 rup.copyOut(tc->getVirtProxy());
2134 /// Target times() function.
2137 timesFunc(SyscallDesc *desc, ThreadContext *tc, Addr bufPtr)
2139 TypedBufferArg<typename OS::tms> bufp(bufPtr);
2141 // Fill in the time structure (in clocks)
2142 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
2143 bufp->tms_utime = clocks;
2144 bufp->tms_stime = 0;
2145 bufp->tms_cutime = 0;
2146 bufp->tms_cstime = 0;
2148 // Convert to host endianness
2149 bufp->tms_utime = htog(bufp->tms_utime, OS::byteOrder);
2152 bufp.copyOut(tc->getVirtProxy());
2154 // Return clock ticks since system boot
2158 /// Target time() function.
2161 timeFunc(SyscallDesc *desc, ThreadContext *tc, Addr taddr)
2163 typename OS::time_t sec, usec;
2164 getElapsedTimeMicro(sec, usec);
2165 sec += seconds_since_epoch;
2168 typename OS::time_t t = sec;
2169 t = htog(t, OS::byteOrder);
2170 PortProxy &p = tc->getVirtProxy();
2171 p.writeBlob(taddr, &t, (int)sizeof(typename OS::time_t));
2178 tgkillFunc(SyscallDesc *desc, ThreadContext *tc, int tgid, int tid, int sig)
2181 * This system call is intended to allow killing a specific thread
2182 * within an arbitrary thread group if sanctioned with permission checks.
2183 * It's usually true that threads share the termination signal as pointed
2184 * out by the pthread_kill man page and this seems to be the intended
2185 * usage. Due to this being an emulated environment, assume the following:
2186 * Threads are allowed to call tgkill because the EUID for all threads
2187 * should be the same. There is no signal handling mechanism for kernel
2188 * registration of signal handlers since signals are poorly supported in
2189 * emulation mode. Since signal handlers cannot be registered, all
2190 * threads within in a thread group must share the termination signal.
2191 * We never exhaust PIDs so there's no chance of finding the wrong one
2192 * due to PID rollover.
2195 System *sys = tc->getSystemPtr();
2196 Process *tgt_proc = nullptr;
2197 for (int i = 0; i < sys->numContexts(); i++) {
2198 Process *temp = sys->threadContexts[i]->getProcessPtr();
2199 if (temp->pid() == tid) {
2205 if (sig != 0 || sig != OS::TGT_SIGABRT)
2208 if (tgt_proc == nullptr)
2211 if (tgid != -1 && tgt_proc->tgid() != tgid)
2214 if (sig == OS::TGT_SIGABRT)
2215 exitGroupFunc(desc, tc, 0);
2222 socketFunc(SyscallDesc *desc, ThreadContext *tc,
2223 int domain, int type, int prot)
2225 auto p = tc->getProcessPtr();
2227 int sim_fd = socket(domain, type, prot);
2231 auto sfdp = std::make_shared<SocketFDEntry>(sim_fd, domain, type, prot);
2232 int tgt_fd = p->fds->allocFD(sfdp);
2239 socketpairFunc(SyscallDesc *desc, ThreadContext *tc,
2240 int domain, int type, int prot, Addr svPtr)
2242 auto p = tc->getProcessPtr();
2244 BufferArg svBuf((Addr)svPtr, 2 * sizeof(int));
2245 int status = socketpair(domain, type, prot, (int *)svBuf.bufferPtr());
2249 int *fds = (int *)svBuf.bufferPtr();
2251 auto sfdp1 = std::make_shared<SocketFDEntry>(fds[0], domain, type, prot);
2252 fds[0] = p->fds->allocFD(sfdp1);
2253 auto sfdp2 = std::make_shared<SocketFDEntry>(fds[1], domain, type, prot);
2254 fds[1] = p->fds->allocFD(sfdp2);
2255 svBuf.copyOut(tc->getVirtProxy());
2262 selectFunc(SyscallDesc *desc, ThreadContext *tc,
2263 int nfds_t, Addr fds_read_ptr, Addr fds_writ_ptr,
2264 Addr fds_excp_ptr, Addr time_val_ptr)
2268 auto p = tc->getProcessPtr();
2270 TypedBufferArg<typename OS::fd_set> rd_t(fds_read_ptr);
2271 TypedBufferArg<typename OS::fd_set> wr_t(fds_writ_ptr);
2272 TypedBufferArg<typename OS::fd_set> ex_t(fds_excp_ptr);
2273 TypedBufferArg<typename OS::timeval> tp(time_val_ptr);
2276 * Host fields. Notice that these use the definitions from the system
2277 * headers instead of the gem5 headers and libraries. If the host and
2278 * target have different header file definitions, this will not work.
2288 * Copy in the fd_set from the target.
2291 rd_t.copyIn(tc->getVirtProxy());
2293 wr_t.copyIn(tc->getVirtProxy());
2295 ex_t.copyIn(tc->getVirtProxy());
2298 * We need to translate the target file descriptor set into a host file
2299 * descriptor set. This involves both our internal process fd array
2300 * and the fd_set defined in Linux header files. The nfds field also
2301 * needs to be updated as it will be only target specific after
2302 * retrieving it from the target; the nfds value is expected to be the
2303 * highest file descriptor that needs to be checked, so we need to extend
2304 * it out for nfds_h when we do the update.
2307 std::map<int, int> trans_map;
2308 auto try_add_host_set = [&](fd_set *tgt_set_entry,
2309 fd_set *hst_set_entry,
2313 * By this point, we know that we are looking at a valid file
2314 * descriptor set on the target. We need to check if the target file
2315 * descriptor value passed in as iter is part of the set.
2317 if (FD_ISSET(iter, tgt_set_entry)) {
2319 * We know that the target file descriptor belongs to the set,
2320 * but we do not yet know if the file descriptor is valid or
2321 * that we have a host mapping. Check that now.
2323 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[iter]);
2326 auto sim_fd = hbfdp->getSimFD();
2329 * Add the sim_fd to tgt_fd translation into trans_map for use
2330 * later when we need to zero the target fd_set structures and
2331 * then update them with hits returned from the host select call.
2333 trans_map[sim_fd] = iter;
2336 * We know that the host file descriptor exists so now we check
2337 * if we need to update the max count for nfds_h before passing
2338 * the duplicated structure into the host.
2340 nfds_h = std::max(nfds_h - 1, sim_fd + 1);
2343 * Add the host file descriptor to the set that we are going to
2344 * pass into the host.
2346 FD_SET(sim_fd, hst_set_entry);
2351 for (int i = 0; i < nfds_t; i++) {
2353 bool ebadf = try_add_host_set((fd_set*)&*rd_t, &rd_h, i);
2354 if (ebadf) return -EBADF;
2357 bool ebadf = try_add_host_set((fd_set*)&*wr_t, &wr_h, i);
2358 if (ebadf) return -EBADF;
2361 bool ebadf = try_add_host_set((fd_set*)&*ex_t, &ex_h, i);
2362 if (ebadf) return -EBADF;
2368 * It might be possible to decrement the timeval based on some
2369 * derivation of wall clock determined from elapsed simulator ticks
2370 * but that seems like overkill. Rather, we just set the timeval with
2371 * zero timeout. (There is no reason to block during the simulation
2372 * as it only decreases simulator performance.)
2377 retval = select(nfds_h,
2378 fds_read_ptr ? &rd_h : nullptr,
2379 fds_writ_ptr ? &wr_h : nullptr,
2380 fds_excp_ptr ? &ex_h : nullptr,
2384 * If the timeval pointer is null, setup a new timeval structure to
2385 * pass into the host select call. Unfortunately, we will need to
2386 * manually check the return value and throw a retry fault if the
2387 * return value is zero. Allowing the system call to block will
2388 * likely deadlock the event queue.
2390 struct timeval tv = { 0, 0 };
2392 retval = select(nfds_h,
2393 fds_read_ptr ? &rd_h : nullptr,
2394 fds_writ_ptr ? &wr_h : nullptr,
2395 fds_excp_ptr ? &ex_h : nullptr,
2400 * If blocking indefinitely, check the signal list to see if a
2401 * signal would break the poll out of the retry cycle and try to
2402 * return the signal interrupt instead.
2404 for (auto sig : tc->getSystemPtr()->signalList)
2405 if (sig.receiver == p)
2407 return SyscallReturn::retry();
2414 FD_ZERO((fd_set*)&*rd_t);
2415 FD_ZERO((fd_set*)&*wr_t);
2416 FD_ZERO((fd_set*)&*ex_t);
2419 * We need to translate the host file descriptor set into a target file
2420 * descriptor set. This involves both our internal process fd array
2421 * and the fd_set defined in header files.
2423 for (int i = 0; i < nfds_h; i++) {
2425 if (FD_ISSET(i, &rd_h))
2426 FD_SET(trans_map[i], (fd_set*)&*rd_t);
2430 if (FD_ISSET(i, &wr_h))
2431 FD_SET(trans_map[i], (fd_set*)&*wr_t);
2435 if (FD_ISSET(i, &ex_h))
2436 FD_SET(trans_map[i], (fd_set*)&*ex_t);
2441 rd_t.copyOut(tc->getVirtProxy());
2443 wr_t.copyOut(tc->getVirtProxy());
2445 ex_t.copyOut(tc->getVirtProxy());
2447 tp.copyOut(tc->getVirtProxy());
2454 readFunc(SyscallDesc *desc, ThreadContext *tc,
2455 int tgt_fd, Addr buf_ptr, int nbytes)
2457 auto p = tc->getProcessPtr();
2459 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2462 int sim_fd = hbfdp->getSimFD();
2466 pfd.events = POLLIN | POLLPRI;
2467 if ((poll(&pfd, 1, 0) == 0)
2468 && !(hbfdp->getFlags() & OS::TGT_O_NONBLOCK))
2469 return SyscallReturn::retry();
2471 BufferArg buf_arg(buf_ptr, nbytes);
2472 int bytes_read = read(sim_fd, buf_arg.bufferPtr(), nbytes);
2475 buf_arg.copyOut(tc->getVirtProxy());
2477 return (bytes_read == -1) ? -errno : bytes_read;
2482 writeFunc(SyscallDesc *desc, ThreadContext *tc,
2483 int tgt_fd, Addr buf_ptr, int nbytes)
2485 auto p = tc->getProcessPtr();
2487 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2490 int sim_fd = hbfdp->getSimFD();
2492 BufferArg buf_arg(buf_ptr, nbytes);
2493 buf_arg.copyIn(tc->getVirtProxy());
2497 pfd.events = POLLOUT;
2500 * We don't want to poll on /dev/random. The kernel will not enable the
2501 * file descriptor for writing unless the entropy in the system falls
2502 * below write_wakeup_threshold. This is not guaranteed to happen
2503 * depending on host settings.
2505 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(hbfdp);
2506 if (ffdp && (ffdp->getFileName() != "/dev/random")) {
2507 if (!poll(&pfd, 1, 0) && !(ffdp->getFlags() & OS::TGT_O_NONBLOCK))
2508 return SyscallReturn::retry();
2511 int bytes_written = write(sim_fd, buf_arg.bufferPtr(), nbytes);
2513 if (bytes_written != -1)
2516 return (bytes_written == -1) ? -errno : bytes_written;
2521 wait4Func(SyscallDesc *desc, ThreadContext *tc,
2522 pid_t pid, Addr statPtr, int options, Addr rusagePtr)
2524 auto p = tc->getProcessPtr();
2527 DPRINTF_SYSCALL(Verbose, "wait4: rusage pointer provided %lx, however "
2528 "functionality not supported. Ignoring rusage pointer.\n",
2532 * Currently, wait4 is only implemented so that it will wait for children
2533 * exit conditions which are denoted by a SIGCHLD signals posted into the
2534 * system signal list. We return no additional information via any of the
2535 * parameters supplied to wait4. If nothing is found in the system signal
2536 * list, we will wait indefinitely for SIGCHLD to post by retrying the
2539 System *sysh = tc->getSystemPtr();
2540 std::list<BasicSignal>::iterator iter;
2541 for (iter=sysh->signalList.begin(); iter!=sysh->signalList.end(); iter++) {
2542 if (iter->receiver == p) {
2544 if ((iter->sender->pgid() == -pid)
2545 && (iter->signalValue == OS::TGT_SIGCHLD))
2547 } else if (pid == -1) {
2548 if (iter->signalValue == OS::TGT_SIGCHLD)
2550 } else if (pid == 0) {
2551 if ((iter->sender->pgid() == p->pgid())
2552 && (iter->signalValue == OS::TGT_SIGCHLD))
2555 if ((iter->sender->pid() == pid)
2556 && (iter->signalValue == OS::TGT_SIGCHLD))
2562 return (options & OS::TGT_WNOHANG) ? 0 : SyscallReturn::retry();
2565 // Set status to EXITED for WIFEXITED evaluations.
2566 const int EXITED = 0;
2567 BufferArg statusBuf(statPtr, sizeof(int));
2568 *(int *)statusBuf.bufferPtr() = EXITED;
2569 statusBuf.copyOut(tc->getVirtProxy());
2571 // Return the child PID.
2572 pid_t retval = iter->sender->pid();
2573 sysh->signalList.erase(iter);
2579 acceptFunc(SyscallDesc *desc, ThreadContext *tc,
2580 int tgt_fd, Addr addrPtr, Addr lenPtr)
2585 auto p = tc->getProcessPtr();
2587 BufferArg *lenBufPtr = nullptr;
2588 BufferArg *addrBufPtr = nullptr;
2590 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
2593 int sim_fd = sfdp->getSimFD();
2596 * We poll the socket file descriptor first to guarantee that we do not
2597 * block on our accept call. The socket can be opened without the
2598 * non-blocking flag (it blocks). This will cause deadlocks between
2599 * communicating processes.
2603 pfd.events = POLLIN | POLLPRI;
2604 if ((poll(&pfd, 1, 0) == 0) && !(sfdp->getFlags() & OS::TGT_O_NONBLOCK))
2605 return SyscallReturn::retry();
2608 lenBufPtr = new BufferArg(lenPtr, sizeof(socklen_t));
2609 lenBufPtr->copyIn(tc->getVirtProxy());
2610 memcpy(&addrLen, (socklen_t *)lenBufPtr->bufferPtr(),
2615 addrBufPtr = new BufferArg(addrPtr, sizeof(struct sockaddr));
2616 addrBufPtr->copyIn(tc->getVirtProxy());
2617 memcpy(&sa, (struct sockaddr *)addrBufPtr->bufferPtr(),
2618 sizeof(struct sockaddr));
2621 host_fd = accept(sim_fd, &sa, &addrLen);
2627 memcpy(addrBufPtr->bufferPtr(), &sa, sizeof(sa));
2628 addrBufPtr->copyOut(tc->getVirtProxy());
2633 *(socklen_t *)lenBufPtr->bufferPtr() = addrLen;
2634 lenBufPtr->copyOut(tc->getVirtProxy());
2638 auto afdp = std::make_shared<SocketFDEntry>(host_fd, sfdp->_domain,
2639 sfdp->_type, sfdp->_protocol);
2640 return p->fds->allocFD(afdp);
2643 /// Target eventfd() function.
2646 eventfdFunc(SyscallDesc *desc, ThreadContext *tc,
2647 unsigned initval, int in_flags)
2649 #if defined(__linux__)
2650 auto p = tc->getProcessPtr();
2652 int sim_fd = eventfd(initval, in_flags);
2656 bool cloexec = in_flags & OS::TGT_O_CLOEXEC;
2658 int flags = cloexec ? OS::TGT_O_CLOEXEC : 0;
2659 flags |= (in_flags & OS::TGT_O_NONBLOCK) ? OS::TGT_O_NONBLOCK : 0;
2661 auto hbfdp = std::make_shared<HBFDEntry>(flags, sim_fd, cloexec);
2662 int tgt_fd = p->fds->allocFD(hbfdp);
2665 warnUnsupportedOS("eventfd");
2670 #endif // __SIM_SYSCALL_EMUL_HH__