syscall_emul.hh revision 9141
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#ifdef __CYGWIN32__
45#include <sys/fcntl.h>  // for O_BINARY
46#endif
47#include <sys/stat.h>
48#include <sys/time.h>
49#include <sys/uio.h>
50#include <fcntl.h>
51
52#include <cerrno>
53#include <string>
54
55#include "base/chunk_generator.hh"
56#include "base/intmath.hh"      // for RoundUp
57#include "base/misc.hh"
58#include "base/trace.hh"
59#include "base/types.hh"
60#include "config/the_isa.hh"
61#include "cpu/base.hh"
62#include "cpu/thread_context.hh"
63#include "debug/SyscallVerbose.hh"
64#include "mem/page_table.hh"
65#include "mem/se_translating_port_proxy.hh"
66#include "sim/byteswap.hh"
67#include "sim/process.hh"
68#include "sim/syscallreturn.hh"
69#include "sim/system.hh"
70
71///
72/// System call descriptor.
73///
74class SyscallDesc {
75
76  public:
77
78    /// Typedef for target syscall handler functions.
79    typedef SyscallReturn (*FuncPtr)(SyscallDesc *, int num,
80                           LiveProcess *, ThreadContext *);
81
82    const char *name;   //!< Syscall name (e.g., "open").
83    FuncPtr funcPtr;    //!< Pointer to emulation function.
84    int flags;          //!< Flags (see Flags enum).
85
86    /// Flag values for controlling syscall behavior.
87    enum Flags {
88        /// Don't set return regs according to funcPtr return value.
89        /// Used for syscalls with non-standard return conventions
90        /// that explicitly set the ThreadContext regs (e.g.,
91        /// sigreturn).
92        SuppressReturnValue = 1
93    };
94
95    /// Constructor.
96    SyscallDesc(const char *_name, FuncPtr _funcPtr, int _flags = 0)
97        : name(_name), funcPtr(_funcPtr), flags(_flags)
98    {
99    }
100
101    /// Emulate the syscall.  Public interface for calling through funcPtr.
102    void doSyscall(int callnum, LiveProcess *proc, ThreadContext *tc);
103};
104
105
106class BaseBufferArg {
107
108  public:
109
110    BaseBufferArg(Addr _addr, int _size) : addr(_addr), size(_size)
111    {
112        bufPtr = new uint8_t[size];
113        // clear out buffer: in case we only partially populate this,
114        // and then do a copyOut(), we want to make sure we don't
115        // introduce any random junk into the simulated address space
116        memset(bufPtr, 0, size);
117    }
118
119    virtual ~BaseBufferArg() { delete [] bufPtr; }
120
121    //
122    // copy data into simulator space (read from target memory)
123    //
124    virtual bool copyIn(SETranslatingPortProxy &memproxy)
125    {
126        memproxy.readBlob(addr, bufPtr, size);
127        return true;    // no EFAULT detection for now
128    }
129
130    //
131    // copy data out of simulator space (write to target memory)
132    //
133    virtual bool copyOut(SETranslatingPortProxy &memproxy)
134    {
135        memproxy.writeBlob(addr, bufPtr, size);
136        return true;    // no EFAULT detection for now
137    }
138
139  protected:
140    Addr addr;
141    int size;
142    uint8_t *bufPtr;
143};
144
145
146class BufferArg : public BaseBufferArg
147{
148  public:
149    BufferArg(Addr _addr, int _size) : BaseBufferArg(_addr, _size) { }
150    void *bufferPtr()   { return bufPtr; }
151};
152
153template <class T>
154class TypedBufferArg : public BaseBufferArg
155{
156  public:
157    // user can optionally specify a specific number of bytes to
158    // allocate to deal with those structs that have variable-size
159    // arrays at the end
160    TypedBufferArg(Addr _addr, int _size = sizeof(T))
161        : BaseBufferArg(_addr, _size)
162    { }
163
164    // type case
165    operator T*() { return (T *)bufPtr; }
166
167    // dereference operators
168    T &operator*()       { return *((T *)bufPtr); }
169    T* operator->()      { return (T *)bufPtr; }
170    T &operator[](int i) { return ((T *)bufPtr)[i]; }
171};
172
173//////////////////////////////////////////////////////////////////////
174//
175// The following emulation functions are generic enough that they
176// don't need to be recompiled for different emulated OS's.  They are
177// defined in sim/syscall_emul.cc.
178//
179//////////////////////////////////////////////////////////////////////
180
181
182/// Handler for unimplemented syscalls that we haven't thought about.
183SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
184                                LiveProcess *p, ThreadContext *tc);
185
186/// Handler for unimplemented syscalls that we never intend to
187/// implement (signal handling, etc.) and should not affect the correct
188/// behavior of the program.  Print a warning only if the appropriate
189/// trace flag is enabled.  Return success to the target program.
190SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
191                         LiveProcess *p, ThreadContext *tc);
192SyscallReturn ignoreWarnOnceFunc(SyscallDesc *desc, int num,
193                         LiveProcess *p, ThreadContext *tc);
194
195/// Target exit() handler: terminate current context.
196SyscallReturn exitFunc(SyscallDesc *desc, int num,
197                       LiveProcess *p, ThreadContext *tc);
198
199/// Target exit_group() handler: terminate simulation. (exit all threads)
200SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
201                       LiveProcess *p, ThreadContext *tc);
202
203/// Target getpagesize() handler.
204SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
205                              LiveProcess *p, ThreadContext *tc);
206
207/// Target brk() handler: set brk address.
208SyscallReturn brkFunc(SyscallDesc *desc, int num,
209                      LiveProcess *p, ThreadContext *tc);
210
211/// Target close() handler.
212SyscallReturn closeFunc(SyscallDesc *desc, int num,
213                        LiveProcess *p, ThreadContext *tc);
214
215/// Target read() handler.
216SyscallReturn readFunc(SyscallDesc *desc, int num,
217                       LiveProcess *p, ThreadContext *tc);
218
219/// Target write() handler.
220SyscallReturn writeFunc(SyscallDesc *desc, int num,
221                        LiveProcess *p, ThreadContext *tc);
222
223/// Target lseek() handler.
224SyscallReturn lseekFunc(SyscallDesc *desc, int num,
225                        LiveProcess *p, ThreadContext *tc);
226
227/// Target _llseek() handler.
228SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
229                        LiveProcess *p, ThreadContext *tc);
230
231/// Target munmap() handler.
232SyscallReturn munmapFunc(SyscallDesc *desc, int num,
233                         LiveProcess *p, ThreadContext *tc);
234
235/// Target gethostname() handler.
236SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
237                              LiveProcess *p, ThreadContext *tc);
238
239/// Target getcwd() handler.
240SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
241                         LiveProcess *p, ThreadContext *tc);
242
243/// Target unlink() handler.
244SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
245                           LiveProcess *p, ThreadContext *tc);
246
247/// Target unlink() handler.
248SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
249                         LiveProcess *p, ThreadContext *tc);
250
251/// Target mkdir() handler.
252SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
253                        LiveProcess *p, ThreadContext *tc);
254
255/// Target rename() handler.
256SyscallReturn renameFunc(SyscallDesc *desc, int num,
257                         LiveProcess *p, ThreadContext *tc);
258
259
260/// Target truncate() handler.
261SyscallReturn truncateFunc(SyscallDesc *desc, int num,
262                           LiveProcess *p, ThreadContext *tc);
263
264
265/// Target ftruncate() handler.
266SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
267                            LiveProcess *p, ThreadContext *tc);
268
269
270/// Target truncate64() handler.
271SyscallReturn truncate64Func(SyscallDesc *desc, int num,
272                             LiveProcess *p, ThreadContext *tc);
273
274/// Target ftruncate64() handler.
275SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
276                              LiveProcess *p, ThreadContext *tc);
277
278
279/// Target umask() handler.
280SyscallReturn umaskFunc(SyscallDesc *desc, int num,
281                        LiveProcess *p, ThreadContext *tc);
282
283
284/// Target chown() handler.
285SyscallReturn chownFunc(SyscallDesc *desc, int num,
286                        LiveProcess *p, ThreadContext *tc);
287
288
289/// Target fchown() handler.
290SyscallReturn fchownFunc(SyscallDesc *desc, int num,
291                         LiveProcess *p, ThreadContext *tc);
292
293/// Target dup() handler.
294SyscallReturn dupFunc(SyscallDesc *desc, int num,
295                      LiveProcess *process, ThreadContext *tc);
296
297/// Target fnctl() handler.
298SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
299                        LiveProcess *process, ThreadContext *tc);
300
301/// Target fcntl64() handler.
302SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
303                        LiveProcess *process, ThreadContext *tc);
304
305/// Target setuid() handler.
306SyscallReturn setuidFunc(SyscallDesc *desc, int num,
307                               LiveProcess *p, ThreadContext *tc);
308
309/// Target getpid() handler.
310SyscallReturn getpidFunc(SyscallDesc *desc, int num,
311                               LiveProcess *p, ThreadContext *tc);
312
313/// Target getuid() handler.
314SyscallReturn getuidFunc(SyscallDesc *desc, int num,
315                               LiveProcess *p, ThreadContext *tc);
316
317/// Target getgid() handler.
318SyscallReturn getgidFunc(SyscallDesc *desc, int num,
319                               LiveProcess *p, ThreadContext *tc);
320
321/// Target getppid() handler.
322SyscallReturn getppidFunc(SyscallDesc *desc, int num,
323                               LiveProcess *p, ThreadContext *tc);
324
325/// Target geteuid() handler.
326SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
327                               LiveProcess *p, ThreadContext *tc);
328
329/// Target getegid() handler.
330SyscallReturn getegidFunc(SyscallDesc *desc, int num,
331                               LiveProcess *p, ThreadContext *tc);
332
333/// Target clone() handler.
334SyscallReturn cloneFunc(SyscallDesc *desc, int num,
335                               LiveProcess *p, ThreadContext *tc);
336
337/// Futex system call
338///  Implemented by Daniel Sanchez
339///  Used by printf's in multi-threaded apps
340template <class OS>
341SyscallReturn
342futexFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
343          ThreadContext *tc)
344{
345    int index_uaddr = 0;
346    int index_op = 1;
347    int index_val = 2;
348    int index_timeout = 3;
349
350    uint64_t uaddr = process->getSyscallArg(tc, index_uaddr);
351    int op = process->getSyscallArg(tc, index_op);
352    int val = process->getSyscallArg(tc, index_val);
353    uint64_t timeout = process->getSyscallArg(tc, index_timeout);
354
355    std::map<uint64_t, std::list<ThreadContext *> * >
356        &futex_map = tc->getSystemPtr()->futexMap;
357
358    DPRINTF(SyscallVerbose, "In sys_futex: Address=%llx, op=%d, val=%d\n",
359            uaddr, op, val);
360
361
362    if (op == OS::TGT_FUTEX_WAIT) {
363        if (timeout != 0) {
364            warn("sys_futex: FUTEX_WAIT with non-null timeout unimplemented;"
365                 "we'll wait indefinitely");
366        }
367
368        uint8_t *buf = new uint8_t[sizeof(int)];
369        tc->getMemProxy().readBlob((Addr)uaddr, buf, (int)sizeof(int));
370        int mem_val = *((int *)buf);
371        delete buf;
372
373        if(val != mem_val) {
374            DPRINTF(SyscallVerbose, "sys_futex: FUTEX_WAKE, read: %d, "
375                                    "expected: %d\n", mem_val, val);
376            return -OS::TGT_EWOULDBLOCK;
377        }
378
379        // Queue the thread context
380        std::list<ThreadContext *> * tcWaitList;
381        if (futex_map.count(uaddr)) {
382            tcWaitList = futex_map.find(uaddr)->second;
383        } else {
384            tcWaitList = new std::list<ThreadContext *>();
385            futex_map.insert(std::pair< uint64_t,
386                            std::list<ThreadContext *> * >(uaddr, tcWaitList));
387        }
388        tcWaitList->push_back(tc);
389        DPRINTF(SyscallVerbose, "sys_futex: FUTEX_WAIT, suspending calling "
390                                "thread context\n");
391        tc->suspend();
392        return 0;
393    } else if (op == OS::TGT_FUTEX_WAKE){
394        int wokenUp = 0;
395        std::list<ThreadContext *> * tcWaitList;
396        if (futex_map.count(uaddr)) {
397            tcWaitList = futex_map.find(uaddr)->second;
398            while (tcWaitList->size() > 0 && wokenUp < val) {
399                tcWaitList->front()->activate();
400                tcWaitList->pop_front();
401                wokenUp++;
402            }
403            if(tcWaitList->empty()) {
404                futex_map.erase(uaddr);
405                delete tcWaitList;
406            }
407        }
408        DPRINTF(SyscallVerbose, "sys_futex: FUTEX_WAKE, activated %d waiting "
409                                "thread contexts\n", wokenUp);
410        return wokenUp;
411    } else {
412        warn("sys_futex: op %d is not implemented, just returning...");
413        return 0;
414    }
415
416}
417
418
419/// Pseudo Funcs  - These functions use a different return convension,
420/// returning a second value in a register other than the normal return register
421SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
422                             LiveProcess *process, ThreadContext *tc);
423
424/// Target getpidPseudo() handler.
425SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
426                               LiveProcess *p, ThreadContext *tc);
427
428/// Target getuidPseudo() handler.
429SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
430                               LiveProcess *p, ThreadContext *tc);
431
432/// Target getgidPseudo() handler.
433SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
434                               LiveProcess *p, ThreadContext *tc);
435
436
437/// A readable name for 1,000,000, for converting microseconds to seconds.
438const int one_million = 1000000;
439
440/// Approximate seconds since the epoch (1/1/1970).  About a billion,
441/// by my reckoning.  We want to keep this a constant (not use the
442/// real-world time) to keep simulations repeatable.
443const unsigned seconds_since_epoch = 1000000000;
444
445/// Helper function to convert current elapsed time to seconds and
446/// microseconds.
447template <class T1, class T2>
448void
449getElapsedTime(T1 &sec, T2 &usec)
450{
451    int elapsed_usecs = curTick() / SimClock::Int::us;
452    sec = elapsed_usecs / one_million;
453    usec = elapsed_usecs % one_million;
454}
455
456//////////////////////////////////////////////////////////////////////
457//
458// The following emulation functions are generic, but need to be
459// templated to account for differences in types, constants, etc.
460//
461//////////////////////////////////////////////////////////////////////
462
463#if NO_STAT64
464    typedef struct stat hst_stat;
465    typedef struct stat hst_stat64;
466#else
467    typedef struct stat hst_stat;
468    typedef struct stat64 hst_stat64;
469#endif
470
471//// Helper function to convert a host stat buffer to a target stat
472//// buffer.  Also copies the target buffer out to the simulated
473//// memory space.  Used by stat(), fstat(), and lstat().
474
475template <typename target_stat, typename host_stat>
476static void
477convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
478{
479    using namespace TheISA;
480
481    if (fakeTTY)
482        tgt->st_dev = 0xA;
483    else
484        tgt->st_dev = host->st_dev;
485    tgt->st_dev = TheISA::htog(tgt->st_dev);
486    tgt->st_ino = host->st_ino;
487    tgt->st_ino = TheISA::htog(tgt->st_ino);
488    tgt->st_mode = host->st_mode;
489    if (fakeTTY) {
490        // Claim to be a character device
491        tgt->st_mode &= ~S_IFMT;    // Clear S_IFMT
492        tgt->st_mode |= S_IFCHR;    // Set S_IFCHR
493    }
494    tgt->st_mode = TheISA::htog(tgt->st_mode);
495    tgt->st_nlink = host->st_nlink;
496    tgt->st_nlink = TheISA::htog(tgt->st_nlink);
497    tgt->st_uid = host->st_uid;
498    tgt->st_uid = TheISA::htog(tgt->st_uid);
499    tgt->st_gid = host->st_gid;
500    tgt->st_gid = TheISA::htog(tgt->st_gid);
501    if (fakeTTY)
502        tgt->st_rdev = 0x880d;
503    else
504        tgt->st_rdev = host->st_rdev;
505    tgt->st_rdev = TheISA::htog(tgt->st_rdev);
506    tgt->st_size = host->st_size;
507    tgt->st_size = TheISA::htog(tgt->st_size);
508    tgt->st_atimeX = host->st_atime;
509    tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
510    tgt->st_mtimeX = host->st_mtime;
511    tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
512    tgt->st_ctimeX = host->st_ctime;
513    tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
514    // Force the block size to be 8k. This helps to ensure buffered io works
515    // consistently across different hosts.
516    tgt->st_blksize = 0x2000;
517    tgt->st_blksize = TheISA::htog(tgt->st_blksize);
518    tgt->st_blocks = host->st_blocks;
519    tgt->st_blocks = TheISA::htog(tgt->st_blocks);
520}
521
522// Same for stat64
523
524template <typename target_stat, typename host_stat64>
525static void
526convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
527{
528    using namespace TheISA;
529
530    convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
531#if defined(STAT_HAVE_NSEC)
532    tgt->st_atime_nsec = host->st_atime_nsec;
533    tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
534    tgt->st_mtime_nsec = host->st_mtime_nsec;
535    tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
536    tgt->st_ctime_nsec = host->st_ctime_nsec;
537    tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
538#else
539    tgt->st_atime_nsec = 0;
540    tgt->st_mtime_nsec = 0;
541    tgt->st_ctime_nsec = 0;
542#endif
543}
544
545//Here are a couple convenience functions
546template<class OS>
547static void
548copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
549        hst_stat *host, bool fakeTTY = false)
550{
551    typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
552    tgt_stat_buf tgt(addr);
553    convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
554    tgt.copyOut(mem);
555}
556
557template<class OS>
558static void
559copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
560        hst_stat64 *host, bool fakeTTY = false)
561{
562    typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
563    tgt_stat_buf tgt(addr);
564    convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
565    tgt.copyOut(mem);
566}
567
568/// Target ioctl() handler.  For the most part, programs call ioctl()
569/// only to find out if their stdout is a tty, to determine whether to
570/// do line or block buffering.  We always claim that output fds are
571/// not TTYs to provide repeatable results.
572template <class OS>
573SyscallReturn
574ioctlFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
575          ThreadContext *tc)
576{
577    int index = 0;
578    int fd = process->getSyscallArg(tc, index);
579    unsigned req = process->getSyscallArg(tc, index);
580
581    DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", fd, req);
582
583    if (fd < 0 || process->sim_fd(fd) < 0) {
584        // doesn't map to any simulator fd: not a valid target fd
585        return -EBADF;
586    }
587
588    if (OS::isTtyReq(req)) {
589        return -ENOTTY;
590    }
591
592    warn("Unsupported ioctl call: ioctl(%d, 0x%x, ...) @ \n",
593         fd, req, tc->pcState());
594    return -ENOTTY;
595}
596
597/// Target open() handler.
598template <class OS>
599SyscallReturn
600openFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
601         ThreadContext *tc)
602{
603    std::string path;
604
605    int index = 0;
606    if (!tc->getMemProxy().tryReadString(path,
607                process->getSyscallArg(tc, index)))
608        return -EFAULT;
609
610    if (path == "/dev/sysdev0") {
611        // This is a memory-mapped high-resolution timer device on Alpha.
612        // We don't support it, so just punt.
613        warn("Ignoring open(%s, ...)\n", path);
614        return -ENOENT;
615    }
616
617    int tgtFlags = process->getSyscallArg(tc, index);
618    int mode = process->getSyscallArg(tc, index);
619    int hostFlags = 0;
620
621    // translate open flags
622    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
623        if (tgtFlags & OS::openFlagTable[i].tgtFlag) {
624            tgtFlags &= ~OS::openFlagTable[i].tgtFlag;
625            hostFlags |= OS::openFlagTable[i].hostFlag;
626        }
627    }
628
629    // any target flags left?
630    if (tgtFlags != 0)
631        warn("Syscall: open: cannot decode flags 0x%x", tgtFlags);
632
633#ifdef __CYGWIN32__
634    hostFlags |= O_BINARY;
635#endif
636
637    // Adjust path for current working directory
638    path = process->fullPath(path);
639
640    DPRINTF(SyscallVerbose, "opening file %s\n", path.c_str());
641
642    int fd;
643    if (!path.compare(0, 6, "/proc/") || !path.compare(0, 8, "/system/") ||
644        !path.compare(0, 10, "/platform/") || !path.compare(0, 5, "/sys/")) {
645        // It's a proc/sys entery and requires special handling
646        fd = OS::openSpecialFile(path, process, tc);
647        return (fd == -1) ? -1 : process->alloc_fd(fd,path.c_str(),hostFlags,mode, false);
648     } else {
649        // open the file
650        fd = open(path.c_str(), hostFlags, mode);
651        return (fd == -1) ? -errno : process->alloc_fd(fd,path.c_str(),hostFlags,mode, false);
652     }
653
654}
655
656/// Target sysinfo() handler.
657template <class OS>
658SyscallReturn
659sysinfoFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
660         ThreadContext *tc)
661{
662
663    int index = 0;
664    TypedBufferArg<typename OS::tgt_sysinfo>
665        sysinfo(process->getSyscallArg(tc, index));
666
667    sysinfo->uptime=seconds_since_epoch;
668    sysinfo->totalram=process->system->memSize();
669
670    sysinfo.copyOut(tc->getMemProxy());
671
672    return 0;
673}
674
675/// Target chmod() handler.
676template <class OS>
677SyscallReturn
678chmodFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
679          ThreadContext *tc)
680{
681    std::string path;
682
683    int index = 0;
684    if (!tc->getMemProxy().tryReadString(path,
685                process->getSyscallArg(tc, index))) {
686        return -EFAULT;
687    }
688
689    uint32_t mode = process->getSyscallArg(tc, index);
690    mode_t hostMode = 0;
691
692    // XXX translate mode flags via OS::something???
693    hostMode = mode;
694
695    // Adjust path for current working directory
696    path = process->fullPath(path);
697
698    // do the chmod
699    int result = chmod(path.c_str(), hostMode);
700    if (result < 0)
701        return -errno;
702
703    return 0;
704}
705
706
707/// Target fchmod() handler.
708template <class OS>
709SyscallReturn
710fchmodFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
711           ThreadContext *tc)
712{
713    int index = 0;
714    int fd = process->getSyscallArg(tc, index);
715    if (fd < 0 || process->sim_fd(fd) < 0) {
716        // doesn't map to any simulator fd: not a valid target fd
717        return -EBADF;
718    }
719
720    uint32_t mode = process->getSyscallArg(tc, index);
721    mode_t hostMode = 0;
722
723    // XXX translate mode flags via OS::someting???
724    hostMode = mode;
725
726    // do the fchmod
727    int result = fchmod(process->sim_fd(fd), hostMode);
728    if (result < 0)
729        return -errno;
730
731    return 0;
732}
733
734/// Target mremap() handler.
735template <class OS>
736SyscallReturn
737mremapFunc(SyscallDesc *desc, int callnum, LiveProcess *process, ThreadContext *tc)
738{
739    int index = 0;
740    Addr start = process->getSyscallArg(tc, index);
741    uint64_t old_length = process->getSyscallArg(tc, index);
742    uint64_t new_length = process->getSyscallArg(tc, index);
743    uint64_t flags = process->getSyscallArg(tc, index);
744
745    if ((start % TheISA::VMPageSize != 0) ||
746            (new_length % TheISA::VMPageSize != 0)) {
747        warn("mremap failing: arguments not page aligned");
748        return -EINVAL;
749    }
750
751    if (new_length > old_length) {
752        if ((start + old_length) == process->mmap_end) {
753            uint64_t diff = new_length - old_length;
754            process->allocateMem(process->mmap_end, diff);
755            process->mmap_end += diff;
756            return start;
757        } else {
758            // sys/mman.h defined MREMAP_MAYMOVE
759            if (!(flags & 1)) {
760                warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
761                return -ENOMEM;
762            } else {
763                process->pTable->remap(start, old_length, process->mmap_end);
764                warn("mremapping to totally new vaddr %08p-%08p, adding %d\n",
765                        process->mmap_end, process->mmap_end + new_length, new_length);
766                start = process->mmap_end;
767                // add on the remaining unallocated pages
768                process->allocateMem(start + old_length,
769                                     new_length - old_length);
770                process->mmap_end += new_length;
771                warn("returning %08p as start\n", start);
772                return start;
773            }
774        }
775    } else {
776        process->pTable->unmap(start + new_length, old_length - new_length);
777        return start;
778    }
779}
780
781/// Target stat() handler.
782template <class OS>
783SyscallReturn
784statFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
785         ThreadContext *tc)
786{
787    std::string path;
788
789    int index = 0;
790    if (!tc->getMemProxy().tryReadString(path,
791                process->getSyscallArg(tc, index))) {
792        return -EFAULT;
793    }
794    Addr bufPtr = process->getSyscallArg(tc, index);
795
796    // Adjust path for current working directory
797    path = process->fullPath(path);
798
799    struct stat hostBuf;
800    int result = stat(path.c_str(), &hostBuf);
801
802    if (result < 0)
803        return -errno;
804
805    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
806
807    return 0;
808}
809
810
811/// Target stat64() handler.
812template <class OS>
813SyscallReturn
814stat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
815           ThreadContext *tc)
816{
817    std::string path;
818
819    int index = 0;
820    if (!tc->getMemProxy().tryReadString(path,
821                process->getSyscallArg(tc, index)))
822        return -EFAULT;
823    Addr bufPtr = process->getSyscallArg(tc, index);
824
825    // Adjust path for current working directory
826    path = process->fullPath(path);
827
828#if NO_STAT64
829    struct stat  hostBuf;
830    int result = stat(path.c_str(), &hostBuf);
831#else
832    struct stat64 hostBuf;
833    int result = stat64(path.c_str(), &hostBuf);
834#endif
835
836    if (result < 0)
837        return -errno;
838
839    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
840
841    return 0;
842}
843
844
845/// Target fstat64() handler.
846template <class OS>
847SyscallReturn
848fstat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
849            ThreadContext *tc)
850{
851    int index = 0;
852    int fd = process->getSyscallArg(tc, index);
853    Addr bufPtr = process->getSyscallArg(tc, index);
854    if (fd < 0 || process->sim_fd(fd) < 0) {
855        // doesn't map to any simulator fd: not a valid target fd
856        return -EBADF;
857    }
858
859#if NO_STAT64
860    struct stat  hostBuf;
861    int result = fstat(process->sim_fd(fd), &hostBuf);
862#else
863    struct stat64  hostBuf;
864    int result = fstat64(process->sim_fd(fd), &hostBuf);
865#endif
866
867    if (result < 0)
868        return -errno;
869
870    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (fd == 1));
871
872    return 0;
873}
874
875
876/// Target lstat() handler.
877template <class OS>
878SyscallReturn
879lstatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
880          ThreadContext *tc)
881{
882    std::string path;
883
884    int index = 0;
885    if (!tc->getMemProxy().tryReadString(path,
886                process->getSyscallArg(tc, index))) {
887        return -EFAULT;
888    }
889    Addr bufPtr = process->getSyscallArg(tc, index);
890
891    // Adjust path for current working directory
892    path = process->fullPath(path);
893
894    struct stat hostBuf;
895    int result = lstat(path.c_str(), &hostBuf);
896
897    if (result < 0)
898        return -errno;
899
900    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
901
902    return 0;
903}
904
905/// Target lstat64() handler.
906template <class OS>
907SyscallReturn
908lstat64Func(SyscallDesc *desc, int callnum, LiveProcess *process,
909            ThreadContext *tc)
910{
911    std::string path;
912
913    int index = 0;
914    if (!tc->getMemProxy().tryReadString(path,
915                process->getSyscallArg(tc, index))) {
916        return -EFAULT;
917    }
918    Addr bufPtr = process->getSyscallArg(tc, index);
919
920    // Adjust path for current working directory
921    path = process->fullPath(path);
922
923#if NO_STAT64
924    struct stat hostBuf;
925    int result = lstat(path.c_str(), &hostBuf);
926#else
927    struct stat64 hostBuf;
928    int result = lstat64(path.c_str(), &hostBuf);
929#endif
930
931    if (result < 0)
932        return -errno;
933
934    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
935
936    return 0;
937}
938
939/// Target fstat() handler.
940template <class OS>
941SyscallReturn
942fstatFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
943          ThreadContext *tc)
944{
945    int index = 0;
946    int fd = process->sim_fd(process->getSyscallArg(tc, index));
947    Addr bufPtr = process->getSyscallArg(tc, index);
948
949    DPRINTF(SyscallVerbose, "fstat(%d, ...)\n", fd);
950
951    if (fd < 0)
952        return -EBADF;
953
954    struct stat hostBuf;
955    int result = fstat(fd, &hostBuf);
956
957    if (result < 0)
958        return -errno;
959
960    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (fd == 1));
961
962    return 0;
963}
964
965
966/// Target statfs() handler.
967template <class OS>
968SyscallReturn
969statfsFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
970           ThreadContext *tc)
971{
972    std::string path;
973
974    int index = 0;
975    if (!tc->getMemProxy().tryReadString(path,
976                process->getSyscallArg(tc, index))) {
977        return -EFAULT;
978    }
979    Addr bufPtr = process->getSyscallArg(tc, index);
980
981    // Adjust path for current working directory
982    path = process->fullPath(path);
983
984    struct statfs hostBuf;
985    int result = statfs(path.c_str(), &hostBuf);
986
987    if (result < 0)
988        return -errno;
989
990    OS::copyOutStatfsBuf(tc->getMemProxy(), bufPtr, &hostBuf);
991
992    return 0;
993}
994
995
996/// Target fstatfs() handler.
997template <class OS>
998SyscallReturn
999fstatfsFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1000            ThreadContext *tc)
1001{
1002    int index = 0;
1003    int fd = process->sim_fd(process->getSyscallArg(tc, index));
1004    Addr bufPtr = process->getSyscallArg(tc, index);
1005
1006    if (fd < 0)
1007        return -EBADF;
1008
1009    struct statfs hostBuf;
1010    int result = fstatfs(fd, &hostBuf);
1011
1012    if (result < 0)
1013        return -errno;
1014
1015    OS::copyOutStatfsBuf(tc->getMemProxy(), bufPtr, &hostBuf);
1016
1017    return 0;
1018}
1019
1020
1021/// Target writev() handler.
1022template <class OS>
1023SyscallReturn
1024writevFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1025           ThreadContext *tc)
1026{
1027    int index = 0;
1028    int fd = process->getSyscallArg(tc, index);
1029    if (fd < 0 || process->sim_fd(fd) < 0) {
1030        // doesn't map to any simulator fd: not a valid target fd
1031        return -EBADF;
1032    }
1033
1034    SETranslatingPortProxy &p = tc->getMemProxy();
1035    uint64_t tiov_base = process->getSyscallArg(tc, index);
1036    size_t count = process->getSyscallArg(tc, index);
1037    struct iovec hiov[count];
1038    for (size_t i = 0; i < count; ++i) {
1039        typename OS::tgt_iovec tiov;
1040
1041        p.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1042                   (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1043        hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1044        hiov[i].iov_base = new char [hiov[i].iov_len];
1045        p.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1046                   hiov[i].iov_len);
1047    }
1048
1049    int result = writev(process->sim_fd(fd), hiov, count);
1050
1051    for (size_t i = 0; i < count; ++i)
1052        delete [] (char *)hiov[i].iov_base;
1053
1054    if (result < 0)
1055        return -errno;
1056
1057    return 0;
1058}
1059
1060
1061/// Target mmap() handler.
1062///
1063/// We don't really handle mmap().  If the target is mmaping an
1064/// anonymous region or /dev/zero, we can get away with doing basically
1065/// nothing (since memory is initialized to zero and the simulator
1066/// doesn't really check addresses anyway).
1067///
1068template <class OS>
1069SyscallReturn
1070mmapFunc(SyscallDesc *desc, int num, LiveProcess *p, ThreadContext *tc)
1071{
1072    int index = 0;
1073    Addr start = p->getSyscallArg(tc, index);
1074    uint64_t length = p->getSyscallArg(tc, index);
1075    index++; // int prot = p->getSyscallArg(tc, index);
1076    int flags = p->getSyscallArg(tc, index);
1077    int tgt_fd = p->getSyscallArg(tc, index);
1078    // int offset = p->getSyscallArg(tc, index);
1079
1080    if (length > 0x100000000ULL)
1081        warn("mmap length argument %#x is unreasonably large.\n", length);
1082
1083    if (!(flags & OS::TGT_MAP_ANONYMOUS)) {
1084        Process::FdMap *fd_map = p->sim_fd_obj(tgt_fd);
1085        if (!fd_map || fd_map->fd < 0) {
1086            warn("mmap failing: target fd %d is not valid\n", tgt_fd);
1087            return -EBADF;
1088        }
1089
1090        if (fd_map->filename != "/dev/zero") {
1091            // This is very likely broken, but leave a warning here
1092            // (rather than panic) in case /dev/zero is known by
1093            // another name on some platform
1094            warn("allowing mmap of file %s; mmap not supported on files"
1095                 " other than /dev/zero\n", fd_map->filename);
1096        }
1097    }
1098
1099    if ((start  % TheISA::VMPageSize) != 0 ||
1100        (length % TheISA::VMPageSize) != 0) {
1101        warn("mmap failing: arguments not page-aligned: "
1102             "start 0x%x length 0x%x",
1103             start, length);
1104        return -EINVAL;
1105    }
1106
1107    // are we ok with clobbering existing mappings?  only set this to
1108    // true if the user has been warned.
1109    bool clobber = false;
1110
1111    // try to use the caller-provided address if there is one
1112    bool use_provided_address = (start != 0);
1113
1114    if (use_provided_address) {
1115        // check to see if the desired address is already in use
1116        if (!p->pTable->isUnmapped(start, length)) {
1117            // there are existing mappings in the desired range
1118            // whether we clobber them or not depends on whether the caller
1119            // specified MAP_FIXED
1120            if (flags & OS::TGT_MAP_FIXED) {
1121                // MAP_FIXED specified: clobber existing mappings
1122                warn("mmap: MAP_FIXED at 0x%x overwrites existing mappings\n",
1123                     start);
1124                clobber = true;
1125            } else {
1126                // MAP_FIXED not specified: ignore suggested start address
1127                warn("mmap: ignoring suggested map address 0x%x\n", start);
1128                use_provided_address = false;
1129            }
1130        }
1131    }
1132
1133    if (!use_provided_address) {
1134        // no address provided, or provided address unusable:
1135        // pick next address from our "mmap region"
1136        if (OS::mmapGrowsDown()) {
1137            start = p->mmap_end - length;
1138            p->mmap_end = start;
1139        } else {
1140            start = p->mmap_end;
1141            p->mmap_end += length;
1142        }
1143    }
1144
1145    p->allocateMem(start, length, clobber);
1146
1147    return start;
1148}
1149
1150/// Target getrlimit() handler.
1151template <class OS>
1152SyscallReturn
1153getrlimitFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1154        ThreadContext *tc)
1155{
1156    int index = 0;
1157    unsigned resource = process->getSyscallArg(tc, index);
1158    TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1159
1160    switch (resource) {
1161        case OS::TGT_RLIMIT_STACK:
1162            // max stack size in bytes: make up a number (8MB for now)
1163            rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1164            rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1165            rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1166            break;
1167
1168        case OS::TGT_RLIMIT_DATA:
1169            // max data segment size in bytes: make up a number
1170            rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1171            rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1172            rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1173            break;
1174
1175        default:
1176            std::cerr << "getrlimitFunc: unimplemented resource " << resource
1177                << std::endl;
1178            abort();
1179            break;
1180    }
1181
1182    rlp.copyOut(tc->getMemProxy());
1183    return 0;
1184}
1185
1186/// Target gettimeofday() handler.
1187template <class OS>
1188SyscallReturn
1189gettimeofdayFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1190        ThreadContext *tc)
1191{
1192    int index = 0;
1193    TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1194
1195    getElapsedTime(tp->tv_sec, tp->tv_usec);
1196    tp->tv_sec += seconds_since_epoch;
1197    tp->tv_sec = TheISA::htog(tp->tv_sec);
1198    tp->tv_usec = TheISA::htog(tp->tv_usec);
1199
1200    tp.copyOut(tc->getMemProxy());
1201
1202    return 0;
1203}
1204
1205
1206/// Target utimes() handler.
1207template <class OS>
1208SyscallReturn
1209utimesFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1210           ThreadContext *tc)
1211{
1212    std::string path;
1213
1214    int index = 0;
1215    if (!tc->getMemProxy().tryReadString(path,
1216                process->getSyscallArg(tc, index))) {
1217        return -EFAULT;
1218    }
1219
1220    TypedBufferArg<typename OS::timeval [2]>
1221        tp(process->getSyscallArg(tc, index));
1222    tp.copyIn(tc->getMemProxy());
1223
1224    struct timeval hostTimeval[2];
1225    for (int i = 0; i < 2; ++i)
1226    {
1227        hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1228        hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1229    }
1230
1231    // Adjust path for current working directory
1232    path = process->fullPath(path);
1233
1234    int result = utimes(path.c_str(), hostTimeval);
1235
1236    if (result < 0)
1237        return -errno;
1238
1239    return 0;
1240}
1241/// Target getrusage() function.
1242template <class OS>
1243SyscallReturn
1244getrusageFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1245              ThreadContext *tc)
1246{
1247    int index = 0;
1248    int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
1249    TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
1250
1251    rup->ru_utime.tv_sec = 0;
1252    rup->ru_utime.tv_usec = 0;
1253    rup->ru_stime.tv_sec = 0;
1254    rup->ru_stime.tv_usec = 0;
1255    rup->ru_maxrss = 0;
1256    rup->ru_ixrss = 0;
1257    rup->ru_idrss = 0;
1258    rup->ru_isrss = 0;
1259    rup->ru_minflt = 0;
1260    rup->ru_majflt = 0;
1261    rup->ru_nswap = 0;
1262    rup->ru_inblock = 0;
1263    rup->ru_oublock = 0;
1264    rup->ru_msgsnd = 0;
1265    rup->ru_msgrcv = 0;
1266    rup->ru_nsignals = 0;
1267    rup->ru_nvcsw = 0;
1268    rup->ru_nivcsw = 0;
1269
1270    switch (who) {
1271      case OS::TGT_RUSAGE_SELF:
1272        getElapsedTime(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
1273        rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
1274        rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
1275        break;
1276
1277      case OS::TGT_RUSAGE_CHILDREN:
1278        // do nothing.  We have no child processes, so they take no time.
1279        break;
1280
1281      default:
1282        // don't really handle THREAD or CHILDREN, but just warn and
1283        // plow ahead
1284        warn("getrusage() only supports RUSAGE_SELF.  Parameter %d ignored.",
1285             who);
1286    }
1287
1288    rup.copyOut(tc->getMemProxy());
1289
1290    return 0;
1291}
1292
1293/// Target times() function.
1294template <class OS>
1295SyscallReturn
1296timesFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1297           ThreadContext *tc)
1298{
1299    int index = 0;
1300    TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
1301
1302    // Fill in the time structure (in clocks)
1303    int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
1304    bufp->tms_utime = clocks;
1305    bufp->tms_stime = 0;
1306    bufp->tms_cutime = 0;
1307    bufp->tms_cstime = 0;
1308
1309    // Convert to host endianness
1310    bufp->tms_utime = TheISA::htog(bufp->tms_utime);
1311
1312    // Write back
1313    bufp.copyOut(tc->getMemProxy());
1314
1315    // Return clock ticks since system boot
1316    return clocks;
1317}
1318
1319/// Target time() function.
1320template <class OS>
1321SyscallReturn
1322timeFunc(SyscallDesc *desc, int callnum, LiveProcess *process,
1323           ThreadContext *tc)
1324{
1325    typename OS::time_t sec, usec;
1326    getElapsedTime(sec, usec);
1327    sec += seconds_since_epoch;
1328
1329    int index = 0;
1330    Addr taddr = (Addr)process->getSyscallArg(tc, index);
1331    if(taddr != 0) {
1332        typename OS::time_t t = sec;
1333        t = TheISA::htog(t);
1334        SETranslatingPortProxy &p = tc->getMemProxy();
1335        p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
1336    }
1337    return sec;
1338}
1339
1340
1341#endif // __SIM_SYSCALL_EMUL_HH__
1342