syscall_emul.hh revision 1354
1/*
2 * Copyright (c) 2003-2004 The Regents of The University of Michigan
3 * All rights reserved.
4 *
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.
15 *
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.
27 */
28
29#ifndef __SIM_SYSCALL_EMUL_HH__
30#define __SIM_SYSCALL_EMUL_HH__
31
32///
33/// @file syscall_emul.hh
34///
35/// This file defines objects used to emulate syscalls from the target
36/// application on the host machine.
37
38#include <errno.h>
39#include <string>
40
41#include "base/intmath.hh"	// for RoundUp
42#include "mem/functional_mem/functional_memory.hh"
43#include "targetarch/isa_traits.hh"	// for Addr
44
45#include "base/trace.hh"
46#include "cpu/exec_context.hh"
47#include "sim/process.hh"
48
49///
50/// System call descriptor.
51///
52class SyscallDesc {
53
54  public:
55
56    /// Typedef for target syscall handler functions.
57    typedef int (*FuncPtr)(SyscallDesc *, int num,
58                           Process *, ExecContext *);
59
60    const char *name;	//!< Syscall name (e.g., "open").
61    FuncPtr funcPtr;	//!< Pointer to emulation function.
62    int flags;		//!< Flags (see Flags enum).
63
64    /// Flag values for controlling syscall behavior.
65    enum Flags {
66        /// Don't set return regs according to funcPtr return value.
67        /// Used for syscalls with non-standard return conventions
68        /// that explicitly set the ExecContext regs (e.g.,
69        /// sigreturn).
70        SuppressReturnValue = 1
71    };
72
73    /// Constructor.
74    SyscallDesc(const char *_name, FuncPtr _funcPtr, int _flags = 0)
75        : name(_name), funcPtr(_funcPtr), flags(_flags)
76    {
77    }
78
79    /// Emulate the syscall.  Public interface for calling through funcPtr.
80    void doSyscall(int callnum, Process *proc, ExecContext *xc);
81};
82
83
84class BaseBufferArg {
85
86  public:
87
88    BaseBufferArg(Addr _addr, int _size) : addr(_addr), size(_size)
89    {
90        bufPtr = new uint8_t[size];
91        // clear out buffer: in case we only partially populate this,
92        // and then do a copyOut(), we want to make sure we don't
93        // introduce any random junk into the simulated address space
94        memset(bufPtr, 0, size);
95    }
96
97    virtual ~BaseBufferArg() { delete [] bufPtr; }
98
99    //
100    // copy data into simulator space (read from target memory)
101    //
102    virtual bool copyIn(FunctionalMemory *mem)
103    {
104        mem->access(Read, addr, bufPtr, size);
105        return true;	// no EFAULT detection for now
106    }
107
108    //
109    // copy data out of simulator space (write to target memory)
110    //
111    virtual bool copyOut(FunctionalMemory *mem)
112    {
113        mem->access(Write, addr, bufPtr, size);
114        return true;	// no EFAULT detection for now
115    }
116
117  protected:
118    Addr addr;
119    int size;
120    uint8_t *bufPtr;
121};
122
123
124class BufferArg : public BaseBufferArg
125{
126  public:
127    BufferArg(Addr _addr, int _size) : BaseBufferArg(_addr, _size) { }
128    void *bufferPtr()	{ return bufPtr; }
129};
130
131template <class T>
132class TypedBufferArg : public BaseBufferArg
133{
134  public:
135    // user can optionally specify a specific number of bytes to
136    // allocate to deal with those structs that have variable-size
137    // arrays at the end
138    TypedBufferArg(Addr _addr, int _size = sizeof(T))
139        : BaseBufferArg(_addr, _size)
140    { }
141
142    // type case
143    operator T*() { return (T *)bufPtr; }
144
145    // dereference operators
146    T &operator*()	 { return *((T *)bufPtr); }
147    T* operator->()	 { return (T *)bufPtr; }
148    T &operator[](int i) { return ((T *)bufPtr)[i]; }
149};
150
151//////////////////////////////////////////////////////////////////////
152//
153// The following emulation functions are generic enough that they
154// don't need to be recompiled for different emulated OS's.  They are
155// defined in sim/syscall_emul.cc.
156//
157//////////////////////////////////////////////////////////////////////
158
159
160/// Handler for unimplemented syscalls that we haven't thought about.
161int unimplementedFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
162
163/// Handler for unimplemented syscalls that we never intend to
164/// implement (signal handling, etc.) and should not affect the correct
165/// behavior of the program.  Print a warning only if the appropriate
166/// trace flag is enabled.  Return success to the target program.
167int ignoreFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
168
169/// Target exit() handler: terminate simulation.
170int exitFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
171
172/// Target getpagesize() handler.
173int getpagesizeFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
174
175/// Target obreak() handler: set brk address.
176int obreakFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
177
178/// Target close() handler.
179int closeFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
180
181/// Target read() handler.
182int readFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
183
184/// Target write() handler.
185int writeFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
186
187/// Target lseek() handler.
188int lseekFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
189
190/// Target munmap() handler.
191int munmapFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
192
193/// Target gethostname() handler.
194int gethostnameFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
195
196/// Target unlink() handler.
197int unlinkFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
198
199/// Target rename() handler.
200int renameFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
201
202/// This struct is used to build an target-OS-dependent table that
203/// maps the target's open() flags to the host open() flags.
204struct OpenFlagTransTable {
205    int tgtFlag;	//!< Target system flag value.
206    int hostFlag;	//!< Corresponding host system flag value.
207};
208
209
210
211/// A readable name for 1,000,000, for converting microseconds to seconds.
212const int one_million = 1000000;
213
214/// Approximate seconds since the epoch (1/1/1970).  About a billion,
215/// by my reckoning.  We want to keep this a constant (not use the
216/// real-world time) to keep simulations repeatable.
217const unsigned seconds_since_epoch = 1000000000;
218
219/// Helper function to convert current elapsed time to seconds and
220/// microseconds.
221template <class T1, class T2>
222void
223getElapsedTime(T1 &sec, T2 &usec)
224{
225    int cycles_per_usec = ticksPerSecond / one_million;
226
227    int elapsed_usecs = curTick / cycles_per_usec;
228    sec = elapsed_usecs / one_million;
229    usec = elapsed_usecs % one_million;
230}
231
232//////////////////////////////////////////////////////////////////////
233//
234// The following emulation functions are generic, but need to be
235// templated to account for differences in types, constants, etc.
236//
237//////////////////////////////////////////////////////////////////////
238
239/// Target ioctl() handler.  For the most part, programs call ioctl()
240/// only to find out if their stdout is a tty, to determine whether to
241/// do line or block buffering.
242template <class OS>
243int
244ioctlFunc(SyscallDesc *desc, int callnum, Process *process,
245          ExecContext *xc)
246{
247    int fd = xc->getSyscallArg(0);
248    unsigned req = xc->getSyscallArg(1);
249
250    // DPRINTFR(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", fd, req);
251
252    if (fd < 0 || process->sim_fd(fd) < 0) {
253        // doesn't map to any simulator fd: not a valid target fd
254        return -EBADF;
255    }
256
257    switch (req) {
258      case OS::TIOCISATTY:
259      case OS::TIOCGETP:
260      case OS::TIOCSETP:
261      case OS::TIOCSETN:
262      case OS::TIOCSETC:
263      case OS::TIOCGETC:
264      case OS::TIOCGETS:
265      case OS::TIOCGETA:
266        return -ENOTTY;
267
268      default:
269        fatal("Unsupported ioctl call: ioctl(%d, 0x%x, ...) @ 0x%llx\n", fd, req, xc->readPC());
270    }
271}
272
273/// Target open() handler.
274template <class OS>
275int
276openFunc(SyscallDesc *desc, int callnum, Process *process,
277         ExecContext *xc)
278{
279    std::string path;
280
281    if (xc->mem->readString(path, xc->getSyscallArg(0)) != No_Fault)
282        return -EFAULT;
283
284    if (path == "/dev/sysdev0") {
285        // This is a memory-mapped high-resolution timer device on Alpha.
286        // We don't support it, so just punt.
287        DCOUT(SyscallWarnings) << "Ignoring open(" << path << ", ...)" << std::endl;
288        return -ENOENT;
289    }
290
291    int tgtFlags = xc->getSyscallArg(1);
292    int mode = xc->getSyscallArg(2);
293    int hostFlags = 0;
294
295    // translate open flags
296    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
297        if (tgtFlags & OS::openFlagTable[i].tgtFlag) {
298            tgtFlags &= ~OS::openFlagTable[i].tgtFlag;
299            hostFlags |= OS::openFlagTable[i].hostFlag;
300        }
301    }
302
303    // any target flags left?
304    if (tgtFlags != 0)
305        std::cerr << "Syscall: open: cannot decode flags: " <<  tgtFlags << std::endl;
306
307#ifdef __CYGWIN32__
308    hostFlags |= O_BINARY;
309#endif
310
311    // open the file
312    int fd = open(path.c_str(), hostFlags, mode);
313
314    return (fd == -1) ? -errno : process->open_fd(fd);
315}
316
317
318/// Target stat() handler.
319template <class OS>
320int
321statFunc(SyscallDesc *desc, int callnum, Process *process,
322         ExecContext *xc)
323{
324    std::string path;
325
326    if (xc->mem->readString(path, xc->getSyscallArg(0)) != No_Fault)
327        return -EFAULT;
328
329    struct stat hostBuf;
330    int result = stat(path.c_str(), &hostBuf);
331
332    if (result < 0)
333        return -errno;
334
335    OS::copyOutStatBuf(xc->mem, xc->getSyscallArg(1), &hostBuf);
336
337    return 0;
338}
339
340
341/// Target lstat() handler.
342template <class OS>
343int
344lstatFunc(SyscallDesc *desc, int callnum, Process *process,
345          ExecContext *xc)
346{
347    std::string path;
348
349    if (xc->mem->readString(path, xc->getSyscallArg(0)) != No_Fault)
350        return -EFAULT;
351
352    struct stat hostBuf;
353    int result = lstat(path.c_str(), &hostBuf);
354
355    if (result < 0)
356        return -errno;
357
358    OS::copyOutStatBuf(xc->mem, xc->getSyscallArg(1), &hostBuf);
359
360    return 0;
361}
362
363/// Target fstat() handler.
364template <class OS>
365int
366fstatFunc(SyscallDesc *desc, int callnum, Process *process,
367          ExecContext *xc)
368{
369    int fd = process->sim_fd(xc->getSyscallArg(0));
370
371    // DPRINTFR(SyscallVerbose, "fstat(%d, ...)\n", fd);
372
373    if (fd < 0)
374        return -EBADF;
375
376    struct stat hostBuf;
377    int result = fstat(fd, &hostBuf);
378
379    if (result < 0)
380        return -errno;
381
382    OS::copyOutStatBuf(xc->mem, xc->getSyscallArg(1), &hostBuf);
383
384    return 0;
385}
386
387
388/// Target mmap() handler.
389///
390/// We don't really handle mmap().  If the target is mmaping an
391/// anonymous region or /dev/zero, we can get away with doing basically
392/// nothing (since memory is initialized to zero and the simulator
393/// doesn't really check addresses anyway).  Always print a warning,
394/// since this could be seriously broken if we're not mapping
395/// /dev/zero.
396//
397/// Someday we should explicitly check for /dev/zero in open, flag the
398/// file descriptor, and fail (or implement!) a non-anonymous mmap to
399/// anything else.
400template <class OS>
401int
402mmapFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc)
403{
404    Addr start = xc->getSyscallArg(0);
405    uint64_t length = xc->getSyscallArg(1);
406    // int prot = xc->getSyscallArg(2);
407    int flags = xc->getSyscallArg(3);
408    // int fd = p->sim_fd(xc->getSyscallArg(4));
409    // int offset = xc->getSyscallArg(5);
410
411    if (start == 0) {
412        // user didn't give an address... pick one from our "mmap region"
413        start = p->mmap_base;
414        p->mmap_base += RoundUp<Addr>(length, VMPageSize);
415    }
416
417    if (!(flags & OS::TGT_MAP_ANONYMOUS)) {
418        DPRINTF(SyscallWarnings, "Warning: allowing mmap of file @ fd %d.  "
419                "This will break if not /dev/zero.", xc->getSyscallArg(4));
420    }
421
422    return start;
423}
424
425/// Target getrlimit() handler.
426template <class OS>
427int
428getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
429              ExecContext *xc)
430{
431    unsigned resource = xc->getSyscallArg(0);
432    TypedBufferArg<typename OS::rlimit> rlp(xc->getSyscallArg(1));
433
434    switch (resource) {
435      case OS::RLIMIT_STACK:
436        // max stack size in bytes: make up a number (2MB for now)
437        rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
438        break;
439
440      default:
441        std::cerr << "getrlimitFunc: unimplemented resource " << resource << std::endl;
442        abort();
443        break;
444    }
445
446    rlp.copyOut(xc->mem);
447    return 0;
448}
449
450/// Target gettimeofday() handler.
451template <class OS>
452int
453gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
454                 ExecContext *xc)
455{
456    TypedBufferArg<typename OS::timeval> tp(xc->getSyscallArg(0));
457
458    getElapsedTime(tp->tv_sec, tp->tv_usec);
459    tp->tv_sec += seconds_since_epoch;
460
461    tp.copyOut(xc->mem);
462
463    return 0;
464}
465
466
467/// Target getrusage() function.
468template <class OS>
469int
470getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
471              ExecContext *xc)
472{
473    int who = xc->getSyscallArg(0);	// THREAD, SELF, or CHILDREN
474    TypedBufferArg<typename OS::rusage> rup(xc->getSyscallArg(1));
475
476    if (who != OS::RUSAGE_SELF) {
477        // don't really handle THREAD or CHILDREN, but just warn and
478        // plow ahead
479        DCOUT(SyscallWarnings)
480            << "Warning: getrusage() only supports RUSAGE_SELF."
481            << "  Parameter " << who << " ignored." << std::endl;
482    }
483
484    getElapsedTime(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
485    rup->ru_stime.tv_sec = 0;
486    rup->ru_stime.tv_usec = 0;
487    rup->ru_maxrss = 0;
488    rup->ru_ixrss = 0;
489    rup->ru_idrss = 0;
490    rup->ru_isrss = 0;
491    rup->ru_minflt = 0;
492    rup->ru_majflt = 0;
493    rup->ru_nswap = 0;
494    rup->ru_inblock = 0;
495    rup->ru_oublock = 0;
496    rup->ru_msgsnd = 0;
497    rup->ru_msgrcv = 0;
498    rup->ru_nsignals = 0;
499    rup->ru_nvcsw = 0;
500    rup->ru_nivcsw = 0;
501
502    rup.copyOut(xc->mem);
503
504    return 0;
505}
506
507#endif // __SIM_SYSCALL_EMUL_HH__
508