syscall_emul.hh revision 5877:9fe574944f31
1/*
2 * Copyright (c) 2003-2005 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 * Authors: Steve Reinhardt
29 *          Kevin Lim
30 */
31
32#ifndef __SIM_SYSCALL_EMUL_HH__
33#define __SIM_SYSCALL_EMUL_HH__
34
35#define NO_STAT64 (defined(__APPLE__) || defined(__OpenBSD__) || \
36                   defined(__FreeBSD__) || defined(__CYGWIN__))
37
38///
39/// @file syscall_emul.hh
40///
41/// This file defines objects used to emulate syscalls from the target
42/// application on the host machine.
43
44#include <errno.h>
45#include <string>
46#ifdef __CYGWIN32__
47#include <sys/fcntl.h>  // for O_BINARY
48#endif
49#include <sys/stat.h>
50#include <fcntl.h>
51#include <sys/uio.h>
52
53#include "sim/host.hh"  // for Addr
54#include "base/chunk_generator.hh"
55#include "base/intmath.hh"      // for RoundUp
56#include "base/misc.hh"
57#include "base/trace.hh"
58#include "cpu/base.hh"
59#include "cpu/thread_context.hh"
60#include "mem/translating_port.hh"
61#include "mem/page_table.hh"
62#include "sim/process.hh"
63
64///
65/// System call descriptor.
66///
67class SyscallDesc {
68
69  public:
70
71    /// Typedef for target syscall handler functions.
72    typedef SyscallReturn (*FuncPtr)(SyscallDesc *, int num,
73                           LiveProcess *, ThreadContext *);
74
75    const char *name;   //!< Syscall name (e.g., "open").
76    FuncPtr funcPtr;    //!< Pointer to emulation function.
77    int flags;          //!< Flags (see Flags enum).
78
79    /// Flag values for controlling syscall behavior.
80    enum Flags {
81        /// Don't set return regs according to funcPtr return value.
82        /// Used for syscalls with non-standard return conventions
83        /// that explicitly set the ThreadContext regs (e.g.,
84        /// sigreturn).
85        SuppressReturnValue = 1
86    };
87
88    /// Constructor.
89    SyscallDesc(const char *_name, FuncPtr _funcPtr, int _flags = 0)
90        : name(_name), funcPtr(_funcPtr), flags(_flags)
91    {
92    }
93
94    /// Emulate the syscall.  Public interface for calling through funcPtr.
95    void doSyscall(int callnum, LiveProcess *proc, ThreadContext *tc);
96};
97
98
99class BaseBufferArg {
100
101  public:
102
103    BaseBufferArg(Addr _addr, int _size) : addr(_addr), size(_size)
104    {
105        bufPtr = new uint8_t[size];
106        // clear out buffer: in case we only partially populate this,
107        // and then do a copyOut(), we want to make sure we don't
108        // introduce any random junk into the simulated address space
109        memset(bufPtr, 0, size);
110    }
111
112    virtual ~BaseBufferArg() { delete [] bufPtr; }
113
114    //
115    // copy data into simulator space (read from target memory)
116    //
117    virtual bool copyIn(TranslatingPort *memport)
118    {
119        memport->readBlob(addr, bufPtr, size);
120        return true;    // no EFAULT detection for now
121    }
122
123    //
124    // copy data out of simulator space (write to target memory)
125    //
126    virtual bool copyOut(TranslatingPort *memport)
127    {
128        memport->writeBlob(addr, bufPtr, size);
129        return true;    // no EFAULT detection for now
130    }
131
132  protected:
133    Addr addr;
134    int size;
135    uint8_t *bufPtr;
136};
137
138
139class BufferArg : public BaseBufferArg
140{
141  public:
142    BufferArg(Addr _addr, int _size) : BaseBufferArg(_addr, _size) { }
143    void *bufferPtr()   { return bufPtr; }
144};
145
146template <class T>
147class TypedBufferArg : public BaseBufferArg
148{
149  public:
150    // user can optionally specify a specific number of bytes to
151    // allocate to deal with those structs that have variable-size
152    // arrays at the end
153    TypedBufferArg(Addr _addr, int _size = sizeof(T))
154        : BaseBufferArg(_addr, _size)
155    { }
156
157    // type case
158    operator T*() { return (T *)bufPtr; }
159
160    // dereference operators
161    T &operator*()       { return *((T *)bufPtr); }
162    T* operator->()      { return (T *)bufPtr; }
163    T &operator[](int i) { return ((T *)bufPtr)[i]; }
164};
165
166//////////////////////////////////////////////////////////////////////
167//
168// The following emulation functions are generic enough that they
169// don't need to be recompiled for different emulated OS's.  They are
170// defined in sim/syscall_emul.cc.
171//
172//////////////////////////////////////////////////////////////////////
173
174
175/// Handler for unimplemented syscalls that we haven't thought about.
176SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
177                                LiveProcess *p, ThreadContext *tc);
178
179/// Handler for unimplemented syscalls that we never intend to
180/// implement (signal handling, etc.) and should not affect the correct
181/// behavior of the program.  Print a warning only if the appropriate
182/// trace flag is enabled.  Return success to the target program.
183SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
184                         LiveProcess *p, ThreadContext *tc);
185
186/// Target exit() handler: terminate simulation.
187SyscallReturn exitFunc(SyscallDesc *desc, int num,
188                       LiveProcess *p, ThreadContext *tc);
189
190/// Target getpagesize() handler.
191SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
192                              LiveProcess *p, ThreadContext *tc);
193
194/// Target brk() handler: set brk address.
195SyscallReturn brkFunc(SyscallDesc *desc, int num,
196                      LiveProcess *p, ThreadContext *tc);
197
198/// Target close() handler.
199SyscallReturn closeFunc(SyscallDesc *desc, int num,
200                        LiveProcess *p, ThreadContext *tc);
201
202/// Target read() handler.
203SyscallReturn readFunc(SyscallDesc *desc, int num,
204                       LiveProcess *p, ThreadContext *tc);
205
206/// Target write() handler.
207SyscallReturn writeFunc(SyscallDesc *desc, int num,
208                        LiveProcess *p, ThreadContext *tc);
209
210/// Target lseek() handler.
211SyscallReturn lseekFunc(SyscallDesc *desc, int num,
212                        LiveProcess *p, ThreadContext *tc);
213
214/// Target _llseek() handler.
215SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
216                        LiveProcess *p, ThreadContext *tc);
217
218/// Target munmap() handler.
219SyscallReturn munmapFunc(SyscallDesc *desc, int num,
220                         LiveProcess *p, ThreadContext *tc);
221
222/// Target gethostname() handler.
223SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
224                              LiveProcess *p, ThreadContext *tc);
225
226/// Target getcwd() handler.
227SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
228                         LiveProcess *p, ThreadContext *tc);
229
230/// Target unlink() handler.
231SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
232                           LiveProcess *p, ThreadContext *tc);
233
234/// Target unlink() handler.
235SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
236                         LiveProcess *p, ThreadContext *tc);
237
238/// Target mkdir() handler.
239SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
240                        LiveProcess *p, ThreadContext *tc);
241
242/// Target rename() handler.
243SyscallReturn renameFunc(SyscallDesc *desc, int num,
244                         LiveProcess *p, ThreadContext *tc);
245
246
247/// Target truncate() handler.
248SyscallReturn truncateFunc(SyscallDesc *desc, int num,
249                           LiveProcess *p, ThreadContext *tc);
250
251
252/// Target ftruncate() handler.
253SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
254                            LiveProcess *p, ThreadContext *tc);
255
256
257/// Target umask() handler.
258SyscallReturn umaskFunc(SyscallDesc *desc, int num,
259                        LiveProcess *p, ThreadContext *tc);
260
261
262/// Target chown() handler.
263SyscallReturn chownFunc(SyscallDesc *desc, int num,
264                        LiveProcess *p, ThreadContext *tc);
265
266
267/// Target fchown() handler.
268SyscallReturn fchownFunc(SyscallDesc *desc, int num,
269                         LiveProcess *p, ThreadContext *tc);
270
271/// Target dup() handler.
272SyscallReturn dupFunc(SyscallDesc *desc, int num,
273                      LiveProcess *process, ThreadContext *tc);
274
275/// Target fnctl() handler.
276SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
277                        LiveProcess *process, ThreadContext *tc);
278
279/// Target fcntl64() handler.
280SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
281                        LiveProcess *process, ThreadContext *tc);
282
283/// Target setuid() handler.
284SyscallReturn setuidFunc(SyscallDesc *desc, int num,
285                               LiveProcess *p, ThreadContext *tc);
286
287/// Target getpid() handler.
288SyscallReturn getpidFunc(SyscallDesc *desc, int num,
289                               LiveProcess *p, ThreadContext *tc);
290
291/// Target getuid() handler.
292SyscallReturn getuidFunc(SyscallDesc *desc, int num,
293                               LiveProcess *p, ThreadContext *tc);
294
295/// Target getgid() handler.
296SyscallReturn getgidFunc(SyscallDesc *desc, int num,
297                               LiveProcess *p, ThreadContext *tc);
298
299/// Target getppid() handler.
300SyscallReturn getppidFunc(SyscallDesc *desc, int num,
301                               LiveProcess *p, ThreadContext *tc);
302
303/// Target geteuid() handler.
304SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
305                               LiveProcess *p, ThreadContext *tc);
306
307/// Target getegid() handler.
308SyscallReturn getegidFunc(SyscallDesc *desc, int num,
309                               LiveProcess *p, ThreadContext *tc);
310
311
312
313/// Pseudo Funcs  - These functions use a different return convension,
314/// returning a second value in a register other than the normal return register
315SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
316                             LiveProcess *process, ThreadContext *tc);
317
318/// Target getpidPseudo() handler.
319SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
320                               LiveProcess *p, ThreadContext *tc);
321
322/// Target getuidPseudo() handler.
323SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
324                               LiveProcess *p, ThreadContext *tc);
325
326/// Target getgidPseudo() handler.
327SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
328                               LiveProcess *p, ThreadContext *tc);
329
330
331/// A readable name for 1,000,000, for converting microseconds to seconds.
332const int one_million = 1000000;
333
334/// Approximate seconds since the epoch (1/1/1970).  About a billion,
335/// by my reckoning.  We want to keep this a constant (not use the
336/// real-world time) to keep simulations repeatable.
337const unsigned seconds_since_epoch = 1000000000;
338
339/// Helper function to convert current elapsed time to seconds and
340/// microseconds.
341template <class T1, class T2>
342void
343getElapsedTime(T1 &sec, T2 &usec)
344{
345    int elapsed_usecs = curTick / Clock::Int::us;
346    sec = elapsed_usecs / one_million;
347    usec = elapsed_usecs % one_million;
348}
349
350//////////////////////////////////////////////////////////////////////
351//
352// The following emulation functions are generic, but need to be
353// templated to account for differences in types, constants, etc.
354//
355//////////////////////////////////////////////////////////////////////
356
357#if NO_STAT64
358    typedef struct stat hst_stat;
359    typedef struct stat hst_stat64;
360#else
361    typedef struct stat hst_stat;
362    typedef struct stat64 hst_stat64;
363#endif
364
365//// Helper function to convert a host stat buffer to a target stat
366//// buffer.  Also copies the target buffer out to the simulated
367//// memory space.  Used by stat(), fstat(), and lstat().
368
369template <typename target_stat, typename host_stat>
370static void
371convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
372{
373    using namespace TheISA;
374
375    if (fakeTTY)
376        tgt->st_dev = 0xA;
377    else
378        tgt->st_dev = host->st_dev;
379    tgt->st_dev = htog(tgt->st_dev);
380    tgt->st_ino = host->st_ino;
381    tgt->st_ino = htog(tgt->st_ino);
382    tgt->st_mode = host->st_mode;
383    if (fakeTTY) {
384        // Claim to be a character device
385        tgt->st_mode &= ~S_IFMT;    // Clear S_IFMT
386        tgt->st_mode |= S_IFCHR;    // Set S_IFCHR
387    }
388    tgt->st_mode = htog(tgt->st_mode);
389    tgt->st_nlink = host->st_nlink;
390    tgt->st_nlink = htog(tgt->st_nlink);
391    tgt->st_uid = host->st_uid;
392    tgt->st_uid = htog(tgt->st_uid);
393    tgt->st_gid = host->st_gid;
394    tgt->st_gid = htog(tgt->st_gid);
395    if (fakeTTY)
396        tgt->st_rdev = 0x880d;
397    else
398        tgt->st_rdev = host->st_rdev;
399    tgt->st_rdev = htog(tgt->st_rdev);
400    tgt->st_size = host->st_size;
401    tgt->st_size = htog(tgt->st_size);
402    tgt->st_atimeX = host->st_atime;
403    tgt->st_atimeX = htog(tgt->st_atimeX);
404    tgt->st_mtimeX = host->st_mtime;
405    tgt->st_mtimeX = htog(tgt->st_mtimeX);
406    tgt->st_ctimeX = host->st_ctime;
407    tgt->st_ctimeX = htog(tgt->st_ctimeX);
408    // Force the block size to be 8k. This helps to ensure buffered io works
409    // consistently across different hosts.
410    tgt->st_blksize = 0x2000;
411    tgt->st_blksize = htog(tgt->st_blksize);
412    tgt->st_blocks = host->st_blocks;
413    tgt->st_blocks = htog(tgt->st_blocks);
414}
415
416// Same for stat64
417
418template <typename target_stat, typename host_stat64>
419static void
420convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
421{
422    using namespace TheISA;
423
424    convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
425#if defined(STAT_HAVE_NSEC)
426    tgt->st_atime_nsec = host->st_atime_nsec;
427    tgt->st_atime_nsec = htog(tgt->st_atime_nsec);
428    tgt->st_mtime_nsec = host->st_mtime_nsec;
429    tgt->st_mtime_nsec = htog(tgt->st_mtime_nsec);
430    tgt->st_ctime_nsec = host->st_ctime_nsec;
431    tgt->st_ctime_nsec = htog(tgt->st_ctime_nsec);
432#else
433    tgt->st_atime_nsec = 0;
434    tgt->st_mtime_nsec = 0;
435    tgt->st_ctime_nsec = 0;
436#endif
437}
438
439//Here are a couple convenience functions
440template<class OS>
441static void
442copyOutStatBuf(TranslatingPort * mem, Addr addr,
443        hst_stat *host, bool fakeTTY = false)
444{
445    typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
446    tgt_stat_buf tgt(addr);
447    convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
448    tgt.copyOut(mem);
449}
450
451template<class OS>
452static void
453copyOutStat64Buf(TranslatingPort * mem, Addr addr,
454        hst_stat64 *host, bool fakeTTY = false)
455{
456    typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
457    tgt_stat_buf tgt(addr);
458    convertStatBuf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
459    tgt.copyOut(mem);
460}
461
462/// Target ioctl() handler.  For the most part, programs call ioctl()
463/// only to find out if their stdout is a tty, to determine whether to
464/// do line or block buffering.
465template <class OS>
466SyscallReturn
467ioctlFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
468          ThreadContext *tc)
469{
470    int fd = tc->getSyscallArg(0);
471    unsigned req = tc->getSyscallArg(1);
472
473    DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", fd, req);
474
475    if (fd < 0 || process->sim_fd(fd) < 0) {
476        // doesn't map to any simulator fd: not a valid target fd
477        return -EBADF;
478    }
479
480    switch (req) {
481      case OS::TIOCISATTY_:
482      case OS::TIOCGETP_:
483      case OS::TIOCSETP_:
484      case OS::TIOCSETN_:
485      case OS::TIOCSETC_:
486      case OS::TIOCGETC_:
487      case OS::TIOCGETS_:
488      case OS::TIOCGETA_:
489        return -ENOTTY;
490
491      default:
492        fatal("Unsupported ioctl call: ioctl(%d, 0x%x, ...) @ 0x%llx\n",
493              fd, req, tc->readPC());
494    }
495}
496
497/// Target open() handler.
498template <class OS>
499SyscallReturn
500openFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
501         ThreadContext *tc)
502{
503    std::string path;
504
505    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
506        return -EFAULT;
507
508    if (path == "/dev/sysdev0") {
509        // This is a memory-mapped high-resolution timer device on Alpha.
510        // We don't support it, so just punt.
511        warn("Ignoring open(%s, ...)\n", path);
512        return -ENOENT;
513    }
514
515    int tgtFlags = tc->getSyscallArg(1);
516    int mode = tc->getSyscallArg(2);
517    int hostFlags = 0;
518
519    // translate open flags
520    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
521        if (tgtFlags & OS::openFlagTable[i].tgtFlag) {
522            tgtFlags &= ~OS::openFlagTable[i].tgtFlag;
523            hostFlags |= OS::openFlagTable[i].hostFlag;
524        }
525    }
526
527    // any target flags left?
528    if (tgtFlags != 0)
529        warn("Syscall: open: cannot decode flags 0x%x", tgtFlags);
530
531#ifdef __CYGWIN32__
532    hostFlags |= O_BINARY;
533#endif
534
535    // Adjust path for current working directory
536    path = process->fullPath(path);
537
538    DPRINTF(SyscallVerbose, "opening file %s\n", path.c_str());
539
540    int fd;
541    if (!path.compare(0, 6, "/proc/") || !path.compare(0, 8, "/system/") ||
542        !path.compare(0, 10, "/platform/") || !path.compare(0, 5, "/sys/")) {
543        // It's a proc/sys entery and requires special handling
544        fd = OS::openSpecialFile(path, process, tc);
545        return (fd == -1) ? -1 : process->alloc_fd(fd,path.c_str(),hostFlags,mode, false);
546     } else {
547        // open the file
548        fd = open(path.c_str(), hostFlags, mode);
549        return (fd == -1) ? -errno : process->alloc_fd(fd,path.c_str(),hostFlags,mode, false);
550     }
551
552}
553
554
555/// Target chmod() handler.
556template <class OS>
557SyscallReturn
558chmodFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
559          ThreadContext *tc)
560{
561    std::string path;
562
563    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
564        return -EFAULT;
565
566    uint32_t mode = tc->getSyscallArg(1);
567    mode_t hostMode = 0;
568
569    // XXX translate mode flags via OS::something???
570    hostMode = mode;
571
572    // Adjust path for current working directory
573    path = process->fullPath(path);
574
575    // do the chmod
576    int result = chmod(path.c_str(), hostMode);
577    if (result < 0)
578        return -errno;
579
580    return 0;
581}
582
583
584/// Target fchmod() handler.
585template <class OS>
586SyscallReturn
587fchmodFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
588           ThreadContext *tc)
589{
590    int fd = tc->getSyscallArg(0);
591    if (fd < 0 || process->sim_fd(fd) < 0) {
592        // doesn't map to any simulator fd: not a valid target fd
593        return -EBADF;
594    }
595
596    uint32_t mode = tc->getSyscallArg(1);
597    mode_t hostMode = 0;
598
599    // XXX translate mode flags via OS::someting???
600    hostMode = mode;
601
602    // do the fchmod
603    int result = fchmod(process->sim_fd(fd), hostMode);
604    if (result < 0)
605        return -errno;
606
607    return 0;
608}
609
610/// Target mremap() handler.
611template <class OS>
612SyscallReturn
613mremapFunc(SyscallDesc *desc, int callnum, LiveProcess *process, ThreadContext *tc)
614{
615    Addr start = tc->getSyscallArg(0);
616    uint64_t old_length = tc->getSyscallArg(1);
617    uint64_t new_length = tc->getSyscallArg(2);
618    uint64_t flags = tc->getSyscallArg(3);
619
620    if ((start % TheISA::VMPageSize != 0) ||
621            (new_length % TheISA::VMPageSize != 0)) {
622        warn("mremap failing: arguments not page aligned");
623        return -EINVAL;
624    }
625
626    if (new_length > old_length) {
627        if ((start + old_length) == process->mmap_end) {
628            uint64_t diff = new_length - old_length;
629            process->pTable->allocate(process->mmap_end, diff);
630            process->mmap_end += diff;
631            return start;
632        } else {
633            // sys/mman.h defined MREMAP_MAYMOVE
634            if (!(flags & 1)) {
635                warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
636                return -ENOMEM;
637            } else {
638                process->pTable->remap(start, old_length, process->mmap_end);
639                warn("mremapping to totally new vaddr %08p-%08p, adding %d\n",
640                        process->mmap_end, process->mmap_end + new_length, new_length);
641                start = process->mmap_end;
642                // add on the remaining unallocated pages
643                process->pTable->allocate(start + old_length, new_length - old_length);
644                process->mmap_end += new_length;
645                warn("returning %08p as start\n", start);
646                return start;
647            }
648        }
649    } else {
650        process->pTable->deallocate(start + new_length, old_length -
651                new_length);
652        return start;
653    }
654}
655
656/// Target stat() handler.
657template <class OS>
658SyscallReturn
659statFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
660         ThreadContext *tc)
661{
662    std::string path;
663
664    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
665    return -EFAULT;
666
667    // Adjust path for current working directory
668    path = process->fullPath(path);
669
670    struct stat hostBuf;
671    int result = stat(path.c_str(), &hostBuf);
672
673    if (result < 0)
674        return -errno;
675
676    copyOutStatBuf<OS>(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
677
678    return 0;
679}
680
681
682/// Target stat64() handler.
683template <class OS>
684SyscallReturn
685stat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
686           ThreadContext *tc)
687{
688    std::string path;
689
690    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
691        return -EFAULT;
692
693    // Adjust path for current working directory
694    path = process->fullPath(path);
695
696#if NO_STAT64
697    struct stat  hostBuf;
698    int result = stat(path.c_str(), &hostBuf);
699#else
700    struct stat64 hostBuf;
701    int result = stat64(path.c_str(), &hostBuf);
702#endif
703
704    if (result < 0)
705        return -errno;
706
707    copyOutStat64Buf<OS>(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
708
709    return 0;
710}
711
712
713/// Target fstat64() handler.
714template <class OS>
715SyscallReturn
716fstat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
717            ThreadContext *tc)
718{
719    int fd = tc->getSyscallArg(0);
720    if (fd < 0 || process->sim_fd(fd) < 0) {
721        // doesn't map to any simulator fd: not a valid target fd
722        return -EBADF;
723    }
724
725#if NO_STAT64
726    struct stat  hostBuf;
727    int result = fstat(process->sim_fd(fd), &hostBuf);
728#else
729    struct stat64  hostBuf;
730    int result = fstat64(process->sim_fd(fd), &hostBuf);
731#endif
732
733    if (result < 0)
734        return -errno;
735
736    copyOutStat64Buf<OS>(tc->getMemPort(), tc->getSyscallArg(1),
737        &hostBuf, (fd == 1));
738
739    return 0;
740}
741
742
743/// Target lstat() handler.
744template <class OS>
745SyscallReturn
746lstatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
747          ThreadContext *tc)
748{
749    std::string path;
750
751    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
752      return -EFAULT;
753
754    // Adjust path for current working directory
755    path = process->fullPath(path);
756
757    struct stat hostBuf;
758    int result = lstat(path.c_str(), &hostBuf);
759
760    if (result < 0)
761        return -errno;
762
763    copyOutStatBuf<OS>(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
764
765    return 0;
766}
767
768/// Target lstat64() handler.
769template <class OS>
770SyscallReturn
771lstat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
772            ThreadContext *tc)
773{
774    std::string path;
775
776    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
777      return -EFAULT;
778
779    // Adjust path for current working directory
780    path = process->fullPath(path);
781
782#if NO_STAT64
783    struct stat hostBuf;
784    int result = lstat(path.c_str(), &hostBuf);
785#else
786    struct stat64 hostBuf;
787    int result = lstat64(path.c_str(), &hostBuf);
788#endif
789
790    if (result < 0)
791        return -errno;
792
793    copyOutStat64Buf<OS>(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
794
795    return 0;
796}
797
798/// Target fstat() handler.
799template <class OS>
800SyscallReturn
801fstatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
802          ThreadContext *tc)
803{
804    int fd = process->sim_fd(tc->getSyscallArg(0));
805
806    DPRINTF(SyscallVerbose, "fstat(%d, ...)\n", fd);
807
808    if (fd < 0)
809        return -EBADF;
810
811    struct stat hostBuf;
812    int result = fstat(fd, &hostBuf);
813
814    if (result < 0)
815        return -errno;
816
817    copyOutStatBuf<OS>(tc->getMemPort(), tc->getSyscallArg(1),
818        &hostBuf, (fd == 1));
819
820    return 0;
821}
822
823
824/// Target statfs() handler.
825template <class OS>
826SyscallReturn
827statfsFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
828           ThreadContext *tc)
829{
830    std::string path;
831
832    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
833      return -EFAULT;
834
835    // Adjust path for current working directory
836    path = process->fullPath(path);
837
838    struct statfs hostBuf;
839    int result = statfs(path.c_str(), &hostBuf);
840
841    if (result < 0)
842        return -errno;
843
844    OS::copyOutStatfsBuf(tc->getMemPort(),
845            (Addr)(tc->getSyscallArg(1)), &hostBuf);
846
847    return 0;
848}
849
850
851/// Target fstatfs() handler.
852template <class OS>
853SyscallReturn
854fstatfsFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
855            ThreadContext *tc)
856{
857    int fd = process->sim_fd(tc->getSyscallArg(0));
858
859    if (fd < 0)
860        return -EBADF;
861
862    struct statfs hostBuf;
863    int result = fstatfs(fd, &hostBuf);
864
865    if (result < 0)
866        return -errno;
867
868    OS::copyOutStatfsBuf(tc->getMemPort(), tc->getSyscallArg(1),
869        &hostBuf);
870
871    return 0;
872}
873
874
875/// Target writev() handler.
876template <class OS>
877SyscallReturn
878writevFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
879           ThreadContext *tc)
880{
881    int fd = tc->getSyscallArg(0);
882    if (fd < 0 || process->sim_fd(fd) < 0) {
883        // doesn't map to any simulator fd: not a valid target fd
884        return -EBADF;
885    }
886
887    TranslatingPort *p = tc->getMemPort();
888    uint64_t tiov_base = tc->getSyscallArg(1);
889    size_t count = tc->getSyscallArg(2);
890    struct iovec hiov[count];
891    for (int i = 0; i < count; ++i)
892    {
893        typename OS::tgt_iovec tiov;
894
895        p->readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
896                    (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
897        hiov[i].iov_len = gtoh(tiov.iov_len);
898        hiov[i].iov_base = new char [hiov[i].iov_len];
899        p->readBlob(gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
900                    hiov[i].iov_len);
901    }
902
903    int result = writev(process->sim_fd(fd), hiov, count);
904
905    for (int i = 0; i < count; ++i)
906    {
907        delete [] (char *)hiov[i].iov_base;
908    }
909
910    if (result < 0)
911        return -errno;
912
913    return 0;
914}
915
916
917/// Target mmap() handler.
918///
919/// We don't really handle mmap().  If the target is mmaping an
920/// anonymous region or /dev/zero, we can get away with doing basically
921/// nothing (since memory is initialized to zero and the simulator
922/// doesn't really check addresses anyway).  Always print a warning,
923/// since this could be seriously broken if we're not mapping
924/// /dev/zero.
925//
926/// Someday we should explicitly check for /dev/zero in open, flag the
927/// file descriptor, and fail (or implement!) a non-anonymous mmap to
928/// anything else.
929template <class OS>
930SyscallReturn
931mmapFunc(SyscallDesc *desc, int num, LiveProcess *p, ThreadContext *tc)
932{
933    Addr start = tc->getSyscallArg(0);
934    uint64_t length = tc->getSyscallArg(1);
935    // int prot = tc->getSyscallArg(2);
936    int flags = tc->getSyscallArg(3);
937    // int fd = p->sim_fd(tc->getSyscallArg(4));
938    // int offset = tc->getSyscallArg(5);
939
940
941    if ((start  % TheISA::VMPageSize) != 0 ||
942        (length % TheISA::VMPageSize) != 0) {
943        warn("mmap failing: arguments not page-aligned: "
944             "start 0x%x length 0x%x",
945             start, length);
946        return -EINVAL;
947    }
948
949    if (start != 0) {
950        warn("mmap: ignoring suggested map address 0x%x, using 0x%x",
951             start, p->mmap_end);
952    }
953
954    // pick next address from our "mmap region"
955    start = p->mmap_end;
956    p->pTable->allocate(start, length);
957    p->mmap_end += length;
958
959    if (!(flags & OS::TGT_MAP_ANONYMOUS)) {
960        warn("allowing mmap of file @ fd %d. "
961             "This will break if not /dev/zero.", tc->getSyscallArg(4));
962    }
963
964    return start;
965}
966
967/// Target getrlimit() handler.
968template <class OS>
969SyscallReturn
970getrlimitFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
971        ThreadContext *tc)
972{
973    unsigned resource = tc->getSyscallArg(0);
974    TypedBufferArg<typename OS::rlimit> rlp(tc->getSyscallArg(1));
975
976    switch (resource) {
977        case OS::TGT_RLIMIT_STACK:
978            // max stack size in bytes: make up a number (8MB for now)
979            rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
980            rlp->rlim_cur = htog(rlp->rlim_cur);
981            rlp->rlim_max = htog(rlp->rlim_max);
982            break;
983
984        case OS::TGT_RLIMIT_DATA:
985            // max data segment size in bytes: make up a number
986            rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
987            rlp->rlim_cur = htog(rlp->rlim_cur);
988            rlp->rlim_max = htog(rlp->rlim_max);
989            break;
990
991        default:
992            std::cerr << "getrlimitFunc: unimplemented resource " << resource
993                << std::endl;
994            abort();
995            break;
996    }
997
998    rlp.copyOut(tc->getMemPort());
999    return 0;
1000}
1001
1002/// Target gettimeofday() handler.
1003template <class OS>
1004SyscallReturn
1005gettimeofdayFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1006        ThreadContext *tc)
1007{
1008    TypedBufferArg<typename OS::timeval> tp(tc->getSyscallArg(0));
1009
1010    getElapsedTime(tp->tv_sec, tp->tv_usec);
1011    tp->tv_sec += seconds_since_epoch;
1012    tp->tv_sec = htog(tp->tv_sec);
1013    tp->tv_usec = htog(tp->tv_usec);
1014
1015    tp.copyOut(tc->getMemPort());
1016
1017    return 0;
1018}
1019
1020
1021/// Target utimes() handler.
1022template <class OS>
1023SyscallReturn
1024utimesFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1025           ThreadContext *tc)
1026{
1027    std::string path;
1028
1029    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
1030      return -EFAULT;
1031
1032    TypedBufferArg<typename OS::timeval [2]> tp(tc->getSyscallArg(1));
1033    tp.copyIn(tc->getMemPort());
1034
1035    struct timeval hostTimeval[2];
1036    for (int i = 0; i < 2; ++i)
1037    {
1038        hostTimeval[i].tv_sec = gtoh((*tp)[i].tv_sec);
1039        hostTimeval[i].tv_usec = gtoh((*tp)[i].tv_usec);
1040    }
1041
1042    // Adjust path for current working directory
1043    path = process->fullPath(path);
1044
1045    int result = utimes(path.c_str(), hostTimeval);
1046
1047    if (result < 0)
1048        return -errno;
1049
1050    return 0;
1051}
1052/// Target getrusage() function.
1053template <class OS>
1054SyscallReturn
1055getrusageFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1056              ThreadContext *tc)
1057{
1058    int who = tc->getSyscallArg(0);     // THREAD, SELF, or CHILDREN
1059    TypedBufferArg<typename OS::rusage> rup(tc->getSyscallArg(1));
1060
1061    rup->ru_utime.tv_sec = 0;
1062    rup->ru_utime.tv_usec = 0;
1063    rup->ru_stime.tv_sec = 0;
1064    rup->ru_stime.tv_usec = 0;
1065    rup->ru_maxrss = 0;
1066    rup->ru_ixrss = 0;
1067    rup->ru_idrss = 0;
1068    rup->ru_isrss = 0;
1069    rup->ru_minflt = 0;
1070    rup->ru_majflt = 0;
1071    rup->ru_nswap = 0;
1072    rup->ru_inblock = 0;
1073    rup->ru_oublock = 0;
1074    rup->ru_msgsnd = 0;
1075    rup->ru_msgrcv = 0;
1076    rup->ru_nsignals = 0;
1077    rup->ru_nvcsw = 0;
1078    rup->ru_nivcsw = 0;
1079
1080    switch (who) {
1081      case OS::TGT_RUSAGE_SELF:
1082        getElapsedTime(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
1083        rup->ru_utime.tv_sec = htog(rup->ru_utime.tv_sec);
1084        rup->ru_utime.tv_usec = htog(rup->ru_utime.tv_usec);
1085        break;
1086
1087      case OS::TGT_RUSAGE_CHILDREN:
1088        // do nothing.  We have no child processes, so they take no time.
1089        break;
1090
1091      default:
1092        // don't really handle THREAD or CHILDREN, but just warn and
1093        // plow ahead
1094        warn("getrusage() only supports RUSAGE_SELF.  Parameter %d ignored.",
1095             who);
1096    }
1097
1098    rup.copyOut(tc->getMemPort());
1099
1100    return 0;
1101}
1102
1103
1104
1105
1106#endif // __SIM_SYSCALL_EMUL_HH__
1107