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