syscall_emul.hh revision 4118:ddd23e5282d7
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 obreak() handler: set brk address.
195SyscallReturn obreakFunc(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 unlink() handler.
227SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
228                         LiveProcess *p, ThreadContext *tc);
229
230/// Target rename() handler.
231SyscallReturn renameFunc(SyscallDesc *desc, int num,
232                         LiveProcess *p, ThreadContext *tc);
233
234
235/// Target truncate() handler.
236SyscallReturn truncateFunc(SyscallDesc *desc, int num,
237                           LiveProcess *p, ThreadContext *tc);
238
239
240/// Target ftruncate() handler.
241SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
242                            LiveProcess *p, ThreadContext *tc);
243
244
245/// Target chown() handler.
246SyscallReturn chownFunc(SyscallDesc *desc, int num,
247                        LiveProcess *p, ThreadContext *tc);
248
249
250/// Target fchown() handler.
251SyscallReturn fchownFunc(SyscallDesc *desc, int num,
252                         LiveProcess *p, ThreadContext *tc);
253
254/// Target dup() handler.
255SyscallReturn dupFunc(SyscallDesc *desc, int num,
256                      LiveProcess *process, ThreadContext *tc);
257
258/// Target fnctl() handler.
259SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
260                        LiveProcess *process, ThreadContext *tc);
261
262/// Target fcntl64() handler.
263SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
264                        LiveProcess *process, ThreadContext *tc);
265
266/// Target setuid() handler.
267SyscallReturn setuidFunc(SyscallDesc *desc, int num,
268                               LiveProcess *p, ThreadContext *tc);
269
270/// Target getpid() handler.
271SyscallReturn getpidFunc(SyscallDesc *desc, int num,
272                               LiveProcess *p, ThreadContext *tc);
273
274/// Target getuid() handler.
275SyscallReturn getuidFunc(SyscallDesc *desc, int num,
276                               LiveProcess *p, ThreadContext *tc);
277
278/// Target getgid() handler.
279SyscallReturn getgidFunc(SyscallDesc *desc, int num,
280                               LiveProcess *p, ThreadContext *tc);
281
282/// Target getppid() handler.
283SyscallReturn getppidFunc(SyscallDesc *desc, int num,
284                               LiveProcess *p, ThreadContext *tc);
285
286/// Target geteuid() handler.
287SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
288                               LiveProcess *p, ThreadContext *tc);
289
290/// Target getegid() handler.
291SyscallReturn getegidFunc(SyscallDesc *desc, int num,
292                               LiveProcess *p, ThreadContext *tc);
293
294
295
296/// Pseudo Funcs  - These functions use a different return convension,
297/// returning a second value in a register other than the normal return register
298SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
299                             LiveProcess *process, ThreadContext *tc);
300
301/// Target getpidPseudo() handler.
302SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
303                               LiveProcess *p, ThreadContext *tc);
304
305/// Target getuidPseudo() handler.
306SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
307                               LiveProcess *p, ThreadContext *tc);
308
309/// Target getgidPseudo() handler.
310SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
311                               LiveProcess *p, ThreadContext *tc);
312
313
314/// A readable name for 1,000,000, for converting microseconds to seconds.
315const int one_million = 1000000;
316
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.
320const unsigned seconds_since_epoch = 1000000000;
321
322/// Helper function to convert current elapsed time to seconds and
323/// microseconds.
324template <class T1, class T2>
325void
326getElapsedTime(T1 &sec, T2 &usec)
327{
328    int elapsed_usecs = curTick / Clock::Int::us;
329    sec = elapsed_usecs / one_million;
330    usec = elapsed_usecs % one_million;
331}
332
333//////////////////////////////////////////////////////////////////////
334//
335// The following emulation functions are generic, but need to be
336// templated to account for differences in types, constants, etc.
337//
338//////////////////////////////////////////////////////////////////////
339
340#if NO_STAT64
341    typedef struct stat hst_stat;
342    typedef struct stat hst_stat64;
343#else
344    typedef struct stat hst_stat;
345    typedef struct stat64 hst_stat64;
346#endif
347
348//// Helper function to convert a host stat buffer to a target stat
349//// buffer.  Also copies the target buffer out to the simulated
350//// memory space.  Used by stat(), fstat(), and lstat().
351
352template <typename target_stat, typename host_stat>
353static void
354convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
355{
356    if (fakeTTY)
357        tgt->st_dev = 0xA;
358    else
359        tgt->st_dev = host->st_dev;
360    tgt->st_dev = htog(tgt->st_dev);
361    tgt->st_ino = host->st_ino;
362    tgt->st_ino = htog(tgt->st_ino);
363    tgt->st_mode = host->st_mode;
364    tgt->st_mode = htog(tgt->st_mode);
365    tgt->st_nlink = host->st_nlink;
366    tgt->st_nlink = htog(tgt->st_nlink);
367    tgt->st_uid = host->st_uid;
368    tgt->st_uid = htog(tgt->st_uid);
369    tgt->st_gid = host->st_gid;
370    tgt->st_gid = htog(tgt->st_gid);
371    if (fakeTTY)
372        tgt->st_rdev = 0x880d;
373    else
374        tgt->st_rdev = host->st_rdev;
375    tgt->st_rdev = htog(tgt->st_rdev);
376    tgt->st_size = host->st_size;
377    tgt->st_size = htog(tgt->st_size);
378    tgt->st_atimeX = host->st_atime;
379    tgt->st_atimeX = htog(tgt->st_atimeX);
380    tgt->st_mtimeX = host->st_mtime;
381    tgt->st_mtimeX = htog(tgt->st_mtimeX);
382    tgt->st_ctimeX = host->st_ctime;
383    tgt->st_ctimeX = htog(tgt->st_ctimeX);
384    // Force the block size to be 8k. This helps to ensure buffered io works
385    // consistently across different hosts.
386    tgt->st_blksize = 0x2000;
387    tgt->st_blksize = htog(tgt->st_blksize);
388    tgt->st_blocks = host->st_blocks;
389    tgt->st_blocks = htog(tgt->st_blocks);
390}
391
392// Same for stat64
393
394template <typename target_stat, typename host_stat64>
395static void
396convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
397{
398    convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
399#if defined(STAT_HAVE_NSEC)
400    tgt->st_atime_nsec = host->st_atime_nsec;
401    tgt->st_atime_nsec = htog(tgt->st_atime_nsec);
402    tgt->st_mtime_nsec = host->st_mtime_nsec;
403    tgt->st_mtime_nsec = htog(tgt->st_mtime_nsec);
404    tgt->st_ctime_nsec = host->st_ctime_nsec;
405    tgt->st_ctime_nsec = htog(tgt->st_ctime_nsec);
406#else
407    tgt->st_atime_nsec = 0;
408    tgt->st_mtime_nsec = 0;
409    tgt->st_ctime_nsec = 0;
410#endif
411}
412
413//Here are a couple convenience functions
414template<class OS>
415static void
416copyOutStatBuf(TranslatingPort * mem, Addr addr,
417        hst_stat *host, bool fakeTTY = false)
418{
419    typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
420    tgt_stat_buf tgt(addr);
421    convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
422    tgt.copyOut(mem);
423}
424
425template<class OS>
426static void
427copyOutStat64Buf(TranslatingPort * mem, Addr addr,
428        hst_stat64 *host, bool fakeTTY = false)
429{
430    typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
431    tgt_stat_buf tgt(addr);
432    convertStatBuf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
433    tgt.copyOut(mem);
434}
435
436/// Target ioctl() handler.  For the most part, programs call ioctl()
437/// only to find out if their stdout is a tty, to determine whether to
438/// do line or block buffering.
439template <class OS>
440SyscallReturn
441ioctlFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
442          ThreadContext *tc)
443{
444    int fd = tc->getSyscallArg(0);
445    unsigned req = tc->getSyscallArg(1);
446
447    DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", fd, req);
448
449    if (fd < 0 || process->sim_fd(fd) < 0) {
450        // doesn't map to any simulator fd: not a valid target fd
451        return -EBADF;
452    }
453
454    switch (req) {
455      case OS::TIOCISATTY:
456      case OS::TIOCGETP:
457      case OS::TIOCSETP:
458      case OS::TIOCSETN:
459      case OS::TIOCSETC:
460      case OS::TIOCGETC:
461      case OS::TIOCGETS:
462      case OS::TIOCGETA:
463        return -ENOTTY;
464
465      default:
466        fatal("Unsupported ioctl call: ioctl(%d, 0x%x, ...) @ 0x%llx\n",
467              fd, req, tc->readPC());
468    }
469}
470
471/// Target open() handler.
472template <class OS>
473SyscallReturn
474openFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
475         ThreadContext *tc)
476{
477    std::string path;
478
479    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
480        return -EFAULT;
481
482    if (path == "/dev/sysdev0") {
483        // This is a memory-mapped high-resolution timer device on Alpha.
484        // We don't support it, so just punt.
485        warn("Ignoring open(%s, ...)\n", path);
486        return -ENOENT;
487    }
488
489    int tgtFlags = tc->getSyscallArg(1);
490    int mode = tc->getSyscallArg(2);
491    int hostFlags = 0;
492
493    // translate open flags
494    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
495        if (tgtFlags & OS::openFlagTable[i].tgtFlag) {
496            tgtFlags &= ~OS::openFlagTable[i].tgtFlag;
497            hostFlags |= OS::openFlagTable[i].hostFlag;
498        }
499    }
500
501    // any target flags left?
502    if (tgtFlags != 0)
503        warn("Syscall: open: cannot decode flags 0x%x", tgtFlags);
504
505#ifdef __CYGWIN32__
506    hostFlags |= O_BINARY;
507#endif
508
509    // Adjust path for current working directory
510    path = process->fullPath(path);
511
512    DPRINTF(SyscallVerbose, "opening file %s\n", path.c_str());
513
514    // open the file
515    int fd = open(path.c_str(), hostFlags, mode);
516
517    return (fd == -1) ? -errno : process->alloc_fd(fd);
518}
519
520
521/// Target chmod() handler.
522template <class OS>
523SyscallReturn
524chmodFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
525          ThreadContext *tc)
526{
527    std::string path;
528
529    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
530        return -EFAULT;
531
532    uint32_t mode = tc->getSyscallArg(1);
533    mode_t hostMode = 0;
534
535    // XXX translate mode flags via OS::something???
536    hostMode = mode;
537
538    // Adjust path for current working directory
539    path = process->fullPath(path);
540
541    // do the chmod
542    int result = chmod(path.c_str(), hostMode);
543    if (result < 0)
544        return -errno;
545
546    return 0;
547}
548
549
550/// Target fchmod() handler.
551template <class OS>
552SyscallReturn
553fchmodFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
554           ThreadContext *tc)
555{
556    int fd = tc->getSyscallArg(0);
557    if (fd < 0 || process->sim_fd(fd) < 0) {
558        // doesn't map to any simulator fd: not a valid target fd
559        return -EBADF;
560    }
561
562    uint32_t mode = tc->getSyscallArg(1);
563    mode_t hostMode = 0;
564
565    // XXX translate mode flags via OS::someting???
566    hostMode = mode;
567
568    // do the fchmod
569    int result = fchmod(process->sim_fd(fd), hostMode);
570    if (result < 0)
571        return -errno;
572
573    return 0;
574}
575
576
577/// Target stat() handler.
578template <class OS>
579SyscallReturn
580statFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
581         ThreadContext *tc)
582{
583    std::string path;
584
585    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
586    return -EFAULT;
587
588    // Adjust path for current working directory
589    path = process->fullPath(path);
590
591    struct stat hostBuf;
592    int result = stat(path.c_str(), &hostBuf);
593
594    if (result < 0)
595        return -errno;
596
597    copyOutStatBuf<OS>(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
598
599    return 0;
600}
601
602
603/// Target fstat64() handler.
604template <class OS>
605SyscallReturn
606fstat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
607            ThreadContext *tc)
608{
609    int fd = tc->getSyscallArg(0);
610    if (fd < 0 || process->sim_fd(fd) < 0) {
611        // doesn't map to any simulator fd: not a valid target fd
612        return -EBADF;
613    }
614
615#if NO_STAT64
616    struct stat  hostBuf;
617    int result = fstat(process->sim_fd(fd), &hostBuf);
618#else
619    struct stat64  hostBuf;
620    int result = fstat64(process->sim_fd(fd), &hostBuf);
621#endif
622
623    if (result < 0)
624        return -errno;
625
626    copyOutStat64Buf<OS>(tc->getMemPort(), tc->getSyscallArg(1),
627        &hostBuf, (fd == 1));
628
629    return 0;
630}
631
632
633/// Target lstat() handler.
634template <class OS>
635SyscallReturn
636lstatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
637          ThreadContext *tc)
638{
639    std::string path;
640
641    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
642      return -EFAULT;
643
644    // Adjust path for current working directory
645    path = process->fullPath(path);
646
647    struct stat hostBuf;
648    int result = lstat(path.c_str(), &hostBuf);
649
650    if (result < 0)
651        return -errno;
652
653    copyOutStatBuf<OS>(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
654
655    return 0;
656}
657
658/// Target lstat64() handler.
659template <class OS>
660SyscallReturn
661lstat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
662            ThreadContext *tc)
663{
664    std::string path;
665
666    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
667      return -EFAULT;
668
669    // Adjust path for current working directory
670    path = process->fullPath(path);
671
672#if NO_STAT64
673    struct stat hostBuf;
674    int result = lstat(path.c_str(), &hostBuf);
675#else
676    struct stat64 hostBuf;
677    int result = lstat64(path.c_str(), &hostBuf);
678#endif
679
680    if (result < 0)
681        return -errno;
682
683    copyOutStat64Buf<OS>(tc->getMemPort(), tc->getSyscallArg(1), &hostBuf);
684
685    return 0;
686}
687
688/// Target fstat() handler.
689template <class OS>
690SyscallReturn
691fstatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
692          ThreadContext *tc)
693{
694    int fd = process->sim_fd(tc->getSyscallArg(0));
695
696    DPRINTF(SyscallVerbose, "fstat(%d, ...)\n", fd);
697
698    if (fd < 0)
699        return -EBADF;
700
701    struct stat hostBuf;
702    int result = fstat(fd, &hostBuf);
703
704    if (result < 0)
705        return -errno;
706
707    copyOutStatBuf<OS>(tc->getMemPort(), tc->getSyscallArg(1),
708        &hostBuf, (fd == 1));
709
710    return 0;
711}
712
713
714/// Target statfs() handler.
715template <class OS>
716SyscallReturn
717statfsFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
718           ThreadContext *tc)
719{
720    std::string path;
721
722    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
723      return -EFAULT;
724
725    // Adjust path for current working directory
726    path = process->fullPath(path);
727
728    struct statfs hostBuf;
729    int result = statfs(path.c_str(), &hostBuf);
730
731    if (result < 0)
732        return -errno;
733
734    OS::copyOutStatfsBuf(tc->getMemPort(),
735            (Addr)(tc->getSyscallArg(1)), &hostBuf);
736
737    return 0;
738}
739
740
741/// Target fstatfs() handler.
742template <class OS>
743SyscallReturn
744fstatfsFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
745            ThreadContext *tc)
746{
747    int fd = process->sim_fd(tc->getSyscallArg(0));
748
749    if (fd < 0)
750        return -EBADF;
751
752    struct statfs hostBuf;
753    int result = fstatfs(fd, &hostBuf);
754
755    if (result < 0)
756        return -errno;
757
758    OS::copyOutStatfsBuf(tc->getMemPort(), tc->getSyscallArg(1),
759        &hostBuf);
760
761    return 0;
762}
763
764
765/// Target writev() handler.
766template <class OS>
767SyscallReturn
768writevFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
769           ThreadContext *tc)
770{
771    int fd = tc->getSyscallArg(0);
772    if (fd < 0 || process->sim_fd(fd) < 0) {
773        // doesn't map to any simulator fd: not a valid target fd
774        return -EBADF;
775    }
776
777    TranslatingPort *p = tc->getMemPort();
778    uint64_t tiov_base = tc->getSyscallArg(1);
779    size_t count = tc->getSyscallArg(2);
780    struct iovec hiov[count];
781    for (int i = 0; i < count; ++i)
782    {
783        typename OS::tgt_iovec tiov;
784
785        p->readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
786                    (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
787        hiov[i].iov_len = gtoh(tiov.iov_len);
788        hiov[i].iov_base = new char [hiov[i].iov_len];
789        p->readBlob(gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
790                    hiov[i].iov_len);
791    }
792
793    int result = writev(process->sim_fd(fd), hiov, count);
794
795    for (int i = 0; i < count; ++i)
796    {
797        delete [] (char *)hiov[i].iov_base;
798    }
799
800    if (result < 0)
801        return -errno;
802
803    return 0;
804}
805
806
807/// Target mmap() handler.
808///
809/// We don't really handle mmap().  If the target is mmaping an
810/// anonymous region or /dev/zero, we can get away with doing basically
811/// nothing (since memory is initialized to zero and the simulator
812/// doesn't really check addresses anyway).  Always print a warning,
813/// since this could be seriously broken if we're not mapping
814/// /dev/zero.
815//
816/// Someday we should explicitly check for /dev/zero in open, flag the
817/// file descriptor, and fail (or implement!) a non-anonymous mmap to
818/// anything else.
819template <class OS>
820SyscallReturn
821mmapFunc(SyscallDesc *desc, int num, LiveProcess *p, ThreadContext *tc)
822{
823    Addr start = tc->getSyscallArg(0);
824    uint64_t length = tc->getSyscallArg(1);
825    // int prot = tc->getSyscallArg(2);
826    int flags = tc->getSyscallArg(3);
827    // int fd = p->sim_fd(tc->getSyscallArg(4));
828    // int offset = tc->getSyscallArg(5);
829
830    if ((start  % TheISA::VMPageSize) != 0 ||
831        (length % TheISA::VMPageSize) != 0) {
832        warn("mmap failing: arguments not page-aligned: "
833             "start 0x%x length 0x%x",
834             start, length);
835        return -EINVAL;
836    }
837
838    if (start != 0) {
839        warn("mmap: ignoring suggested map address 0x%x, using 0x%x",
840             start, p->mmap_end);
841    }
842
843    // pick next address from our "mmap region"
844    start = p->mmap_end;
845    p->pTable->allocate(start, length);
846    p->mmap_end += length;
847
848    if (!(flags & OS::TGT_MAP_ANONYMOUS)) {
849        warn("allowing mmap of file @ fd %d. "
850             "This will break if not /dev/zero.", tc->getSyscallArg(4));
851    }
852
853    return start;
854}
855
856/// Target getrlimit() handler.
857template <class OS>
858SyscallReturn
859getrlimitFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
860        ThreadContext *tc)
861{
862    unsigned resource = tc->getSyscallArg(0);
863    TypedBufferArg<typename OS::rlimit> rlp(tc->getSyscallArg(1));
864
865    switch (resource) {
866        case OS::TGT_RLIMIT_STACK:
867            // max stack size in bytes: make up a number (2MB for now)
868            rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
869            rlp->rlim_cur = htog(rlp->rlim_cur);
870            rlp->rlim_max = htog(rlp->rlim_max);
871            break;
872
873        default:
874            std::cerr << "getrlimitFunc: unimplemented resource " << resource
875                << std::endl;
876            abort();
877            break;
878    }
879
880    rlp.copyOut(tc->getMemPort());
881    return 0;
882}
883
884/// Target gettimeofday() handler.
885template <class OS>
886SyscallReturn
887gettimeofdayFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
888        ThreadContext *tc)
889{
890    TypedBufferArg<typename OS::timeval> tp(tc->getSyscallArg(0));
891
892    getElapsedTime(tp->tv_sec, tp->tv_usec);
893    tp->tv_sec += seconds_since_epoch;
894    tp->tv_sec = htog(tp->tv_sec);
895    tp->tv_usec = htog(tp->tv_usec);
896
897    tp.copyOut(tc->getMemPort());
898
899    return 0;
900}
901
902
903/// Target utimes() handler.
904template <class OS>
905SyscallReturn
906utimesFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
907           ThreadContext *tc)
908{
909    std::string path;
910
911    if (!tc->getMemPort()->tryReadString(path, tc->getSyscallArg(0)))
912      return -EFAULT;
913
914    TypedBufferArg<typename OS::timeval [2]> tp(tc->getSyscallArg(1));
915    tp.copyIn(tc->getMemPort());
916
917    struct timeval hostTimeval[2];
918    for (int i = 0; i < 2; ++i)
919    {
920        hostTimeval[i].tv_sec = gtoh((*tp)[i].tv_sec);
921        hostTimeval[i].tv_usec = gtoh((*tp)[i].tv_usec);
922    }
923
924    // Adjust path for current working directory
925    path = process->fullPath(path);
926
927    int result = utimes(path.c_str(), hostTimeval);
928
929    if (result < 0)
930        return -errno;
931
932    return 0;
933}
934/// Target getrusage() function.
935template <class OS>
936SyscallReturn
937getrusageFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
938              ThreadContext *tc)
939{
940    int who = tc->getSyscallArg(0);	// THREAD, SELF, or CHILDREN
941    TypedBufferArg<typename OS::rusage> rup(tc->getSyscallArg(1));
942
943    rup->ru_utime.tv_sec = 0;
944    rup->ru_utime.tv_usec = 0;
945    rup->ru_stime.tv_sec = 0;
946    rup->ru_stime.tv_usec = 0;
947    rup->ru_maxrss = 0;
948    rup->ru_ixrss = 0;
949    rup->ru_idrss = 0;
950    rup->ru_isrss = 0;
951    rup->ru_minflt = 0;
952    rup->ru_majflt = 0;
953    rup->ru_nswap = 0;
954    rup->ru_inblock = 0;
955    rup->ru_oublock = 0;
956    rup->ru_msgsnd = 0;
957    rup->ru_msgrcv = 0;
958    rup->ru_nsignals = 0;
959    rup->ru_nvcsw = 0;
960    rup->ru_nivcsw = 0;
961
962    switch (who) {
963      case OS::TGT_RUSAGE_SELF:
964        getElapsedTime(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
965        rup->ru_utime.tv_sec = htog(rup->ru_utime.tv_sec);
966        rup->ru_utime.tv_usec = htog(rup->ru_utime.tv_usec);
967        break;
968
969      case OS::TGT_RUSAGE_CHILDREN:
970        // do nothing.  We have no child processes, so they take no time.
971        break;
972
973      default:
974        // don't really handle THREAD or CHILDREN, but just warn and
975        // plow ahead
976        warn("getrusage() only supports RUSAGE_SELF.  Parameter %d ignored.",
977             who);
978    }
979
980    rup.copyOut(tc->getMemPort());
981
982    return 0;
983}
984
985
986
987
988#endif // __SIM_SYSCALL_EMUL_HH__
989