2 * Copyright (c) 2003-2005 The Regents of The University of Michigan
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 * Authors: Steve Reinhardt
33 #ifndef __SIM_SYSCALL_EMUL_HH__
34 #define __SIM_SYSCALL_EMUL_HH__
36 #define NO_STAT64 (defined(__APPLE__) || defined(__OpenBSD__) || \
37 defined(__FreeBSD__) || defined(__CYGWIN__))
40 /// @file syscall_emul.hh
42 /// This file defines objects used to emulate syscalls from the target
43 /// application on the host machine.
48 #include <sys/fcntl.h> // for O_BINARY
52 #include "arch/isa_traits.hh" // for Addr
53 #include "base/chunk_generator.hh"
54 #include "base/intmath.hh" // for RoundUp
55 #include "base/misc.hh"
56 #include "base/trace.hh"
57 #include "cpu/base.hh"
58 #include "cpu/thread_context.hh"
59 #include "mem/translating_port.hh"
60 #include "mem/page_table.hh"
61 #include "sim/process.hh"
64 /// System call descriptor.
70 /// Typedef for target syscall handler functions.
71 typedef SyscallReturn (*FuncPtr)(SyscallDesc *, int num,
72 Process *, ThreadContext *);
74 const char *name; //!< Syscall name (e.g., "open").
75 FuncPtr funcPtr; //!< Pointer to emulation function.
76 int flags; //!< Flags (see Flags enum).
78 /// Flag values for controlling syscall behavior.
80 /// Don't set return regs according to funcPtr return value.
81 /// Used for syscalls with non-standard return conventions
82 /// that explicitly set the ThreadContext regs (e.g.,
84 SuppressReturnValue = 1
88 SyscallDesc(const char *_name, FuncPtr _funcPtr, int _flags = 0)
89 : name(_name), funcPtr(_funcPtr), flags(_flags)
93 /// Emulate the syscall. Public interface for calling through funcPtr.
94 void doSyscall(int callnum, Process *proc, ThreadContext *tc);
102 BaseBufferArg(Addr _addr, int _size) : addr(_addr), size(_size)
104 bufPtr = new uint8_t[size];
105 // clear out buffer: in case we only partially populate this,
106 // and then do a copyOut(), we want to make sure we don't
107 // introduce any random junk into the simulated address space
108 memset(bufPtr, 0, size);
111 virtual ~BaseBufferArg() { delete [] bufPtr; }
114 // copy data into simulator space (read from target memory)
116 virtual bool copyIn(TranslatingPort *memport)
118 memport->readBlob(addr, bufPtr, size);
119 return true; // no EFAULT detection for now
123 // copy data out of simulator space (write to target memory)
125 virtual bool copyOut(TranslatingPort *memport)
127 memport->writeBlob(addr, bufPtr, size);
128 return true; // no EFAULT detection for now
138 class BufferArg : public BaseBufferArg
141 BufferArg(Addr _addr, int _size) : BaseBufferArg(_addr, _size) { }
142 void *bufferPtr() { return bufPtr; }
146 class TypedBufferArg : public BaseBufferArg
149 // user can optionally specify a specific number of bytes to
150 // allocate to deal with those structs that have variable-size
152 TypedBufferArg(Addr _addr, int _size = sizeof(T))
153 : BaseBufferArg(_addr, _size)
157 operator T*() { return (T *)bufPtr; }
159 // dereference operators
160 T &operator*() { return *((T *)bufPtr); }
161 T* operator->() { return (T *)bufPtr; }
162 T &operator[](int i) { return ((T *)bufPtr)[i]; }
165 //////////////////////////////////////////////////////////////////////
167 // The following emulation functions are generic enough that they
168 // don't need to be recompiled for different emulated OS's. They are
169 // defined in sim/syscall_emul.cc.
171 //////////////////////////////////////////////////////////////////////
174 /// Handler for unimplemented syscalls that we haven't thought about.
175 SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
176 Process *p, ThreadContext *tc);
178 /// Handler for unimplemented syscalls that we never intend to
179 /// implement (signal handling, etc.) and should not affect the correct
180 /// behavior of the program. Print a warning only if the appropriate
181 /// trace flag is enabled. Return success to the target program.
182 SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
183 Process *p, ThreadContext *tc);
185 /// Target exit() handler: terminate simulation.
186 SyscallReturn exitFunc(SyscallDesc *desc, int num,
187 Process *p, ThreadContext *tc);
189 /// Target getpagesize() handler.
190 SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
191 Process *p, ThreadContext *tc);
193 /// Target obreak() handler: set brk address.
194 SyscallReturn obreakFunc(SyscallDesc *desc, int num,
195 Process *p, ThreadContext *tc);
197 /// Target close() handler.
198 SyscallReturn closeFunc(SyscallDesc *desc, int num,
199 Process *p, ThreadContext *tc);
201 /// Target read() handler.
202 SyscallReturn readFunc(SyscallDesc *desc, int num,
203 Process *p, ThreadContext *tc);
205 /// Target write() handler.
206 SyscallReturn writeFunc(SyscallDesc *desc, int num,
207 Process *p, ThreadContext *tc);
209 /// Target lseek() handler.
210 SyscallReturn lseekFunc(SyscallDesc *desc, int num,
211 Process *p, ThreadContext *tc);
213 /// Target munmap() handler.
214 SyscallReturn munmapFunc(SyscallDesc *desc, int num,
215 Process *p, ThreadContext *tc);
217 /// Target gethostname() handler.
218 SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
219 Process *p, ThreadContext *tc);
221 /// Target unlink() handler.
222 SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
223 Process *p, ThreadContext *tc);
225 /// Target rename() handler.
226 SyscallReturn renameFunc(SyscallDesc *desc, int num,
227 Process *p, ThreadContext *tc);
230 /// Target truncate() handler.
231 SyscallReturn truncateFunc(SyscallDesc *desc, int num,
232 Process *p, ThreadContext *tc);
235 /// Target ftruncate() handler.
236 SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
237 Process *p, ThreadContext *tc);
240 /// Target chown() handler.
241 SyscallReturn chownFunc(SyscallDesc *desc, int num,
242 Process *p, ThreadContext *tc);
245 /// Target fchown() handler.
246 SyscallReturn fchownFunc(SyscallDesc *desc, int num,
247 Process *p, ThreadContext *tc);
249 /// Target fnctl() handler.
250 SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
251 Process *process, ThreadContext *tc);
253 /// Target fcntl64() handler.
254 SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
255 Process *process, ThreadContext *tc);
257 /// Target setuid() handler.
258 SyscallReturn setuidFunc(SyscallDesc *desc, int num,
259 Process *p, ThreadContext *tc);
261 /// Target getpid() handler.
262 SyscallReturn getpidFunc(SyscallDesc *desc, int num,
263 Process *p, ThreadContext *tc);
265 /// Target getuid() handler.
266 SyscallReturn getuidFunc(SyscallDesc *desc, int num,
267 Process *p, ThreadContext *tc);
269 /// Target getgid() handler.
270 SyscallReturn getgidFunc(SyscallDesc *desc, int num,
271 Process *p, ThreadContext *tc);
273 /// Target getppid() handler.
274 SyscallReturn getppidFunc(SyscallDesc *desc, int num,
275 Process *p, ThreadContext *tc);
277 /// Target geteuid() handler.
278 SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
279 Process *p, ThreadContext *tc);
281 /// Target getegid() handler.
282 SyscallReturn getegidFunc(SyscallDesc *desc, int num,
283 Process *p, ThreadContext *tc);
287 /// Pseudo Funcs - These functions use a different return convension,
288 /// returning a second value in a register other than the normal return register
289 SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
290 Process *process, ThreadContext *tc);
292 /// Target getpidPseudo() handler.
293 SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
294 Process *p, ThreadContext *tc);
296 /// Target getuidPseudo() handler.
297 SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
298 Process *p, ThreadContext *tc);
300 /// Target getgidPseudo() handler.
301 SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
302 Process *p, ThreadContext *tc);
305 /// This struct is used to build an target-OS-dependent table that
306 /// maps the target's open() flags to the host open() flags.
307 struct OpenFlagTransTable {
308 int tgtFlag; //!< Target system flag value.
309 int hostFlag; //!< Corresponding host system flag value.
314 /// A readable name for 1,000,000, for converting microseconds to seconds.
315 const int one_million = 1000000;
317 /// Approximate seconds since the epoch (1/1/1970). About a billion,
318 /// by my reckoning. We want to keep this a constant (not use the
319 /// real-world time) to keep simulations repeatable.
320 const unsigned seconds_since_epoch = 1000000000;
322 /// Helper function to convert current elapsed time to seconds and
324 template <class T1, class T2>
326 getElapsedTime(T1 &sec, T2 &usec)
328 int elapsed_usecs = curTick / Clock::Int::us;
329 sec = elapsed_usecs / one_million;
330 usec = elapsed_usecs % one_million;
333 //////////////////////////////////////////////////////////////////////
335 // The following emulation functions are generic, but need to be
336 // templated to account for differences in types, constants, etc.
338 //////////////////////////////////////////////////////////////////////
340 /// Target ioctl() handler. For the most part, programs call ioctl()
341 /// only to find out if their stdout is a tty, to determine whether to
342 /// do line or block buffering.
345 ioctlFunc(SyscallDesc *desc, int callnum, Process *process,
348 int fd = tc->getSyscallArg(0);
349 unsigned req = tc->getSyscallArg(1);
351 DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", fd, req);
353 if (fd < 0 || process->sim_fd(fd) < 0) {
354 // doesn't map to any simulator fd: not a valid target fd
370 fatal("Unsupported ioctl call: ioctl(%d, 0x%x, ...) @ 0x%llx\n",
371 fd, req, tc->readPC());
375 /// Target open() handler.
378 openFunc(SyscallDesc *desc, int callnum, Process *process,
383 if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
386 if (path == "/dev/sysdev0") {
387 // This is a memory-mapped high-resolution timer device on Alpha.
388 // We don't support it, so just punt.
389 warn("Ignoring open(%s, ...)\n", path);
393 int tgtFlags = tc->getSyscallArg(1);
394 int mode = tc->getSyscallArg(2);
397 // translate open flags
398 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
399 if (tgtFlags & OS::openFlagTable[i].tgtFlag) {
400 tgtFlags &= ~OS::openFlagTable[i].tgtFlag;
401 hostFlags |= OS::openFlagTable[i].hostFlag;
405 // any target flags left?
407 warn("Syscall: open: cannot decode flags 0x%x", tgtFlags);
410 hostFlags |= O_BINARY;
413 DPRINTF(SyscallVerbose, "opening file %s\n", path.c_str());
416 int fd = open(path.c_str(), hostFlags, mode);
418 return (fd == -1) ? -errno : process->alloc_fd(fd);
422 /// Target chmod() handler.
425 chmodFunc(SyscallDesc *desc, int callnum, Process *process,
430 if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
433 uint32_t mode = tc->getSyscallArg(1);
436 // XXX translate mode flags via OS::something???
440 int result = chmod(path.c_str(), hostMode);
448 /// Target fchmod() handler.
451 fchmodFunc(SyscallDesc *desc, int callnum, Process *process,
454 int fd = tc->getSyscallArg(0);
455 if (fd < 0 || process->sim_fd(fd) < 0) {
456 // doesn't map to any simulator fd: not a valid target fd
460 uint32_t mode = tc->getSyscallArg(1);
463 // XXX translate mode flags via OS::someting???
467 int result = fchmod(process->sim_fd(fd), hostMode);
475 /// Target stat() handler.
478 statFunc(SyscallDesc *desc, int callnum, Process *process,
483 if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
487 int result = stat(path.c_str(), &hostBuf);
492 OS::copyOutStatBuf(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
498 /// Target fstat64() handler.
501 fstat64Func(SyscallDesc *desc, int callnum, Process *process,
504 int fd = tc->getSyscallArg(0);
505 if (fd < 0 || process->sim_fd(fd) < 0) {
506 // doesn't map to any simulator fd: not a valid target fd
512 int result = fstat(process->sim_fd(fd), &hostBuf);
514 struct stat64 hostBuf;
515 int result = fstat64(process->sim_fd(fd), &hostBuf);
521 OS::copyOutStat64Buf(tc->getMemPort(), fd, tc->getSyscallArg(1), &hostBuf);
527 /// Target lstat() handler.
530 lstatFunc(SyscallDesc *desc, int callnum, Process *process,
535 if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
539 int result = lstat(path.c_str(), &hostBuf);
544 OS::copyOutStatBuf(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
549 /// Target lstat64() handler.
552 lstat64Func(SyscallDesc *desc, int callnum, Process *process,
557 if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
562 int result = lstat(path.c_str(), &hostBuf);
564 struct stat64 hostBuf;
565 int result = lstat64(path.c_str(), &hostBuf);
571 OS::copyOutStat64Buf(tc->getMemPort(), -1, tc->getSyscallArg(1), &hostBuf);
576 /// Target fstat() handler.
579 fstatFunc(SyscallDesc *desc, int callnum, Process *process,
582 int fd = process->sim_fd(tc->getSyscallArg(0));
584 DPRINTF(SyscallVerbose, "fstat(%d, ...)\n", fd);
590 int result = fstat(fd, &hostBuf);
595 OS::copyOutStatBuf(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
601 /// Target statfs() handler.
604 statfsFunc(SyscallDesc *desc, int callnum, Process *process,
609 if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
612 struct statfs hostBuf;
613 int result = statfs(path.c_str(), &hostBuf);
618 OS::copyOutStatfsBuf(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
624 /// Target fstatfs() handler.
627 fstatfsFunc(SyscallDesc *desc, int callnum, Process *process,
630 int fd = process->sim_fd(tc->getSyscallArg(0));
635 struct statfs hostBuf;
636 int result = fstatfs(fd, &hostBuf);
641 OS::copyOutStatfsBuf(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
647 /// Target writev() handler.
650 writevFunc(SyscallDesc *desc, int callnum, Process *process,
653 int fd = tc->getSyscallArg(0);
654 if (fd < 0 || process->sim_fd(fd) < 0) {
655 // doesn't map to any simulator fd: not a valid target fd
659 TranslatingPort *p = tc->getMemPort();
660 uint64_t tiov_base = tc->getSyscallArg(1);
661 size_t count = tc->getSyscallArg(2);
662 struct iovec hiov[count];
663 for (int i = 0; i < count; ++i)
665 typename OS::tgt_iovec tiov;
667 p->readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
668 (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
669 hiov[i].iov_len = gtoh(tiov.iov_len);
670 hiov[i].iov_base = new char [hiov[i].iov_len];
671 p->readBlob(gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
675 int result = writev(process->sim_fd(fd), hiov, count);
677 for (int i = 0; i < count; ++i)
679 delete [] (char *)hiov[i].iov_base;
689 /// Target mmap() handler.
691 /// We don't really handle mmap(). If the target is mmaping an
692 /// anonymous region or /dev/zero, we can get away with doing basically
693 /// nothing (since memory is initialized to zero and the simulator
694 /// doesn't really check addresses anyway). Always print a warning,
695 /// since this could be seriously broken if we're not mapping
698 /// Someday we should explicitly check for /dev/zero in open, flag the
699 /// file descriptor, and fail (or implement!) a non-anonymous mmap to
703 mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
705 Addr start = tc->getSyscallArg(0);
706 uint64_t length = tc->getSyscallArg(1);
707 // int prot = tc->getSyscallArg(2);
708 int flags = tc->getSyscallArg(3);
709 // int fd = p->sim_fd(tc->getSyscallArg(4));
710 // int offset = tc->getSyscallArg(5);
712 if ((start % TheISA::VMPageSize) != 0 ||
713 (length % TheISA::VMPageSize) != 0) {
714 warn("mmap failing: arguments not page-aligned: "
715 "start 0x%x length 0x%x",
721 warn("mmap: ignoring suggested map address 0x%x, using 0x%x",
725 // pick next address from our "mmap region"
727 p->pTable->allocate(start, length);
728 p->mmap_end += length;
730 if (!(flags & OS::TGT_MAP_ANONYMOUS)) {
731 warn("allowing mmap of file @ fd %d. "
732 "This will break if not /dev/zero.", tc->getSyscallArg(4));
738 /// Target getrlimit() handler.
741 getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
744 unsigned resource = tc->getSyscallArg(0);
745 TypedBufferArg<typename OS::rlimit> rlp(tc->getSyscallArg(1));
748 case OS::TGT_RLIMIT_STACK:
749 // max stack size in bytes: make up a number (2MB for now)
750 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
751 rlp->rlim_cur = htog(rlp->rlim_cur);
752 rlp->rlim_max = htog(rlp->rlim_max);
756 std::cerr << "getrlimitFunc: unimplemented resource " << resource
762 rlp.copyOut(tc->getMemPort());
766 /// Target gettimeofday() handler.
769 gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
772 TypedBufferArg<typename OS::timeval> tp(tc->getSyscallArg(0));
774 getElapsedTime(tp->tv_sec, tp->tv_usec);
775 tp->tv_sec += seconds_since_epoch;
776 tp->tv_sec = htog(tp->tv_sec);
777 tp->tv_usec = htog(tp->tv_usec);
779 tp.copyOut(tc->getMemPort());
785 /// Target utimes() handler.
788 utimesFunc(SyscallDesc *desc, int callnum, Process *process,
793 if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
796 TypedBufferArg<typename OS::timeval [2]> tp(tc->getSyscallArg(1));
797 tp.copyIn(tc->getMemPort());
799 struct timeval hostTimeval[2];
800 for (int i = 0; i < 2; ++i)
802 hostTimeval[i].tv_sec = gtoh((*tp)[i].tv_sec);
803 hostTimeval[i].tv_usec = gtoh((*tp)[i].tv_usec);
805 int result = utimes(path.c_str(), hostTimeval);
812 /// Target getrusage() function.
815 getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
818 int who = tc->getSyscallArg(0); // THREAD, SELF, or CHILDREN
819 TypedBufferArg<typename OS::rusage> rup(tc->getSyscallArg(1));
821 if (who != OS::TGT_RUSAGE_SELF) {
822 // don't really handle THREAD or CHILDREN, but just warn and
824 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
828 getElapsedTime(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
829 rup->ru_utime.tv_sec = htog(rup->ru_utime.tv_sec);
830 rup->ru_utime.tv_usec = htog(rup->ru_utime.tv_usec);
832 rup->ru_stime.tv_sec = 0;
833 rup->ru_stime.tv_usec = 0;
845 rup->ru_nsignals = 0;
849 rup.copyOut(tc->getMemPort());
857 #endif // __SIM_SYSCALL_EMUL_HH__