syscall_emul.hh revision 11907
1/*
2 * Copyright (c) 2012-2013, 2015 ARM Limited
3 * Copyright (c) 2015 Advanced Micro Devices, Inc.
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2003-2005 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Steve Reinhardt
42 *          Kevin Lim
43 */
44
45#ifndef __SIM_SYSCALL_EMUL_HH__
46#define __SIM_SYSCALL_EMUL_HH__
47
48#define NO_STAT64 (defined(__APPLE__) || defined(__OpenBSD__) || \
49  defined(__FreeBSD__) || defined(__CYGWIN__) || \
50  defined(__NetBSD__))
51
52#define NO_STATFS (defined(__APPLE__) || defined(__OpenBSD__) || \
53  defined(__FreeBSD__) || defined(__NetBSD__))
54
55#define NO_FALLOCATE (defined(__APPLE__) || defined(__OpenBSD__) || \
56  defined(__FreeBSD__) || defined(__NetBSD__))
57
58///
59/// @file syscall_emul.hh
60///
61/// This file defines objects used to emulate syscalls from the target
62/// application on the host machine.
63
64#ifdef __CYGWIN32__
65#include <sys/fcntl.h>
66
67#endif
68#include <fcntl.h>
69#include <sys/mman.h>
70#include <sys/stat.h>
71#if (NO_STATFS == 0)
72#include <sys/statfs.h>
73#else
74#include <sys/mount.h>
75#endif
76#include <sys/time.h>
77#include <sys/uio.h>
78#include <unistd.h>
79
80#include <cerrno>
81#include <memory>
82#include <string>
83
84#include "arch/utility.hh"
85#include "base/intmath.hh"
86#include "base/loader/object_file.hh"
87#include "base/misc.hh"
88#include "base/trace.hh"
89#include "base/types.hh"
90#include "config/the_isa.hh"
91#include "cpu/base.hh"
92#include "cpu/thread_context.hh"
93#include "mem/page_table.hh"
94#include "params/Process.hh"
95#include "sim/emul_driver.hh"
96#include "sim/process.hh"
97#include "sim/syscall_debug_macros.hh"
98#include "sim/syscall_desc.hh"
99#include "sim/syscall_emul_buf.hh"
100#include "sim/syscall_return.hh"
101
102//////////////////////////////////////////////////////////////////////
103//
104// The following emulation functions are generic enough that they
105// don't need to be recompiled for different emulated OS's.  They are
106// defined in sim/syscall_emul.cc.
107//
108//////////////////////////////////////////////////////////////////////
109
110
111/// Handler for unimplemented syscalls that we haven't thought about.
112SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
113                                Process *p, ThreadContext *tc);
114
115/// Handler for unimplemented syscalls that we never intend to
116/// implement (signal handling, etc.) and should not affect the correct
117/// behavior of the program.  Print a warning only if the appropriate
118/// trace flag is enabled.  Return success to the target program.
119SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
120                         Process *p, ThreadContext *tc);
121
122// Target fallocateFunc() handler.
123SyscallReturn fallocateFunc(SyscallDesc *desc, int num,
124                            Process *p, ThreadContext *tc);
125
126/// Target exit() handler: terminate current context.
127SyscallReturn exitFunc(SyscallDesc *desc, int num,
128                       Process *p, ThreadContext *tc);
129
130/// Target exit_group() handler: terminate simulation. (exit all threads)
131SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
132                       Process *p, ThreadContext *tc);
133
134/// Target set_tid_address() handler.
135SyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
136                                Process *p, ThreadContext *tc);
137
138/// Target getpagesize() handler.
139SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
140                              Process *p, ThreadContext *tc);
141
142/// Target brk() handler: set brk address.
143SyscallReturn brkFunc(SyscallDesc *desc, int num,
144                      Process *p, ThreadContext *tc);
145
146/// Target close() handler.
147SyscallReturn closeFunc(SyscallDesc *desc, int num,
148                        Process *p, ThreadContext *tc);
149
150// Target read() handler.
151SyscallReturn readFunc(SyscallDesc *desc, int num,
152                       Process *p, ThreadContext *tc);
153
154/// Target write() handler.
155SyscallReturn writeFunc(SyscallDesc *desc, int num,
156                        Process *p, ThreadContext *tc);
157
158/// Target lseek() handler.
159SyscallReturn lseekFunc(SyscallDesc *desc, int num,
160                        Process *p, ThreadContext *tc);
161
162/// Target _llseek() handler.
163SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
164                          Process *p, ThreadContext *tc);
165
166/// Target munmap() handler.
167SyscallReturn munmapFunc(SyscallDesc *desc, int num,
168                         Process *p, ThreadContext *tc);
169
170/// Target gethostname() handler.
171SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
172                              Process *p, ThreadContext *tc);
173
174/// Target getcwd() handler.
175SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
176                         Process *p, ThreadContext *tc);
177
178/// Target readlink() handler.
179SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
180                           Process *p, ThreadContext *tc,
181                           int index = 0);
182SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
183                           Process *p, ThreadContext *tc);
184
185/// Target unlink() handler.
186SyscallReturn unlinkHelper(SyscallDesc *desc, int num,
187                           Process *p, ThreadContext *tc,
188                           int index);
189SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
190                         Process *p, ThreadContext *tc);
191
192/// Target mkdir() handler.
193SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
194                        Process *p, ThreadContext *tc);
195
196/// Target rename() handler.
197SyscallReturn renameFunc(SyscallDesc *desc, int num,
198                         Process *p, ThreadContext *tc);
199
200
201/// Target truncate() handler.
202SyscallReturn truncateFunc(SyscallDesc *desc, int num,
203                           Process *p, ThreadContext *tc);
204
205
206/// Target ftruncate() handler.
207SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
208                            Process *p, ThreadContext *tc);
209
210
211/// Target truncate64() handler.
212SyscallReturn truncate64Func(SyscallDesc *desc, int num,
213                             Process *p, ThreadContext *tc);
214
215/// Target ftruncate64() handler.
216SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
217                              Process *p, ThreadContext *tc);
218
219
220/// Target umask() handler.
221SyscallReturn umaskFunc(SyscallDesc *desc, int num,
222                        Process *p, ThreadContext *tc);
223
224/// Target gettid() handler.
225SyscallReturn gettidFunc(SyscallDesc *desc, int num,
226                         Process *p, ThreadContext *tc);
227
228/// Target chown() handler.
229SyscallReturn chownFunc(SyscallDesc *desc, int num,
230                        Process *p, ThreadContext *tc);
231
232/// Target setpgid() handler.
233SyscallReturn setpgidFunc(SyscallDesc *desc, int num,
234                          Process *p, ThreadContext *tc);
235
236/// Target fchown() handler.
237SyscallReturn fchownFunc(SyscallDesc *desc, int num,
238                         Process *p, ThreadContext *tc);
239
240/// Target dup() handler.
241SyscallReturn dupFunc(SyscallDesc *desc, int num,
242                      Process *process, ThreadContext *tc);
243
244/// Target fcntl() handler.
245SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
246                        Process *process, ThreadContext *tc);
247
248/// Target fcntl64() handler.
249SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
250                          Process *process, ThreadContext *tc);
251
252/// Target setuid() handler.
253SyscallReturn setuidFunc(SyscallDesc *desc, int num,
254                         Process *p, ThreadContext *tc);
255
256/// Target getpid() handler.
257SyscallReturn getpidFunc(SyscallDesc *desc, int num,
258                         Process *p, ThreadContext *tc);
259
260/// Target getuid() handler.
261SyscallReturn getuidFunc(SyscallDesc *desc, int num,
262                         Process *p, ThreadContext *tc);
263
264/// Target getgid() handler.
265SyscallReturn getgidFunc(SyscallDesc *desc, int num,
266                         Process *p, ThreadContext *tc);
267
268/// Target getppid() handler.
269SyscallReturn getppidFunc(SyscallDesc *desc, int num,
270                          Process *p, ThreadContext *tc);
271
272/// Target geteuid() handler.
273SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
274                          Process *p, ThreadContext *tc);
275
276/// Target getegid() handler.
277SyscallReturn getegidFunc(SyscallDesc *desc, int num,
278                          Process *p, ThreadContext *tc);
279
280/// Target access() handler
281SyscallReturn accessFunc(SyscallDesc *desc, int num,
282                         Process *p, ThreadContext *tc);
283SyscallReturn accessFunc(SyscallDesc *desc, int num,
284                         Process *p, ThreadContext *tc,
285                         int index);
286
287/// Futex system call
288/// Implemented by Daniel Sanchez
289/// Used by printf's in multi-threaded apps
290template <class OS>
291SyscallReturn
292futexFunc(SyscallDesc *desc, int callnum, Process *process,
293          ThreadContext *tc)
294{
295    int index_uaddr = 0;
296    int index_op = 1;
297    int index_val = 2;
298    int index_timeout = 3;
299
300    uint64_t uaddr = process->getSyscallArg(tc, index_uaddr);
301    int op = process->getSyscallArg(tc, index_op);
302    int val = process->getSyscallArg(tc, index_val);
303    uint64_t timeout = process->getSyscallArg(tc, index_timeout);
304
305    std::map<uint64_t, std::list<ThreadContext *> * >
306        &futex_map = tc->getSystemPtr()->futexMap;
307
308    DPRINTF(SyscallVerbose, "futex: Address=%llx, op=%d, val=%d\n",
309            uaddr, op, val);
310
311    op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
312
313    if (op == OS::TGT_FUTEX_WAIT) {
314        if (timeout != 0) {
315            warn("futex: FUTEX_WAIT with non-null timeout unimplemented;"
316                 "we'll wait indefinitely");
317        }
318
319        uint8_t *buf = new uint8_t[sizeof(int)];
320        tc->getMemProxy().readBlob((Addr)uaddr, buf, (int)sizeof(int));
321        int mem_val = *((int *)buf);
322        delete[] buf;
323
324        if (val != mem_val) {
325            DPRINTF(SyscallVerbose, "futex: FUTEX_WAKE, read: %d, "
326                                    "expected: %d\n", mem_val, val);
327            return -OS::TGT_EWOULDBLOCK;
328        }
329
330        // Queue the thread context
331        std::list<ThreadContext *> * tcWaitList;
332        if (futex_map.count(uaddr)) {
333            tcWaitList = futex_map.find(uaddr)->second;
334        } else {
335            tcWaitList = new std::list<ThreadContext *>();
336            futex_map.insert(std::pair< uint64_t,
337                            std::list<ThreadContext *> * >(uaddr, tcWaitList));
338        }
339        tcWaitList->push_back(tc);
340        DPRINTF(SyscallVerbose, "futex: FUTEX_WAIT, suspending calling thread "
341                                "context on address 0x%lx\n", uaddr);
342        tc->suspend();
343        return 0;
344    } else if (op == OS::TGT_FUTEX_WAKE){
345        int wokenUp = 0;
346        std::list<ThreadContext *> * tcWaitList;
347        if (futex_map.count(uaddr)) {
348            tcWaitList = futex_map.find(uaddr)->second;
349            while (tcWaitList->size() > 0 && wokenUp < val) {
350                tcWaitList->front()->activate();
351                tcWaitList->pop_front();
352                wokenUp++;
353            }
354            if (tcWaitList->empty()) {
355                futex_map.erase(uaddr);
356                delete tcWaitList;
357            }
358        }
359        DPRINTF(SyscallVerbose, "futex: FUTEX_WAKE, activated %d waiting "
360                                "thread context on address 0x%lx\n",
361                                wokenUp, uaddr);
362        return wokenUp;
363    } else {
364        warn("futex: op %d is not implemented, just returning...", op);
365        return 0;
366    }
367
368}
369
370
371/// Pseudo Funcs  - These functions use a different return convension,
372/// returning a second value in a register other than the normal return register
373SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
374                             Process *process, ThreadContext *tc);
375
376/// Target getpidPseudo() handler.
377SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
378                               Process *p, ThreadContext *tc);
379
380/// Target getuidPseudo() handler.
381SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
382                               Process *p, ThreadContext *tc);
383
384/// Target getgidPseudo() handler.
385SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
386                               Process *p, ThreadContext *tc);
387
388
389/// A readable name for 1,000,000, for converting microseconds to seconds.
390const int one_million = 1000000;
391/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
392const int one_billion = 1000000000;
393
394/// Approximate seconds since the epoch (1/1/1970).  About a billion,
395/// by my reckoning.  We want to keep this a constant (not use the
396/// real-world time) to keep simulations repeatable.
397const unsigned seconds_since_epoch = 1000000000;
398
399/// Helper function to convert current elapsed time to seconds and
400/// microseconds.
401template <class T1, class T2>
402void
403getElapsedTimeMicro(T1 &sec, T2 &usec)
404{
405    uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
406    sec = elapsed_usecs / one_million;
407    usec = elapsed_usecs % one_million;
408}
409
410/// Helper function to convert current elapsed time to seconds and
411/// nanoseconds.
412template <class T1, class T2>
413void
414getElapsedTimeNano(T1 &sec, T2 &nsec)
415{
416    uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
417    sec = elapsed_nsecs / one_billion;
418    nsec = elapsed_nsecs % one_billion;
419}
420
421//////////////////////////////////////////////////////////////////////
422//
423// The following emulation functions are generic, but need to be
424// templated to account for differences in types, constants, etc.
425//
426//////////////////////////////////////////////////////////////////////
427
428    typedef struct statfs hst_statfs;
429#if NO_STAT64
430    typedef struct stat hst_stat;
431    typedef struct stat hst_stat64;
432#else
433    typedef struct stat hst_stat;
434    typedef struct stat64 hst_stat64;
435#endif
436
437//// Helper function to convert a host stat buffer to a target stat
438//// buffer.  Also copies the target buffer out to the simulated
439//// memory space.  Used by stat(), fstat(), and lstat().
440
441template <typename target_stat, typename host_stat>
442static void
443convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
444{
445    using namespace TheISA;
446
447    if (fakeTTY)
448        tgt->st_dev = 0xA;
449    else
450        tgt->st_dev = host->st_dev;
451    tgt->st_dev = TheISA::htog(tgt->st_dev);
452    tgt->st_ino = host->st_ino;
453    tgt->st_ino = TheISA::htog(tgt->st_ino);
454    tgt->st_mode = host->st_mode;
455    if (fakeTTY) {
456        // Claim to be a character device
457        tgt->st_mode &= ~S_IFMT;    // Clear S_IFMT
458        tgt->st_mode |= S_IFCHR;    // Set S_IFCHR
459    }
460    tgt->st_mode = TheISA::htog(tgt->st_mode);
461    tgt->st_nlink = host->st_nlink;
462    tgt->st_nlink = TheISA::htog(tgt->st_nlink);
463    tgt->st_uid = host->st_uid;
464    tgt->st_uid = TheISA::htog(tgt->st_uid);
465    tgt->st_gid = host->st_gid;
466    tgt->st_gid = TheISA::htog(tgt->st_gid);
467    if (fakeTTY)
468        tgt->st_rdev = 0x880d;
469    else
470        tgt->st_rdev = host->st_rdev;
471    tgt->st_rdev = TheISA::htog(tgt->st_rdev);
472    tgt->st_size = host->st_size;
473    tgt->st_size = TheISA::htog(tgt->st_size);
474    tgt->st_atimeX = host->st_atime;
475    tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
476    tgt->st_mtimeX = host->st_mtime;
477    tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
478    tgt->st_ctimeX = host->st_ctime;
479    tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
480    // Force the block size to be 8KB. This helps to ensure buffered io works
481    // consistently across different hosts.
482    tgt->st_blksize = 0x2000;
483    tgt->st_blksize = TheISA::htog(tgt->st_blksize);
484    tgt->st_blocks = host->st_blocks;
485    tgt->st_blocks = TheISA::htog(tgt->st_blocks);
486}
487
488// Same for stat64
489
490template <typename target_stat, typename host_stat64>
491static void
492convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
493{
494    using namespace TheISA;
495
496    convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
497#if defined(STAT_HAVE_NSEC)
498    tgt->st_atime_nsec = host->st_atime_nsec;
499    tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
500    tgt->st_mtime_nsec = host->st_mtime_nsec;
501    tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
502    tgt->st_ctime_nsec = host->st_ctime_nsec;
503    tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
504#else
505    tgt->st_atime_nsec = 0;
506    tgt->st_mtime_nsec = 0;
507    tgt->st_ctime_nsec = 0;
508#endif
509}
510
511// Here are a couple of convenience functions
512template<class OS>
513static void
514copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
515               hst_stat *host, bool fakeTTY = false)
516{
517    typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
518    tgt_stat_buf tgt(addr);
519    convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
520    tgt.copyOut(mem);
521}
522
523template<class OS>
524static void
525copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
526                 hst_stat64 *host, bool fakeTTY = false)
527{
528    typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
529    tgt_stat_buf tgt(addr);
530    convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
531    tgt.copyOut(mem);
532}
533
534template <class OS>
535static void
536copyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
537                 hst_statfs *host)
538{
539    TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
540
541    tgt->f_type = TheISA::htog(host->f_type);
542#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
543    tgt->f_bsize = TheISA::htog(host->f_iosize);
544#else
545    tgt->f_bsize = TheISA::htog(host->f_bsize);
546#endif
547    tgt->f_blocks = TheISA::htog(host->f_blocks);
548    tgt->f_bfree = TheISA::htog(host->f_bfree);
549    tgt->f_bavail = TheISA::htog(host->f_bavail);
550    tgt->f_files = TheISA::htog(host->f_files);
551    tgt->f_ffree = TheISA::htog(host->f_ffree);
552    memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
553#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
554    tgt->f_namelen = TheISA::htog(host->f_namemax);
555    tgt->f_frsize = TheISA::htog(host->f_bsize);
556#elif defined(__APPLE__)
557    tgt->f_namelen = 0;
558    tgt->f_frsize = 0;
559#else
560    tgt->f_namelen = TheISA::htog(host->f_namelen);
561    tgt->f_frsize = TheISA::htog(host->f_frsize);
562#endif
563#if defined(__linux__)
564    memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
565#else
566    /*
567     * The fields are different sizes per OS. Don't bother with
568     * f_spare or f_reserved on non-Linux for now.
569     */
570    memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
571#endif
572
573    tgt.copyOut(mem);
574}
575
576/// Target ioctl() handler.  For the most part, programs call ioctl()
577/// only to find out if their stdout is a tty, to determine whether to
578/// do line or block buffering.  We always claim that output fds are
579/// not TTYs to provide repeatable results.
580template <class OS>
581SyscallReturn
582ioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
583{
584    int index = 0;
585    int tgt_fd = p->getSyscallArg(tc, index);
586    unsigned req = p->getSyscallArg(tc, index);
587
588    DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
589
590    if (OS::isTtyReq(req))
591        return -ENOTTY;
592
593    auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
594    if (!dfdp)
595        return -EBADF;
596
597    /**
598     * If the driver is valid, issue the ioctl through it. Otherwise,
599     * there's an implicit assumption that the device is a TTY type and we
600     * return that we do not have a valid TTY.
601     */
602    EmulatedDriver *emul_driver = dfdp->getDriver();
603    if (emul_driver)
604        return emul_driver->ioctl(p, tc, req);
605
606    /**
607     * For lack of a better return code, return ENOTTY. Ideally, we should
608     * return something better here, but at least we issue the warning.
609     */
610    warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
611         tgt_fd, req, tc->pcState());
612    return -ENOTTY;
613}
614
615template <class OS>
616SyscallReturn
617openImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
618         bool isopenat)
619{
620    int index = 0;
621    int tgt_dirfd = -1;
622
623    /**
624     * If using the openat variant, read in the target directory file
625     * descriptor from the simulated process.
626     */
627    if (isopenat)
628        tgt_dirfd = p->getSyscallArg(tc, index);
629
630    /**
631     * Retrieve the simulated process' memory proxy and then read in the path
632     * string from that memory space into the host's working memory space.
633     */
634    std::string path;
635    if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
636        return -EFAULT;
637
638#ifdef __CYGWIN32__
639    int host_flags = O_BINARY;
640#else
641    int host_flags = 0;
642#endif
643    /**
644     * Translate target flags into host flags. Flags exist which are not
645     * ported between architectures which can cause check failures.
646     */
647    int tgt_flags = p->getSyscallArg(tc, index);
648    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
649        if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
650            tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
651            host_flags |= OS::openFlagTable[i].hostFlag;
652        }
653    }
654    if (tgt_flags) {
655        warn("open%s: cannot decode flags 0x%x",
656             isopenat ? "at" : "", tgt_flags);
657    }
658#ifdef __CYGWIN32__
659    host_flags |= O_BINARY;
660#endif
661
662    int mode = p->getSyscallArg(tc, index);
663
664    /**
665     * If the simulated process called open or openat with AT_FDCWD specified,
666     * take the current working directory value which was passed into the
667     * process class as a Python parameter and append the current path to
668     * create a full path.
669     * Otherwise, openat with a valid target directory file descriptor has
670     * been called. If the path option, which was passed in as a parameter,
671     * is not absolute, retrieve the directory file descriptor's path and
672     * prepend it to the path passed in as a parameter.
673     * In every case, we should have a full path (which is relevant to the
674     * host) to work with after this block has been passed.
675     */
676    if (!isopenat || (isopenat && tgt_dirfd == OS::TGT_AT_FDCWD)) {
677        path = p->fullPath(path);
678    } else if (!startswith(path, "/")) {
679        std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
680        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
681        if (!ffdp)
682            return -EBADF;
683        path.insert(0, ffdp->getFileName());
684    }
685
686    /**
687     * Since this is an emulated environment, we create pseudo file
688     * descriptors for device requests that have been registered with
689     * the process class through Python; this allows us to create a file
690     * descriptor for subsequent ioctl or mmap calls.
691     */
692    if (startswith(path, "/dev/")) {
693        std::string filename = path.substr(strlen("/dev/"));
694        EmulatedDriver *drv = p->findDriver(filename);
695        if (drv) {
696            DPRINTF_SYSCALL(Verbose, "open%s: passing call to "
697                            "driver open with path[%s]\n",
698                            isopenat ? "at" : "", path.c_str());
699            return drv->open(p, tc, mode, host_flags);
700        }
701        /**
702         * Fall through here for pass through to host devices, such
703         * as /dev/zero
704         */
705    }
706
707    /**
708     * Some special paths and files cannot be called on the host and need
709     * to be handled as special cases inside the simulator.
710     * If the full path that was created above does not match any of the
711     * special cases, pass it through to the open call on the host to let
712     * the host open the file on our behalf.
713     * If the host cannot open the file, return the host's error code back
714     * through the system call to the simulated process.
715     */
716    int sim_fd = -1;
717    std::vector<std::string> special_paths =
718            { "/proc/", "/system/", "/sys/", "/platform/", "/etc/passwd" };
719    for (auto entry : special_paths) {
720        if (startswith(path, entry))
721            sim_fd = OS::openSpecialFile(path, p, tc);
722    }
723    if (sim_fd == -1) {
724        sim_fd = open(path.c_str(), host_flags, mode);
725    }
726    if (sim_fd == -1) {
727        int local = -errno;
728        DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s\n",
729                        isopenat ? "at" : "", path.c_str());
730        return local;
731    }
732
733    /**
734     * The file was opened successfully and needs to be recorded in the
735     * process' file descriptor array so that it can be retrieved later.
736     * The target file descriptor that is chosen will be the lowest unused
737     * file descriptor.
738     * Return the indirect target file descriptor back to the simulated
739     * process to act as a handle for the opened file.
740     */
741    auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
742    int tgt_fd = p->fds->allocFD(ffdp);
743    DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n",
744                    isopenat ? "at" : "", sim_fd, tgt_fd, path.c_str());
745    return tgt_fd;
746}
747
748/// Target open() handler.
749template <class OS>
750SyscallReturn
751openFunc(SyscallDesc *desc, int callnum, Process *process,
752         ThreadContext *tc)
753{
754    return openImpl<OS>(desc, callnum, process, tc, false);
755}
756
757/// Target openat() handler.
758template <class OS>
759SyscallReturn
760openatFunc(SyscallDesc *desc, int callnum, Process *process,
761           ThreadContext *tc)
762{
763    return openImpl<OS>(desc, callnum, process, tc, true);
764}
765
766/// Target unlinkat() handler.
767template <class OS>
768SyscallReturn
769unlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
770             ThreadContext *tc)
771{
772    int index = 0;
773    int dirfd = process->getSyscallArg(tc, index);
774    if (dirfd != OS::TGT_AT_FDCWD)
775        warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
776
777    return unlinkHelper(desc, callnum, process, tc, 1);
778}
779
780/// Target facessat() handler
781template <class OS>
782SyscallReturn
783faccessatFunc(SyscallDesc *desc, int callnum, Process *process,
784              ThreadContext *tc)
785{
786    int index = 0;
787    int dirfd = process->getSyscallArg(tc, index);
788    if (dirfd != OS::TGT_AT_FDCWD)
789        warn("faccessat: first argument not AT_FDCWD; unlikely to work");
790    return accessFunc(desc, callnum, process, tc, 1);
791}
792
793/// Target readlinkat() handler
794template <class OS>
795SyscallReturn
796readlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
797               ThreadContext *tc)
798{
799    int index = 0;
800    int dirfd = process->getSyscallArg(tc, index);
801    if (dirfd != OS::TGT_AT_FDCWD)
802        warn("openat: first argument not AT_FDCWD; unlikely to work");
803    return readlinkFunc(desc, callnum, process, tc, 1);
804}
805
806/// Target renameat() handler.
807template <class OS>
808SyscallReturn
809renameatFunc(SyscallDesc *desc, int callnum, Process *process,
810             ThreadContext *tc)
811{
812    int index = 0;
813
814    int olddirfd = process->getSyscallArg(tc, index);
815    if (olddirfd != OS::TGT_AT_FDCWD)
816        warn("renameat: first argument not AT_FDCWD; unlikely to work");
817
818    std::string old_name;
819
820    if (!tc->getMemProxy().tryReadString(old_name,
821                                         process->getSyscallArg(tc, index)))
822        return -EFAULT;
823
824    int newdirfd = process->getSyscallArg(tc, index);
825    if (newdirfd != OS::TGT_AT_FDCWD)
826        warn("renameat: third argument not AT_FDCWD; unlikely to work");
827
828    std::string new_name;
829
830    if (!tc->getMemProxy().tryReadString(new_name,
831                                         process->getSyscallArg(tc, index)))
832        return -EFAULT;
833
834    // Adjust path for current working directory
835    old_name = process->fullPath(old_name);
836    new_name = process->fullPath(new_name);
837
838    int result = rename(old_name.c_str(), new_name.c_str());
839    return (result == -1) ? -errno : result;
840}
841
842/// Target sysinfo() handler.
843template <class OS>
844SyscallReturn
845sysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
846            ThreadContext *tc)
847{
848
849    int index = 0;
850    TypedBufferArg<typename OS::tgt_sysinfo>
851        sysinfo(process->getSyscallArg(tc, index));
852
853    sysinfo->uptime = seconds_since_epoch;
854    sysinfo->totalram = process->system->memSize();
855    sysinfo->mem_unit = 1;
856
857    sysinfo.copyOut(tc->getMemProxy());
858
859    return 0;
860}
861
862/// Target chmod() handler.
863template <class OS>
864SyscallReturn
865chmodFunc(SyscallDesc *desc, int callnum, Process *process,
866          ThreadContext *tc)
867{
868    std::string path;
869
870    int index = 0;
871    if (!tc->getMemProxy().tryReadString(path,
872                process->getSyscallArg(tc, index))) {
873        return -EFAULT;
874    }
875
876    uint32_t mode = process->getSyscallArg(tc, index);
877    mode_t hostMode = 0;
878
879    // XXX translate mode flags via OS::something???
880    hostMode = mode;
881
882    // Adjust path for current working directory
883    path = process->fullPath(path);
884
885    // do the chmod
886    int result = chmod(path.c_str(), hostMode);
887    if (result < 0)
888        return -errno;
889
890    return 0;
891}
892
893
894/// Target fchmod() handler.
895template <class OS>
896SyscallReturn
897fchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
898{
899    int index = 0;
900    int tgt_fd = p->getSyscallArg(tc, index);
901    uint32_t mode = p->getSyscallArg(tc, index);
902
903    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
904    if (!ffdp)
905        return -EBADF;
906    int sim_fd = ffdp->getSimFD();
907
908    mode_t hostMode = mode;
909
910    int result = fchmod(sim_fd, hostMode);
911
912    return (result < 0) ? -errno : 0;
913}
914
915/// Target mremap() handler.
916template <class OS>
917SyscallReturn
918mremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
919{
920    int index = 0;
921    Addr start = process->getSyscallArg(tc, index);
922    uint64_t old_length = process->getSyscallArg(tc, index);
923    uint64_t new_length = process->getSyscallArg(tc, index);
924    uint64_t flags = process->getSyscallArg(tc, index);
925    uint64_t provided_address = 0;
926    bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
927
928    if (use_provided_address)
929        provided_address = process->getSyscallArg(tc, index);
930
931    if ((start % TheISA::PageBytes != 0) ||
932        (provided_address % TheISA::PageBytes != 0)) {
933        warn("mremap failing: arguments not page aligned");
934        return -EINVAL;
935    }
936
937    new_length = roundUp(new_length, TheISA::PageBytes);
938
939    if (new_length > old_length) {
940        std::shared_ptr<MemState> mem_state = process->memState;
941        Addr mmap_end = mem_state->getMmapEnd();
942
943        if ((start + old_length) == mmap_end &&
944            (!use_provided_address || provided_address == start)) {
945            uint64_t diff = new_length - old_length;
946            process->allocateMem(mmap_end, diff);
947            mem_state->setMmapEnd(mmap_end + diff);
948            return start;
949        } else {
950            if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
951                warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
952                return -ENOMEM;
953            } else {
954                uint64_t new_start = use_provided_address ?
955                    provided_address : mmap_end;
956                process->pTable->remap(start, old_length, new_start);
957                warn("mremapping to new vaddr %08p-%08p, adding %d\n",
958                     new_start, new_start + new_length,
959                     new_length - old_length);
960                // add on the remaining unallocated pages
961                process->allocateMem(new_start + old_length,
962                                     new_length - old_length,
963                                     use_provided_address /* clobber */);
964                if (!use_provided_address)
965                    mem_state->setMmapEnd(mmap_end + new_length);
966                if (use_provided_address &&
967                    new_start + new_length > mem_state->getMmapEnd()) {
968                    // something fishy going on here, at least notify the user
969                    // @todo: increase mmap_end?
970                    warn("mmap region limit exceeded with MREMAP_FIXED\n");
971                }
972                warn("returning %08p as start\n", new_start);
973                return new_start;
974            }
975        }
976    } else {
977        if (use_provided_address && provided_address != start)
978            process->pTable->remap(start, new_length, provided_address);
979        process->pTable->unmap(start + new_length, old_length - new_length);
980        return use_provided_address ? provided_address : start;
981    }
982}
983
984/// Target stat() handler.
985template <class OS>
986SyscallReturn
987statFunc(SyscallDesc *desc, int callnum, Process *process,
988         ThreadContext *tc)
989{
990    std::string path;
991
992    int index = 0;
993    if (!tc->getMemProxy().tryReadString(path,
994                process->getSyscallArg(tc, index))) {
995        return -EFAULT;
996    }
997    Addr bufPtr = process->getSyscallArg(tc, index);
998
999    // Adjust path for current working directory
1000    path = process->fullPath(path);
1001
1002    struct stat hostBuf;
1003    int result = stat(path.c_str(), &hostBuf);
1004
1005    if (result < 0)
1006        return -errno;
1007
1008    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1009
1010    return 0;
1011}
1012
1013
1014/// Target stat64() handler.
1015template <class OS>
1016SyscallReturn
1017stat64Func(SyscallDesc *desc, int callnum, Process *process,
1018           ThreadContext *tc)
1019{
1020    std::string path;
1021
1022    int index = 0;
1023    if (!tc->getMemProxy().tryReadString(path,
1024                process->getSyscallArg(tc, index)))
1025        return -EFAULT;
1026    Addr bufPtr = process->getSyscallArg(tc, index);
1027
1028    // Adjust path for current working directory
1029    path = process->fullPath(path);
1030
1031#if NO_STAT64
1032    struct stat  hostBuf;
1033    int result = stat(path.c_str(), &hostBuf);
1034#else
1035    struct stat64 hostBuf;
1036    int result = stat64(path.c_str(), &hostBuf);
1037#endif
1038
1039    if (result < 0)
1040        return -errno;
1041
1042    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1043
1044    return 0;
1045}
1046
1047
1048/// Target fstatat64() handler.
1049template <class OS>
1050SyscallReturn
1051fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
1052              ThreadContext *tc)
1053{
1054    int index = 0;
1055    int dirfd = process->getSyscallArg(tc, index);
1056    if (dirfd != OS::TGT_AT_FDCWD)
1057        warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1058
1059    std::string path;
1060    if (!tc->getMemProxy().tryReadString(path,
1061                process->getSyscallArg(tc, index)))
1062        return -EFAULT;
1063    Addr bufPtr = process->getSyscallArg(tc, index);
1064
1065    // Adjust path for current working directory
1066    path = process->fullPath(path);
1067
1068#if NO_STAT64
1069    struct stat  hostBuf;
1070    int result = stat(path.c_str(), &hostBuf);
1071#else
1072    struct stat64 hostBuf;
1073    int result = stat64(path.c_str(), &hostBuf);
1074#endif
1075
1076    if (result < 0)
1077        return -errno;
1078
1079    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1080
1081    return 0;
1082}
1083
1084
1085/// Target fstat64() handler.
1086template <class OS>
1087SyscallReturn
1088fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1089{
1090    int index = 0;
1091    int tgt_fd = p->getSyscallArg(tc, index);
1092    Addr bufPtr = p->getSyscallArg(tc, index);
1093
1094    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1095    if (!ffdp)
1096        return -EBADF;
1097    int sim_fd = ffdp->getSimFD();
1098
1099#if NO_STAT64
1100    struct stat  hostBuf;
1101    int result = fstat(sim_fd, &hostBuf);
1102#else
1103    struct stat64  hostBuf;
1104    int result = fstat64(sim_fd, &hostBuf);
1105#endif
1106
1107    if (result < 0)
1108        return -errno;
1109
1110    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1111
1112    return 0;
1113}
1114
1115
1116/// Target lstat() handler.
1117template <class OS>
1118SyscallReturn
1119lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1120          ThreadContext *tc)
1121{
1122    std::string path;
1123
1124    int index = 0;
1125    if (!tc->getMemProxy().tryReadString(path,
1126                process->getSyscallArg(tc, index))) {
1127        return -EFAULT;
1128    }
1129    Addr bufPtr = process->getSyscallArg(tc, index);
1130
1131    // Adjust path for current working directory
1132    path = process->fullPath(path);
1133
1134    struct stat hostBuf;
1135    int result = lstat(path.c_str(), &hostBuf);
1136
1137    if (result < 0)
1138        return -errno;
1139
1140    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1141
1142    return 0;
1143}
1144
1145/// Target lstat64() handler.
1146template <class OS>
1147SyscallReturn
1148lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1149            ThreadContext *tc)
1150{
1151    std::string path;
1152
1153    int index = 0;
1154    if (!tc->getMemProxy().tryReadString(path,
1155                process->getSyscallArg(tc, index))) {
1156        return -EFAULT;
1157    }
1158    Addr bufPtr = process->getSyscallArg(tc, index);
1159
1160    // Adjust path for current working directory
1161    path = process->fullPath(path);
1162
1163#if NO_STAT64
1164    struct stat hostBuf;
1165    int result = lstat(path.c_str(), &hostBuf);
1166#else
1167    struct stat64 hostBuf;
1168    int result = lstat64(path.c_str(), &hostBuf);
1169#endif
1170
1171    if (result < 0)
1172        return -errno;
1173
1174    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1175
1176    return 0;
1177}
1178
1179/// Target fstat() handler.
1180template <class OS>
1181SyscallReturn
1182fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1183{
1184    int index = 0;
1185    int tgt_fd = p->getSyscallArg(tc, index);
1186    Addr bufPtr = p->getSyscallArg(tc, index);
1187
1188    DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1189
1190    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1191    if (!ffdp)
1192        return -EBADF;
1193    int sim_fd = ffdp->getSimFD();
1194
1195    struct stat hostBuf;
1196    int result = fstat(sim_fd, &hostBuf);
1197
1198    if (result < 0)
1199        return -errno;
1200
1201    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1202
1203    return 0;
1204}
1205
1206
1207/// Target statfs() handler.
1208template <class OS>
1209SyscallReturn
1210statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1211           ThreadContext *tc)
1212{
1213#if NO_STATFS
1214    warn("Host OS cannot support calls to statfs. Ignoring syscall");
1215#else
1216    std::string path;
1217
1218    int index = 0;
1219    if (!tc->getMemProxy().tryReadString(path,
1220                process->getSyscallArg(tc, index))) {
1221        return -EFAULT;
1222    }
1223    Addr bufPtr = process->getSyscallArg(tc, index);
1224
1225    // Adjust path for current working directory
1226    path = process->fullPath(path);
1227
1228    struct statfs hostBuf;
1229    int result = statfs(path.c_str(), &hostBuf);
1230
1231    if (result < 0)
1232        return -errno;
1233
1234    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1235#endif
1236    return 0;
1237}
1238
1239template <class OS>
1240SyscallReturn
1241cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1242{
1243    int index = 0;
1244    TheISA::IntReg flags = p->getSyscallArg(tc, index);
1245    TheISA::IntReg newStack = p->getSyscallArg(tc, index);
1246    Addr ptidPtr = p->getSyscallArg(tc, index);
1247    Addr ctidPtr = p->getSyscallArg(tc, index);
1248    Addr tlsPtr M5_VAR_USED = p->getSyscallArg(tc, index);
1249
1250    if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1251        ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1252        ((flags & OS::TGT_CLONE_FS)     &&  (flags & OS::TGT_CLONE_NEWNS)) ||
1253        ((flags & OS::TGT_CLONE_NEWIPC) &&  (flags & OS::TGT_CLONE_SYSVSEM)) ||
1254        ((flags & OS::TGT_CLONE_NEWPID) &&  (flags & OS::TGT_CLONE_THREAD)) ||
1255        ((flags & OS::TGT_CLONE_VM)     && !(newStack)))
1256        return -EINVAL;
1257
1258    ThreadContext *ctc;
1259    if (!(ctc = p->findFreeContext()))
1260        fatal("clone: no spare thread context in system");
1261
1262    /**
1263     * Note that ProcessParams is generated by swig and there are no other
1264     * examples of how to create anything but this default constructor. The
1265     * fields are manually initialized instead of passing parameters to the
1266     * constructor.
1267     */
1268    ProcessParams *pp = new ProcessParams();
1269    pp->executable.assign(*(new std::string(p->progName())));
1270    pp->cmd.push_back(*(new std::string(p->progName())));
1271    pp->system = p->system;
1272    pp->cwd.assign(p->getcwd());
1273    pp->input.assign("stdin");
1274    pp->output.assign("stdout");
1275    pp->errout.assign("stderr");
1276    pp->uid = p->uid();
1277    pp->euid = p->euid();
1278    pp->gid = p->gid();
1279    pp->egid = p->egid();
1280
1281    /* Find the first free PID that's less than the maximum */
1282    std::set<int> const& pids = p->system->PIDs;
1283    int temp_pid = *pids.begin();
1284    do {
1285        temp_pid++;
1286    } while (pids.find(temp_pid) != pids.end());
1287    if (temp_pid >= System::maxPID)
1288        fatal("temp_pid is too large: %d", temp_pid);
1289
1290    pp->pid = temp_pid;
1291    pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1292    Process *cp = pp->create();
1293    delete pp;
1294
1295    Process *owner = ctc->getProcessPtr();
1296    ctc->setProcessPtr(cp);
1297    cp->assignThreadContext(ctc->contextId());
1298    owner->revokeThreadContext(ctc->contextId());
1299
1300    if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1301        BufferArg ptidBuf(ptidPtr, sizeof(long));
1302        long *ptid = (long *)ptidBuf.bufferPtr();
1303        *ptid = cp->pid();
1304        ptidBuf.copyOut(tc->getMemProxy());
1305    }
1306
1307    cp->initState();
1308    p->clone(tc, ctc, cp, flags);
1309
1310    if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1311        BufferArg ctidBuf(ctidPtr, sizeof(long));
1312        long *ctid = (long *)ctidBuf.bufferPtr();
1313        *ctid = cp->pid();
1314        ctidBuf.copyOut(ctc->getMemProxy());
1315    }
1316
1317    if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1318        cp->childClearTID = (uint64_t)ctidPtr;
1319
1320    ctc->clearArchRegs();
1321
1322#if THE_ISA == ALPHA_ISA
1323    TheISA::copyMiscRegs(tc, ctc);
1324#elif THE_ISA == SPARC_ISA
1325    TheISA::copyRegs(tc, ctc);
1326    ctc->setIntReg(TheISA::NumIntArchRegs + 6, 0);
1327    ctc->setIntReg(TheISA::NumIntArchRegs + 4, 0);
1328    ctc->setIntReg(TheISA::NumIntArchRegs + 3, TheISA::NWindows - 2);
1329    ctc->setIntReg(TheISA::NumIntArchRegs + 5, TheISA::NWindows);
1330    ctc->setMiscReg(TheISA::MISCREG_CWP, 0);
1331    ctc->setIntReg(TheISA::NumIntArchRegs + 7, 0);
1332    ctc->setMiscRegNoEffect(TheISA::MISCREG_TL, 0);
1333    ctc->setMiscReg(TheISA::MISCREG_ASI, TheISA::ASI_PRIMARY);
1334    for (int y = 8; y < 32; y++)
1335        ctc->setIntReg(y, tc->readIntReg(y));
1336#elif THE_ISA == ARM_ISA or THE_ISA == X86_ISA
1337    TheISA::copyRegs(tc, ctc);
1338#endif
1339
1340#if THE_ISA == X86_ISA
1341    if (flags & OS::TGT_CLONE_SETTLS) {
1342        ctc->setMiscRegNoEffect(TheISA::MISCREG_FS_BASE, tlsPtr);
1343        ctc->setMiscRegNoEffect(TheISA::MISCREG_FS_EFF_BASE, tlsPtr);
1344    }
1345#endif
1346
1347    if (newStack)
1348        ctc->setIntReg(TheISA::StackPointerReg, newStack);
1349
1350    cp->setSyscallReturn(ctc, 0);
1351
1352#if THE_ISA == ALPHA_ISA
1353    ctc->setIntReg(TheISA::SyscallSuccessReg, 0);
1354#elif THE_ISA == SPARC_ISA
1355    tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1356    ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1357#endif
1358
1359    ctc->pcState(tc->nextInstAddr());
1360    ctc->activate();
1361
1362    return cp->pid();
1363}
1364
1365/// Target fstatfs() handler.
1366template <class OS>
1367SyscallReturn
1368fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1369{
1370    int index = 0;
1371    int tgt_fd = p->getSyscallArg(tc, index);
1372    Addr bufPtr = p->getSyscallArg(tc, index);
1373
1374    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1375    if (!ffdp)
1376        return -EBADF;
1377    int sim_fd = ffdp->getSimFD();
1378
1379    struct statfs hostBuf;
1380    int result = fstatfs(sim_fd, &hostBuf);
1381
1382    if (result < 0)
1383        return -errno;
1384
1385    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1386
1387    return 0;
1388}
1389
1390
1391/// Target writev() handler.
1392template <class OS>
1393SyscallReturn
1394writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1395{
1396    int index = 0;
1397    int tgt_fd = p->getSyscallArg(tc, index);
1398
1399    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1400    if (!hbfdp)
1401        return -EBADF;
1402    int sim_fd = hbfdp->getSimFD();
1403
1404    SETranslatingPortProxy &prox = tc->getMemProxy();
1405    uint64_t tiov_base = p->getSyscallArg(tc, index);
1406    size_t count = p->getSyscallArg(tc, index);
1407    struct iovec hiov[count];
1408    for (size_t i = 0; i < count; ++i) {
1409        typename OS::tgt_iovec tiov;
1410
1411        prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1412                      (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1413        hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1414        hiov[i].iov_base = new char [hiov[i].iov_len];
1415        prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1416                      hiov[i].iov_len);
1417    }
1418
1419    int result = writev(sim_fd, hiov, count);
1420
1421    for (size_t i = 0; i < count; ++i)
1422        delete [] (char *)hiov[i].iov_base;
1423
1424    if (result < 0)
1425        return -errno;
1426
1427    return result;
1428}
1429
1430/// Real mmap handler.
1431template <class OS>
1432SyscallReturn
1433mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1434         bool is_mmap2)
1435{
1436    int index = 0;
1437    Addr start = p->getSyscallArg(tc, index);
1438    uint64_t length = p->getSyscallArg(tc, index);
1439    int prot = p->getSyscallArg(tc, index);
1440    int tgt_flags = p->getSyscallArg(tc, index);
1441    int tgt_fd = p->getSyscallArg(tc, index);
1442    int offset = p->getSyscallArg(tc, index);
1443
1444    if (is_mmap2)
1445        offset *= TheISA::PageBytes;
1446
1447    if (start & (TheISA::PageBytes - 1) ||
1448        offset & (TheISA::PageBytes - 1) ||
1449        (tgt_flags & OS::TGT_MAP_PRIVATE &&
1450         tgt_flags & OS::TGT_MAP_SHARED) ||
1451        (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1452         !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1453        !length) {
1454        return -EINVAL;
1455    }
1456
1457    if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1458        // With shared mmaps, there are two cases to consider:
1459        // 1) anonymous: writes should modify the mapping and this should be
1460        // visible to observers who share the mapping. Currently, it's
1461        // difficult to update the shared mapping because there's no
1462        // structure which maintains information about the which virtual
1463        // memory areas are shared. If that structure existed, it would be
1464        // possible to make the translations point to the same frames.
1465        // 2) file-backed: writes should modify the mapping and the file
1466        // which is backed by the mapping. The shared mapping problem is the
1467        // same as what was mentioned about the anonymous mappings. For
1468        // file-backed mappings, the writes to the file are difficult
1469        // because it requires syncing what the mapping holds with the file
1470        // that resides on the host system. So, any write on a real system
1471        // would cause the change to be propagated to the file mapping at
1472        // some point in the future (the inode is tracked along with the
1473        // mapping). This isn't guaranteed to always happen, but it usually
1474        // works well enough. The guarantee is provided by the msync system
1475        // call. We could force the change through with shared mappings with
1476        // a call to msync, but that again would require more information
1477        // than we currently maintain.
1478        warn("mmap: writing to shared mmap region is currently "
1479             "unsupported. The write succeeds on the target, but it "
1480             "will not be propagated to the host or shared mappings");
1481    }
1482
1483    length = roundUp(length, TheISA::PageBytes);
1484
1485    int sim_fd = -1;
1486    uint8_t *pmap = nullptr;
1487    if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1488        std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1489
1490        auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1491        if (dfdp) {
1492            EmulatedDriver *emul_driver = dfdp->getDriver();
1493            return emul_driver->mmap(p, tc, start, length, prot,
1494                                     tgt_flags, tgt_fd, offset);
1495        }
1496
1497        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1498        if (!ffdp)
1499            return -EBADF;
1500        sim_fd = ffdp->getSimFD();
1501
1502        pmap = (decltype(pmap))mmap(NULL, length, PROT_READ, MAP_PRIVATE,
1503                                    sim_fd, offset);
1504
1505        if (pmap == (decltype(pmap))-1) {
1506            warn("mmap: failed to map file into host address space");
1507            return -errno;
1508        }
1509    }
1510
1511    // Extend global mmap region if necessary. Note that we ignore the
1512    // start address unless MAP_FIXED is specified.
1513    if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1514        std::shared_ptr<MemState> mem_state = p->memState;
1515        Addr mmap_end = mem_state->getMmapEnd();
1516
1517        start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1518        mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1519
1520        mem_state->setMmapEnd(mmap_end);
1521    }
1522
1523    DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1524                    start, start + length - 1);
1525
1526    // We only allow mappings to overwrite existing mappings if
1527    // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1528    // because we ignore the start hint if TGT_MAP_FIXED is not set.
1529    int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1530    if (clobber) {
1531        for (auto tc : p->system->threadContexts) {
1532            // If we might be overwriting old mappings, we need to
1533            // invalidate potentially stale mappings out of the TLBs.
1534            tc->getDTBPtr()->flushAll();
1535            tc->getITBPtr()->flushAll();
1536        }
1537    }
1538
1539    // Allocate physical memory and map it in. If the page table is already
1540    // mapped and clobber is not set, the simulator will issue throw a
1541    // fatal and bail out of the simulation.
1542    p->allocateMem(start, length, clobber);
1543
1544    // Transfer content into target address space.
1545    SETranslatingPortProxy &tp = tc->getMemProxy();
1546    if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1547        // In general, we should zero the mapped area for anonymous mappings,
1548        // with something like:
1549        //     tp.memsetBlob(start, 0, length);
1550        // However, given that we don't support sparse mappings, and
1551        // some applications can map a couple of gigabytes of space
1552        // (intending sparse usage), that can get painfully expensive.
1553        // Fortunately, since we don't properly implement munmap either,
1554        // there's no danger of remapping used memory, so for now all
1555        // newly mapped memory should already be zeroed so we can skip it.
1556    } else {
1557        // It is possible to mmap an area larger than a file, however
1558        // accessing unmapped portions the system triggers a "Bus error"
1559        // on the host. We must know when to stop copying the file from
1560        // the host into the target address space.
1561        struct stat file_stat;
1562        if (fstat(sim_fd, &file_stat) > 0)
1563            fatal("mmap: cannot stat file");
1564
1565        // Copy the portion of the file that is resident. This requires
1566        // checking both the mmap size and the filesize that we are
1567        // trying to mmap into this space; the mmap size also depends
1568        // on the specified offset into the file.
1569        uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1570                                 length);
1571        tp.writeBlob(start, pmap, size);
1572
1573        // Cleanup the mmap region before exiting this function.
1574        munmap(pmap, length);
1575
1576        // Maintain the symbol table for dynamic executables.
1577        // The loader will call mmap to map the images into its address
1578        // space and we intercept that here. We can verify that we are
1579        // executing inside the loader by checking the program counter value.
1580        // XXX: with multiprogrammed workloads or multi-node configurations,
1581        // this will not work since there is a single global symbol table.
1582        ObjectFile *interpreter = p->getInterpreter();
1583        if (interpreter) {
1584            Addr text_start = interpreter->textBase();
1585            Addr text_end = text_start + interpreter->textSize();
1586
1587            Addr pc = tc->pcState().pc();
1588
1589            if (pc >= text_start && pc < text_end) {
1590                std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1591                auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1592                ObjectFile *lib = createObjectFile(ffdp->getFileName());
1593
1594                if (lib) {
1595                    lib->loadAllSymbols(debugSymbolTable,
1596                                        lib->textBase(), start);
1597                }
1598            }
1599        }
1600
1601        // Note that we do not zero out the remainder of the mapping. This
1602        // is done by a real system, but it probably will not affect
1603        // execution (hopefully).
1604    }
1605
1606    return start;
1607}
1608
1609template <class OS>
1610SyscallReturn
1611pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1612{
1613    int index = 0;
1614    int tgt_fd = p->getSyscallArg(tc, index);
1615    Addr bufPtr = p->getSyscallArg(tc, index);
1616    int nbytes = p->getSyscallArg(tc, index);
1617    int offset = p->getSyscallArg(tc, index);
1618
1619    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1620    if (!ffdp)
1621        return -EBADF;
1622    int sim_fd = ffdp->getSimFD();
1623
1624    BufferArg bufArg(bufPtr, nbytes);
1625    bufArg.copyIn(tc->getMemProxy());
1626
1627    int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1628
1629    return (bytes_written == -1) ? -errno : bytes_written;
1630}
1631
1632/// Target mmap() handler.
1633template <class OS>
1634SyscallReturn
1635mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1636{
1637    return mmapImpl<OS>(desc, num, p, tc, false);
1638}
1639
1640/// Target mmap2() handler.
1641template <class OS>
1642SyscallReturn
1643mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1644{
1645    return mmapImpl<OS>(desc, num, p, tc, true);
1646}
1647
1648/// Target getrlimit() handler.
1649template <class OS>
1650SyscallReturn
1651getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1652              ThreadContext *tc)
1653{
1654    int index = 0;
1655    unsigned resource = process->getSyscallArg(tc, index);
1656    TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1657
1658    switch (resource) {
1659      case OS::TGT_RLIMIT_STACK:
1660        // max stack size in bytes: make up a number (8MB for now)
1661        rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1662        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1663        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1664        break;
1665
1666      case OS::TGT_RLIMIT_DATA:
1667        // max data segment size in bytes: make up a number
1668        rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1669        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1670        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1671        break;
1672
1673      default:
1674        warn("getrlimit: unimplemented resource %d", resource);
1675        return -EINVAL;
1676        break;
1677    }
1678
1679    rlp.copyOut(tc->getMemProxy());
1680    return 0;
1681}
1682
1683/// Target clock_gettime() function.
1684template <class OS>
1685SyscallReturn
1686clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1687{
1688    int index = 1;
1689    //int clk_id = p->getSyscallArg(tc, index);
1690    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1691
1692    getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1693    tp->tv_sec += seconds_since_epoch;
1694    tp->tv_sec = TheISA::htog(tp->tv_sec);
1695    tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1696
1697    tp.copyOut(tc->getMemProxy());
1698
1699    return 0;
1700}
1701
1702/// Target clock_getres() function.
1703template <class OS>
1704SyscallReturn
1705clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1706{
1707    int index = 1;
1708    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1709
1710    // Set resolution at ns, which is what clock_gettime() returns
1711    tp->tv_sec = 0;
1712    tp->tv_nsec = 1;
1713
1714    tp.copyOut(tc->getMemProxy());
1715
1716    return 0;
1717}
1718
1719/// Target gettimeofday() handler.
1720template <class OS>
1721SyscallReturn
1722gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1723                 ThreadContext *tc)
1724{
1725    int index = 0;
1726    TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1727
1728    getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1729    tp->tv_sec += seconds_since_epoch;
1730    tp->tv_sec = TheISA::htog(tp->tv_sec);
1731    tp->tv_usec = TheISA::htog(tp->tv_usec);
1732
1733    tp.copyOut(tc->getMemProxy());
1734
1735    return 0;
1736}
1737
1738
1739/// Target utimes() handler.
1740template <class OS>
1741SyscallReturn
1742utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1743           ThreadContext *tc)
1744{
1745    std::string path;
1746
1747    int index = 0;
1748    if (!tc->getMemProxy().tryReadString(path,
1749                process->getSyscallArg(tc, index))) {
1750        return -EFAULT;
1751    }
1752
1753    TypedBufferArg<typename OS::timeval [2]>
1754        tp(process->getSyscallArg(tc, index));
1755    tp.copyIn(tc->getMemProxy());
1756
1757    struct timeval hostTimeval[2];
1758    for (int i = 0; i < 2; ++i) {
1759        hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1760        hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1761    }
1762
1763    // Adjust path for current working directory
1764    path = process->fullPath(path);
1765
1766    int result = utimes(path.c_str(), hostTimeval);
1767
1768    if (result < 0)
1769        return -errno;
1770
1771    return 0;
1772}
1773
1774template <class OS>
1775SyscallReturn
1776execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1777{
1778    desc->setFlags(0);
1779
1780    int index = 0;
1781    std::string path;
1782    SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
1783    if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
1784        return -EFAULT;
1785
1786    if (access(path.c_str(), F_OK) == -1)
1787        return -EACCES;
1788
1789    auto read_in = [](std::vector<std::string> & vect,
1790                      SETranslatingPortProxy & mem_proxy,
1791                      Addr mem_loc)
1792    {
1793        for (int inc = 0; ; inc++) {
1794            BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
1795            b.copyIn(mem_proxy);
1796
1797            if (!*(Addr*)b.bufferPtr())
1798                break;
1799
1800            vect.push_back(std::string());
1801            mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
1802        }
1803    };
1804
1805    /**
1806     * Note that ProcessParams is generated by swig and there are no other
1807     * examples of how to create anything but this default constructor. The
1808     * fields are manually initialized instead of passing parameters to the
1809     * constructor.
1810     */
1811    ProcessParams *pp = new ProcessParams();
1812    pp->executable = path;
1813    Addr argv_mem_loc = p->getSyscallArg(tc, index);
1814    read_in(pp->cmd, mem_proxy, argv_mem_loc);
1815    Addr envp_mem_loc = p->getSyscallArg(tc, index);
1816    read_in(pp->env, mem_proxy, envp_mem_loc);
1817    pp->uid = p->uid();
1818    pp->egid = p->egid();
1819    pp->euid = p->euid();
1820    pp->gid = p->gid();
1821    pp->ppid = p->ppid();
1822    pp->pid = p->pid();
1823    pp->input.assign("cin");
1824    pp->output.assign("cout");
1825    pp->errout.assign("cerr");
1826    pp->cwd.assign(p->getcwd());
1827    pp->system = p->system;
1828    /**
1829     * Prevent process object creation with identical PIDs (which will trip
1830     * a fatal check in Process constructor). The execve call is supposed to
1831     * take over the currently executing process' identity but replace
1832     * whatever it is doing with a new process image. Instead of hijacking
1833     * the process object in the simulator, we create a new process object
1834     * and bind to the previous process' thread below (hijacking the thread).
1835     */
1836    p->system->PIDs.erase(p->pid());
1837    Process *new_p = pp->create();
1838    delete pp;
1839
1840    /**
1841     * Work through the file descriptor array and close any files marked
1842     * close-on-exec.
1843     */
1844    new_p->fds = p->fds;
1845    for (int i = 0; i < new_p->fds->getSize(); i++) {
1846        std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
1847        if (fdep && fdep->getCOE())
1848            new_p->fds->closeFDEntry(i);
1849    }
1850
1851    *new_p->sigchld = true;
1852
1853    delete p;
1854    tc->clearArchRegs();
1855    tc->setProcessPtr(new_p);
1856    new_p->assignThreadContext(tc->contextId());
1857    new_p->initState();
1858    tc->activate();
1859    TheISA::PCState pcState = tc->pcState();
1860    tc->setNPC(pcState.instAddr());
1861
1862    desc->setFlags(SyscallDesc::SuppressReturnValue);
1863    return 0;
1864}
1865
1866/// Target getrusage() function.
1867template <class OS>
1868SyscallReturn
1869getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
1870              ThreadContext *tc)
1871{
1872    int index = 0;
1873    int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
1874    TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
1875
1876    rup->ru_utime.tv_sec = 0;
1877    rup->ru_utime.tv_usec = 0;
1878    rup->ru_stime.tv_sec = 0;
1879    rup->ru_stime.tv_usec = 0;
1880    rup->ru_maxrss = 0;
1881    rup->ru_ixrss = 0;
1882    rup->ru_idrss = 0;
1883    rup->ru_isrss = 0;
1884    rup->ru_minflt = 0;
1885    rup->ru_majflt = 0;
1886    rup->ru_nswap = 0;
1887    rup->ru_inblock = 0;
1888    rup->ru_oublock = 0;
1889    rup->ru_msgsnd = 0;
1890    rup->ru_msgrcv = 0;
1891    rup->ru_nsignals = 0;
1892    rup->ru_nvcsw = 0;
1893    rup->ru_nivcsw = 0;
1894
1895    switch (who) {
1896      case OS::TGT_RUSAGE_SELF:
1897        getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
1898        rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
1899        rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
1900        break;
1901
1902      case OS::TGT_RUSAGE_CHILDREN:
1903        // do nothing.  We have no child processes, so they take no time.
1904        break;
1905
1906      default:
1907        // don't really handle THREAD or CHILDREN, but just warn and
1908        // plow ahead
1909        warn("getrusage() only supports RUSAGE_SELF.  Parameter %d ignored.",
1910             who);
1911    }
1912
1913    rup.copyOut(tc->getMemProxy());
1914
1915    return 0;
1916}
1917
1918/// Target times() function.
1919template <class OS>
1920SyscallReturn
1921timesFunc(SyscallDesc *desc, int callnum, Process *process,
1922          ThreadContext *tc)
1923{
1924    int index = 0;
1925    TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
1926
1927    // Fill in the time structure (in clocks)
1928    int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
1929    bufp->tms_utime = clocks;
1930    bufp->tms_stime = 0;
1931    bufp->tms_cutime = 0;
1932    bufp->tms_cstime = 0;
1933
1934    // Convert to host endianness
1935    bufp->tms_utime = TheISA::htog(bufp->tms_utime);
1936
1937    // Write back
1938    bufp.copyOut(tc->getMemProxy());
1939
1940    // Return clock ticks since system boot
1941    return clocks;
1942}
1943
1944/// Target time() function.
1945template <class OS>
1946SyscallReturn
1947timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
1948{
1949    typename OS::time_t sec, usec;
1950    getElapsedTimeMicro(sec, usec);
1951    sec += seconds_since_epoch;
1952
1953    int index = 0;
1954    Addr taddr = (Addr)process->getSyscallArg(tc, index);
1955    if (taddr != 0) {
1956        typename OS::time_t t = sec;
1957        t = TheISA::htog(t);
1958        SETranslatingPortProxy &p = tc->getMemProxy();
1959        p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
1960    }
1961    return sec;
1962}
1963
1964
1965#endif // __SIM_SYSCALL_EMUL_HH__
1966