syscall_emul.hh revision 511
110453SAndrew.Bardsley@arm.com/*
210453SAndrew.Bardsley@arm.com * Copyright (c) 2003 The Regents of The University of Michigan
310453SAndrew.Bardsley@arm.com * All rights reserved.
410453SAndrew.Bardsley@arm.com *
510453SAndrew.Bardsley@arm.com * Redistribution and use in source and binary forms, with or without
610453SAndrew.Bardsley@arm.com * modification, are permitted provided that the following conditions are
710453SAndrew.Bardsley@arm.com * met: redistributions of source code must retain the above copyright
810453SAndrew.Bardsley@arm.com * notice, this list of conditions and the following disclaimer;
910453SAndrew.Bardsley@arm.com * redistributions in binary form must reproduce the above copyright
1010453SAndrew.Bardsley@arm.com * notice, this list of conditions and the following disclaimer in the
1110453SAndrew.Bardsley@arm.com * documentation and/or other materials provided with the distribution;
1210453SAndrew.Bardsley@arm.com * neither the name of the copyright holders nor the names of its
1310453SAndrew.Bardsley@arm.com * contributors may be used to endorse or promote products derived from
1410453SAndrew.Bardsley@arm.com * this software without specific prior written permission.
1510453SAndrew.Bardsley@arm.com *
1610453SAndrew.Bardsley@arm.com * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1710453SAndrew.Bardsley@arm.com * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1810453SAndrew.Bardsley@arm.com * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
1910453SAndrew.Bardsley@arm.com * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
2010453SAndrew.Bardsley@arm.com * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
2110453SAndrew.Bardsley@arm.com * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
2210453SAndrew.Bardsley@arm.com * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
2310453SAndrew.Bardsley@arm.com * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
2410453SAndrew.Bardsley@arm.com * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
2510453SAndrew.Bardsley@arm.com * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2610453SAndrew.Bardsley@arm.com * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2710453SAndrew.Bardsley@arm.com */
2810453SAndrew.Bardsley@arm.com
2910453SAndrew.Bardsley@arm.com#ifndef __SYSCALL_EMUL_HH__
3010453SAndrew.Bardsley@arm.com#define __SYSCALL_EMUL_HH__
3110453SAndrew.Bardsley@arm.com
3210453SAndrew.Bardsley@arm.com///
3310453SAndrew.Bardsley@arm.com/// @file syscall_emul.hh
3410453SAndrew.Bardsley@arm.com///
3510453SAndrew.Bardsley@arm.com/// This file defines objects used to emulate syscalls from the target
3610453SAndrew.Bardsley@arm.com/// application on the host machine.
3710453SAndrew.Bardsley@arm.com
3810453SAndrew.Bardsley@arm.com#include <string>
3910453SAndrew.Bardsley@arm.com
4010453SAndrew.Bardsley@arm.com#include "base/intmath.hh"	// for RoundUp
4110453SAndrew.Bardsley@arm.com#include "targetarch/isa_traits.hh"	// for Addr
4210453SAndrew.Bardsley@arm.com#include "mem/functional_mem/functional_memory.hh"
4310453SAndrew.Bardsley@arm.com
4410453SAndrew.Bardsley@arm.comclass Process;
4510453SAndrew.Bardsley@arm.comclass ExecContext;
4610453SAndrew.Bardsley@arm.com
4710453SAndrew.Bardsley@arm.com///
4810453SAndrew.Bardsley@arm.com/// System call descriptor.
4910453SAndrew.Bardsley@arm.com///
5010453SAndrew.Bardsley@arm.comclass SyscallDesc {
5110453SAndrew.Bardsley@arm.com
5210453SAndrew.Bardsley@arm.com  public:
5310453SAndrew.Bardsley@arm.com
5410453SAndrew.Bardsley@arm.com    /// Typedef for target syscall handler functions.
5510453SAndrew.Bardsley@arm.com    typedef int (*FuncPtr)(SyscallDesc *, int num,
5610453SAndrew.Bardsley@arm.com                           Process *, ExecContext *);
5710453SAndrew.Bardsley@arm.com
5810453SAndrew.Bardsley@arm.com    const char *name;	//!< Syscall name (e.g., "open").
5910453SAndrew.Bardsley@arm.com    FuncPtr funcPtr;	//!< Pointer to emulation function.
6010453SAndrew.Bardsley@arm.com    int flags;		//!< Flags (see Flags enum).
6110453SAndrew.Bardsley@arm.com
6210453SAndrew.Bardsley@arm.com    /// Flag values for controlling syscall behavior.
6310453SAndrew.Bardsley@arm.com    enum Flags {
6410453SAndrew.Bardsley@arm.com        /// Don't set return regs according to funcPtr return value.
6510453SAndrew.Bardsley@arm.com        /// Used for syscalls with non-standard return conventions
6610453SAndrew.Bardsley@arm.com        /// that explicitly set the ExecContext regs (e.g.,
6710453SAndrew.Bardsley@arm.com        /// sigreturn).
6810453SAndrew.Bardsley@arm.com        SuppressReturnValue = 1
6910453SAndrew.Bardsley@arm.com    };
7010453SAndrew.Bardsley@arm.com
7110453SAndrew.Bardsley@arm.com    /// Constructor.
7210453SAndrew.Bardsley@arm.com    SyscallDesc(const char *_name, FuncPtr _funcPtr, int _flags = 0)
7310453SAndrew.Bardsley@arm.com        : name(_name), funcPtr(_funcPtr), flags(_flags)
7410453SAndrew.Bardsley@arm.com    {
7510453SAndrew.Bardsley@arm.com    }
7610453SAndrew.Bardsley@arm.com
7710453SAndrew.Bardsley@arm.com    /// Emulate the syscall.  Public interface for calling through funcPtr.
7810453SAndrew.Bardsley@arm.com    void doSyscall(int callnum, Process *proc, ExecContext *xc);
7910453SAndrew.Bardsley@arm.com};
8010453SAndrew.Bardsley@arm.com
8110453SAndrew.Bardsley@arm.com
8210453SAndrew.Bardsley@arm.comclass BaseBufferArg {
8310453SAndrew.Bardsley@arm.com
8410453SAndrew.Bardsley@arm.com  public:
8510453SAndrew.Bardsley@arm.com
8610453SAndrew.Bardsley@arm.com    BaseBufferArg(Addr _addr, int _size) : addr(_addr), size(_size)
8710453SAndrew.Bardsley@arm.com    {
8810453SAndrew.Bardsley@arm.com        bufPtr = new uint8_t[size];
8910453SAndrew.Bardsley@arm.com        // clear out buffer: in case we only partially populate this,
9010453SAndrew.Bardsley@arm.com        // and then do a copyOut(), we want to make sure we don't
9110453SAndrew.Bardsley@arm.com        // introduce any random junk into the simulated address space
9210453SAndrew.Bardsley@arm.com        memset(bufPtr, 0, size);
9310453SAndrew.Bardsley@arm.com    }
9410453SAndrew.Bardsley@arm.com
9510453SAndrew.Bardsley@arm.com    virtual ~BaseBufferArg() { delete [] bufPtr; }
9610453SAndrew.Bardsley@arm.com
9710453SAndrew.Bardsley@arm.com    //
9810453SAndrew.Bardsley@arm.com    // copy data into simulator space (read from target memory)
9910453SAndrew.Bardsley@arm.com    //
10010453SAndrew.Bardsley@arm.com    virtual bool copyIn(FunctionalMemory *mem)
10110453SAndrew.Bardsley@arm.com    {
10210453SAndrew.Bardsley@arm.com        mem->access(Read, addr, bufPtr, size);
10310453SAndrew.Bardsley@arm.com        return true;	// no EFAULT detection for now
10410453SAndrew.Bardsley@arm.com    }
10510453SAndrew.Bardsley@arm.com
10610453SAndrew.Bardsley@arm.com    //
10710453SAndrew.Bardsley@arm.com    // copy data out of simulator space (write to target memory)
10810453SAndrew.Bardsley@arm.com    //
10910453SAndrew.Bardsley@arm.com    virtual bool copyOut(FunctionalMemory *mem)
11010453SAndrew.Bardsley@arm.com    {
11110453SAndrew.Bardsley@arm.com        mem->access(Write, addr, bufPtr, size);
11210453SAndrew.Bardsley@arm.com        return true;	// no EFAULT detection for now
11310453SAndrew.Bardsley@arm.com    }
11410453SAndrew.Bardsley@arm.com
11510453SAndrew.Bardsley@arm.com  protected:
11610453SAndrew.Bardsley@arm.com    Addr addr;
11710453SAndrew.Bardsley@arm.com    int size;
11810453SAndrew.Bardsley@arm.com    uint8_t *bufPtr;
11910453SAndrew.Bardsley@arm.com};
12010453SAndrew.Bardsley@arm.com
12110453SAndrew.Bardsley@arm.com
12210453SAndrew.Bardsley@arm.comclass BufferArg : public BaseBufferArg
12310453SAndrew.Bardsley@arm.com{
12410453SAndrew.Bardsley@arm.com  public:
12510453SAndrew.Bardsley@arm.com    BufferArg(Addr _addr, int _size) : BaseBufferArg(_addr, _size) { }
12610453SAndrew.Bardsley@arm.com    void *bufferPtr()	{ return bufPtr; }
12710453SAndrew.Bardsley@arm.com};
12810453SAndrew.Bardsley@arm.com
12910453SAndrew.Bardsley@arm.comtemplate <class T>
13010453SAndrew.Bardsley@arm.comclass TypedBufferArg : public BaseBufferArg
13110453SAndrew.Bardsley@arm.com{
13210453SAndrew.Bardsley@arm.com  public:
13310453SAndrew.Bardsley@arm.com    // user can optionally specify a specific number of bytes to
13410453SAndrew.Bardsley@arm.com    // allocate to deal with those structs that have variable-size
13510453SAndrew.Bardsley@arm.com    // arrays at the end
13610453SAndrew.Bardsley@arm.com    TypedBufferArg(Addr _addr, int _size = sizeof(T))
13710453SAndrew.Bardsley@arm.com        : BaseBufferArg(_addr, _size)
13810453SAndrew.Bardsley@arm.com    { }
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/// Target unlink() handler.
195int unlinkFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
196
197/// Target rename() handler.
198int renameFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc);
199
200//////////////////////////////////////////////////////////////////////
201//
202// The following emulation functions are generic, but need to be
203// templated to account for differences in types, constants, etc.
204//
205//////////////////////////////////////////////////////////////////////
206
207/// Target ioctl() handler.  For the most part, programs call ioctl()
208/// only to find out if their stdout is a tty, to determine whether to
209/// do line or block buffering.
210template <class OS>
211int
212ioctlFunc(SyscallDesc *desc, int callnum, Process *process,
213          ExecContext *xc)
214{
215    int fd = xc->getSyscallArg(0);
216    unsigned req = xc->getSyscallArg(1);
217
218    // DPRINTFR(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", fd, req);
219
220    if (fd < 0 || process->sim_fd(fd) < 0) {
221        // doesn't map to any simulator fd: not a valid target fd
222        return -EBADF;
223    }
224
225    switch (req) {
226      case OS::TIOCISATTY:
227      case OS::TIOCGETP:
228      case OS::TIOCSETP:
229      case OS::TIOCSETN:
230      case OS::TIOCSETC:
231      case OS::TIOCGETC:
232      case OS::TIOCGETS:
233      case OS::TIOCGETA:
234        return -ENOTTY;
235
236      default:
237        fatal("Unsupported ioctl call: ioctl(%d, 0x%x, ...) @ 0x%llx\n", fd, req, xc->readPC());
238    }
239}
240
241/// This struct is used to build an target-OS-dependent table that
242/// maps the target's open() flags to the host open() flags.
243struct OpenFlagTransTable {
244    int tgtFlag;	//!< Target system flag value.
245    int hostFlag;	//!< Corresponding host system flag value.
246};
247
248
249/// Target open() handler.
250template <class OS>
251int
252openFunc(SyscallDesc *desc, int callnum, Process *process,
253         ExecContext *xc)
254{
255    std::string path;
256
257    if (xc->mem->readString(path, xc->getSyscallArg(0)) != No_Fault)
258        return -EFAULT;
259
260    if (path == "/dev/sysdev0") {
261        // This is a memory-mapped high-resolution timer device on Alpha.
262        // We don't support it, so just punt.
263        DCOUT(SyscallWarnings) << "Ignoring open(" << path << ", ...)" << endl;
264        return -ENOENT;
265    }
266
267    int tgtFlags = xc->getSyscallArg(1);
268    int mode = xc->getSyscallArg(2);
269    int hostFlags = 0;
270
271    // translate open flags
272    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
273        if (tgtFlags & OS::openFlagTable[i].tgtFlag) {
274            tgtFlags &= ~OS::openFlagTable[i].tgtFlag;
275            hostFlags |= OS::openFlagTable[i].hostFlag;
276        }
277    }
278
279    // any target flags left?
280    if (tgtFlags != 0)
281        cerr << "Syscall: open: cannot decode flags: " <<  tgtFlags << endl;
282
283#ifdef __CYGWIN32__
284    hostFlags |= O_BINARY;
285#endif
286
287    // open the file
288    int fd = open(path.c_str(), hostFlags, mode);
289
290    return (fd == -1) ? -errno : process->open_fd(fd);
291}
292
293
294/// Target stat() handler.
295template <class OS>
296int
297statFunc(SyscallDesc *desc, int callnum, Process *process,
298         ExecContext *xc)
299{
300    std::string path;
301
302    if (xc->mem->readString(path, xc->getSyscallArg(0)) != No_Fault)
303        return -EFAULT;
304
305    struct stat hostBuf;
306    int result = stat(path.c_str(), &hostBuf);
307
308    if (result < 0)
309        return -errno;
310
311    OS::copyOutStatBuf(xc->mem, xc->getSyscallArg(1), &hostBuf);
312
313    return 0;
314}
315
316
317/// Target lstat() handler.
318template <class OS>
319int
320lstatFunc(SyscallDesc *desc, int callnum, Process *process,
321          ExecContext *xc)
322{
323    std::string path;
324
325    if (xc->mem->readString(path, xc->getSyscallArg(0)) != No_Fault)
326        return -EFAULT;
327
328    struct stat hostBuf;
329    int result = lstat(path.c_str(), &hostBuf);
330
331    if (result < 0)
332        return -errno;
333
334    OS::copyOutStatBuf(xc->mem, xc->getSyscallArg(1), &hostBuf);
335
336    return 0;
337}
338
339/// Target fstat() handler.
340template <class OS>
341int
342fstatFunc(SyscallDesc *desc, int callnum, Process *process,
343          ExecContext *xc)
344{
345    int fd = process->sim_fd(xc->getSyscallArg(0));
346
347    // DPRINTFR(SyscallVerbose, "fstat(%d, ...)\n", fd);
348
349    if (fd < 0)
350        return -EBADF;
351
352    struct stat hostBuf;
353    int result = fstat(fd, &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
364/// Target mmap() handler.
365///
366/// We don't really handle mmap().  If the target is mmaping an
367/// anonymous region or /dev/zero, we can get away with doing basically
368/// nothing (since memory is initialized to zero and the simulator
369/// doesn't really check addresses anyway).  Always print a warning,
370/// since this could be seriously broken if we're not mapping
371/// /dev/zero.
372//
373/// Someday we should explicitly check for /dev/zero in open, flag the
374/// file descriptor, and fail (or implement!) a non-anonymous mmap to
375/// anything else.
376template <class OS>
377int
378mmapFunc(SyscallDesc *desc, int num, Process *p, ExecContext *xc)
379{
380    Addr start = xc->getSyscallArg(0);
381    uint64_t length = xc->getSyscallArg(1);
382    // int prot = xc->getSyscallArg(2);
383    int flags = xc->getSyscallArg(3);
384    // int fd = p->sim_fd(xc->getSyscallArg(4));
385    // int offset = xc->getSyscallArg(5);
386
387    if (start == 0) {
388        // user didn't give an address... pick one from our "mmap region"
389        start = p->mmap_base;
390        p->mmap_base += RoundUp<Addr>(length, VMPageSize);
391    }
392
393    if (!(flags & OS::TGT_MAP_ANONYMOUS)) {
394        DPRINTF(SyscallWarnings, "Warning: allowing mmap of file @ fd %d.  "
395                "This will break if not /dev/zero.", xc->getSyscallArg(4));
396    }
397
398    return start;
399}
400
401/// Target getrlimit() handler.
402template <class OS>
403int
404getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
405              ExecContext *xc)
406{
407    unsigned resource = xc->getSyscallArg(0);
408    TypedBufferArg<typename OS::rlimit> rlp(xc->getSyscallArg(1));
409
410    switch (resource) {
411      case OS::RLIMIT_STACK:
412        // max stack size in bytes: make up a number (2MB for now)
413        rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
414        break;
415
416      default:
417        cerr << "getrlimitFunc: unimplemented resource " << resource << endl;
418        abort();
419        break;
420    }
421
422    rlp.copyOut(xc->mem);
423    return 0;
424}
425
426/// A readable name for 1,000,000, for converting microseconds to seconds.
427const int one_million = 1000000;
428
429/// Approximate seconds since the epoch (1/1/1970).  About a billion,
430/// by my reckoning.  We want to keep this a constant (not use the
431/// real-world time) to keep simulations repeatable.
432const unsigned seconds_since_epoch = 1000000000;
433
434/// Helper function to convert current elapsed time to seconds and
435/// microseconds.
436template <class T1, class T2>
437void
438getElapsedTime(T1 &sec, T2 &usec)
439{
440    int cycles_per_usec = ticksPerSecond / one_million;
441
442    int elapsed_usecs = curTick / cycles_per_usec;
443    sec = elapsed_usecs / one_million;
444    usec = elapsed_usecs % one_million;
445}
446
447
448/// Target gettimeofday() handler.
449template <class OS>
450int
451gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
452                 ExecContext *xc)
453{
454    TypedBufferArg<typename OS::timeval> tp(xc->getSyscallArg(0));
455
456    getElapsedTime(tp->tv_sec, tp->tv_usec);
457    tp->tv_sec += seconds_since_epoch;
458
459    tp.copyOut(xc->mem);
460
461    return 0;
462}
463
464
465/// Target getrusage() function.
466template <class OS>
467int
468getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
469              ExecContext *xc)
470{
471    int who = xc->getSyscallArg(0);	// THREAD, SELF, or CHILDREN
472    TypedBufferArg<typename OS::rusage> rup(xc->getSyscallArg(1));
473
474    if (who != OS::RUSAGE_SELF) {
475        // don't really handle THREAD or CHILDREN, but just warn and
476        // plow ahead
477        DCOUT(SyscallWarnings)
478            << "Warning: getrusage() only supports RUSAGE_SELF."
479            << "  Parameter " << who << " ignored." << endl;
480    }
481
482    getElapsedTime(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
483    rup->ru_stime.tv_sec = 0;
484    rup->ru_stime.tv_usec = 0;
485    rup->ru_maxrss = 0;
486    rup->ru_ixrss = 0;
487    rup->ru_idrss = 0;
488    rup->ru_isrss = 0;
489    rup->ru_minflt = 0;
490    rup->ru_majflt = 0;
491    rup->ru_nswap = 0;
492    rup->ru_inblock = 0;
493    rup->ru_oublock = 0;
494    rup->ru_msgsnd = 0;
495    rup->ru_msgrcv = 0;
496    rup->ru_nsignals = 0;
497    rup->ru_nvcsw = 0;
498    rup->ru_nivcsw = 0;
499
500    rup.copyOut(xc->mem);
501
502    return 0;
503}
504
505
506
507#endif // __SYSCALL_EMUL_HH__
508