2 * Copyright (c) 2012-2013, 2015, 2019-2020 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 SyscallReturn getcpuFunc(SyscallDesc *desc, ThreadContext *tc,
358 Addr cpu_ptr, Addr node_ptr, Addr tcache_ptr);
360 // Target getsockname() handler.
361 SyscallReturn getsocknameFunc(SyscallDesc *desc, ThreadContext *tc,
362 int tgt_fd, Addr addrPtr, Addr lenPtr);
364 /// Futex system call
365 /// Implemented by Daniel Sanchez
366 /// Used by printf's in multi-threaded apps
369 futexFunc(SyscallDesc *desc, ThreadContext *tc,
370 Addr uaddr, int op, int val, int timeout, Addr uaddr2, int val3)
374 auto process = tc->getProcessPtr();
377 * Unsupported option that does not affect the correctness of the
378 * application. This is a performance optimization utilized by Linux.
380 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
381 op &= ~OS::TGT_FUTEX_CLOCK_REALTIME_FLAG;
383 FutexMap &futex_map = tc->getSystemPtr()->futexMap;
385 if (OS::TGT_FUTEX_WAIT == op || OS::TGT_FUTEX_WAIT_BITSET == op) {
386 // Ensure futex system call accessed atomically.
387 BufferArg buf(uaddr, sizeof(int));
388 buf.copyIn(tc->getVirtProxy());
389 int mem_val = *(int*)buf.bufferPtr();
392 * The value in memory at uaddr is not equal with the expected val
393 * (a different thread must have changed it before the system call was
394 * invoked). In this case, we need to throw an error.
397 return -OS::TGT_EWOULDBLOCK;
399 if (OS::TGT_FUTEX_WAIT == op) {
400 futex_map.suspend(uaddr, process->tgid(), tc);
402 futex_map.suspend_bitset(uaddr, process->tgid(), tc, val3);
406 } else if (OS::TGT_FUTEX_WAKE == op) {
407 return futex_map.wakeup(uaddr, process->tgid(), val);
408 } else if (OS::TGT_FUTEX_WAKE_BITSET == op) {
409 return futex_map.wakeup_bitset(uaddr, process->tgid(), val3);
410 } else if (OS::TGT_FUTEX_REQUEUE == op ||
411 OS::TGT_FUTEX_CMP_REQUEUE == op) {
413 // Ensure futex system call accessed atomically.
414 BufferArg buf(uaddr, sizeof(int));
415 buf.copyIn(tc->getVirtProxy());
416 int mem_val = *(int*)buf.bufferPtr();
418 * For CMP_REQUEUE, the whole operation is only started only if
419 * val3 is still the value of the futex pointed to by uaddr.
421 if (OS::TGT_FUTEX_CMP_REQUEUE && val3 != mem_val)
422 return -OS::TGT_EWOULDBLOCK;
423 return futex_map.requeue(uaddr, process->tgid(), val, timeout, uaddr2);
424 } else if (OS::TGT_FUTEX_WAKE_OP == op) {
426 * The FUTEX_WAKE_OP operation is equivalent to executing the
427 * following code atomically and totally ordered with respect to
428 * other futex operations on any of the two supplied futex words:
430 * int oldval = *(int *) addr2;
431 * *(int *) addr2 = oldval op oparg;
432 * futex(addr1, FUTEX_WAKE, val, 0, 0, 0);
433 * if (oldval cmp cmparg)
434 * futex(addr2, FUTEX_WAKE, val2, 0, 0, 0);
436 * (op, oparg, cmp, cmparg are encoded in val3)
438 * +---+---+-----------+-----------+
439 * |op |cmp| oparg | cmparg |
440 * +---+---+-----------+-----------+
441 * 4 4 12 12 <== # of bits
443 * reference: http://man7.org/linux/man-pages/man2/futex.2.html
446 // get value from simulated-space
447 BufferArg buf(uaddr2, sizeof(int));
448 buf.copyIn(tc->getVirtProxy());
449 int oldval = *(int*)buf.bufferPtr();
451 // extract op, oparg, cmp, cmparg from val3
452 int wake_cmparg = val3 & 0xfff;
453 int wake_oparg = (val3 & 0xfff000) >> 12;
454 int wake_cmp = (val3 & 0xf000000) >> 24;
455 int wake_op = (val3 & 0xf0000000) >> 28;
456 if ((wake_op & OS::TGT_FUTEX_OP_ARG_SHIFT) >> 3 == 1)
457 wake_oparg = (1 << wake_oparg);
458 wake_op &= ~OS::TGT_FUTEX_OP_ARG_SHIFT;
459 // perform operation on the value of the second futex
460 if (wake_op == OS::TGT_FUTEX_OP_SET)
462 else if (wake_op == OS::TGT_FUTEX_OP_ADD)
463 newval += wake_oparg;
464 else if (wake_op == OS::TGT_FUTEX_OP_OR)
465 newval |= wake_oparg;
466 else if (wake_op == OS::TGT_FUTEX_OP_ANDN)
467 newval &= ~wake_oparg;
468 else if (wake_op == OS::TGT_FUTEX_OP_XOR)
469 newval ^= wake_oparg;
470 // copy updated value back to simulated-space
471 *(int*)buf.bufferPtr() = newval;
472 buf.copyOut(tc->getVirtProxy());
473 // perform the first wake-up
474 int woken1 = futex_map.wakeup(uaddr, process->tgid(), val);
476 // calculate the condition of the second wake-up
477 bool is_wake2 = false;
478 if (wake_cmp == OS::TGT_FUTEX_OP_CMP_EQ)
479 is_wake2 = oldval == wake_cmparg;
480 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_NE)
481 is_wake2 = oldval != wake_cmparg;
482 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LT)
483 is_wake2 = oldval < wake_cmparg;
484 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LE)
485 is_wake2 = oldval <= wake_cmparg;
486 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GT)
487 is_wake2 = oldval > wake_cmparg;
488 else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GE)
489 is_wake2 = oldval >= wake_cmparg;
490 // perform the second wake-up
492 woken2 = futex_map.wakeup(uaddr2, process->tgid(), timeout);
494 return woken1 + woken2;
496 warn("futex: op %d not implemented; ignoring.", op);
500 /// Pseudo Funcs - These functions use a different return convension,
501 /// returning a second value in a register other than the normal return register
502 SyscallReturn pipePseudoFunc(SyscallDesc *desc, ThreadContext *tc);
505 /// Approximate seconds since the epoch (1/1/1970). About a billion,
506 /// by my reckoning. We want to keep this a constant (not use the
507 /// real-world time) to keep simulations repeatable.
508 const unsigned seconds_since_epoch = 1000 * 1000 * 1000;
510 /// Helper function to convert current elapsed time to seconds and
512 template <class T1, class T2>
514 getElapsedTimeMicro(T1 &sec, T2 &usec)
516 static const int OneMillion = 1000 * 1000;
518 uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
519 sec = elapsed_usecs / OneMillion;
520 usec = elapsed_usecs % OneMillion;
523 /// Helper function to convert current elapsed time to seconds and
525 template <class T1, class T2>
527 getElapsedTimeNano(T1 &sec, T2 &nsec)
529 static const int OneBillion = 1000 * 1000 * 1000;
531 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
532 sec = elapsed_nsecs / OneBillion;
533 nsec = elapsed_nsecs % OneBillion;
536 //////////////////////////////////////////////////////////////////////
538 // The following emulation functions are generic, but need to be
539 // templated to account for differences in types, constants, etc.
541 //////////////////////////////////////////////////////////////////////
543 typedef struct statfs hst_statfs;
545 typedef struct stat hst_stat;
546 typedef struct stat hst_stat64;
548 typedef struct stat hst_stat;
549 typedef struct stat64 hst_stat64;
552 //// Helper function to convert a host stat buffer to a target stat
553 //// buffer. Also copies the target buffer out to the simulated
554 //// memory space. Used by stat(), fstat(), and lstat().
556 template <typename target_stat, typename host_stat>
558 convertStatBuf(target_stat &tgt, host_stat *host,
559 ByteOrder bo, bool fakeTTY=false)
564 tgt->st_dev = host->st_dev;
565 tgt->st_dev = htog(tgt->st_dev, bo);
566 tgt->st_ino = host->st_ino;
567 tgt->st_ino = htog(tgt->st_ino, bo);
568 tgt->st_mode = host->st_mode;
570 // Claim to be a character device
571 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT
572 tgt->st_mode |= S_IFCHR; // Set S_IFCHR
574 tgt->st_mode = htog(tgt->st_mode, bo);
575 tgt->st_nlink = host->st_nlink;
576 tgt->st_nlink = htog(tgt->st_nlink, bo);
577 tgt->st_uid = host->st_uid;
578 tgt->st_uid = htog(tgt->st_uid, bo);
579 tgt->st_gid = host->st_gid;
580 tgt->st_gid = htog(tgt->st_gid, bo);
582 tgt->st_rdev = 0x880d;
584 tgt->st_rdev = host->st_rdev;
585 tgt->st_rdev = htog(tgt->st_rdev, bo);
586 tgt->st_size = host->st_size;
587 tgt->st_size = htog(tgt->st_size, bo);
588 tgt->st_atimeX = host->st_atime;
589 tgt->st_atimeX = htog(tgt->st_atimeX, bo);
590 tgt->st_mtimeX = host->st_mtime;
591 tgt->st_mtimeX = htog(tgt->st_mtimeX, bo);
592 tgt->st_ctimeX = host->st_ctime;
593 tgt->st_ctimeX = htog(tgt->st_ctimeX, bo);
594 // Force the block size to be 8KB. This helps to ensure buffered io works
595 // consistently across different hosts.
596 tgt->st_blksize = 0x2000;
597 tgt->st_blksize = htog(tgt->st_blksize, bo);
598 tgt->st_blocks = host->st_blocks;
599 tgt->st_blocks = htog(tgt->st_blocks, bo);
604 template <typename target_stat, typename host_stat64>
606 convertStat64Buf(target_stat &tgt, host_stat64 *host,
607 ByteOrder bo, bool fakeTTY=false)
609 convertStatBuf<target_stat, host_stat64>(tgt, host, bo, fakeTTY);
610 #if defined(STAT_HAVE_NSEC)
611 tgt->st_atime_nsec = host->st_atime_nsec;
612 tgt->st_atime_nsec = htog(tgt->st_atime_nsec, bo);
613 tgt->st_mtime_nsec = host->st_mtime_nsec;
614 tgt->st_mtime_nsec = htog(tgt->st_mtime_nsec, bo);
615 tgt->st_ctime_nsec = host->st_ctime_nsec;
616 tgt->st_ctime_nsec = htog(tgt->st_ctime_nsec, bo);
618 tgt->st_atime_nsec = 0;
619 tgt->st_mtime_nsec = 0;
620 tgt->st_ctime_nsec = 0;
624 // Here are a couple of convenience functions
627 copyOutStatBuf(PortProxy &mem, Addr addr,
628 hst_stat *host, bool fakeTTY = false)
630 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
631 tgt_stat_buf tgt(addr);
632 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, OS::byteOrder, fakeTTY);
638 copyOutStat64Buf(PortProxy &mem, Addr addr,
639 hst_stat64 *host, bool fakeTTY = false)
641 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
642 tgt_stat_buf tgt(addr);
643 convertStat64Buf<tgt_stat_buf, hst_stat64>(
644 tgt, host, OS::byteOrder, fakeTTY);
650 copyOutStatfsBuf(PortProxy &mem, Addr addr,
653 TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
655 const ByteOrder bo = OS::byteOrder;
657 tgt->f_type = htog(host->f_type, bo);
658 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
659 tgt->f_bsize = htog(host->f_iosize, bo);
661 tgt->f_bsize = htog(host->f_bsize, bo);
663 tgt->f_blocks = htog(host->f_blocks, bo);
664 tgt->f_bfree = htog(host->f_bfree, bo);
665 tgt->f_bavail = htog(host->f_bavail, bo);
666 tgt->f_files = htog(host->f_files, bo);
667 tgt->f_ffree = htog(host->f_ffree, bo);
668 memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
669 #if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
670 tgt->f_namelen = htog(host->f_namemax, bo);
671 tgt->f_frsize = htog(host->f_bsize, bo);
672 #elif defined(__APPLE__)
676 tgt->f_namelen = htog(host->f_namelen, bo);
677 tgt->f_frsize = htog(host->f_frsize, bo);
679 #if defined(__linux__)
680 memcpy(&tgt->f_spare, &host->f_spare,
681 std::min(sizeof(host->f_spare), sizeof(tgt->f_spare)));
684 * The fields are different sizes per OS. Don't bother with
685 * f_spare or f_reserved on non-Linux for now.
687 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
693 /// Target ioctl() handler. For the most part, programs call ioctl()
694 /// only to find out if their stdout is a tty, to determine whether to
695 /// do line or block buffering. We always claim that output fds are
696 /// not TTYs to provide repeatable results.
699 ioctlFunc(SyscallDesc *desc, ThreadContext *tc,
700 int tgt_fd, unsigned req, Addr addr)
702 auto p = tc->getProcessPtr();
704 DPRINTF_SYSCALL(Verbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
706 if (OS::isTtyReq(req))
709 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
711 EmulatedDriver *emul_driver = dfdp->getDriver();
713 return emul_driver->ioctl(tc, req, addr);
716 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
722 BufferArg conf_arg(addr, sizeof(ifconf));
723 conf_arg.copyIn(tc->getVirtProxy());
725 ifconf *conf = (ifconf*)conf_arg.bufferPtr();
726 Addr ifc_buf_addr = (Addr)conf->ifc_buf;
727 BufferArg ifc_buf_arg(ifc_buf_addr, conf->ifc_len);
728 ifc_buf_arg.copyIn(tc->getVirtProxy());
730 conf->ifc_buf = (char*)ifc_buf_arg.bufferPtr();
732 status = ioctl(sfdp->getSimFD(), req, conf_arg.bufferPtr());
734 conf->ifc_buf = (char*)ifc_buf_addr;
735 ifc_buf_arg.copyOut(tc->getVirtProxy());
736 conf_arg.copyOut(tc->getVirtProxy());
742 #if defined(__linux__)
747 #if defined(__linux__)
751 BufferArg req_arg(addr, sizeof(ifreq));
752 req_arg.copyIn(tc->getVirtProxy());
754 status = ioctl(sfdp->getSimFD(), req, req_arg.bufferPtr());
756 req_arg.copyOut(tc->getVirtProxy());
763 * For lack of a better return code, return ENOTTY. Ideally, we should
764 * return something better here, but at least we issue the warning.
766 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
767 tgt_fd, req, tc->pcState());
771 /// Target open() handler.
774 openatFunc(SyscallDesc *desc, ThreadContext *tc,
775 int tgt_dirfd, Addr pathname, int tgt_flags, int mode)
777 auto p = tc->getProcessPtr();
780 * Retrieve the simulated process' memory proxy and then read in the path
781 * string from that memory space into the host's working memory space.
784 if (!tc->getVirtProxy().tryReadString(path, pathname))
788 int host_flags = O_BINARY;
793 * Translate target flags into host flags. Flags exist which are not
794 * ported between architectures which can cause check failures.
796 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
797 if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
798 tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
799 host_flags |= OS::openFlagTable[i].hostFlag;
803 warn("%s: cannot decode flags %#x", desc->name(), tgt_flags);
806 host_flags |= O_BINARY;
810 * If the simulated process called open or openat with AT_FDCWD specified,
811 * take the current working directory value which was passed into the
812 * process class as a Python parameter and append the current path to
813 * create a full path.
814 * Otherwise, openat with a valid target directory file descriptor has
815 * been called. If the path option, which was passed in as a parameter,
816 * is not absolute, retrieve the directory file descriptor's path and
817 * prepend it to the path passed in as a parameter.
818 * In every case, we should have a full path (which is relevant to the
819 * host) to work with after this block has been passed.
821 std::string redir_path = path;
822 std::string abs_path = path;
823 if (tgt_dirfd == OS::TGT_AT_FDCWD) {
824 abs_path = p->absolutePath(path, true);
825 redir_path = p->checkPathRedirect(path);
826 } else if (!startswith(path, "/")) {
827 std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
828 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
831 abs_path = ffdp->getFileName() + path;
832 redir_path = p->checkPathRedirect(abs_path);
836 * Since this is an emulated environment, we create pseudo file
837 * descriptors for device requests that have been registered with
838 * the process class through Python; this allows us to create a file
839 * descriptor for subsequent ioctl or mmap calls.
841 if (startswith(abs_path, "/dev/")) {
842 std::string filename = abs_path.substr(strlen("/dev/"));
843 EmulatedDriver *drv = p->findDriver(filename);
845 DPRINTF_SYSCALL(Verbose, "%s: passing call to "
846 "driver open with path[%s]\n",
847 desc->name(), abs_path.c_str());
848 return drv->open(tc, mode, host_flags);
851 * Fall through here for pass through to host devices, such
857 * We make several attempts resolve a call to open.
859 * 1) Resolve any path redirection before hand. This will set the path
860 * up with variable 'redir_path' which may contain a modified path or
861 * the original path value. This should already be done in prior code.
862 * 2) Try to handle the access using 'special_paths'. Some special_paths
863 * and files cannot be called on the host and need to be handled as
864 * special cases inside the simulator. These special_paths are handled by
865 * C++ routines to provide output back to userspace.
866 * 3) If the full path that was created above does not match any of the
867 * special cases, pass it through to the open call on the __HOST__ to let
868 * the host open the file on our behalf. Again, the openImpl tries to
869 * USE_THE_HOST_FILESYSTEM_OPEN (with a possible redirection to the
870 * faux-filesystem files). The faux-filesystem is dynamically created
871 * during simulator configuration using Python functions.
872 * 4) If the host cannot open the file, the open attempt failed in "3)".
873 * Return the host's error code back through the system call to the
874 * simulated process. If running a debug trace, also notify the user that
875 * the open call failed.
877 * Any success will set sim_fd to something other than -1 and skip the
878 * next conditions effectively bypassing them.
881 std::string used_path;
882 std::vector<std::string> special_paths =
883 { "/proc/meminfo/", "/system/", "/platform/", "/etc/passwd",
884 "/proc/self/maps", "/dev/urandom",
885 "/sys/devices/system/cpu/online" };
886 for (auto entry : special_paths) {
887 if (startswith(path, entry)) {
888 sim_fd = OS::openSpecialFile(abs_path, p, tc);
889 used_path = abs_path;
893 sim_fd = open(redir_path.c_str(), host_flags, mode);
894 used_path = redir_path;
898 DPRINTF_SYSCALL(Verbose, "%s: failed -> path:%s "
899 "(inferred from:%s)\n", desc->name(),
900 used_path.c_str(), path.c_str());
905 * The file was opened successfully and needs to be recorded in the
906 * process' file descriptor array so that it can be retrieved later.
907 * The target file descriptor that is chosen will be the lowest unused
909 * Return the indirect target file descriptor back to the simulated
910 * process to act as a handle for the opened file.
912 auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
913 int tgt_fd = p->fds->allocFD(ffdp);
914 DPRINTF_SYSCALL(Verbose, "%s: sim_fd[%d], target_fd[%d] -> path:%s\n"
915 "(inferred from:%s)\n", desc->name(),
916 sim_fd, tgt_fd, used_path.c_str(), path.c_str());
920 /// Target open() handler.
923 openFunc(SyscallDesc *desc, ThreadContext *tc,
924 Addr pathname, int tgt_flags, int mode)
926 return openatFunc<OS>(
927 desc, tc, OS::TGT_AT_FDCWD, pathname, tgt_flags, mode);
930 /// Target unlinkat() handler.
933 unlinkatFunc(SyscallDesc *desc, ThreadContext *tc, int dirfd, Addr pathname)
935 if (dirfd != OS::TGT_AT_FDCWD)
936 warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
938 return unlinkFunc(desc, tc, pathname);
941 /// Target facessat() handler
944 faccessatFunc(SyscallDesc *desc, ThreadContext *tc,
945 int dirfd, Addr pathname, int mode)
947 if (dirfd != OS::TGT_AT_FDCWD)
948 warn("faccessat: first argument not AT_FDCWD; unlikely to work");
949 return accessFunc(desc, tc, pathname, mode);
952 /// Target readlinkat() handler
955 readlinkatFunc(SyscallDesc *desc, ThreadContext *tc,
956 int dirfd, Addr pathname, Addr buf, size_t bufsiz)
958 if (dirfd != OS::TGT_AT_FDCWD)
959 warn("openat: first argument not AT_FDCWD; unlikely to work");
960 return readlinkFunc(desc, tc, pathname, buf, bufsiz);
963 /// Target renameat() handler.
966 renameatFunc(SyscallDesc *desc, ThreadContext *tc,
967 int olddirfd, Addr oldpath, int newdirfd, Addr newpath)
969 if (olddirfd != OS::TGT_AT_FDCWD)
970 warn("renameat: first argument not AT_FDCWD; unlikely to work");
972 if (newdirfd != OS::TGT_AT_FDCWD)
973 warn("renameat: third argument not AT_FDCWD; unlikely to work");
975 return renameFunc(desc, tc, oldpath, newpath);
978 /// Target sysinfo() handler.
981 sysinfoFunc(SyscallDesc *desc, ThreadContext *tc, Addr info)
983 auto process = tc->getProcessPtr();
985 TypedBufferArg<typename OS::tgt_sysinfo> sysinfo(info);
987 sysinfo->uptime = seconds_since_epoch;
988 sysinfo->totalram = process->system->memSize();
989 sysinfo->mem_unit = 1;
991 sysinfo.copyOut(tc->getVirtProxy());
996 /// Target chmod() handler.
999 chmodFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, mode_t mode)
1002 auto process = tc->getProcessPtr();
1004 if (!tc->getVirtProxy().tryReadString(path, pathname))
1007 mode_t hostMode = 0;
1009 // XXX translate mode flags via OS::something???
1012 // Adjust path for cwd and redirection
1013 path = process->checkPathRedirect(path);
1016 int result = chmod(path.c_str(), hostMode);
1025 pollFunc(SyscallDesc *desc, ThreadContext *tc,
1026 Addr fdsPtr, int nfds, int tmout)
1028 auto p = tc->getProcessPtr();
1030 BufferArg fdsBuf(fdsPtr, sizeof(struct pollfd) * nfds);
1031 fdsBuf.copyIn(tc->getVirtProxy());
1034 * Record the target file descriptors in a local variable. We need to
1035 * replace them with host file descriptors but we need a temporary copy
1036 * for later. Afterwards, replace each target file descriptor in the
1037 * poll_fd array with its host_fd.
1039 int temp_tgt_fds[nfds];
1040 for (int index = 0; index < nfds; index++) {
1041 temp_tgt_fds[index] = ((struct pollfd *)fdsBuf.bufferPtr())[index].fd;
1042 auto tgt_fd = temp_tgt_fds[index];
1043 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1046 auto host_fd = hbfdp->getSimFD();
1047 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = host_fd;
1051 * We cannot allow an infinite poll to occur or it will inevitably cause
1052 * a deadlock in the gem5 simulator with clone. We must pass in tmout with
1053 * a non-negative value, however it also makes no sense to poll on the
1054 * underlying host for any other time than tmout a zero timeout.
1058 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1061 * If blocking indefinitely, check the signal list to see if a
1062 * signal would break the poll out of the retry cycle and try
1063 * to return the signal interrupt instead.
1065 System *sysh = tc->getSystemPtr();
1066 std::list<BasicSignal>::iterator it;
1067 for (it=sysh->signalList.begin(); it!=sysh->signalList.end(); it++)
1068 if (it->receiver == p)
1070 return SyscallReturn::retry();
1073 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1079 * Replace each host_fd in the returned poll_fd array with its original
1080 * target file descriptor.
1082 for (int index = 0; index < nfds; index++) {
1083 auto tgt_fd = temp_tgt_fds[index];
1084 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = tgt_fd;
1088 * Copy out the pollfd struct because the host may have updated fields
1091 fdsBuf.copyOut(tc->getVirtProxy());
1096 /// Target fchmod() handler.
1099 fchmodFunc(SyscallDesc *desc, ThreadContext *tc, int tgt_fd, uint32_t mode)
1101 auto p = tc->getProcessPtr();
1103 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1106 int sim_fd = ffdp->getSimFD();
1108 mode_t hostMode = mode;
1110 int result = fchmod(sim_fd, hostMode);
1112 return (result < 0) ? -errno : 0;
1115 /// Target mremap() handler.
1118 mremapFunc(SyscallDesc *desc, ThreadContext *tc,
1119 Addr start, uint64_t old_length, uint64_t new_length, uint64_t flags,
1120 GuestABI::VarArgs<uint64_t> varargs)
1122 auto p = tc->getProcessPtr();
1123 Addr page_bytes = tc->getSystemPtr()->getPageBytes();
1124 uint64_t provided_address = 0;
1125 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
1127 if (use_provided_address)
1128 provided_address = varargs.get<uint64_t>();
1130 if ((start % page_bytes != 0) ||
1131 (provided_address % page_bytes != 0)) {
1132 warn("mremap failing: arguments not page aligned");
1136 new_length = roundUp(new_length, page_bytes);
1138 if (new_length > old_length) {
1139 Addr mmap_end = p->memState->getMmapEnd();
1141 if ((start + old_length) == mmap_end &&
1142 (!use_provided_address || provided_address == start)) {
1143 // This case cannot occur when growing downward, as
1144 // start is greater than or equal to mmap_end.
1145 uint64_t diff = new_length - old_length;
1146 p->memState->mapRegion(mmap_end, diff, "remapped");
1147 p->memState->setMmapEnd(mmap_end + diff);
1150 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
1151 warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
1154 uint64_t new_start = provided_address;
1155 if (!use_provided_address) {
1156 new_start = p->mmapGrowsDown() ?
1157 mmap_end - new_length : mmap_end;
1158 mmap_end = p->mmapGrowsDown() ?
1159 new_start : mmap_end + new_length;
1160 p->memState->setMmapEnd(mmap_end);
1163 warn("mremapping to new vaddr %08p-%08p, adding %d\n",
1164 new_start, new_start + new_length,
1165 new_length - old_length);
1167 // add on the remaining unallocated pages
1168 p->allocateMem(new_start + old_length,
1169 new_length - old_length,
1170 use_provided_address /* clobber */);
1172 if (use_provided_address &&
1173 ((new_start + new_length > p->memState->getMmapEnd() &&
1174 !p->mmapGrowsDown()) ||
1175 (new_start < p->memState->getMmapEnd() &&
1176 p->mmapGrowsDown()))) {
1177 // something fishy going on here, at least notify the user
1178 // @todo: increase mmap_end?
1179 warn("mmap region limit exceeded with MREMAP_FIXED\n");
1182 warn("returning %08p as start\n", new_start);
1183 p->memState->remapRegion(start, new_start, old_length);
1189 if (use_provided_address && provided_address != start)
1190 p->memState->remapRegion(start, provided_address, new_length);
1191 if (new_length != old_length)
1192 p->memState->unmapRegion(start + new_length,
1193 old_length - new_length);
1194 return use_provided_address ? provided_address : start;
1198 /// Target stat() handler.
1201 statFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1204 auto process = tc->getProcessPtr();
1206 if (!tc->getVirtProxy().tryReadString(path, pathname))
1209 // Adjust path for cwd and redirection
1210 path = process->checkPathRedirect(path);
1212 struct stat hostBuf;
1213 int result = stat(path.c_str(), &hostBuf);
1218 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1224 /// Target stat64() handler.
1227 stat64Func(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1230 auto process = tc->getProcessPtr();
1232 if (!tc->getVirtProxy().tryReadString(path, pathname))
1235 // Adjust path for cwd and redirection
1236 path = process->checkPathRedirect(path);
1239 struct stat hostBuf;
1240 int result = stat(path.c_str(), &hostBuf);
1242 struct stat64 hostBuf;
1243 int result = stat64(path.c_str(), &hostBuf);
1249 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1255 /// Target fstatat64() handler.
1258 fstatat64Func(SyscallDesc *desc, ThreadContext *tc,
1259 int dirfd, Addr pathname, Addr bufPtr)
1261 auto process = tc->getProcessPtr();
1262 if (dirfd != OS::TGT_AT_FDCWD)
1263 warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1266 if (!tc->getVirtProxy().tryReadString(path, pathname))
1269 // Adjust path for cwd and redirection
1270 path = process->checkPathRedirect(path);
1273 struct stat hostBuf;
1274 int result = stat(path.c_str(), &hostBuf);
1276 struct stat64 hostBuf;
1277 int result = stat64(path.c_str(), &hostBuf);
1283 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1289 /// Target fstat64() handler.
1292 fstat64Func(SyscallDesc *desc, ThreadContext *tc, int tgt_fd, Addr bufPtr)
1294 auto p = tc->getProcessPtr();
1296 auto ffdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1299 int sim_fd = ffdp->getSimFD();
1302 struct stat hostBuf;
1303 int result = fstat(sim_fd, &hostBuf);
1305 struct stat64 hostBuf;
1306 int result = fstat64(sim_fd, &hostBuf);
1312 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1318 /// Target lstat() handler.
1321 lstatFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1324 auto process = tc->getProcessPtr();
1326 if (!tc->getVirtProxy().tryReadString(path, pathname))
1329 // Adjust path for cwd and redirection
1330 path = process->checkPathRedirect(path);
1332 struct stat hostBuf;
1333 int result = lstat(path.c_str(), &hostBuf);
1338 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1343 /// Target lstat64() handler.
1346 lstat64Func(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1349 auto process = tc->getProcessPtr();
1351 if (!tc->getVirtProxy().tryReadString(path, pathname))
1354 // Adjust path for cwd and redirection
1355 path = process->checkPathRedirect(path);
1358 struct stat hostBuf;
1359 int result = lstat(path.c_str(), &hostBuf);
1361 struct stat64 hostBuf;
1362 int result = lstat64(path.c_str(), &hostBuf);
1368 copyOutStat64Buf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1373 /// Target fstat() handler.
1376 fstatFunc(SyscallDesc *desc, ThreadContext *tc, int tgt_fd, Addr bufPtr)
1378 auto p = tc->getProcessPtr();
1380 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1382 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1385 int sim_fd = ffdp->getSimFD();
1387 struct stat hostBuf;
1388 int result = fstat(sim_fd, &hostBuf);
1393 copyOutStatBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1398 /// Target statfs() handler.
1401 statfsFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr bufPtr)
1403 #if defined(__linux__)
1405 auto process = tc->getProcessPtr();
1407 if (!tc->getVirtProxy().tryReadString(path, pathname))
1410 // Adjust path for cwd and redirection
1411 path = process->checkPathRedirect(path);
1413 struct statfs hostBuf;
1414 int result = statfs(path.c_str(), &hostBuf);
1419 copyOutStatfsBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1422 warnUnsupportedOS("statfs");
1429 cloneFunc(SyscallDesc *desc, ThreadContext *tc, RegVal flags, RegVal newStack,
1430 Addr ptidPtr, Addr ctidPtr, Addr tlsPtr)
1432 auto p = tc->getProcessPtr();
1434 if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1435 ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1436 ((flags & OS::TGT_CLONE_FS) && (flags & OS::TGT_CLONE_NEWNS)) ||
1437 ((flags & OS::TGT_CLONE_NEWIPC) && (flags & OS::TGT_CLONE_SYSVSEM)) ||
1438 ((flags & OS::TGT_CLONE_NEWPID) && (flags & OS::TGT_CLONE_THREAD)) ||
1439 ((flags & OS::TGT_CLONE_VM) && !(newStack)))
1443 if (!(ctc = tc->getSystemPtr()->findFreeContext())) {
1444 DPRINTF_SYSCALL(Verbose, "clone: no spare thread context in system"
1445 "[cpu %d, thread %d]", tc->cpuId(), tc->threadId());
1450 * Note that ProcessParams is generated by swig and there are no other
1451 * examples of how to create anything but this default constructor. The
1452 * fields are manually initialized instead of passing parameters to the
1455 ProcessParams *pp = new ProcessParams();
1456 pp->executable.assign(*(new std::string(p->progName())));
1457 pp->cmd.push_back(*(new std::string(p->progName())));
1458 pp->system = p->system;
1459 pp->cwd.assign(p->tgtCwd);
1460 pp->input.assign("stdin");
1461 pp->output.assign("stdout");
1462 pp->errout.assign("stderr");
1464 pp->euid = p->euid();
1466 pp->egid = p->egid();
1468 /* Find the first free PID that's less than the maximum */
1469 std::set<int> const& pids = p->system->PIDs;
1470 int temp_pid = *pids.begin();
1473 } while (pids.find(temp_pid) != pids.end());
1474 if (temp_pid >= System::maxPID)
1475 fatal("temp_pid is too large: %d", temp_pid);
1478 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1479 pp->useArchPT = p->useArchPT;
1480 pp->kvmInSE = p->kvmInSE;
1481 Process *cp = pp->create();
1482 // TODO: there is no way to know when the Process SimObject is done with
1483 // the params pointer. Both the params pointer (pp) and the process
1484 // pointer (cp) are normally managed in python and are never cleaned up.
1486 Process *owner = ctc->getProcessPtr();
1487 ctc->setProcessPtr(cp);
1488 cp->assignThreadContext(ctc->contextId());
1489 owner->revokeThreadContext(ctc->contextId());
1491 if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1492 BufferArg ptidBuf(ptidPtr, sizeof(long));
1493 long *ptid = (long *)ptidBuf.bufferPtr();
1495 ptidBuf.copyOut(tc->getVirtProxy());
1498 if (flags & OS::TGT_CLONE_THREAD) {
1499 cp->pTable->shared = true;
1500 cp->useForClone = true;
1503 p->clone(tc, ctc, cp, flags);
1505 if (flags & OS::TGT_CLONE_THREAD) {
1507 cp->sigchld = p->sigchld;
1508 } else if (flags & OS::TGT_SIGCHLD) {
1509 *cp->sigchld = true;
1512 if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1513 BufferArg ctidBuf(ctidPtr, sizeof(long));
1514 long *ctid = (long *)ctidBuf.bufferPtr();
1516 ctidBuf.copyOut(ctc->getVirtProxy());
1519 if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1520 cp->childClearTID = (uint64_t)ctidPtr;
1522 ctc->clearArchRegs();
1524 OS::archClone(flags, p, cp, tc, ctc, newStack, tlsPtr);
1526 desc->returnInto(ctc, 0);
1528 #if THE_ISA == SPARC_ISA
1529 tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1530 ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1533 TheISA::PCState cpc = tc->pcState();
1544 cloneBackwardsFunc(SyscallDesc *desc, ThreadContext *tc, RegVal flags,
1545 RegVal newStack, Addr ptidPtr, Addr tlsPtr, Addr ctidPtr)
1547 return cloneFunc<OS>(desc, tc, flags, newStack, ptidPtr, ctidPtr, tlsPtr);
1550 /// Target fstatfs() handler.
1553 fstatfsFunc(SyscallDesc *desc, ThreadContext *tc, int tgt_fd, Addr bufPtr)
1555 auto p = tc->getProcessPtr();
1557 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1560 int sim_fd = ffdp->getSimFD();
1562 struct statfs hostBuf;
1563 int result = fstatfs(sim_fd, &hostBuf);
1568 copyOutStatfsBuf<OS>(tc->getVirtProxy(), bufPtr, &hostBuf);
1573 /// Target readv() handler.
1576 readvFunc(SyscallDesc *desc, ThreadContext *tc,
1577 int tgt_fd, uint64_t tiov_base, size_t count)
1579 auto p = tc->getProcessPtr();
1581 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1584 int sim_fd = ffdp->getSimFD();
1586 PortProxy &prox = tc->getVirtProxy();
1587 typename OS::tgt_iovec tiov[count];
1588 struct iovec hiov[count];
1589 for (size_t i = 0; i < count; ++i) {
1590 prox.readBlob(tiov_base + (i * sizeof(typename OS::tgt_iovec)),
1591 &tiov[i], sizeof(typename OS::tgt_iovec));
1592 hiov[i].iov_len = gtoh(tiov[i].iov_len, OS::byteOrder);
1593 hiov[i].iov_base = new char [hiov[i].iov_len];
1596 int result = readv(sim_fd, hiov, count);
1597 int local_errno = errno;
1599 for (size_t i = 0; i < count; ++i) {
1601 prox.writeBlob(htog(tiov[i].iov_base, OS::byteOrder),
1602 hiov[i].iov_base, hiov[i].iov_len);
1604 delete [] (char *)hiov[i].iov_base;
1607 return (result == -1) ? -local_errno : result;
1610 /// Target writev() handler.
1613 writevFunc(SyscallDesc *desc, ThreadContext *tc,
1614 int tgt_fd, uint64_t tiov_base, size_t count)
1616 auto p = tc->getProcessPtr();
1618 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1621 int sim_fd = hbfdp->getSimFD();
1623 PortProxy &prox = tc->getVirtProxy();
1624 struct iovec hiov[count];
1625 for (size_t i = 0; i < count; ++i) {
1626 typename OS::tgt_iovec tiov;
1628 prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1629 &tiov, sizeof(typename OS::tgt_iovec));
1630 hiov[i].iov_len = gtoh(tiov.iov_len, OS::byteOrder);
1631 hiov[i].iov_base = new char [hiov[i].iov_len];
1632 prox.readBlob(gtoh(tiov.iov_base, OS::byteOrder), hiov[i].iov_base,
1636 int result = writev(sim_fd, hiov, count);
1638 for (size_t i = 0; i < count; ++i)
1639 delete [] (char *)hiov[i].iov_base;
1641 return (result == -1) ? -errno : result;
1644 /// Target mmap() handler.
1647 mmapFunc(SyscallDesc *desc, ThreadContext *tc,
1648 Addr start, typename OS::size_t length, int prot,
1649 int tgt_flags, int tgt_fd, typename OS::off_t offset)
1651 auto p = tc->getProcessPtr();
1652 Addr page_bytes = tc->getSystemPtr()->getPageBytes();
1654 if (start & (page_bytes - 1) ||
1655 offset & (page_bytes - 1) ||
1656 (tgt_flags & OS::TGT_MAP_PRIVATE &&
1657 tgt_flags & OS::TGT_MAP_SHARED) ||
1658 (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1659 !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1664 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1665 // With shared mmaps, there are two cases to consider:
1666 // 1) anonymous: writes should modify the mapping and this should be
1667 // visible to observers who share the mapping. Currently, it's
1668 // difficult to update the shared mapping because there's no
1669 // structure which maintains information about the which virtual
1670 // memory areas are shared. If that structure existed, it would be
1671 // possible to make the translations point to the same frames.
1672 // 2) file-backed: writes should modify the mapping and the file
1673 // which is backed by the mapping. The shared mapping problem is the
1674 // same as what was mentioned about the anonymous mappings. For
1675 // file-backed mappings, the writes to the file are difficult
1676 // because it requires syncing what the mapping holds with the file
1677 // that resides on the host system. So, any write on a real system
1678 // would cause the change to be propagated to the file mapping at
1679 // some point in the future (the inode is tracked along with the
1680 // mapping). This isn't guaranteed to always happen, but it usually
1681 // works well enough. The guarantee is provided by the msync system
1682 // call. We could force the change through with shared mappings with
1683 // a call to msync, but that again would require more information
1684 // than we currently maintain.
1685 warn_once("mmap: writing to shared mmap region is currently "
1686 "unsupported. The write succeeds on the target, but it "
1687 "will not be propagated to the host or shared mappings");
1690 length = roundUp(length, page_bytes);
1693 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1694 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1696 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1698 EmulatedDriver *emul_driver = dfdp->getDriver();
1699 return emul_driver->mmap(tc, start, length, prot, tgt_flags,
1703 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1706 sim_fd = ffdp->getSimFD();
1709 * Maintain the symbol table for dynamic executables.
1710 * The loader will call mmap to map the images into its address
1711 * space and we intercept that here. We can verify that we are
1712 * executing inside the loader by checking the program counter value.
1713 * XXX: with multiprogrammed workloads or multi-node configurations,
1714 * this will not work since there is a single global symbol table.
1716 if (p->interpImage.contains(tc->pcState().instAddr())) {
1717 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1718 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1719 auto *lib = Loader::createObjectFile(p->checkPathRedirect(
1720 ffdp->getFileName()));
1721 DPRINTF_SYSCALL(Verbose, "Loading symbols from %s\n",
1722 ffdp->getFileName());
1725 Addr offset = lib->buildImage().minAddr() + start;
1726 Loader::debugSymbolTable.insert(*lib->symtab().offset(offset));
1732 * Not TGT_MAP_FIXED means we can start wherever we want.
1734 if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1736 * If the application provides us with a hint, we should make some
1737 * small amount of effort to accomodate it. Basically, we check if
1738 * every single VA within the requested range is unused. If it is,
1739 * we give the application the range. If not, we fall back to
1740 * extending the global mmap region.
1742 if (!(start && p->memState->isUnmapped(start, length))) {
1744 * Extend global mmap region to give us some room for the app.
1746 start = p->memState->extendMmap(length);
1750 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1751 start, start + length - 1);
1754 * We only allow mappings to overwrite existing mappings if
1755 * TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1756 * because we ignore the start hint if TGT_MAP_FIXED is not set.
1758 if (tgt_flags & OS::TGT_MAP_FIXED) {
1760 * We might already have some old VMAs mapped to this region, so
1761 * make sure to clear em out!
1763 p->memState->unmapRegion(start, length);
1767 * Figure out a human-readable name for the mapping.
1769 std::string region_name;
1770 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1771 region_name = "anon";
1773 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1774 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1775 region_name = ffdp->getFileName();
1779 * Setup the correct VMA for this region. The physical pages will be
1782 p->memState->mapRegion(start, length, region_name, sim_fd, offset);
1789 pread64Func(SyscallDesc *desc, ThreadContext *tc,
1790 int tgt_fd, Addr bufPtr, int nbytes, int offset)
1792 auto p = tc->getProcessPtr();
1794 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1797 int sim_fd = ffdp->getSimFD();
1799 BufferArg bufArg(bufPtr, nbytes);
1801 int bytes_read = pread(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1803 bufArg.copyOut(tc->getVirtProxy());
1805 return (bytes_read == -1) ? -errno : bytes_read;
1810 pwrite64Func(SyscallDesc *desc, ThreadContext *tc,
1811 int tgt_fd, Addr bufPtr, int nbytes, int offset)
1813 auto p = tc->getProcessPtr();
1815 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1818 int sim_fd = ffdp->getSimFD();
1820 BufferArg bufArg(bufPtr, nbytes);
1821 bufArg.copyIn(tc->getVirtProxy());
1823 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1825 return (bytes_written == -1) ? -errno : bytes_written;
1828 /// Target mmap2() handler.
1831 mmap2Func(SyscallDesc *desc, ThreadContext *tc,
1832 Addr start, typename OS::size_t length, int prot,
1833 int tgt_flags, int tgt_fd, typename OS::off_t offset)
1835 return mmapFunc<OS>(desc, tc, start, length, prot, tgt_flags,
1836 tgt_fd, offset * tc->getSystemPtr()->getPageBytes());
1839 /// Target getrlimit() handler.
1842 getrlimitFunc(SyscallDesc *desc, ThreadContext *tc,
1843 unsigned resource, Addr rlim)
1845 TypedBufferArg<typename OS::rlimit> rlp(rlim);
1847 const ByteOrder bo = OS::byteOrder;
1849 case OS::TGT_RLIMIT_STACK:
1850 // max stack size in bytes: make up a number (8MB for now)
1851 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1852 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1853 rlp->rlim_max = htog(rlp->rlim_max, bo);
1856 case OS::TGT_RLIMIT_DATA:
1857 // max data segment size in bytes: make up a number
1858 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1859 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1860 rlp->rlim_max = htog(rlp->rlim_max, bo);
1863 case OS::TGT_RLIMIT_NPROC:
1864 rlp->rlim_cur = rlp->rlim_max = tc->getSystemPtr()->numContexts();
1865 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1866 rlp->rlim_max = htog(rlp->rlim_max, bo);
1870 warn("getrlimit: unimplemented resource %d", resource);
1875 rlp.copyOut(tc->getVirtProxy());
1881 prlimitFunc(SyscallDesc *desc, ThreadContext *tc,
1882 int pid, int resource, Addr n, Addr o)
1885 warn("prlimit: ignoring rlimits for nonzero pid");
1889 warn("prlimit: ignoring new rlimit");
1891 const ByteOrder bo = OS::byteOrder;
1892 TypedBufferArg<typename OS::rlimit> rlp(o);
1894 case OS::TGT_RLIMIT_STACK:
1895 // max stack size in bytes: make up a number (8MB for now)
1896 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1897 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1898 rlp->rlim_max = htog(rlp->rlim_max, bo);
1900 case OS::TGT_RLIMIT_DATA:
1901 // max data segment size in bytes: make up a number
1902 rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
1903 rlp->rlim_cur = htog(rlp->rlim_cur, bo);
1904 rlp->rlim_max = htog(rlp->rlim_max, bo);
1907 warn("prlimit: unimplemented resource %d", resource);
1911 rlp.copyOut(tc->getVirtProxy());
1916 /// Target clock_gettime() function.
1919 clock_gettimeFunc(SyscallDesc *desc, ThreadContext *tc,
1920 int clk_id, Addr tp_ptr)
1922 TypedBufferArg<typename OS::timespec> tp(tp_ptr);
1924 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1925 tp->tv_sec += seconds_since_epoch;
1926 tp->tv_sec = htog(tp->tv_sec, OS::byteOrder);
1927 tp->tv_nsec = htog(tp->tv_nsec, OS::byteOrder);
1929 tp.copyOut(tc->getVirtProxy());
1934 /// Target clock_getres() function.
1937 clock_getresFunc(SyscallDesc *desc, ThreadContext *tc, int clk_id, Addr tp_ptr)
1939 TypedBufferArg<typename OS::timespec> tp(tp_ptr);
1941 // Set resolution at ns, which is what clock_gettime() returns
1945 tp.copyOut(tc->getVirtProxy());
1950 /// Target gettimeofday() handler.
1953 gettimeofdayFunc(SyscallDesc *desc, ThreadContext *tc,
1954 Addr tv_ptr, Addr tz_ptr)
1956 TypedBufferArg<typename OS::timeval> tp(tv_ptr);
1958 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1959 tp->tv_sec += seconds_since_epoch;
1960 tp->tv_sec = htog(tp->tv_sec, OS::byteOrder);
1961 tp->tv_usec = htog(tp->tv_usec, OS::byteOrder);
1963 tp.copyOut(tc->getVirtProxy());
1969 /// Target utimes() handler.
1972 utimesFunc(SyscallDesc *desc, ThreadContext *tc, Addr pathname, Addr times)
1975 auto process = tc->getProcessPtr();
1977 if (!tc->getVirtProxy().tryReadString(path, pathname))
1980 TypedBufferArg<typename OS::timeval [2]> tp(times);
1981 tp.copyIn(tc->getVirtProxy());
1983 struct timeval hostTimeval[2];
1984 for (int i = 0; i < 2; ++i) {
1985 hostTimeval[i].tv_sec = gtoh((*tp)[i].tv_sec, OS::byteOrder);
1986 hostTimeval[i].tv_usec = gtoh((*tp)[i].tv_usec, OS::byteOrder);
1989 // Adjust path for cwd and redirection
1990 path = process->checkPathRedirect(path);
1992 int result = utimes(path.c_str(), hostTimeval);
2002 execveFunc(SyscallDesc *desc, ThreadContext *tc,
2003 Addr pathname, Addr argv_mem_loc, Addr envp_mem_loc)
2005 auto p = tc->getProcessPtr();
2008 PortProxy & mem_proxy = tc->getVirtProxy();
2009 if (!mem_proxy.tryReadString(path, pathname))
2012 if (access(path.c_str(), F_OK) == -1)
2015 auto read_in = [](std::vector<std::string> &vect,
2016 PortProxy &mem_proxy, Addr mem_loc)
2018 for (int inc = 0; ; inc++) {
2019 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
2020 b.copyIn(mem_proxy);
2022 if (!*(Addr*)b.bufferPtr())
2025 vect.push_back(std::string());
2026 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
2031 * Note that ProcessParams is generated by swig and there are no other
2032 * examples of how to create anything but this default constructor. The
2033 * fields are manually initialized instead of passing parameters to the
2036 ProcessParams *pp = new ProcessParams();
2037 pp->executable = path;
2038 read_in(pp->cmd, mem_proxy, argv_mem_loc);
2039 read_in(pp->env, mem_proxy, envp_mem_loc);
2041 pp->egid = p->egid();
2042 pp->euid = p->euid();
2044 pp->ppid = p->ppid();
2046 pp->input.assign("cin");
2047 pp->output.assign("cout");
2048 pp->errout.assign("cerr");
2049 pp->cwd.assign(p->tgtCwd);
2050 pp->system = p->system;
2052 * Prevent process object creation with identical PIDs (which will trip
2053 * a fatal check in Process constructor). The execve call is supposed to
2054 * take over the currently executing process' identity but replace
2055 * whatever it is doing with a new process image. Instead of hijacking
2056 * the process object in the simulator, we create a new process object
2057 * and bind to the previous process' thread below (hijacking the thread).
2059 p->system->PIDs.erase(p->pid());
2060 Process *new_p = pp->create();
2064 * Work through the file descriptor array and close any files marked
2067 new_p->fds = p->fds;
2068 for (int i = 0; i < new_p->fds->getSize(); i++) {
2069 std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
2070 if (fdep && fdep->getCOE())
2071 new_p->fds->closeFDEntry(i);
2074 *new_p->sigchld = true;
2077 tc->clearArchRegs();
2078 tc->setProcessPtr(new_p);
2079 new_p->assignThreadContext(tc->contextId());
2082 TheISA::PCState pcState = tc->pcState();
2083 tc->setNPC(pcState.instAddr());
2085 return SyscallReturn();
2088 /// Target getrusage() function.
2091 getrusageFunc(SyscallDesc *desc, ThreadContext *tc,
2092 int who /* THREAD, SELF, or CHILDREN */, Addr usage)
2094 TypedBufferArg<typename OS::rusage> rup(usage);
2096 rup->ru_utime.tv_sec = 0;
2097 rup->ru_utime.tv_usec = 0;
2098 rup->ru_stime.tv_sec = 0;
2099 rup->ru_stime.tv_usec = 0;
2107 rup->ru_inblock = 0;
2108 rup->ru_oublock = 0;
2111 rup->ru_nsignals = 0;
2116 case OS::TGT_RUSAGE_SELF:
2117 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
2118 rup->ru_utime.tv_sec = htog(rup->ru_utime.tv_sec, OS::byteOrder);
2119 rup->ru_utime.tv_usec = htog(rup->ru_utime.tv_usec, OS::byteOrder);
2122 case OS::TGT_RUSAGE_CHILDREN:
2123 // do nothing. We have no child processes, so they take no time.
2127 // don't really handle THREAD or CHILDREN, but just warn and
2129 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
2133 rup.copyOut(tc->getVirtProxy());
2138 /// Target times() function.
2141 timesFunc(SyscallDesc *desc, ThreadContext *tc, Addr bufPtr)
2143 TypedBufferArg<typename OS::tms> bufp(bufPtr);
2145 // Fill in the time structure (in clocks)
2146 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
2147 bufp->tms_utime = clocks;
2148 bufp->tms_stime = 0;
2149 bufp->tms_cutime = 0;
2150 bufp->tms_cstime = 0;
2152 // Convert to host endianness
2153 bufp->tms_utime = htog(bufp->tms_utime, OS::byteOrder);
2156 bufp.copyOut(tc->getVirtProxy());
2158 // Return clock ticks since system boot
2162 /// Target time() function.
2165 timeFunc(SyscallDesc *desc, ThreadContext *tc, Addr taddr)
2167 typename OS::time_t sec, usec;
2168 getElapsedTimeMicro(sec, usec);
2169 sec += seconds_since_epoch;
2172 typename OS::time_t t = sec;
2173 t = htog(t, OS::byteOrder);
2174 PortProxy &p = tc->getVirtProxy();
2175 p.writeBlob(taddr, &t, (int)sizeof(typename OS::time_t));
2182 tgkillFunc(SyscallDesc *desc, ThreadContext *tc, int tgid, int tid, int sig)
2185 * This system call is intended to allow killing a specific thread
2186 * within an arbitrary thread group if sanctioned with permission checks.
2187 * It's usually true that threads share the termination signal as pointed
2188 * out by the pthread_kill man page and this seems to be the intended
2189 * usage. Due to this being an emulated environment, assume the following:
2190 * Threads are allowed to call tgkill because the EUID for all threads
2191 * should be the same. There is no signal handling mechanism for kernel
2192 * registration of signal handlers since signals are poorly supported in
2193 * emulation mode. Since signal handlers cannot be registered, all
2194 * threads within in a thread group must share the termination signal.
2195 * We never exhaust PIDs so there's no chance of finding the wrong one
2196 * due to PID rollover.
2199 System *sys = tc->getSystemPtr();
2200 Process *tgt_proc = nullptr;
2201 for (int i = 0; i < sys->numContexts(); i++) {
2202 Process *temp = sys->threadContexts[i]->getProcessPtr();
2203 if (temp->pid() == tid) {
2209 if (sig != 0 || sig != OS::TGT_SIGABRT)
2212 if (tgt_proc == nullptr)
2215 if (tgid != -1 && tgt_proc->tgid() != tgid)
2218 if (sig == OS::TGT_SIGABRT)
2219 exitGroupFunc(desc, tc, 0);
2226 socketFunc(SyscallDesc *desc, ThreadContext *tc,
2227 int domain, int type, int prot)
2229 auto p = tc->getProcessPtr();
2231 int sim_fd = socket(domain, type, prot);
2235 auto sfdp = std::make_shared<SocketFDEntry>(sim_fd, domain, type, prot);
2236 int tgt_fd = p->fds->allocFD(sfdp);
2243 socketpairFunc(SyscallDesc *desc, ThreadContext *tc,
2244 int domain, int type, int prot, Addr svPtr)
2246 auto p = tc->getProcessPtr();
2248 BufferArg svBuf((Addr)svPtr, 2 * sizeof(int));
2249 int status = socketpair(domain, type, prot, (int *)svBuf.bufferPtr());
2253 int *fds = (int *)svBuf.bufferPtr();
2255 auto sfdp1 = std::make_shared<SocketFDEntry>(fds[0], domain, type, prot);
2256 fds[0] = p->fds->allocFD(sfdp1);
2257 auto sfdp2 = std::make_shared<SocketFDEntry>(fds[1], domain, type, prot);
2258 fds[1] = p->fds->allocFD(sfdp2);
2259 svBuf.copyOut(tc->getVirtProxy());
2266 selectFunc(SyscallDesc *desc, ThreadContext *tc,
2267 int nfds_t, Addr fds_read_ptr, Addr fds_writ_ptr,
2268 Addr fds_excp_ptr, Addr time_val_ptr)
2272 auto p = tc->getProcessPtr();
2274 TypedBufferArg<typename OS::fd_set> rd_t(fds_read_ptr);
2275 TypedBufferArg<typename OS::fd_set> wr_t(fds_writ_ptr);
2276 TypedBufferArg<typename OS::fd_set> ex_t(fds_excp_ptr);
2277 TypedBufferArg<typename OS::timeval> tp(time_val_ptr);
2280 * Host fields. Notice that these use the definitions from the system
2281 * headers instead of the gem5 headers and libraries. If the host and
2282 * target have different header file definitions, this will not work.
2292 * Copy in the fd_set from the target.
2295 rd_t.copyIn(tc->getVirtProxy());
2297 wr_t.copyIn(tc->getVirtProxy());
2299 ex_t.copyIn(tc->getVirtProxy());
2302 * We need to translate the target file descriptor set into a host file
2303 * descriptor set. This involves both our internal process fd array
2304 * and the fd_set defined in Linux header files. The nfds field also
2305 * needs to be updated as it will be only target specific after
2306 * retrieving it from the target; the nfds value is expected to be the
2307 * highest file descriptor that needs to be checked, so we need to extend
2308 * it out for nfds_h when we do the update.
2311 std::map<int, int> trans_map;
2312 auto try_add_host_set = [&](fd_set *tgt_set_entry,
2313 fd_set *hst_set_entry,
2317 * By this point, we know that we are looking at a valid file
2318 * descriptor set on the target. We need to check if the target file
2319 * descriptor value passed in as iter is part of the set.
2321 if (FD_ISSET(iter, tgt_set_entry)) {
2323 * We know that the target file descriptor belongs to the set,
2324 * but we do not yet know if the file descriptor is valid or
2325 * that we have a host mapping. Check that now.
2327 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[iter]);
2330 auto sim_fd = hbfdp->getSimFD();
2333 * Add the sim_fd to tgt_fd translation into trans_map for use
2334 * later when we need to zero the target fd_set structures and
2335 * then update them with hits returned from the host select call.
2337 trans_map[sim_fd] = iter;
2340 * We know that the host file descriptor exists so now we check
2341 * if we need to update the max count for nfds_h before passing
2342 * the duplicated structure into the host.
2344 nfds_h = std::max(nfds_h - 1, sim_fd + 1);
2347 * Add the host file descriptor to the set that we are going to
2348 * pass into the host.
2350 FD_SET(sim_fd, hst_set_entry);
2355 for (int i = 0; i < nfds_t; i++) {
2357 bool ebadf = try_add_host_set((fd_set*)&*rd_t, &rd_h, i);
2358 if (ebadf) return -EBADF;
2361 bool ebadf = try_add_host_set((fd_set*)&*wr_t, &wr_h, i);
2362 if (ebadf) return -EBADF;
2365 bool ebadf = try_add_host_set((fd_set*)&*ex_t, &ex_h, i);
2366 if (ebadf) return -EBADF;
2372 * It might be possible to decrement the timeval based on some
2373 * derivation of wall clock determined from elapsed simulator ticks
2374 * but that seems like overkill. Rather, we just set the timeval with
2375 * zero timeout. (There is no reason to block during the simulation
2376 * as it only decreases simulator performance.)
2381 retval = select(nfds_h,
2382 fds_read_ptr ? &rd_h : nullptr,
2383 fds_writ_ptr ? &wr_h : nullptr,
2384 fds_excp_ptr ? &ex_h : nullptr,
2388 * If the timeval pointer is null, setup a new timeval structure to
2389 * pass into the host select call. Unfortunately, we will need to
2390 * manually check the return value and throw a retry fault if the
2391 * return value is zero. Allowing the system call to block will
2392 * likely deadlock the event queue.
2394 struct timeval tv = { 0, 0 };
2396 retval = select(nfds_h,
2397 fds_read_ptr ? &rd_h : nullptr,
2398 fds_writ_ptr ? &wr_h : nullptr,
2399 fds_excp_ptr ? &ex_h : nullptr,
2404 * If blocking indefinitely, check the signal list to see if a
2405 * signal would break the poll out of the retry cycle and try to
2406 * return the signal interrupt instead.
2408 for (auto sig : tc->getSystemPtr()->signalList)
2409 if (sig.receiver == p)
2411 return SyscallReturn::retry();
2418 FD_ZERO((fd_set*)&*rd_t);
2419 FD_ZERO((fd_set*)&*wr_t);
2420 FD_ZERO((fd_set*)&*ex_t);
2423 * We need to translate the host file descriptor set into a target file
2424 * descriptor set. This involves both our internal process fd array
2425 * and the fd_set defined in header files.
2427 for (int i = 0; i < nfds_h; i++) {
2429 if (FD_ISSET(i, &rd_h))
2430 FD_SET(trans_map[i], (fd_set*)&*rd_t);
2434 if (FD_ISSET(i, &wr_h))
2435 FD_SET(trans_map[i], (fd_set*)&*wr_t);
2439 if (FD_ISSET(i, &ex_h))
2440 FD_SET(trans_map[i], (fd_set*)&*ex_t);
2445 rd_t.copyOut(tc->getVirtProxy());
2447 wr_t.copyOut(tc->getVirtProxy());
2449 ex_t.copyOut(tc->getVirtProxy());
2451 tp.copyOut(tc->getVirtProxy());
2458 readFunc(SyscallDesc *desc, ThreadContext *tc,
2459 int tgt_fd, Addr buf_ptr, int nbytes)
2461 auto p = tc->getProcessPtr();
2463 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2466 int sim_fd = hbfdp->getSimFD();
2470 pfd.events = POLLIN | POLLPRI;
2471 if ((poll(&pfd, 1, 0) == 0)
2472 && !(hbfdp->getFlags() & OS::TGT_O_NONBLOCK))
2473 return SyscallReturn::retry();
2475 BufferArg buf_arg(buf_ptr, nbytes);
2476 int bytes_read = read(sim_fd, buf_arg.bufferPtr(), nbytes);
2479 buf_arg.copyOut(tc->getVirtProxy());
2481 return (bytes_read == -1) ? -errno : bytes_read;
2486 writeFunc(SyscallDesc *desc, ThreadContext *tc,
2487 int tgt_fd, Addr buf_ptr, int nbytes)
2489 auto p = tc->getProcessPtr();
2491 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2494 int sim_fd = hbfdp->getSimFD();
2496 BufferArg buf_arg(buf_ptr, nbytes);
2497 buf_arg.copyIn(tc->getVirtProxy());
2501 pfd.events = POLLOUT;
2504 * We don't want to poll on /dev/random. The kernel will not enable the
2505 * file descriptor for writing unless the entropy in the system falls
2506 * below write_wakeup_threshold. This is not guaranteed to happen
2507 * depending on host settings.
2509 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(hbfdp);
2510 if (ffdp && (ffdp->getFileName() != "/dev/random")) {
2511 if (!poll(&pfd, 1, 0) && !(ffdp->getFlags() & OS::TGT_O_NONBLOCK))
2512 return SyscallReturn::retry();
2515 int bytes_written = write(sim_fd, buf_arg.bufferPtr(), nbytes);
2517 if (bytes_written != -1)
2520 return (bytes_written == -1) ? -errno : bytes_written;
2525 wait4Func(SyscallDesc *desc, ThreadContext *tc,
2526 pid_t pid, Addr statPtr, int options, Addr rusagePtr)
2528 auto p = tc->getProcessPtr();
2531 DPRINTF_SYSCALL(Verbose, "wait4: rusage pointer provided %lx, however "
2532 "functionality not supported. Ignoring rusage pointer.\n",
2536 * Currently, wait4 is only implemented so that it will wait for children
2537 * exit conditions which are denoted by a SIGCHLD signals posted into the
2538 * system signal list. We return no additional information via any of the
2539 * parameters supplied to wait4. If nothing is found in the system signal
2540 * list, we will wait indefinitely for SIGCHLD to post by retrying the
2543 System *sysh = tc->getSystemPtr();
2544 std::list<BasicSignal>::iterator iter;
2545 for (iter=sysh->signalList.begin(); iter!=sysh->signalList.end(); iter++) {
2546 if (iter->receiver == p) {
2548 if ((iter->sender->pgid() == -pid)
2549 && (iter->signalValue == OS::TGT_SIGCHLD))
2551 } else if (pid == -1) {
2552 if (iter->signalValue == OS::TGT_SIGCHLD)
2554 } else if (pid == 0) {
2555 if ((iter->sender->pgid() == p->pgid())
2556 && (iter->signalValue == OS::TGT_SIGCHLD))
2559 if ((iter->sender->pid() == pid)
2560 && (iter->signalValue == OS::TGT_SIGCHLD))
2566 return (options & OS::TGT_WNOHANG) ? 0 : SyscallReturn::retry();
2569 // Set status to EXITED for WIFEXITED evaluations.
2570 const int EXITED = 0;
2571 BufferArg statusBuf(statPtr, sizeof(int));
2572 *(int *)statusBuf.bufferPtr() = EXITED;
2573 statusBuf.copyOut(tc->getVirtProxy());
2575 // Return the child PID.
2576 pid_t retval = iter->sender->pid();
2577 sysh->signalList.erase(iter);
2583 acceptFunc(SyscallDesc *desc, ThreadContext *tc,
2584 int tgt_fd, Addr addrPtr, Addr lenPtr)
2589 auto p = tc->getProcessPtr();
2591 BufferArg *lenBufPtr = nullptr;
2592 BufferArg *addrBufPtr = nullptr;
2594 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
2597 int sim_fd = sfdp->getSimFD();
2600 * We poll the socket file descriptor first to guarantee that we do not
2601 * block on our accept call. The socket can be opened without the
2602 * non-blocking flag (it blocks). This will cause deadlocks between
2603 * communicating processes.
2607 pfd.events = POLLIN | POLLPRI;
2608 if ((poll(&pfd, 1, 0) == 0) && !(sfdp->getFlags() & OS::TGT_O_NONBLOCK))
2609 return SyscallReturn::retry();
2612 lenBufPtr = new BufferArg(lenPtr, sizeof(socklen_t));
2613 lenBufPtr->copyIn(tc->getVirtProxy());
2614 memcpy(&addrLen, (socklen_t *)lenBufPtr->bufferPtr(),
2619 addrBufPtr = new BufferArg(addrPtr, sizeof(struct sockaddr));
2620 addrBufPtr->copyIn(tc->getVirtProxy());
2621 memcpy(&sa, (struct sockaddr *)addrBufPtr->bufferPtr(),
2622 sizeof(struct sockaddr));
2625 host_fd = accept(sim_fd, &sa, &addrLen);
2631 memcpy(addrBufPtr->bufferPtr(), &sa, sizeof(sa));
2632 addrBufPtr->copyOut(tc->getVirtProxy());
2637 *(socklen_t *)lenBufPtr->bufferPtr() = addrLen;
2638 lenBufPtr->copyOut(tc->getVirtProxy());
2642 auto afdp = std::make_shared<SocketFDEntry>(host_fd, sfdp->_domain,
2643 sfdp->_type, sfdp->_protocol);
2644 return p->fds->allocFD(afdp);
2647 /// Target eventfd() function.
2650 eventfdFunc(SyscallDesc *desc, ThreadContext *tc,
2651 unsigned initval, int in_flags)
2653 #if defined(__linux__)
2654 auto p = tc->getProcessPtr();
2656 int sim_fd = eventfd(initval, in_flags);
2660 bool cloexec = in_flags & OS::TGT_O_CLOEXEC;
2662 int flags = cloexec ? OS::TGT_O_CLOEXEC : 0;
2663 flags |= (in_flags & OS::TGT_O_NONBLOCK) ? OS::TGT_O_NONBLOCK : 0;
2665 auto hbfdp = std::make_shared<HBFDEntry>(flags, sim_fd, cloexec);
2666 int tgt_fd = p->fds->allocFD(hbfdp);
2669 warnUnsupportedOS("eventfd");
2674 #endif // __SIM_SYSCALL_EMUL_HH__