2 * Copyright (c) 2012-2013, 2015 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.
41 * Authors: Steve Reinhardt
45 #ifndef __SIM_SYSCALL_EMUL_HH__
46 #define __SIM_SYSCALL_EMUL_HH__
48 #define NO_STAT64 (defined(__APPLE__) || defined(__OpenBSD__) || \
49 defined(__FreeBSD__) || defined(__CYGWIN__) || \
53 /// @file syscall_emul.hh
55 /// This file defines objects used to emulate syscalls from the target
56 /// application on the host machine.
59 #include <sys/fcntl.h> // for O_BINARY
70 #include "base/chunk_generator.hh"
71 #include "base/intmath.hh" // for RoundUp
72 #include "base/misc.hh"
73 #include "base/trace.hh"
74 #include "base/types.hh"
75 #include "config/the_isa.hh"
76 #include "cpu/base.hh"
77 #include "cpu/thread_context.hh"
78 #include "debug/SyscallBase.hh"
79 #include "debug/SyscallVerbose.hh"
80 #include "mem/page_table.hh"
81 #include "sim/byteswap.hh"
82 #include "sim/emul_driver.hh"
83 #include "sim/process.hh"
84 #include "sim/syscall_emul_buf.hh"
85 #include "sim/syscallreturn.hh"
86 #include "sim/system.hh"
88 // This wrapper macro helps out with readability a bit. FLAGEXT specifies
89 // the verbosity and FMT is the message to be appended to the syscall
90 // header information. The syscall header information contains the cpuid
92 #define DPRINTF_SYSCALL(FLAGEXT, FMT, ...) \
93 DPRINTFS(Syscall##FLAGEXT, tc->getCpuPtr(), "T%d : syscall " FMT, \
94 tc->threadId(), __VA_ARGS__)
97 /// System call descriptor.
103 /// Typedef for target syscall handler functions.
104 typedef SyscallReturn (*FuncPtr)(SyscallDesc *, int num,
105 LiveProcess *, ThreadContext *);
107 const char *name; //!< Syscall name (e.g., "open").
108 FuncPtr funcPtr; //!< Pointer to emulation function.
109 int flags; //!< Flags (see Flags enum).
110 bool warned; //!< Have we warned about unimplemented syscall?
112 /// Flag values for controlling syscall behavior.
114 /// Don't set return regs according to funcPtr return value.
115 /// Used for syscalls with non-standard return conventions
116 /// that explicitly set the ThreadContext regs (e.g.,
118 SuppressReturnValue = 1,
123 SyscallDesc(const char *_name, FuncPtr _funcPtr, int _flags = 0)
124 : name(_name), funcPtr(_funcPtr), flags(_flags), warned(false)
128 /// Emulate the syscall. Public interface for calling through funcPtr.
129 void doSyscall(int callnum, LiveProcess *proc, ThreadContext *tc);
131 /// Is the WarnOnce flag set?
132 bool warnOnce() const { return (flags & WarnOnce); }
136 //////////////////////////////////////////////////////////////////////
138 // The following emulation functions are generic enough that they
139 // don't need to be recompiled for different emulated OS's. They are
140 // defined in sim/syscall_emul.cc.
142 //////////////////////////////////////////////////////////////////////
145 /// Handler for unimplemented syscalls that we haven't thought about.
146 SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
147 LiveProcess *p, ThreadContext *tc);
149 /// Handler for unimplemented syscalls that we never intend to
150 /// implement (signal handling, etc.) and should not affect the correct
151 /// behavior of the program. Print a warning only if the appropriate
152 /// trace flag is enabled. Return success to the target program.
153 SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
154 LiveProcess *p, ThreadContext *tc);
156 /// Target exit() handler: terminate current context.
157 SyscallReturn exitFunc(SyscallDesc *desc, int num,
158 LiveProcess *p, ThreadContext *tc);
160 /// Target exit_group() handler: terminate simulation. (exit all threads)
161 SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
162 LiveProcess *p, ThreadContext *tc);
164 /// Target getpagesize() handler.
165 SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
166 LiveProcess *p, ThreadContext *tc);
168 /// Target brk() handler: set brk address.
169 SyscallReturn brkFunc(SyscallDesc *desc, int num,
170 LiveProcess *p, ThreadContext *tc);
172 /// Target close() handler.
173 SyscallReturn closeFunc(SyscallDesc *desc, int num,
174 LiveProcess *p, ThreadContext *tc);
176 /// Target read() handler.
177 SyscallReturn readFunc(SyscallDesc *desc, int num,
178 LiveProcess *p, ThreadContext *tc);
180 /// Target write() handler.
181 SyscallReturn writeFunc(SyscallDesc *desc, int num,
182 LiveProcess *p, ThreadContext *tc);
184 /// Target lseek() handler.
185 SyscallReturn lseekFunc(SyscallDesc *desc, int num,
186 LiveProcess *p, ThreadContext *tc);
188 /// Target _llseek() handler.
189 SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
190 LiveProcess *p, ThreadContext *tc);
192 /// Target munmap() handler.
193 SyscallReturn munmapFunc(SyscallDesc *desc, int num,
194 LiveProcess *p, ThreadContext *tc);
196 /// Target gethostname() handler.
197 SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
198 LiveProcess *p, ThreadContext *tc);
200 /// Target getcwd() handler.
201 SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
202 LiveProcess *p, ThreadContext *tc);
204 /// Target readlink() handler.
205 SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
206 LiveProcess *p, ThreadContext *tc,
208 SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
209 LiveProcess *p, ThreadContext *tc);
211 /// Target unlink() handler.
212 SyscallReturn unlinkHelper(SyscallDesc *desc, int num,
213 LiveProcess *p, ThreadContext *tc,
215 SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
216 LiveProcess *p, ThreadContext *tc);
218 /// Target mkdir() handler.
219 SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
220 LiveProcess *p, ThreadContext *tc);
222 /// Target rename() handler.
223 SyscallReturn renameFunc(SyscallDesc *desc, int num,
224 LiveProcess *p, ThreadContext *tc);
227 /// Target truncate() handler.
228 SyscallReturn truncateFunc(SyscallDesc *desc, int num,
229 LiveProcess *p, ThreadContext *tc);
232 /// Target ftruncate() handler.
233 SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
234 LiveProcess *p, ThreadContext *tc);
237 /// Target truncate64() handler.
238 SyscallReturn truncate64Func(SyscallDesc *desc, int num,
239 LiveProcess *p, ThreadContext *tc);
241 /// Target ftruncate64() handler.
242 SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
243 LiveProcess *p, ThreadContext *tc);
246 /// Target umask() handler.
247 SyscallReturn umaskFunc(SyscallDesc *desc, int num,
248 LiveProcess *p, ThreadContext *tc);
251 /// Target chown() handler.
252 SyscallReturn chownFunc(SyscallDesc *desc, int num,
253 LiveProcess *p, ThreadContext *tc);
256 /// Target fchown() handler.
257 SyscallReturn fchownFunc(SyscallDesc *desc, int num,
258 LiveProcess *p, ThreadContext *tc);
260 /// Target dup() handler.
261 SyscallReturn dupFunc(SyscallDesc *desc, int num,
262 LiveProcess *process, ThreadContext *tc);
264 /// Target fnctl() handler.
265 SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
266 LiveProcess *process, ThreadContext *tc);
268 /// Target fcntl64() handler.
269 SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
270 LiveProcess *process, ThreadContext *tc);
272 /// Target setuid() handler.
273 SyscallReturn setuidFunc(SyscallDesc *desc, int num,
274 LiveProcess *p, ThreadContext *tc);
276 /// Target getpid() handler.
277 SyscallReturn getpidFunc(SyscallDesc *desc, int num,
278 LiveProcess *p, ThreadContext *tc);
280 /// Target getuid() handler.
281 SyscallReturn getuidFunc(SyscallDesc *desc, int num,
282 LiveProcess *p, ThreadContext *tc);
284 /// Target getgid() handler.
285 SyscallReturn getgidFunc(SyscallDesc *desc, int num,
286 LiveProcess *p, ThreadContext *tc);
288 /// Target getppid() handler.
289 SyscallReturn getppidFunc(SyscallDesc *desc, int num,
290 LiveProcess *p, ThreadContext *tc);
292 /// Target geteuid() handler.
293 SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
294 LiveProcess *p, ThreadContext *tc);
296 /// Target getegid() handler.
297 SyscallReturn getegidFunc(SyscallDesc *desc, int num,
298 LiveProcess *p, ThreadContext *tc);
300 /// Target clone() handler.
301 SyscallReturn cloneFunc(SyscallDesc *desc, int num,
302 LiveProcess *p, ThreadContext *tc);
304 /// Target access() handler
305 SyscallReturn accessFunc(SyscallDesc *desc, int num,
306 LiveProcess *p, ThreadContext *tc);
307 SyscallReturn accessFunc(SyscallDesc *desc, int num,
308 LiveProcess *p, ThreadContext *tc,
311 /// Futex system call
312 /// Implemented by Daniel Sanchez
313 /// Used by printf's in multi-threaded apps
316 futexFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
322 int index_timeout = 3;
324 uint64_t uaddr = process->getSyscallArg(tc, index_uaddr);
325 int op = process->getSyscallArg(tc, index_op);
326 int val = process->getSyscallArg(tc, index_val);
327 uint64_t timeout = process->getSyscallArg(tc, index_timeout);
329 std::map<uint64_t, std::list<ThreadContext *> * >
330 &futex_map = tc->getSystemPtr()->futexMap;
332 DPRINTF(SyscallVerbose, "In sys_futex: Address=%llx, op=%d, val=%d\n",
335 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
337 if (op == OS::TGT_FUTEX_WAIT) {
339 warn("sys_futex: FUTEX_WAIT with non-null timeout unimplemented;"
340 "we'll wait indefinitely");
343 uint8_t *buf = new uint8_t[sizeof(int)];
344 tc->getMemProxy().readBlob((Addr)uaddr, buf, (int)sizeof(int));
345 int mem_val = *((int *)buf);
348 if (val != mem_val) {
349 DPRINTF(SyscallVerbose, "sys_futex: FUTEX_WAKE, read: %d, "
350 "expected: %d\n", mem_val, val);
351 return -OS::TGT_EWOULDBLOCK;
354 // Queue the thread context
355 std::list<ThreadContext *> * tcWaitList;
356 if (futex_map.count(uaddr)) {
357 tcWaitList = futex_map.find(uaddr)->second;
359 tcWaitList = new std::list<ThreadContext *>();
360 futex_map.insert(std::pair< uint64_t,
361 std::list<ThreadContext *> * >(uaddr, tcWaitList));
363 tcWaitList->push_back(tc);
364 DPRINTF(SyscallVerbose, "sys_futex: FUTEX_WAIT, suspending calling "
368 } else if (op == OS::TGT_FUTEX_WAKE){
370 std::list<ThreadContext *> * tcWaitList;
371 if (futex_map.count(uaddr)) {
372 tcWaitList = futex_map.find(uaddr)->second;
373 while (tcWaitList->size() > 0 && wokenUp < val) {
374 tcWaitList->front()->activate();
375 tcWaitList->pop_front();
378 if (tcWaitList->empty()) {
379 futex_map.erase(uaddr);
383 DPRINTF(SyscallVerbose, "sys_futex: FUTEX_WAKE, activated %d waiting "
384 "thread contexts\n", wokenUp);
387 warn("sys_futex: op %d is not implemented, just returning...", op);
394 /// Pseudo Funcs - These functions use a different return convension,
395 /// returning a second value in a register other than the normal return register
396 SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
397 LiveProcess *process, ThreadContext *tc);
399 /// Target getpidPseudo() handler.
400 SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
401 LiveProcess *p, ThreadContext *tc);
403 /// Target getuidPseudo() handler.
404 SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
405 LiveProcess *p, ThreadContext *tc);
407 /// Target getgidPseudo() handler.
408 SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
409 LiveProcess *p, ThreadContext *tc);
412 /// A readable name for 1,000,000, for converting microseconds to seconds.
413 const int one_million = 1000000;
414 /// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
415 const int one_billion = 1000000000;
417 /// Approximate seconds since the epoch (1/1/1970). About a billion,
418 /// by my reckoning. We want to keep this a constant (not use the
419 /// real-world time) to keep simulations repeatable.
420 const unsigned seconds_since_epoch = 1000000000;
422 /// Helper function to convert current elapsed time to seconds and
424 template <class T1, class T2>
426 getElapsedTimeMicro(T1 &sec, T2 &usec)
428 uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
429 sec = elapsed_usecs / one_million;
430 usec = elapsed_usecs % one_million;
433 /// Helper function to convert current elapsed time to seconds and
435 template <class T1, class T2>
437 getElapsedTimeNano(T1 &sec, T2 &nsec)
439 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
440 sec = elapsed_nsecs / one_billion;
441 nsec = elapsed_nsecs % one_billion;
444 //////////////////////////////////////////////////////////////////////
446 // The following emulation functions are generic, but need to be
447 // templated to account for differences in types, constants, etc.
449 //////////////////////////////////////////////////////////////////////
452 typedef struct stat hst_stat;
453 typedef struct stat hst_stat64;
455 typedef struct stat hst_stat;
456 typedef struct stat64 hst_stat64;
459 //// Helper function to convert a host stat buffer to a target stat
460 //// buffer. Also copies the target buffer out to the simulated
461 //// memory space. Used by stat(), fstat(), and lstat().
463 template <typename target_stat, typename host_stat>
465 convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
467 using namespace TheISA;
472 tgt->st_dev = host->st_dev;
473 tgt->st_dev = TheISA::htog(tgt->st_dev);
474 tgt->st_ino = host->st_ino;
475 tgt->st_ino = TheISA::htog(tgt->st_ino);
476 tgt->st_mode = host->st_mode;
478 // Claim to be a character device
479 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT
480 tgt->st_mode |= S_IFCHR; // Set S_IFCHR
482 tgt->st_mode = TheISA::htog(tgt->st_mode);
483 tgt->st_nlink = host->st_nlink;
484 tgt->st_nlink = TheISA::htog(tgt->st_nlink);
485 tgt->st_uid = host->st_uid;
486 tgt->st_uid = TheISA::htog(tgt->st_uid);
487 tgt->st_gid = host->st_gid;
488 tgt->st_gid = TheISA::htog(tgt->st_gid);
490 tgt->st_rdev = 0x880d;
492 tgt->st_rdev = host->st_rdev;
493 tgt->st_rdev = TheISA::htog(tgt->st_rdev);
494 tgt->st_size = host->st_size;
495 tgt->st_size = TheISA::htog(tgt->st_size);
496 tgt->st_atimeX = host->st_atime;
497 tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
498 tgt->st_mtimeX = host->st_mtime;
499 tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
500 tgt->st_ctimeX = host->st_ctime;
501 tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
502 // Force the block size to be 8k. This helps to ensure buffered io works
503 // consistently across different hosts.
504 tgt->st_blksize = 0x2000;
505 tgt->st_blksize = TheISA::htog(tgt->st_blksize);
506 tgt->st_blocks = host->st_blocks;
507 tgt->st_blocks = TheISA::htog(tgt->st_blocks);
512 template <typename target_stat, typename host_stat64>
514 convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
516 using namespace TheISA;
518 convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
519 #if defined(STAT_HAVE_NSEC)
520 tgt->st_atime_nsec = host->st_atime_nsec;
521 tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
522 tgt->st_mtime_nsec = host->st_mtime_nsec;
523 tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
524 tgt->st_ctime_nsec = host->st_ctime_nsec;
525 tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
527 tgt->st_atime_nsec = 0;
528 tgt->st_mtime_nsec = 0;
529 tgt->st_ctime_nsec = 0;
533 //Here are a couple convenience functions
536 copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
537 hst_stat *host, bool fakeTTY = false)
539 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
540 tgt_stat_buf tgt(addr);
541 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
547 copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
548 hst_stat64 *host, bool fakeTTY = false)
550 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
551 tgt_stat_buf tgt(addr);
552 convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
556 /// Target ioctl() handler. For the most part, programs call ioctl()
557 /// only to find out if their stdout is a tty, to determine whether to
558 /// do line or block buffering. We always claim that output fds are
559 /// not TTYs to provide repeatable results.
562 ioctlFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
566 int tgt_fd = process->getSyscallArg(tc, index);
567 unsigned req = process->getSyscallArg(tc, index);
569 DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
571 FDEntry *fde = process->getFDEntry(tgt_fd);
574 // doesn't map to any simulator fd: not a valid target fd
578 if (fde->driver != NULL) {
579 return fde->driver->ioctl(process, tc, req);
582 if (OS::isTtyReq(req)) {
586 warn("Unsupported ioctl call: ioctl(%d, 0x%x, ...) @ \n",
587 tgt_fd, req, tc->pcState());
593 openFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
594 ThreadContext *tc, int index)
598 if (!tc->getMemProxy().tryReadString(path,
599 process->getSyscallArg(tc, index)))
602 int tgtFlags = process->getSyscallArg(tc, index);
603 int mode = process->getSyscallArg(tc, index);
606 // translate open flags
607 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
608 if (tgtFlags & OS::openFlagTable[i].tgtFlag) {
609 tgtFlags &= ~OS::openFlagTable[i].tgtFlag;
610 hostFlags |= OS::openFlagTable[i].hostFlag;
614 // any target flags left?
616 warn("Syscall: open: cannot decode flags 0x%x", tgtFlags);
619 hostFlags |= O_BINARY;
622 // Adjust path for current working directory
623 path = process->fullPath(path);
625 DPRINTF(SyscallVerbose, "opening file %s\n", path.c_str());
627 if (startswith(path, "/dev/")) {
628 std::string filename = path.substr(strlen("/dev/"));
629 if (filename == "sysdev0") {
630 // This is a memory-mapped high-resolution timer device on Alpha.
631 // We don't support it, so just punt.
632 warn("Ignoring open(%s, ...)\n", path);
636 EmulatedDriver *drv = process->findDriver(filename);
638 // the driver's open method will allocate a fd from the
639 // process if necessary.
640 return drv->open(process, tc, mode, hostFlags);
643 // fall through here for pass through to host devices, such as
649 if (startswith(path, "/proc/") || startswith(path, "/system/") ||
650 startswith(path, "/platform/") || startswith(path, "/sys/")) {
651 // It's a proc/sys entry and requires special handling
652 fd = OS::openSpecialFile(path, process, tc);
653 local_errno = ENOENT;
656 fd = open(path.c_str(), hostFlags, mode);
663 return process->allocFD(fd, path.c_str(), hostFlags, mode, false);
666 /// Target open() handler.
669 openFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
672 return openFunc<OS>(desc, callnum, process, tc, 0);
675 /// Target openat() handler.
678 openatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
682 int dirfd = process->getSyscallArg(tc, index);
683 if (dirfd != OS::TGT_AT_FDCWD)
684 warn("openat: first argument not AT_FDCWD; unlikely to work");
685 return openFunc<OS>(desc, callnum, process, tc, 1);
688 /// Target unlinkat() handler.
691 unlinkatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
695 int dirfd = process->getSyscallArg(tc, index);
696 if (dirfd != OS::TGT_AT_FDCWD)
697 warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
699 return unlinkHelper(desc, callnum, process, tc, 1);
702 /// Target facessat() handler
705 faccessatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
709 int dirfd = process->getSyscallArg(tc, index);
710 if (dirfd != OS::TGT_AT_FDCWD)
711 warn("faccessat: first argument not AT_FDCWD; unlikely to work");
712 return accessFunc(desc, callnum, process, tc, 1);
715 /// Target readlinkat() handler
718 readlinkatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
722 int dirfd = process->getSyscallArg(tc, index);
723 if (dirfd != OS::TGT_AT_FDCWD)
724 warn("openat: first argument not AT_FDCWD; unlikely to work");
725 return readlinkFunc(desc, callnum, process, tc, 1);
728 /// Target renameat() handler.
731 renameatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
736 int olddirfd = process->getSyscallArg(tc, index);
737 if (olddirfd != OS::TGT_AT_FDCWD)
738 warn("renameat: first argument not AT_FDCWD; unlikely to work");
740 std::string old_name;
742 if (!tc->getMemProxy().tryReadString(old_name,
743 process->getSyscallArg(tc, index)))
746 int newdirfd = process->getSyscallArg(tc, index);
747 if (newdirfd != OS::TGT_AT_FDCWD)
748 warn("renameat: third argument not AT_FDCWD; unlikely to work");
750 std::string new_name;
752 if (!tc->getMemProxy().tryReadString(new_name,
753 process->getSyscallArg(tc, index)))
756 // Adjust path for current working directory
757 old_name = process->fullPath(old_name);
758 new_name = process->fullPath(new_name);
760 int result = rename(old_name.c_str(), new_name.c_str());
761 return (result == -1) ? -errno : result;
764 /// Target sysinfo() handler.
767 sysinfoFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
772 TypedBufferArg<typename OS::tgt_sysinfo>
773 sysinfo(process->getSyscallArg(tc, index));
775 sysinfo->uptime=seconds_since_epoch;
776 sysinfo->totalram=process->system->memSize();
778 sysinfo.copyOut(tc->getMemProxy());
783 /// Target chmod() handler.
786 chmodFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
792 if (!tc->getMemProxy().tryReadString(path,
793 process->getSyscallArg(tc, index))) {
797 uint32_t mode = process->getSyscallArg(tc, index);
800 // XXX translate mode flags via OS::something???
803 // Adjust path for current working directory
804 path = process->fullPath(path);
807 int result = chmod(path.c_str(), hostMode);
815 /// Target fchmod() handler.
818 fchmodFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
822 int tgt_fd = process->getSyscallArg(tc, index);
823 uint32_t mode = process->getSyscallArg(tc, index);
825 int sim_fd = process->getSimFD(tgt_fd);
831 // XXX translate mode flags via OS::someting???
835 int result = fchmod(sim_fd, hostMode);
842 /// Target mremap() handler.
845 mremapFunc(SyscallDesc *desc, int callnum, LiveProcess *process, ThreadContext *tc)
848 Addr start = process->getSyscallArg(tc, index);
849 uint64_t old_length = process->getSyscallArg(tc, index);
850 uint64_t new_length = process->getSyscallArg(tc, index);
851 uint64_t flags = process->getSyscallArg(tc, index);
852 uint64_t provided_address = 0;
853 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
855 if (use_provided_address)
856 provided_address = process->getSyscallArg(tc, index);
858 if ((start % TheISA::PageBytes != 0) ||
859 (provided_address % TheISA::PageBytes != 0)) {
860 warn("mremap failing: arguments not page aligned");
864 new_length = roundUp(new_length, TheISA::PageBytes);
866 if (new_length > old_length) {
867 if ((start + old_length) == process->mmap_end &&
868 (!use_provided_address || provided_address == start)) {
869 uint64_t diff = new_length - old_length;
870 process->allocateMem(process->mmap_end, diff);
871 process->mmap_end += diff;
874 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
875 warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
878 uint64_t new_start = use_provided_address ?
879 provided_address : process->mmap_end;
880 process->pTable->remap(start, old_length, new_start);
881 warn("mremapping to new vaddr %08p-%08p, adding %d\n",
882 new_start, new_start + new_length,
883 new_length - old_length);
884 // add on the remaining unallocated pages
885 process->allocateMem(new_start + old_length,
886 new_length - old_length,
887 use_provided_address /* clobber */);
888 if (!use_provided_address)
889 process->mmap_end += new_length;
890 if (use_provided_address &&
891 new_start + new_length > process->mmap_end) {
892 // something fishy going on here, at least notify the user
893 // @todo: increase mmap_end?
894 warn("mmap region limit exceeded with MREMAP_FIXED\n");
896 warn("returning %08p as start\n", new_start);
901 if (use_provided_address && provided_address != start)
902 process->pTable->remap(start, new_length, provided_address);
903 process->pTable->unmap(start + new_length, old_length - new_length);
904 return use_provided_address ? provided_address : start;
908 /// Target stat() handler.
911 statFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
917 if (!tc->getMemProxy().tryReadString(path,
918 process->getSyscallArg(tc, index))) {
921 Addr bufPtr = process->getSyscallArg(tc, index);
923 // Adjust path for current working directory
924 path = process->fullPath(path);
927 int result = stat(path.c_str(), &hostBuf);
932 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
938 /// Target stat64() handler.
941 stat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
947 if (!tc->getMemProxy().tryReadString(path,
948 process->getSyscallArg(tc, index)))
950 Addr bufPtr = process->getSyscallArg(tc, index);
952 // Adjust path for current working directory
953 path = process->fullPath(path);
957 int result = stat(path.c_str(), &hostBuf);
959 struct stat64 hostBuf;
960 int result = stat64(path.c_str(), &hostBuf);
966 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
972 /// Target fstatat64() handler.
975 fstatat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
979 int dirfd = process->getSyscallArg(tc, index);
980 if (dirfd != OS::TGT_AT_FDCWD)
981 warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
984 if (!tc->getMemProxy().tryReadString(path,
985 process->getSyscallArg(tc, index)))
987 Addr bufPtr = process->getSyscallArg(tc, index);
989 // Adjust path for current working directory
990 path = process->fullPath(path);
994 int result = stat(path.c_str(), &hostBuf);
996 struct stat64 hostBuf;
997 int result = stat64(path.c_str(), &hostBuf);
1003 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1009 /// Target fstat64() handler.
1012 fstat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
1016 int tgt_fd = process->getSyscallArg(tc, index);
1017 Addr bufPtr = process->getSyscallArg(tc, index);
1019 int sim_fd = process->getSimFD(tgt_fd);
1024 struct stat hostBuf;
1025 int result = fstat(sim_fd, &hostBuf);
1027 struct stat64 hostBuf;
1028 int result = fstat64(sim_fd, &hostBuf);
1034 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1040 /// Target lstat() handler.
1043 lstatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1049 if (!tc->getMemProxy().tryReadString(path,
1050 process->getSyscallArg(tc, index))) {
1053 Addr bufPtr = process->getSyscallArg(tc, index);
1055 // Adjust path for current working directory
1056 path = process->fullPath(path);
1058 struct stat hostBuf;
1059 int result = lstat(path.c_str(), &hostBuf);
1064 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1069 /// Target lstat64() handler.
1072 lstat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
1078 if (!tc->getMemProxy().tryReadString(path,
1079 process->getSyscallArg(tc, index))) {
1082 Addr bufPtr = process->getSyscallArg(tc, index);
1084 // Adjust path for current working directory
1085 path = process->fullPath(path);
1088 struct stat hostBuf;
1089 int result = lstat(path.c_str(), &hostBuf);
1091 struct stat64 hostBuf;
1092 int result = lstat64(path.c_str(), &hostBuf);
1098 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1103 /// Target fstat() handler.
1106 fstatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1110 int tgt_fd = process->getSyscallArg(tc, index);
1111 Addr bufPtr = process->getSyscallArg(tc, index);
1113 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1115 int sim_fd = process->getSimFD(tgt_fd);
1119 struct stat hostBuf;
1120 int result = fstat(sim_fd, &hostBuf);
1125 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1131 /// Target statfs() handler.
1134 statfsFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1140 if (!tc->getMemProxy().tryReadString(path,
1141 process->getSyscallArg(tc, index))) {
1144 Addr bufPtr = process->getSyscallArg(tc, index);
1146 // Adjust path for current working directory
1147 path = process->fullPath(path);
1149 struct statfs hostBuf;
1150 int result = statfs(path.c_str(), &hostBuf);
1155 OS::copyOutStatfsBuf(tc->getMemProxy(), bufPtr, &hostBuf);
1161 /// Target fstatfs() handler.
1164 fstatfsFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1168 int tgt_fd = process->getSyscallArg(tc, index);
1169 Addr bufPtr = process->getSyscallArg(tc, index);
1171 int sim_fd = process->getSimFD(tgt_fd);
1175 struct statfs hostBuf;
1176 int result = fstatfs(sim_fd, &hostBuf);
1181 OS::copyOutStatfsBuf(tc->getMemProxy(), bufPtr, &hostBuf);
1187 /// Target writev() handler.
1190 writevFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1194 int tgt_fd = process->getSyscallArg(tc, index);
1196 int sim_fd = process->getSimFD(tgt_fd);
1200 SETranslatingPortProxy &p = tc->getMemProxy();
1201 uint64_t tiov_base = process->getSyscallArg(tc, index);
1202 size_t count = process->getSyscallArg(tc, index);
1203 struct iovec hiov[count];
1204 for (size_t i = 0; i < count; ++i) {
1205 typename OS::tgt_iovec tiov;
1207 p.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1208 (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1209 hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1210 hiov[i].iov_base = new char [hiov[i].iov_len];
1211 p.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1215 int result = writev(sim_fd, hiov, count);
1217 for (size_t i = 0; i < count; ++i)
1218 delete [] (char *)hiov[i].iov_base;
1226 /// Real mmap handler.
1229 mmapImpl(SyscallDesc *desc, int num, LiveProcess *p, ThreadContext *tc,
1233 Addr start = p->getSyscallArg(tc, index);
1234 uint64_t length = p->getSyscallArg(tc, index);
1235 int prot = p->getSyscallArg(tc, index);
1236 int tgt_flags = p->getSyscallArg(tc, index);
1237 int tgt_fd = p->getSyscallArg(tc, index);
1238 int offset = p->getSyscallArg(tc, index);
1241 offset *= TheISA::PageBytes;
1243 if (start & (TheISA::PageBytes - 1) ||
1244 offset & (TheISA::PageBytes - 1) ||
1245 (tgt_flags & OS::TGT_MAP_PRIVATE &&
1246 tgt_flags & OS::TGT_MAP_SHARED) ||
1247 (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1248 !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1253 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1254 // With shared mmaps, there are two cases to consider:
1255 // 1) anonymous: writes should modify the mapping and this should be
1256 // visible to observers who share the mapping. Currently, it's
1257 // difficult to update the shared mapping because there's no
1258 // structure which maintains information about the which virtual
1259 // memory areas are shared. If that structure existed, it would be
1260 // possible to make the translations point to the same frames.
1261 // 2) file-backed: writes should modify the mapping and the file
1262 // which is backed by the mapping. The shared mapping problem is the
1263 // same as what was mentioned about the anonymous mappings. For
1264 // file-backed mappings, the writes to the file are difficult
1265 // because it requires syncing what the mapping holds with the file
1266 // that resides on the host system. So, any write on a real system
1267 // would cause the change to be propagated to the file mapping at
1268 // some point in the future (the inode is tracked along with the
1269 // mapping). This isn't guaranteed to always happen, but it usually
1270 // works well enough. The guarantee is provided by the msync system
1271 // call. We could force the change through with shared mappings with
1272 // a call to msync, but that again would require more information
1273 // than we currently maintain.
1274 warn("mmap: writing to shared mmap region is currently "
1275 "unsupported. The write succeeds on the target, but it "
1276 "will not be propagated to the host or shared mappings");
1279 length = roundUp(length, TheISA::PageBytes);
1282 uint8_t *pmap = nullptr;
1283 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1284 sim_fd = p->getSimFD(tgt_fd);
1288 pmap = (decltype(pmap))mmap(NULL, length, PROT_READ, MAP_PRIVATE,
1291 if (pmap == (decltype(pmap))-1) {
1292 warn("mmap: failed to map file into host address space");
1297 // Extend global mmap region if necessary. Note that we ignore the
1298 // start address unless MAP_FIXED is specified.
1299 if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1300 start = (OS::mmapGrowsDown()) ? p->mmap_end - length : p->mmap_end;
1301 p->mmap_end = (OS::mmapGrowsDown()) ? start : p->mmap_end + length;
1304 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1305 start, start + length - 1);
1307 // We only allow mappings to overwrite existing mappings if
1308 // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1309 // because we ignore the start hint if TGT_MAP_FIXED is not set.
1310 int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1312 for (auto tc : p->system->threadContexts) {
1313 // If we might be overwriting old mappings, we need to
1314 // invalidate potentially stale mappings out of the TLBs.
1315 tc->getDTBPtr()->flushAll();
1316 tc->getITBPtr()->flushAll();
1320 // Allocate physical memory and map it in. If the page table is already
1321 // mapped and clobber is not set, the simulator will issue throw a
1322 // fatal and bail out of the simulation.
1323 p->allocateMem(start, length, clobber);
1325 // Transfer content into target address space.
1326 SETranslatingPortProxy &tp = tc->getMemProxy();
1327 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1328 // In general, we should zero the mapped area for anonymous mappings,
1329 // with something like:
1330 // tp.memsetBlob(start, 0, length);
1331 // However, given that we don't support sparse mappings, and
1332 // some applications can map a couple of gigabytes of space
1333 // (intending sparse usage), that can get painfully expensive.
1334 // Fortunately, since we don't properly implement munmap either,
1335 // there's no danger of remapping used memory, so for now all
1336 // newly mapped memory should already be zeroed so we can skip it.
1338 // It is possible to mmap an area larger than a file, however
1339 // accessing unmapped portions the system triggers a "Bus error"
1340 // on the host. We must know when to stop copying the file from
1341 // the host into the target address space.
1342 struct stat file_stat;
1343 if (fstat(sim_fd, &file_stat) > 0)
1344 fatal("mmap: cannot stat file");
1346 // Copy the portion of the file that is resident. This requires
1347 // checking both the mmap size and the filesize that we are
1348 // trying to mmap into this space; the mmap size also depends
1349 // on the specified offset into the file.
1350 uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1352 tp.writeBlob(start, pmap, size);
1354 // Cleanup the mmap region before exiting this function.
1355 munmap(pmap, length);
1357 // Note that we do not zero out the remainder of the mapping. This
1358 // is done by a real system, but it probably will not affect
1359 // execution (hopefully).
1365 /// Target mmap() handler.
1368 mmapFunc(SyscallDesc *desc, int num, LiveProcess *p, ThreadContext *tc)
1370 return mmapImpl<OS>(desc, num, p, tc, false);
1373 /// Target mmap2() handler.
1376 mmap2Func(SyscallDesc *desc, int num, LiveProcess *p, ThreadContext *tc)
1378 return mmapImpl<OS>(desc, num, p, tc, true);
1381 /// Target getrlimit() handler.
1384 getrlimitFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1388 unsigned resource = process->getSyscallArg(tc, index);
1389 TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1392 case OS::TGT_RLIMIT_STACK:
1393 // max stack size in bytes: make up a number (8MB for now)
1394 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1395 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1396 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1399 case OS::TGT_RLIMIT_DATA:
1400 // max data segment size in bytes: make up a number
1401 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1402 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1403 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1407 warn("getrlimit: unimplemented resource %d", resource);
1412 rlp.copyOut(tc->getMemProxy());
1416 /// Target clock_gettime() function.
1419 clock_gettimeFunc(SyscallDesc *desc, int num, LiveProcess *p, ThreadContext *tc)
1422 //int clk_id = p->getSyscallArg(tc, index);
1423 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1425 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1426 tp->tv_sec += seconds_since_epoch;
1427 tp->tv_sec = TheISA::htog(tp->tv_sec);
1428 tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1430 tp.copyOut(tc->getMemProxy());
1435 /// Target clock_getres() function.
1438 clock_getresFunc(SyscallDesc *desc, int num, LiveProcess *p, ThreadContext *tc)
1441 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1443 // Set resolution at ns, which is what clock_gettime() returns
1447 tp.copyOut(tc->getMemProxy());
1452 /// Target gettimeofday() handler.
1455 gettimeofdayFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1459 TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1461 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1462 tp->tv_sec += seconds_since_epoch;
1463 tp->tv_sec = TheISA::htog(tp->tv_sec);
1464 tp->tv_usec = TheISA::htog(tp->tv_usec);
1466 tp.copyOut(tc->getMemProxy());
1472 /// Target utimes() handler.
1475 utimesFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1481 if (!tc->getMemProxy().tryReadString(path,
1482 process->getSyscallArg(tc, index))) {
1486 TypedBufferArg<typename OS::timeval [2]>
1487 tp(process->getSyscallArg(tc, index));
1488 tp.copyIn(tc->getMemProxy());
1490 struct timeval hostTimeval[2];
1491 for (int i = 0; i < 2; ++i)
1493 hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1494 hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1497 // Adjust path for current working directory
1498 path = process->fullPath(path);
1500 int result = utimes(path.c_str(), hostTimeval);
1507 /// Target getrusage() function.
1510 getrusageFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1514 int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
1515 TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
1517 rup->ru_utime.tv_sec = 0;
1518 rup->ru_utime.tv_usec = 0;
1519 rup->ru_stime.tv_sec = 0;
1520 rup->ru_stime.tv_usec = 0;
1528 rup->ru_inblock = 0;
1529 rup->ru_oublock = 0;
1532 rup->ru_nsignals = 0;
1537 case OS::TGT_RUSAGE_SELF:
1538 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
1539 rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
1540 rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
1543 case OS::TGT_RUSAGE_CHILDREN:
1544 // do nothing. We have no child processes, so they take no time.
1548 // don't really handle THREAD or CHILDREN, but just warn and
1550 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
1554 rup.copyOut(tc->getMemProxy());
1559 /// Target times() function.
1562 timesFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1566 TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
1568 // Fill in the time structure (in clocks)
1569 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
1570 bufp->tms_utime = clocks;
1571 bufp->tms_stime = 0;
1572 bufp->tms_cutime = 0;
1573 bufp->tms_cstime = 0;
1575 // Convert to host endianness
1576 bufp->tms_utime = TheISA::htog(bufp->tms_utime);
1579 bufp.copyOut(tc->getMemProxy());
1581 // Return clock ticks since system boot
1585 /// Target time() function.
1588 timeFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1591 typename OS::time_t sec, usec;
1592 getElapsedTimeMicro(sec, usec);
1593 sec += seconds_since_epoch;
1596 Addr taddr = (Addr)process->getSyscallArg(tc, index);
1598 typename OS::time_t t = sec;
1599 t = TheISA::htog(t);
1600 SETranslatingPortProxy &p = tc->getMemProxy();
1601 p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
1607 #endif // __SIM_SYSCALL_EMUL_HH__