syscall_emul.hh revision 11913
12221SN/A/*
22221SN/A * Copyright (c) 2012-2013, 2015 ARM Limited
32221SN/A * Copyright (c) 2015 Advanced Micro Devices, Inc.
42221SN/A * All rights reserved
52221SN/A *
62221SN/A * The license below extends only to copyright in the software and shall
72221SN/A * not be construed as granting a license to any other intellectual
82221SN/A * property including but not limited to intellectual property relating
92221SN/A * to a hardware implementation of the functionality of the software
102221SN/A * licensed hereunder.  You may use the software subject to the license
112221SN/A * terms below provided that you ensure that this notice is replicated
122221SN/A * unmodified and in its entirety in all distributions of the software,
132221SN/A * modified or unmodified, in source code or in binary form.
142221SN/A *
152221SN/A * Copyright (c) 2003-2005 The Regents of The University of Michigan
162221SN/A * All rights reserved.
172221SN/A *
182221SN/A * Redistribution and use in source and binary forms, with or without
192221SN/A * modification, are permitted provided that the following conditions are
202221SN/A * met: redistributions of source code must retain the above copyright
212221SN/A * notice, this list of conditions and the following disclaimer;
222221SN/A * redistributions in binary form must reproduce the above copyright
232221SN/A * notice, this list of conditions and the following disclaimer in the
242221SN/A * documentation and/or other materials provided with the distribution;
252221SN/A * neither the name of the copyright holders nor the names of its
262221SN/A * contributors may be used to endorse or promote products derived from
272665Ssaidi@eecs.umich.edu * this software without specific prior written permission.
282665Ssaidi@eecs.umich.edu *
292665Ssaidi@eecs.umich.edu * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
302221SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
312221SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
323415Sgblack@eecs.umich.edu * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
333415Sgblack@eecs.umich.edu * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
342223SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
353415Sgblack@eecs.umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
368778Sgblack@eecs.umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
373578Sgblack@eecs.umich.edu * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
383415Sgblack@eecs.umich.edu * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
393415Sgblack@eecs.umich.edu * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
408750Sgblack@eecs.umich.edu *
413415Sgblack@eecs.umich.edu * Authors: Steve Reinhardt
422680Sktlim@umich.edu *          Kevin Lim
433415Sgblack@eecs.umich.edu */
442800Ssaidi@eecs.umich.edu
458750Sgblack@eecs.umich.edu#ifndef __SIM_SYSCALL_EMUL_HH__
462221SN/A#define __SIM_SYSCALL_EMUL_HH__
473415Sgblack@eecs.umich.edu
483415Sgblack@eecs.umich.edu#define NO_STAT64 (defined(__APPLE__) || defined(__OpenBSD__) || \
492223SN/A  defined(__FreeBSD__) || defined(__CYGWIN__) || \
502221SN/A  defined(__NetBSD__))
512221SN/A
523573Sgblack@eecs.umich.edu#define NO_STATFS (defined(__APPLE__) || defined(__OpenBSD__) || \
533576Sgblack@eecs.umich.edu  defined(__FreeBSD__) || defined(__NetBSD__))
549551Sandreas.hansson@arm.com
552221SN/A#define NO_FALLOCATE (defined(__APPLE__) || defined(__OpenBSD__) || \
563573Sgblack@eecs.umich.edu  defined(__FreeBSD__) || defined(__NetBSD__))
573576Sgblack@eecs.umich.edu
589551Sandreas.hansson@arm.com///
592221SN/A/// @file syscall_emul.hh
603573Sgblack@eecs.umich.edu///
613576Sgblack@eecs.umich.edu/// This file defines objects used to emulate syscalls from the target
629551Sandreas.hansson@arm.com/// application on the host machine.
632221SN/A
643573Sgblack@eecs.umich.edu#ifdef __CYGWIN32__
653576Sgblack@eecs.umich.edu#include <sys/fcntl.h>
669551Sandreas.hansson@arm.com
672221SN/A#endif
683573Sgblack@eecs.umich.edu#include <fcntl.h>
693576Sgblack@eecs.umich.edu#include <sys/mman.h>
709551Sandreas.hansson@arm.com#include <sys/stat.h>
712221SN/A#if (NO_STATFS == 0)
723573Sgblack@eecs.umich.edu#include <sys/statfs.h>
733576Sgblack@eecs.umich.edu#else
749551Sandreas.hansson@arm.com#include <sys/mount.h>
752221SN/A#endif
763573Sgblack@eecs.umich.edu#include <sys/time.h>
773576Sgblack@eecs.umich.edu#include <sys/uio.h>
789551Sandreas.hansson@arm.com#include <unistd.h>
793576Sgblack@eecs.umich.edu
803576Sgblack@eecs.umich.edu#include <cerrno>
813576Sgblack@eecs.umich.edu#include <memory>
823576Sgblack@eecs.umich.edu#include <string>
833576Sgblack@eecs.umich.edu
842221SN/A#include "arch/utility.hh"
853573Sgblack@eecs.umich.edu#include "base/intmath.hh"
863576Sgblack@eecs.umich.edu#include "base/loader/object_file.hh"
879551Sandreas.hansson@arm.com#include "base/misc.hh"
882221SN/A#include "base/trace.hh"
893573Sgblack@eecs.umich.edu#include "base/types.hh"
903576Sgblack@eecs.umich.edu#include "config/the_isa.hh"
919551Sandreas.hansson@arm.com#include "cpu/base.hh"
922221SN/A#include "cpu/thread_context.hh"
933573Sgblack@eecs.umich.edu#include "mem/page_table.hh"
943576Sgblack@eecs.umich.edu#include "params/Process.hh"
959551Sandreas.hansson@arm.com#include "sim/emul_driver.hh"
963576Sgblack@eecs.umich.edu#include "sim/futex_map.hh"
973576Sgblack@eecs.umich.edu#include "sim/process.hh"
983576Sgblack@eecs.umich.edu#include "sim/syscall_debug_macros.hh"
993576Sgblack@eecs.umich.edu#include "sim/syscall_desc.hh"
1003576Sgblack@eecs.umich.edu#include "sim/syscall_emul_buf.hh"
1013576Sgblack@eecs.umich.edu#include "sim/syscall_return.hh"
1023576Sgblack@eecs.umich.edu
1033576Sgblack@eecs.umich.edu//////////////////////////////////////////////////////////////////////
1043576Sgblack@eecs.umich.edu//
1053576Sgblack@eecs.umich.edu// The following emulation functions are generic enough that they
1062221SN/A// don't need to be recompiled for different emulated OS's.  They are
1073573Sgblack@eecs.umich.edu// defined in sim/syscall_emul.cc.
1083576Sgblack@eecs.umich.edu//
1099551Sandreas.hansson@arm.com//////////////////////////////////////////////////////////////////////
1102221SN/A
1113573Sgblack@eecs.umich.edu
1123576Sgblack@eecs.umich.edu/// Handler for unimplemented syscalls that we haven't thought about.
1139551Sandreas.hansson@arm.comSyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
1142221SN/A                                Process *p, ThreadContext *tc);
1153573Sgblack@eecs.umich.edu
1163576Sgblack@eecs.umich.edu/// Handler for unimplemented syscalls that we never intend to
1179551Sandreas.hansson@arm.com/// implement (signal handling, etc.) and should not affect the correct
1182221SN/A/// behavior of the program.  Print a warning only if the appropriate
1193573Sgblack@eecs.umich.edu/// trace flag is enabled.  Return success to the target program.
1203576Sgblack@eecs.umich.eduSyscallReturn ignoreFunc(SyscallDesc *desc, int num,
1219551Sandreas.hansson@arm.com                         Process *p, ThreadContext *tc);
1222221SN/A
1233573Sgblack@eecs.umich.edu// Target fallocateFunc() handler.
1243576Sgblack@eecs.umich.eduSyscallReturn fallocateFunc(SyscallDesc *desc, int num,
1259551Sandreas.hansson@arm.com                            Process *p, ThreadContext *tc);
1262221SN/A
1273573Sgblack@eecs.umich.edu/// Target exit() handler: terminate current context.
1283576Sgblack@eecs.umich.eduSyscallReturn exitFunc(SyscallDesc *desc, int num,
1299551Sandreas.hansson@arm.com                       Process *p, ThreadContext *tc);
1302223SN/A
1313573Sgblack@eecs.umich.edu/// Target exit_group() handler: terminate simulation. (exit all threads)
1323576Sgblack@eecs.umich.eduSyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
1339551Sandreas.hansson@arm.com                       Process *p, ThreadContext *tc);
1342223SN/A
1353573Sgblack@eecs.umich.edu/// Target set_tid_address() handler.
1363576Sgblack@eecs.umich.eduSyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
1379551Sandreas.hansson@arm.com                                Process *p, ThreadContext *tc);
1382223SN/A
1393573Sgblack@eecs.umich.edu/// Target getpagesize() handler.
1403576Sgblack@eecs.umich.eduSyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
1419551Sandreas.hansson@arm.com                              Process *p, ThreadContext *tc);
1422223SN/A
1433573Sgblack@eecs.umich.edu/// Target brk() handler: set brk address.
1443576Sgblack@eecs.umich.eduSyscallReturn brkFunc(SyscallDesc *desc, int num,
1459551Sandreas.hansson@arm.com                      Process *p, ThreadContext *tc);
1463576Sgblack@eecs.umich.edu
1473576Sgblack@eecs.umich.edu/// Target close() handler.
1483576Sgblack@eecs.umich.eduSyscallReturn closeFunc(SyscallDesc *desc, int num,
1493576Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
1503576Sgblack@eecs.umich.edu
1512223SN/A// Target read() handler.
1523573Sgblack@eecs.umich.eduSyscallReturn readFunc(SyscallDesc *desc, int num,
1533576Sgblack@eecs.umich.edu                       Process *p, ThreadContext *tc);
1549551Sandreas.hansson@arm.com
1552223SN/A/// Target write() handler.
1563573Sgblack@eecs.umich.eduSyscallReturn writeFunc(SyscallDesc *desc, int num,
1573576Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
1589551Sandreas.hansson@arm.com
1592223SN/A/// Target lseek() handler.
1603573Sgblack@eecs.umich.eduSyscallReturn lseekFunc(SyscallDesc *desc, int num,
1613576Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
1629551Sandreas.hansson@arm.com
1632223SN/A/// Target _llseek() handler.
1643573Sgblack@eecs.umich.eduSyscallReturn _llseekFunc(SyscallDesc *desc, int num,
1653576Sgblack@eecs.umich.edu                          Process *p, ThreadContext *tc);
1669551Sandreas.hansson@arm.com
1672223SN/A/// Target munmap() handler.
1683573Sgblack@eecs.umich.eduSyscallReturn munmapFunc(SyscallDesc *desc, int num,
1693576Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
1709551Sandreas.hansson@arm.com
1712223SN/A/// Target gethostname() handler.
1723573Sgblack@eecs.umich.eduSyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
1733576Sgblack@eecs.umich.edu                              Process *p, ThreadContext *tc);
1749551Sandreas.hansson@arm.com
1752223SN/A/// Target getcwd() handler.
1763573Sgblack@eecs.umich.eduSyscallReturn getcwdFunc(SyscallDesc *desc, int num,
1773576Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
1789551Sandreas.hansson@arm.com
1792223SN/A/// Target readlink() handler.
1803573Sgblack@eecs.umich.eduSyscallReturn readlinkFunc(SyscallDesc *desc, int num,
1813576Sgblack@eecs.umich.edu                           Process *p, ThreadContext *tc,
1829551Sandreas.hansson@arm.com                           int index = 0);
1832223SN/ASyscallReturn readlinkFunc(SyscallDesc *desc, int num,
1843573Sgblack@eecs.umich.edu                           Process *p, ThreadContext *tc);
1853576Sgblack@eecs.umich.edu
1869551Sandreas.hansson@arm.com/// Target unlink() handler.
1872223SN/ASyscallReturn unlinkHelper(SyscallDesc *desc, int num,
1883573Sgblack@eecs.umich.edu                           Process *p, ThreadContext *tc,
1893576Sgblack@eecs.umich.edu                           int index);
1909551Sandreas.hansson@arm.comSyscallReturn unlinkFunc(SyscallDesc *desc, int num,
1912223SN/A                         Process *p, ThreadContext *tc);
1923576Sgblack@eecs.umich.edu
1933576Sgblack@eecs.umich.edu/// Target mkdir() handler.
1943576Sgblack@eecs.umich.eduSyscallReturn mkdirFunc(SyscallDesc *desc, int num,
1953576Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
1962527SN/A
1973573Sgblack@eecs.umich.edu/// Target rename() handler.
1983576Sgblack@eecs.umich.eduSyscallReturn renameFunc(SyscallDesc *desc, int num,
1999551Sandreas.hansson@arm.com                         Process *p, ThreadContext *tc);
2002223SN/A
2013573Sgblack@eecs.umich.edu
2023576Sgblack@eecs.umich.edu/// Target truncate() handler.
2039551Sandreas.hansson@arm.comSyscallReturn truncateFunc(SyscallDesc *desc, int num,
2042223SN/A                           Process *p, ThreadContext *tc);
2053573Sgblack@eecs.umich.edu
2063576Sgblack@eecs.umich.edu
2079551Sandreas.hansson@arm.com/// Target ftruncate() handler.
2082223SN/ASyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
2093573Sgblack@eecs.umich.edu                            Process *p, ThreadContext *tc);
2104103Ssaidi@eecs.umich.edu
2119551Sandreas.hansson@arm.com
2124103Ssaidi@eecs.umich.edu/// Target truncate64() handler.
2134103Ssaidi@eecs.umich.eduSyscallReturn truncate64Func(SyscallDesc *desc, int num,
2143576Sgblack@eecs.umich.edu                             Process *p, ThreadContext *tc);
2159551Sandreas.hansson@arm.com
2162223SN/A/// Target ftruncate64() handler.
2173573Sgblack@eecs.umich.eduSyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
2183576Sgblack@eecs.umich.edu                              Process *p, ThreadContext *tc);
2199551Sandreas.hansson@arm.com
2202223SN/A
2213573Sgblack@eecs.umich.edu/// Target umask() handler.
2223576Sgblack@eecs.umich.eduSyscallReturn umaskFunc(SyscallDesc *desc, int num,
2239551Sandreas.hansson@arm.com                        Process *p, ThreadContext *tc);
2243576Sgblack@eecs.umich.edu
2253576Sgblack@eecs.umich.edu/// Target gettid() handler.
2263576Sgblack@eecs.umich.eduSyscallReturn gettidFunc(SyscallDesc *desc, int num,
2279551Sandreas.hansson@arm.com                         Process *p, ThreadContext *tc);
2283576Sgblack@eecs.umich.edu
2293576Sgblack@eecs.umich.edu/// Target chown() handler.
2303576Sgblack@eecs.umich.eduSyscallReturn chownFunc(SyscallDesc *desc, int num,
2319551Sandreas.hansson@arm.com                        Process *p, ThreadContext *tc);
2323576Sgblack@eecs.umich.edu
2333576Sgblack@eecs.umich.edu/// Target setpgid() handler.
2343576Sgblack@eecs.umich.eduSyscallReturn setpgidFunc(SyscallDesc *desc, int num,
2359551Sandreas.hansson@arm.com                          Process *p, ThreadContext *tc);
2363576Sgblack@eecs.umich.edu
2373576Sgblack@eecs.umich.edu/// Target fchown() handler.
2383576Sgblack@eecs.umich.eduSyscallReturn fchownFunc(SyscallDesc *desc, int num,
2399551Sandreas.hansson@arm.com                         Process *p, ThreadContext *tc);
2403576Sgblack@eecs.umich.edu
2413576Sgblack@eecs.umich.edu/// Target dup() handler.
2423576Sgblack@eecs.umich.eduSyscallReturn dupFunc(SyscallDesc *desc, int num,
2439551Sandreas.hansson@arm.com                      Process *process, ThreadContext *tc);
2443576Sgblack@eecs.umich.edu
2453576Sgblack@eecs.umich.edu/// Target dup2() handler.
2463893Shsul@eecs.umich.eduSyscallReturn dup2Func(SyscallDesc *desc, int num,
2479551Sandreas.hansson@arm.com                       Process *process, ThreadContext *tc);
2483576Sgblack@eecs.umich.edu
2493576Sgblack@eecs.umich.edu/// Target fcntl() handler.
2503576Sgblack@eecs.umich.eduSyscallReturn fcntlFunc(SyscallDesc *desc, int num,
2519551Sandreas.hansson@arm.com                        Process *process, ThreadContext *tc);
2523576Sgblack@eecs.umich.edu
2533576Sgblack@eecs.umich.edu/// Target fcntl64() handler.
2543576Sgblack@eecs.umich.eduSyscallReturn fcntl64Func(SyscallDesc *desc, int num,
2559551Sandreas.hansson@arm.com                          Process *process, ThreadContext *tc);
2563576Sgblack@eecs.umich.edu
2573576Sgblack@eecs.umich.edu/// Target setuid() handler.
2583576Sgblack@eecs.umich.eduSyscallReturn setuidFunc(SyscallDesc *desc, int num,
2599551Sandreas.hansson@arm.com                         Process *p, ThreadContext *tc);
2603576Sgblack@eecs.umich.edu
2613576Sgblack@eecs.umich.edu/// Target pipe() handler.
2623576Sgblack@eecs.umich.eduSyscallReturn pipeFunc(SyscallDesc *desc, int num,
2639551Sandreas.hansson@arm.com                       Process *p, ThreadContext *tc);
2643576Sgblack@eecs.umich.edu
2653576Sgblack@eecs.umich.edu/// Internal pipe() handler.
2663576Sgblack@eecs.umich.eduSyscallReturn pipeImpl(SyscallDesc *desc, int num, Process *p,
2679551Sandreas.hansson@arm.com                       ThreadContext *tc, bool pseudoPipe);
2682223SN/A
2693415Sgblack@eecs.umich.edu/// Target getpid() handler.
2703578Sgblack@eecs.umich.eduSyscallReturn getpidFunc(SyscallDesc *desc, int num,
2713578Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
2723415Sgblack@eecs.umich.edu
2733415Sgblack@eecs.umich.edu/// Target getuid() handler.
2747741Sgblack@eecs.umich.eduSyscallReturn getuidFunc(SyscallDesc *desc, int num,
2757741Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
2763415Sgblack@eecs.umich.edu
2773578Sgblack@eecs.umich.edu/// Target getgid() handler.
2783578Sgblack@eecs.umich.eduSyscallReturn getgidFunc(SyscallDesc *desc, int num,
2798829Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
2808829Sgblack@eecs.umich.edu
2818829Sgblack@eecs.umich.edu/// Target getppid() handler.
2828829Sgblack@eecs.umich.eduSyscallReturn getppidFunc(SyscallDesc *desc, int num,
2837741Sgblack@eecs.umich.edu                          Process *p, ThreadContext *tc);
2847741Sgblack@eecs.umich.edu
2858829Sgblack@eecs.umich.edu/// Target geteuid() handler.
2868829Sgblack@eecs.umich.eduSyscallReturn geteuidFunc(SyscallDesc *desc, int num,
2878829Sgblack@eecs.umich.edu                          Process *p, ThreadContext *tc);
2883578Sgblack@eecs.umich.edu
2893578Sgblack@eecs.umich.edu/// Target getegid() handler.
2903578Sgblack@eecs.umich.eduSyscallReturn getegidFunc(SyscallDesc *desc, int num,
2913578Sgblack@eecs.umich.edu                          Process *p, ThreadContext *tc);
2923578Sgblack@eecs.umich.edu
2933578Sgblack@eecs.umich.edu/// Target access() handler
2943578Sgblack@eecs.umich.eduSyscallReturn accessFunc(SyscallDesc *desc, int num,
2957741Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
2967741Sgblack@eecs.umich.eduSyscallReturn accessFunc(SyscallDesc *desc, int num,
2973578Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc,
2984172Ssaidi@eecs.umich.edu                         int index);
2994172Ssaidi@eecs.umich.edu
3008829Sgblack@eecs.umich.edu/// Futex system call
3018829Sgblack@eecs.umich.edu/// Implemented by Daniel Sanchez
3023761Sgblack@eecs.umich.edu/// Used by printf's in multi-threaded apps
3034172Ssaidi@eecs.umich.edutemplate <class OS>
3044172Ssaidi@eecs.umich.eduSyscallReturn
3054172Ssaidi@eecs.umich.edufutexFunc(SyscallDesc *desc, int callnum, Process *process,
3064172Ssaidi@eecs.umich.edu          ThreadContext *tc)
3077720Sgblack@eecs.umich.edu{
3083578Sgblack@eecs.umich.edu    using namespace std;
3093578Sgblack@eecs.umich.edu
3103578Sgblack@eecs.umich.edu    int index = 0;
3118829Sgblack@eecs.umich.edu    Addr uaddr = process->getSyscallArg(tc, index);
3123928Ssaidi@eecs.umich.edu    int op = process->getSyscallArg(tc, index);
3137741Sgblack@eecs.umich.edu    int val = process->getSyscallArg(tc, index);
3143578Sgblack@eecs.umich.edu
3157741Sgblack@eecs.umich.edu    /*
3163578Sgblack@eecs.umich.edu     * Unsupported option that does not affect the correctness of the
3177741Sgblack@eecs.umich.edu     * application. This is a performance optimization utilized by Linux.
3183578Sgblack@eecs.umich.edu     */
3197741Sgblack@eecs.umich.edu    op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
3208829Sgblack@eecs.umich.edu
3217741Sgblack@eecs.umich.edu    FutexMap &futex_map = tc->getSystemPtr()->futexMap;
3223578Sgblack@eecs.umich.edu
3233578Sgblack@eecs.umich.edu    if (OS::TGT_FUTEX_WAIT == op) {
3247741Sgblack@eecs.umich.edu        // Ensure futex system call accessed atomically.
3254172Ssaidi@eecs.umich.edu        BufferArg buf(uaddr, sizeof(int));
3263578Sgblack@eecs.umich.edu        buf.copyIn(tc->getMemProxy());
3277741Sgblack@eecs.umich.edu        int mem_val = *(int*)buf.bufferPtr();
3287720Sgblack@eecs.umich.edu
3297741Sgblack@eecs.umich.edu        /*
3307720Sgblack@eecs.umich.edu         * The value in memory at uaddr is not equal with the expected val
3313578Sgblack@eecs.umich.edu         * (a different thread must have changed it before the system call was
3327741Sgblack@eecs.umich.edu         * invoked). In this case, we need to throw an error.
3338829Sgblack@eecs.umich.edu         */
3343578Sgblack@eecs.umich.edu        if (val != mem_val)
3357741Sgblack@eecs.umich.edu            return -OS::TGT_EWOULDBLOCK;
3364172Ssaidi@eecs.umich.edu
3373578Sgblack@eecs.umich.edu        futex_map.suspend(uaddr, process->tgid(), tc);
3387741Sgblack@eecs.umich.edu
3394172Ssaidi@eecs.umich.edu        return 0;
3403578Sgblack@eecs.umich.edu    } else if (OS::TGT_FUTEX_WAKE == op) {
3418829Sgblack@eecs.umich.edu        return futex_map.wakeup(uaddr, process->tgid(), val);
3428829Sgblack@eecs.umich.edu    }
3438829Sgblack@eecs.umich.edu
3448829Sgblack@eecs.umich.edu    warn("futex: op %d not implemented; ignoring.", op);
3458829Sgblack@eecs.umich.edu    return -ENOSYS;
3463578Sgblack@eecs.umich.edu}
3478829Sgblack@eecs.umich.edu
3488829Sgblack@eecs.umich.edu
3498829Sgblack@eecs.umich.edu/// Pseudo Funcs  - These functions use a different return convension,
3508829Sgblack@eecs.umich.edu/// returning a second value in a register other than the normal return register
3518829Sgblack@eecs.umich.eduSyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
3523578Sgblack@eecs.umich.edu                             Process *process, ThreadContext *tc);
3533578Sgblack@eecs.umich.edu
3543893Shsul@eecs.umich.edu/// Target getpidPseudo() handler.
3553415Sgblack@eecs.umich.eduSyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
3563893Shsul@eecs.umich.edu                               Process *p, ThreadContext *tc);
3573415Sgblack@eecs.umich.edu
3583893Shsul@eecs.umich.edu/// Target getuidPseudo() handler.
3593415Sgblack@eecs.umich.eduSyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
3603415Sgblack@eecs.umich.edu                               Process *p, ThreadContext *tc);
3613415Sgblack@eecs.umich.edu
3623420Sgblack@eecs.umich.edu/// Target getgidPseudo() handler.
3637741Sgblack@eecs.umich.eduSyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
3643415Sgblack@eecs.umich.edu                               Process *p, ThreadContext *tc);
3654172Ssaidi@eecs.umich.edu
3663415Sgblack@eecs.umich.edu
3673415Sgblack@eecs.umich.edu/// A readable name for 1,000,000, for converting microseconds to seconds.
3683415Sgblack@eecs.umich.educonst int one_million = 1000000;
3697741Sgblack@eecs.umich.edu/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
3707741Sgblack@eecs.umich.educonst int one_billion = 1000000000;
3717741Sgblack@eecs.umich.edu
3727741Sgblack@eecs.umich.edu/// Approximate seconds since the epoch (1/1/1970).  About a billion,
3737741Sgblack@eecs.umich.edu/// by my reckoning.  We want to keep this a constant (not use the
3747741Sgblack@eecs.umich.edu/// real-world time) to keep simulations repeatable.
3757741Sgblack@eecs.umich.educonst unsigned seconds_since_epoch = 1000000000;
3767741Sgblack@eecs.umich.edu
3777741Sgblack@eecs.umich.edu/// Helper function to convert current elapsed time to seconds and
3787741Sgblack@eecs.umich.edu/// microseconds.
3798829Sgblack@eecs.umich.edutemplate <class T1, class T2>
3808829Sgblack@eecs.umich.eduvoid
3817741Sgblack@eecs.umich.edugetElapsedTimeMicro(T1 &sec, T2 &usec)
3827741Sgblack@eecs.umich.edu{
3837741Sgblack@eecs.umich.edu    uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
3847741Sgblack@eecs.umich.edu    sec = elapsed_usecs / one_million;
3857741Sgblack@eecs.umich.edu    usec = elapsed_usecs % one_million;
3867741Sgblack@eecs.umich.edu}
3877741Sgblack@eecs.umich.edu
3887741Sgblack@eecs.umich.edu/// Helper function to convert current elapsed time to seconds and
3897741Sgblack@eecs.umich.edu/// nanoseconds.
3907741Sgblack@eecs.umich.edutemplate <class T1, class T2>
3917741Sgblack@eecs.umich.eduvoid
3928829Sgblack@eecs.umich.edugetElapsedTimeNano(T1 &sec, T2 &nsec)
3937741Sgblack@eecs.umich.edu{
3947741Sgblack@eecs.umich.edu    uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
3957741Sgblack@eecs.umich.edu    sec = elapsed_nsecs / one_billion;
3967741Sgblack@eecs.umich.edu    nsec = elapsed_nsecs % one_billion;
3977741Sgblack@eecs.umich.edu}
3987741Sgblack@eecs.umich.edu
3997741Sgblack@eecs.umich.edu//////////////////////////////////////////////////////////////////////
4007741Sgblack@eecs.umich.edu//
4017741Sgblack@eecs.umich.edu// The following emulation functions are generic, but need to be
4027741Sgblack@eecs.umich.edu// templated to account for differences in types, constants, etc.
4038829Sgblack@eecs.umich.edu//
4047741Sgblack@eecs.umich.edu//////////////////////////////////////////////////////////////////////
4057741Sgblack@eecs.umich.edu
4067741Sgblack@eecs.umich.edu    typedef struct statfs hst_statfs;
4077741Sgblack@eecs.umich.edu#if NO_STAT64
4087741Sgblack@eecs.umich.edu    typedef struct stat hst_stat;
4097741Sgblack@eecs.umich.edu    typedef struct stat hst_stat64;
4107741Sgblack@eecs.umich.edu#else
4117741Sgblack@eecs.umich.edu    typedef struct stat hst_stat;
4127741Sgblack@eecs.umich.edu    typedef struct stat64 hst_stat64;
4137741Sgblack@eecs.umich.edu#endif
4147741Sgblack@eecs.umich.edu
4157741Sgblack@eecs.umich.edu//// Helper function to convert a host stat buffer to a target stat
4168829Sgblack@eecs.umich.edu//// buffer.  Also copies the target buffer out to the simulated
4177741Sgblack@eecs.umich.edu//// memory space.  Used by stat(), fstat(), and lstat().
4187741Sgblack@eecs.umich.edu
4197741Sgblack@eecs.umich.edutemplate <typename target_stat, typename host_stat>
4207741Sgblack@eecs.umich.edustatic void
4217741Sgblack@eecs.umich.educonvertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
4227741Sgblack@eecs.umich.edu{
4237741Sgblack@eecs.umich.edu    using namespace TheISA;
4247741Sgblack@eecs.umich.edu
4257741Sgblack@eecs.umich.edu    if (fakeTTY)
4267741Sgblack@eecs.umich.edu        tgt->st_dev = 0xA;
4278829Sgblack@eecs.umich.edu    else
4288829Sgblack@eecs.umich.edu        tgt->st_dev = host->st_dev;
4298829Sgblack@eecs.umich.edu    tgt->st_dev = TheISA::htog(tgt->st_dev);
4308829Sgblack@eecs.umich.edu    tgt->st_ino = host->st_ino;
4318829Sgblack@eecs.umich.edu    tgt->st_ino = TheISA::htog(tgt->st_ino);
4328829Sgblack@eecs.umich.edu    tgt->st_mode = host->st_mode;
4337741Sgblack@eecs.umich.edu    if (fakeTTY) {
4347741Sgblack@eecs.umich.edu        // Claim to be a character device
4358829Sgblack@eecs.umich.edu        tgt->st_mode &= ~S_IFMT;    // Clear S_IFMT
4367741Sgblack@eecs.umich.edu        tgt->st_mode |= S_IFCHR;    // Set S_IFCHR
4378829Sgblack@eecs.umich.edu    }
4388829Sgblack@eecs.umich.edu    tgt->st_mode = TheISA::htog(tgt->st_mode);
4398829Sgblack@eecs.umich.edu    tgt->st_nlink = host->st_nlink;
4408829Sgblack@eecs.umich.edu    tgt->st_nlink = TheISA::htog(tgt->st_nlink);
4418829Sgblack@eecs.umich.edu    tgt->st_uid = host->st_uid;
4427741Sgblack@eecs.umich.edu    tgt->st_uid = TheISA::htog(tgt->st_uid);
4438829Sgblack@eecs.umich.edu    tgt->st_gid = host->st_gid;
4448829Sgblack@eecs.umich.edu    tgt->st_gid = TheISA::htog(tgt->st_gid);
4457741Sgblack@eecs.umich.edu    if (fakeTTY)
4468829Sgblack@eecs.umich.edu        tgt->st_rdev = 0x880d;
4477741Sgblack@eecs.umich.edu    else
4487741Sgblack@eecs.umich.edu        tgt->st_rdev = host->st_rdev;
4497741Sgblack@eecs.umich.edu    tgt->st_rdev = TheISA::htog(tgt->st_rdev);
4507741Sgblack@eecs.umich.edu    tgt->st_size = host->st_size;
4517741Sgblack@eecs.umich.edu    tgt->st_size = TheISA::htog(tgt->st_size);
4527741Sgblack@eecs.umich.edu    tgt->st_atimeX = host->st_atime;
4537741Sgblack@eecs.umich.edu    tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
4547741Sgblack@eecs.umich.edu    tgt->st_mtimeX = host->st_mtime;
4557741Sgblack@eecs.umich.edu    tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
4567741Sgblack@eecs.umich.edu    tgt->st_ctimeX = host->st_ctime;
4577741Sgblack@eecs.umich.edu    tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
4587741Sgblack@eecs.umich.edu    // Force the block size to be 8KB. This helps to ensure buffered io works
4597741Sgblack@eecs.umich.edu    // consistently across different hosts.
4607741Sgblack@eecs.umich.edu    tgt->st_blksize = 0x2000;
4617741Sgblack@eecs.umich.edu    tgt->st_blksize = TheISA::htog(tgt->st_blksize);
4627741Sgblack@eecs.umich.edu    tgt->st_blocks = host->st_blocks;
4637741Sgblack@eecs.umich.edu    tgt->st_blocks = TheISA::htog(tgt->st_blocks);
4647741Sgblack@eecs.umich.edu}
4657741Sgblack@eecs.umich.edu
4667741Sgblack@eecs.umich.edu// Same for stat64
4673578Sgblack@eecs.umich.edu
4683585Sgblack@eecs.umich.edutemplate <typename target_stat, typename host_stat64>
4693603Ssaidi@eecs.umich.edustatic void
4703595Sgblack@eecs.umich.educonvertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
4713578Sgblack@eecs.umich.edu{
4723578Sgblack@eecs.umich.edu    using namespace TheISA;
4733578Sgblack@eecs.umich.edu
4747741Sgblack@eecs.umich.edu    convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
4757741Sgblack@eecs.umich.edu#if defined(STAT_HAVE_NSEC)
4763578Sgblack@eecs.umich.edu    tgt->st_atime_nsec = host->st_atime_nsec;
4774172Ssaidi@eecs.umich.edu    tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
4783578Sgblack@eecs.umich.edu    tgt->st_mtime_nsec = host->st_mtime_nsec;
4793578Sgblack@eecs.umich.edu    tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
4803578Sgblack@eecs.umich.edu    tgt->st_ctime_nsec = host->st_ctime_nsec;
4813578Sgblack@eecs.umich.edu    tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
4827741Sgblack@eecs.umich.edu#else
4837741Sgblack@eecs.umich.edu    tgt->st_atime_nsec = 0;
4843578Sgblack@eecs.umich.edu    tgt->st_mtime_nsec = 0;
4854172Ssaidi@eecs.umich.edu    tgt->st_ctime_nsec = 0;
4863578Sgblack@eecs.umich.edu#endif
4873578Sgblack@eecs.umich.edu}
4883578Sgblack@eecs.umich.edu
4893578Sgblack@eecs.umich.edu// Here are a couple of convenience functions
4903578Sgblack@eecs.umich.edutemplate<class OS>
4913578Sgblack@eecs.umich.edustatic void
4927741Sgblack@eecs.umich.educopyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
49310417Sandreas.hansson@arm.com               hst_stat *host, bool fakeTTY = false)
4942221SN/A{
4952680Sktlim@umich.edu    typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
4968750Sgblack@eecs.umich.edu    tgt_stat_buf tgt(addr);
4978750Sgblack@eecs.umich.edu    convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
4988750Sgblack@eecs.umich.edu    tgt.copyOut(mem);
4992223SN/A}
5002221SN/A
5017741Sgblack@eecs.umich.edutemplate<class OS>
5027741Sgblack@eecs.umich.edustatic void
5034172Ssaidi@eecs.umich.educopyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
5044172Ssaidi@eecs.umich.edu                 hst_stat64 *host, bool fakeTTY = false)
5058829Sgblack@eecs.umich.edu{
5068829Sgblack@eecs.umich.edu    typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
5073578Sgblack@eecs.umich.edu    tgt_stat_buf tgt(addr);
5083578Sgblack@eecs.umich.edu    convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
5093578Sgblack@eecs.umich.edu    tgt.copyOut(mem);
5103578Sgblack@eecs.umich.edu}
5118829Sgblack@eecs.umich.edu
5123746Sgblack@eecs.umich.edutemplate <class OS>
5138829Sgblack@eecs.umich.edustatic void
5143578Sgblack@eecs.umich.educopyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
5153578Sgblack@eecs.umich.edu                 hst_statfs *host)
5163746Sgblack@eecs.umich.edu{
5173578Sgblack@eecs.umich.edu    TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
5183578Sgblack@eecs.umich.edu
5193578Sgblack@eecs.umich.edu    tgt->f_type = TheISA::htog(host->f_type);
5208829Sgblack@eecs.umich.edu#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
5213595Sgblack@eecs.umich.edu    tgt->f_bsize = TheISA::htog(host->f_iosize);
5223893Shsul@eecs.umich.edu#else
5237741Sgblack@eecs.umich.edu    tgt->f_bsize = TheISA::htog(host->f_bsize);
5247741Sgblack@eecs.umich.edu#endif
5253578Sgblack@eecs.umich.edu    tgt->f_blocks = TheISA::htog(host->f_blocks);
5263893Shsul@eecs.umich.edu    tgt->f_bfree = TheISA::htog(host->f_bfree);
5273825Ssaidi@eecs.umich.edu    tgt->f_bavail = TheISA::htog(host->f_bavail);
5287741Sgblack@eecs.umich.edu    tgt->f_files = TheISA::htog(host->f_files);
5297741Sgblack@eecs.umich.edu    tgt->f_ffree = TheISA::htog(host->f_ffree);
5307741Sgblack@eecs.umich.edu    memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
5313893Shsul@eecs.umich.edu#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
5327741Sgblack@eecs.umich.edu    tgt->f_namelen = TheISA::htog(host->f_namemax);
5333578Sgblack@eecs.umich.edu    tgt->f_frsize = TheISA::htog(host->f_bsize);
5343585Sgblack@eecs.umich.edu#elif defined(__APPLE__)
5353893Shsul@eecs.umich.edu    tgt->f_namelen = 0;
5365570Snate@binkert.org    tgt->f_frsize = 0;
5373578Sgblack@eecs.umich.edu#else
5383585Sgblack@eecs.umich.edu    tgt->f_namelen = TheISA::htog(host->f_namelen);
5393826Ssaidi@eecs.umich.edu    tgt->f_frsize = TheISA::htog(host->f_frsize);
5403578Sgblack@eecs.umich.edu#endif
5417741Sgblack@eecs.umich.edu#if defined(__linux__)
5423578Sgblack@eecs.umich.edu    memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
5433578Sgblack@eecs.umich.edu#else
5447720Sgblack@eecs.umich.edu    /*
5457720Sgblack@eecs.umich.edu     * The fields are different sizes per OS. Don't bother with
5467720Sgblack@eecs.umich.edu     * f_spare or f_reserved on non-Linux for now.
5477720Sgblack@eecs.umich.edu     */
5487720Sgblack@eecs.umich.edu    memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
5497720Sgblack@eecs.umich.edu#endif
5507720Sgblack@eecs.umich.edu
5513420Sgblack@eecs.umich.edu    tgt.copyOut(mem);
5522221SN/A}
5537741Sgblack@eecs.umich.edu
55410417Sandreas.hansson@arm.com/// Target ioctl() handler.  For the most part, programs call ioctl()
5553523Sgblack@eecs.umich.edu/// only to find out if their stdout is a tty, to determine whether to
5567741Sgblack@eecs.umich.edu/// do line or block buffering.  We always claim that output fds are
5577741Sgblack@eecs.umich.edu/// not TTYs to provide repeatable results.
5587741Sgblack@eecs.umich.edutemplate <class OS>
5593595Sgblack@eecs.umich.eduSyscallReturn
5604172Ssaidi@eecs.umich.eduioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
5614172Ssaidi@eecs.umich.edu{
5624172Ssaidi@eecs.umich.edu    int index = 0;
5633595Sgblack@eecs.umich.edu    int tgt_fd = p->getSyscallArg(tc, index);
5648829Sgblack@eecs.umich.edu    unsigned req = p->getSyscallArg(tc, index);
5658829Sgblack@eecs.umich.edu
5668829Sgblack@eecs.umich.edu    DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
5678829Sgblack@eecs.umich.edu
5683595Sgblack@eecs.umich.edu    if (OS::isTtyReq(req))
5697741Sgblack@eecs.umich.edu        return -ENOTTY;
5708829Sgblack@eecs.umich.edu
5718829Sgblack@eecs.umich.edu    auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
5728829Sgblack@eecs.umich.edu    if (!dfdp)
5738829Sgblack@eecs.umich.edu        return -EBADF;
5748829Sgblack@eecs.umich.edu
5758829Sgblack@eecs.umich.edu    /**
5763595Sgblack@eecs.umich.edu     * If the driver is valid, issue the ioctl through it. Otherwise,
5777741Sgblack@eecs.umich.edu     * there's an implicit assumption that the device is a TTY type and we
5784172Ssaidi@eecs.umich.edu     * return that we do not have a valid TTY.
5793595Sgblack@eecs.umich.edu     */
5807741Sgblack@eecs.umich.edu    EmulatedDriver *emul_driver = dfdp->getDriver();
5817741Sgblack@eecs.umich.edu    if (emul_driver)
5823746Sgblack@eecs.umich.edu        return emul_driver->ioctl(p, tc, req);
5833746Sgblack@eecs.umich.edu
5843595Sgblack@eecs.umich.edu    /**
5853595Sgblack@eecs.umich.edu     * For lack of a better return code, return ENOTTY. Ideally, we should
5867720Sgblack@eecs.umich.edu     * return something better here, but at least we issue the warning.
5877720Sgblack@eecs.umich.edu     */
5887720Sgblack@eecs.umich.edu    warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
5897720Sgblack@eecs.umich.edu         tgt_fd, req, tc->pcState());
5907720Sgblack@eecs.umich.edu    return -ENOTTY;
5917720Sgblack@eecs.umich.edu}
5927720Sgblack@eecs.umich.edu
5937720Sgblack@eecs.umich.edutemplate <class OS>
5943595Sgblack@eecs.umich.eduSyscallReturn
5957741Sgblack@eecs.umich.eduopenImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
5967741Sgblack@eecs.umich.edu         bool isopenat)
5973523Sgblack@eecs.umich.edu{
5983595Sgblack@eecs.umich.edu    int index = 0;
5993595Sgblack@eecs.umich.edu    int tgt_dirfd = -1;
6003595Sgblack@eecs.umich.edu
6014172Ssaidi@eecs.umich.edu    /**
6023595Sgblack@eecs.umich.edu     * If using the openat variant, read in the target directory file
6033523Sgblack@eecs.umich.edu     * descriptor from the simulated process.
6047741Sgblack@eecs.umich.edu     */
6053523Sgblack@eecs.umich.edu    if (isopenat)
6063523Sgblack@eecs.umich.edu        tgt_dirfd = p->getSyscallArg(tc, index);
6073523Sgblack@eecs.umich.edu
6083523Sgblack@eecs.umich.edu    /**
6093523Sgblack@eecs.umich.edu     * Retrieve the simulated process' memory proxy and then read in the path
6103523Sgblack@eecs.umich.edu     * string from that memory space into the host's working memory space.
6113523Sgblack@eecs.umich.edu     */
6123523Sgblack@eecs.umich.edu    std::string path;
6133523Sgblack@eecs.umich.edu    if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
6142221SN/A        return -EFAULT;
6152221SN/A
6167741Sgblack@eecs.umich.edu#ifdef __CYGWIN32__
61710417Sandreas.hansson@arm.com    int host_flags = O_BINARY;
61810417Sandreas.hansson@arm.com#else
6194997Sgblack@eecs.umich.edu    int host_flags = 0;
6208767Sgblack@eecs.umich.edu#endif
6218767Sgblack@eecs.umich.edu    /**
6228806Sgblack@eecs.umich.edu     * Translate target flags into host flags. Flags exist which are not
6238806Sgblack@eecs.umich.edu     * ported between architectures which can cause check failures.
6248806Sgblack@eecs.umich.edu     */
6258806Sgblack@eecs.umich.edu    int tgt_flags = p->getSyscallArg(tc, index);
6268806Sgblack@eecs.umich.edu    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
6278806Sgblack@eecs.umich.edu        if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
6288806Sgblack@eecs.umich.edu            tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
6298806Sgblack@eecs.umich.edu            host_flags |= OS::openFlagTable[i].hostFlag;
6304997Sgblack@eecs.umich.edu        }
6318806Sgblack@eecs.umich.edu    }
6328806Sgblack@eecs.umich.edu    if (tgt_flags) {
6338806Sgblack@eecs.umich.edu        warn("open%s: cannot decode flags 0x%x",
6344997Sgblack@eecs.umich.edu             isopenat ? "at" : "", tgt_flags);
6354997Sgblack@eecs.umich.edu    }
6364997Sgblack@eecs.umich.edu#ifdef __CYGWIN32__
6377741Sgblack@eecs.umich.edu    host_flags |= O_BINARY;
63810417Sandreas.hansson@arm.com#endif
6394997Sgblack@eecs.umich.edu
6408767Sgblack@eecs.umich.edu    int mode = p->getSyscallArg(tc, index);
6418767Sgblack@eecs.umich.edu
6428806Sgblack@eecs.umich.edu    /**
6438806Sgblack@eecs.umich.edu     * If the simulated process called open or openat with AT_FDCWD specified,
6448806Sgblack@eecs.umich.edu     * take the current working directory value which was passed into the
6458806Sgblack@eecs.umich.edu     * process class as a Python parameter and append the current path to
6468806Sgblack@eecs.umich.edu     * create a full path.
6478806Sgblack@eecs.umich.edu     * Otherwise, openat with a valid target directory file descriptor has
6488806Sgblack@eecs.umich.edu     * been called. If the path option, which was passed in as a parameter,
6498806Sgblack@eecs.umich.edu     * is not absolute, retrieve the directory file descriptor's path and
6508806Sgblack@eecs.umich.edu     * prepend it to the path passed in as a parameter.
6518806Sgblack@eecs.umich.edu     * In every case, we should have a full path (which is relevant to the
6528806Sgblack@eecs.umich.edu     * host) to work with after this block has been passed.
6538806Sgblack@eecs.umich.edu     */
6548767Sgblack@eecs.umich.edu    if (!isopenat || (isopenat && tgt_dirfd == OS::TGT_AT_FDCWD)) {
6558806Sgblack@eecs.umich.edu        path = p->fullPath(path);
6568806Sgblack@eecs.umich.edu    } else if (!startswith(path, "/")) {
6578806Sgblack@eecs.umich.edu        std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
6584997Sgblack@eecs.umich.edu        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
6594997Sgblack@eecs.umich.edu        if (!ffdp)
6604997Sgblack@eecs.umich.edu            return -EBADF;
6617741Sgblack@eecs.umich.edu        path.insert(0, ffdp->getFileName());
66210417Sandreas.hansson@arm.com    }
6633415Sgblack@eecs.umich.edu
6648778Sgblack@eecs.umich.edu    /**
6658778Sgblack@eecs.umich.edu     * Since this is an emulated environment, we create pseudo file
6668806Sgblack@eecs.umich.edu     * descriptors for device requests that have been registered with
6678806Sgblack@eecs.umich.edu     * the process class through Python; this allows us to create a file
6683415Sgblack@eecs.umich.edu     * descriptor for subsequent ioctl or mmap calls.
6698806Sgblack@eecs.umich.edu     */
6703415Sgblack@eecs.umich.edu    if (startswith(path, "/dev/")) {
6718806Sgblack@eecs.umich.edu        std::string filename = path.substr(strlen("/dev/"));
6723415Sgblack@eecs.umich.edu        EmulatedDriver *drv = p->findDriver(filename);
6738806Sgblack@eecs.umich.edu        if (drv) {
6748806Sgblack@eecs.umich.edu            DPRINTF_SYSCALL(Verbose, "open%s: passing call to "
6758806Sgblack@eecs.umich.edu                            "driver open with path[%s]\n",
6768806Sgblack@eecs.umich.edu                            isopenat ? "at" : "", path.c_str());
6778806Sgblack@eecs.umich.edu            return drv->open(p, tc, mode, host_flags);
6788806Sgblack@eecs.umich.edu        }
6793415Sgblack@eecs.umich.edu        /**
6803415Sgblack@eecs.umich.edu         * Fall through here for pass through to host devices, such
6817741Sgblack@eecs.umich.edu         * as /dev/zero
68210417Sandreas.hansson@arm.com         */
6833415Sgblack@eecs.umich.edu    }
6848778Sgblack@eecs.umich.edu
6858778Sgblack@eecs.umich.edu    /**
6868806Sgblack@eecs.umich.edu     * Some special paths and files cannot be called on the host and need
6878806Sgblack@eecs.umich.edu     * to be handled as special cases inside the simulator.
6883415Sgblack@eecs.umich.edu     * If the full path that was created above does not match any of the
6898806Sgblack@eecs.umich.edu     * special cases, pass it through to the open call on the host to let
6903415Sgblack@eecs.umich.edu     * the host open the file on our behalf.
6918806Sgblack@eecs.umich.edu     * If the host cannot open the file, return the host's error code back
6923415Sgblack@eecs.umich.edu     * through the system call to the simulated process.
6938806Sgblack@eecs.umich.edu     */
6948806Sgblack@eecs.umich.edu    int sim_fd = -1;
6958806Sgblack@eecs.umich.edu    std::vector<std::string> special_paths =
6968806Sgblack@eecs.umich.edu            { "/proc/", "/system/", "/sys/", "/platform/", "/etc/passwd" };
6978806Sgblack@eecs.umich.edu    for (auto entry : special_paths) {
6988806Sgblack@eecs.umich.edu        if (startswith(path, entry))
6993415Sgblack@eecs.umich.edu            sim_fd = OS::openSpecialFile(path, p, tc);
7003415Sgblack@eecs.umich.edu    }
7017741Sgblack@eecs.umich.edu    if (sim_fd == -1) {
70210417Sandreas.hansson@arm.com        sim_fd = open(path.c_str(), host_flags, mode);
7034111Sgblack@eecs.umich.edu    }
7048778Sgblack@eecs.umich.edu    if (sim_fd == -1) {
7058778Sgblack@eecs.umich.edu        int local = -errno;
7068806Sgblack@eecs.umich.edu        DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s\n",
7078806Sgblack@eecs.umich.edu                        isopenat ? "at" : "", path.c_str());
7084111Sgblack@eecs.umich.edu        return local;
7098806Sgblack@eecs.umich.edu    }
7108806Sgblack@eecs.umich.edu
7118806Sgblack@eecs.umich.edu    /**
7124111Sgblack@eecs.umich.edu     * The file was opened successfully and needs to be recorded in the
7138806Sgblack@eecs.umich.edu     * process' file descriptor array so that it can be retrieved later.
7144111Sgblack@eecs.umich.edu     * The target file descriptor that is chosen will be the lowest unused
7158806Sgblack@eecs.umich.edu     * file descriptor.
7168806Sgblack@eecs.umich.edu     * Return the indirect target file descriptor back to the simulated
7174111Sgblack@eecs.umich.edu     * process to act as a handle for the opened file.
7188806Sgblack@eecs.umich.edu     */
7198806Sgblack@eecs.umich.edu    auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
7208806Sgblack@eecs.umich.edu    int tgt_fd = p->fds->allocFD(ffdp);
7218806Sgblack@eecs.umich.edu    DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n",
7228806Sgblack@eecs.umich.edu                    isopenat ? "at" : "", sim_fd, tgt_fd, path.c_str());
7238806Sgblack@eecs.umich.edu    return tgt_fd;
7248806Sgblack@eecs.umich.edu}
7254111Sgblack@eecs.umich.edu
7264111Sgblack@eecs.umich.edu/// Target open() handler.
7272223SN/Atemplate <class OS>
7282221SN/ASyscallReturn
729openFunc(SyscallDesc *desc, int callnum, Process *process,
730         ThreadContext *tc)
731{
732    return openImpl<OS>(desc, callnum, process, tc, false);
733}
734
735/// Target openat() handler.
736template <class OS>
737SyscallReturn
738openatFunc(SyscallDesc *desc, int callnum, Process *process,
739           ThreadContext *tc)
740{
741    return openImpl<OS>(desc, callnum, process, tc, true);
742}
743
744/// Target unlinkat() handler.
745template <class OS>
746SyscallReturn
747unlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
748             ThreadContext *tc)
749{
750    int index = 0;
751    int dirfd = process->getSyscallArg(tc, index);
752    if (dirfd != OS::TGT_AT_FDCWD)
753        warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
754
755    return unlinkHelper(desc, callnum, process, tc, 1);
756}
757
758/// Target facessat() handler
759template <class OS>
760SyscallReturn
761faccessatFunc(SyscallDesc *desc, int callnum, Process *process,
762              ThreadContext *tc)
763{
764    int index = 0;
765    int dirfd = process->getSyscallArg(tc, index);
766    if (dirfd != OS::TGT_AT_FDCWD)
767        warn("faccessat: first argument not AT_FDCWD; unlikely to work");
768    return accessFunc(desc, callnum, process, tc, 1);
769}
770
771/// Target readlinkat() handler
772template <class OS>
773SyscallReturn
774readlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
775               ThreadContext *tc)
776{
777    int index = 0;
778    int dirfd = process->getSyscallArg(tc, index);
779    if (dirfd != OS::TGT_AT_FDCWD)
780        warn("openat: first argument not AT_FDCWD; unlikely to work");
781    return readlinkFunc(desc, callnum, process, tc, 1);
782}
783
784/// Target renameat() handler.
785template <class OS>
786SyscallReturn
787renameatFunc(SyscallDesc *desc, int callnum, Process *process,
788             ThreadContext *tc)
789{
790    int index = 0;
791
792    int olddirfd = process->getSyscallArg(tc, index);
793    if (olddirfd != OS::TGT_AT_FDCWD)
794        warn("renameat: first argument not AT_FDCWD; unlikely to work");
795
796    std::string old_name;
797
798    if (!tc->getMemProxy().tryReadString(old_name,
799                                         process->getSyscallArg(tc, index)))
800        return -EFAULT;
801
802    int newdirfd = process->getSyscallArg(tc, index);
803    if (newdirfd != OS::TGT_AT_FDCWD)
804        warn("renameat: third argument not AT_FDCWD; unlikely to work");
805
806    std::string new_name;
807
808    if (!tc->getMemProxy().tryReadString(new_name,
809                                         process->getSyscallArg(tc, index)))
810        return -EFAULT;
811
812    // Adjust path for current working directory
813    old_name = process->fullPath(old_name);
814    new_name = process->fullPath(new_name);
815
816    int result = rename(old_name.c_str(), new_name.c_str());
817    return (result == -1) ? -errno : result;
818}
819
820/// Target sysinfo() handler.
821template <class OS>
822SyscallReturn
823sysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
824            ThreadContext *tc)
825{
826
827    int index = 0;
828    TypedBufferArg<typename OS::tgt_sysinfo>
829        sysinfo(process->getSyscallArg(tc, index));
830
831    sysinfo->uptime = seconds_since_epoch;
832    sysinfo->totalram = process->system->memSize();
833    sysinfo->mem_unit = 1;
834
835    sysinfo.copyOut(tc->getMemProxy());
836
837    return 0;
838}
839
840/// Target chmod() handler.
841template <class OS>
842SyscallReturn
843chmodFunc(SyscallDesc *desc, int callnum, Process *process,
844          ThreadContext *tc)
845{
846    std::string path;
847
848    int index = 0;
849    if (!tc->getMemProxy().tryReadString(path,
850                process->getSyscallArg(tc, index))) {
851        return -EFAULT;
852    }
853
854    uint32_t mode = process->getSyscallArg(tc, index);
855    mode_t hostMode = 0;
856
857    // XXX translate mode flags via OS::something???
858    hostMode = mode;
859
860    // Adjust path for current working directory
861    path = process->fullPath(path);
862
863    // do the chmod
864    int result = chmod(path.c_str(), hostMode);
865    if (result < 0)
866        return -errno;
867
868    return 0;
869}
870
871
872/// Target fchmod() handler.
873template <class OS>
874SyscallReturn
875fchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
876{
877    int index = 0;
878    int tgt_fd = p->getSyscallArg(tc, index);
879    uint32_t mode = p->getSyscallArg(tc, index);
880
881    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
882    if (!ffdp)
883        return -EBADF;
884    int sim_fd = ffdp->getSimFD();
885
886    mode_t hostMode = mode;
887
888    int result = fchmod(sim_fd, hostMode);
889
890    return (result < 0) ? -errno : 0;
891}
892
893/// Target mremap() handler.
894template <class OS>
895SyscallReturn
896mremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
897{
898    int index = 0;
899    Addr start = process->getSyscallArg(tc, index);
900    uint64_t old_length = process->getSyscallArg(tc, index);
901    uint64_t new_length = process->getSyscallArg(tc, index);
902    uint64_t flags = process->getSyscallArg(tc, index);
903    uint64_t provided_address = 0;
904    bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
905
906    if (use_provided_address)
907        provided_address = process->getSyscallArg(tc, index);
908
909    if ((start % TheISA::PageBytes != 0) ||
910        (provided_address % TheISA::PageBytes != 0)) {
911        warn("mremap failing: arguments not page aligned");
912        return -EINVAL;
913    }
914
915    new_length = roundUp(new_length, TheISA::PageBytes);
916
917    if (new_length > old_length) {
918        std::shared_ptr<MemState> mem_state = process->memState;
919        Addr mmap_end = mem_state->getMmapEnd();
920
921        if ((start + old_length) == mmap_end &&
922            (!use_provided_address || provided_address == start)) {
923            uint64_t diff = new_length - old_length;
924            process->allocateMem(mmap_end, diff);
925            mem_state->setMmapEnd(mmap_end + diff);
926            return start;
927        } else {
928            if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
929                warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
930                return -ENOMEM;
931            } else {
932                uint64_t new_start = use_provided_address ?
933                    provided_address : mmap_end;
934                process->pTable->remap(start, old_length, new_start);
935                warn("mremapping to new vaddr %08p-%08p, adding %d\n",
936                     new_start, new_start + new_length,
937                     new_length - old_length);
938                // add on the remaining unallocated pages
939                process->allocateMem(new_start + old_length,
940                                     new_length - old_length,
941                                     use_provided_address /* clobber */);
942                if (!use_provided_address)
943                    mem_state->setMmapEnd(mmap_end + new_length);
944                if (use_provided_address &&
945                    new_start + new_length > mem_state->getMmapEnd()) {
946                    // something fishy going on here, at least notify the user
947                    // @todo: increase mmap_end?
948                    warn("mmap region limit exceeded with MREMAP_FIXED\n");
949                }
950                warn("returning %08p as start\n", new_start);
951                return new_start;
952            }
953        }
954    } else {
955        if (use_provided_address && provided_address != start)
956            process->pTable->remap(start, new_length, provided_address);
957        process->pTable->unmap(start + new_length, old_length - new_length);
958        return use_provided_address ? provided_address : start;
959    }
960}
961
962/// Target stat() handler.
963template <class OS>
964SyscallReturn
965statFunc(SyscallDesc *desc, int callnum, Process *process,
966         ThreadContext *tc)
967{
968    std::string path;
969
970    int index = 0;
971    if (!tc->getMemProxy().tryReadString(path,
972                process->getSyscallArg(tc, index))) {
973        return -EFAULT;
974    }
975    Addr bufPtr = process->getSyscallArg(tc, index);
976
977    // Adjust path for current working directory
978    path = process->fullPath(path);
979
980    struct stat hostBuf;
981    int result = stat(path.c_str(), &hostBuf);
982
983    if (result < 0)
984        return -errno;
985
986    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
987
988    return 0;
989}
990
991
992/// Target stat64() handler.
993template <class OS>
994SyscallReturn
995stat64Func(SyscallDesc *desc, int callnum, Process *process,
996           ThreadContext *tc)
997{
998    std::string path;
999
1000    int index = 0;
1001    if (!tc->getMemProxy().tryReadString(path,
1002                process->getSyscallArg(tc, index)))
1003        return -EFAULT;
1004    Addr bufPtr = process->getSyscallArg(tc, index);
1005
1006    // Adjust path for current working directory
1007    path = process->fullPath(path);
1008
1009#if NO_STAT64
1010    struct stat  hostBuf;
1011    int result = stat(path.c_str(), &hostBuf);
1012#else
1013    struct stat64 hostBuf;
1014    int result = stat64(path.c_str(), &hostBuf);
1015#endif
1016
1017    if (result < 0)
1018        return -errno;
1019
1020    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1021
1022    return 0;
1023}
1024
1025
1026/// Target fstatat64() handler.
1027template <class OS>
1028SyscallReturn
1029fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
1030              ThreadContext *tc)
1031{
1032    int index = 0;
1033    int dirfd = process->getSyscallArg(tc, index);
1034    if (dirfd != OS::TGT_AT_FDCWD)
1035        warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1036
1037    std::string path;
1038    if (!tc->getMemProxy().tryReadString(path,
1039                process->getSyscallArg(tc, index)))
1040        return -EFAULT;
1041    Addr bufPtr = process->getSyscallArg(tc, index);
1042
1043    // Adjust path for current working directory
1044    path = process->fullPath(path);
1045
1046#if NO_STAT64
1047    struct stat  hostBuf;
1048    int result = stat(path.c_str(), &hostBuf);
1049#else
1050    struct stat64 hostBuf;
1051    int result = stat64(path.c_str(), &hostBuf);
1052#endif
1053
1054    if (result < 0)
1055        return -errno;
1056
1057    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1058
1059    return 0;
1060}
1061
1062
1063/// Target fstat64() handler.
1064template <class OS>
1065SyscallReturn
1066fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1067{
1068    int index = 0;
1069    int tgt_fd = p->getSyscallArg(tc, index);
1070    Addr bufPtr = p->getSyscallArg(tc, index);
1071
1072    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1073    if (!ffdp)
1074        return -EBADF;
1075    int sim_fd = ffdp->getSimFD();
1076
1077#if NO_STAT64
1078    struct stat  hostBuf;
1079    int result = fstat(sim_fd, &hostBuf);
1080#else
1081    struct stat64  hostBuf;
1082    int result = fstat64(sim_fd, &hostBuf);
1083#endif
1084
1085    if (result < 0)
1086        return -errno;
1087
1088    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1089
1090    return 0;
1091}
1092
1093
1094/// Target lstat() handler.
1095template <class OS>
1096SyscallReturn
1097lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1098          ThreadContext *tc)
1099{
1100    std::string path;
1101
1102    int index = 0;
1103    if (!tc->getMemProxy().tryReadString(path,
1104                process->getSyscallArg(tc, index))) {
1105        return -EFAULT;
1106    }
1107    Addr bufPtr = process->getSyscallArg(tc, index);
1108
1109    // Adjust path for current working directory
1110    path = process->fullPath(path);
1111
1112    struct stat hostBuf;
1113    int result = lstat(path.c_str(), &hostBuf);
1114
1115    if (result < 0)
1116        return -errno;
1117
1118    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1119
1120    return 0;
1121}
1122
1123/// Target lstat64() handler.
1124template <class OS>
1125SyscallReturn
1126lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1127            ThreadContext *tc)
1128{
1129    std::string path;
1130
1131    int index = 0;
1132    if (!tc->getMemProxy().tryReadString(path,
1133                process->getSyscallArg(tc, index))) {
1134        return -EFAULT;
1135    }
1136    Addr bufPtr = process->getSyscallArg(tc, index);
1137
1138    // Adjust path for current working directory
1139    path = process->fullPath(path);
1140
1141#if NO_STAT64
1142    struct stat hostBuf;
1143    int result = lstat(path.c_str(), &hostBuf);
1144#else
1145    struct stat64 hostBuf;
1146    int result = lstat64(path.c_str(), &hostBuf);
1147#endif
1148
1149    if (result < 0)
1150        return -errno;
1151
1152    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1153
1154    return 0;
1155}
1156
1157/// Target fstat() handler.
1158template <class OS>
1159SyscallReturn
1160fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1161{
1162    int index = 0;
1163    int tgt_fd = p->getSyscallArg(tc, index);
1164    Addr bufPtr = p->getSyscallArg(tc, index);
1165
1166    DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1167
1168    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1169    if (!ffdp)
1170        return -EBADF;
1171    int sim_fd = ffdp->getSimFD();
1172
1173    struct stat hostBuf;
1174    int result = fstat(sim_fd, &hostBuf);
1175
1176    if (result < 0)
1177        return -errno;
1178
1179    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1180
1181    return 0;
1182}
1183
1184
1185/// Target statfs() handler.
1186template <class OS>
1187SyscallReturn
1188statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1189           ThreadContext *tc)
1190{
1191#if NO_STATFS
1192    warn("Host OS cannot support calls to statfs. Ignoring syscall");
1193#else
1194    std::string path;
1195
1196    int index = 0;
1197    if (!tc->getMemProxy().tryReadString(path,
1198                process->getSyscallArg(tc, index))) {
1199        return -EFAULT;
1200    }
1201    Addr bufPtr = process->getSyscallArg(tc, index);
1202
1203    // Adjust path for current working directory
1204    path = process->fullPath(path);
1205
1206    struct statfs hostBuf;
1207    int result = statfs(path.c_str(), &hostBuf);
1208
1209    if (result < 0)
1210        return -errno;
1211
1212    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1213#endif
1214    return 0;
1215}
1216
1217template <class OS>
1218SyscallReturn
1219cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1220{
1221    int index = 0;
1222    TheISA::IntReg flags = p->getSyscallArg(tc, index);
1223    TheISA::IntReg newStack = p->getSyscallArg(tc, index);
1224    Addr ptidPtr = p->getSyscallArg(tc, index);
1225    Addr ctidPtr = p->getSyscallArg(tc, index);
1226    Addr tlsPtr M5_VAR_USED = p->getSyscallArg(tc, index);
1227
1228    if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1229        ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1230        ((flags & OS::TGT_CLONE_FS)     &&  (flags & OS::TGT_CLONE_NEWNS)) ||
1231        ((flags & OS::TGT_CLONE_NEWIPC) &&  (flags & OS::TGT_CLONE_SYSVSEM)) ||
1232        ((flags & OS::TGT_CLONE_NEWPID) &&  (flags & OS::TGT_CLONE_THREAD)) ||
1233        ((flags & OS::TGT_CLONE_VM)     && !(newStack)))
1234        return -EINVAL;
1235
1236    ThreadContext *ctc;
1237    if (!(ctc = p->findFreeContext()))
1238        fatal("clone: no spare thread context in system");
1239
1240    /**
1241     * Note that ProcessParams is generated by swig and there are no other
1242     * examples of how to create anything but this default constructor. The
1243     * fields are manually initialized instead of passing parameters to the
1244     * constructor.
1245     */
1246    ProcessParams *pp = new ProcessParams();
1247    pp->executable.assign(*(new std::string(p->progName())));
1248    pp->cmd.push_back(*(new std::string(p->progName())));
1249    pp->system = p->system;
1250    pp->cwd.assign(p->getcwd());
1251    pp->input.assign("stdin");
1252    pp->output.assign("stdout");
1253    pp->errout.assign("stderr");
1254    pp->uid = p->uid();
1255    pp->euid = p->euid();
1256    pp->gid = p->gid();
1257    pp->egid = p->egid();
1258
1259    /* Find the first free PID that's less than the maximum */
1260    std::set<int> const& pids = p->system->PIDs;
1261    int temp_pid = *pids.begin();
1262    do {
1263        temp_pid++;
1264    } while (pids.find(temp_pid) != pids.end());
1265    if (temp_pid >= System::maxPID)
1266        fatal("temp_pid is too large: %d", temp_pid);
1267
1268    pp->pid = temp_pid;
1269    pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1270    Process *cp = pp->create();
1271    delete pp;
1272
1273    Process *owner = ctc->getProcessPtr();
1274    ctc->setProcessPtr(cp);
1275    cp->assignThreadContext(ctc->contextId());
1276    owner->revokeThreadContext(ctc->contextId());
1277
1278    if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1279        BufferArg ptidBuf(ptidPtr, sizeof(long));
1280        long *ptid = (long *)ptidBuf.bufferPtr();
1281        *ptid = cp->pid();
1282        ptidBuf.copyOut(tc->getMemProxy());
1283    }
1284
1285    cp->initState();
1286    p->clone(tc, ctc, cp, flags);
1287
1288    if (flags & OS::TGT_CLONE_THREAD) {
1289        delete cp->sigchld;
1290        cp->sigchld = p->sigchld;
1291    } else if (flags & OS::TGT_SIGCHLD) {
1292        *cp->sigchld = true;
1293    }
1294
1295    if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1296        BufferArg ctidBuf(ctidPtr, sizeof(long));
1297        long *ctid = (long *)ctidBuf.bufferPtr();
1298        *ctid = cp->pid();
1299        ctidBuf.copyOut(ctc->getMemProxy());
1300    }
1301
1302    if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1303        cp->childClearTID = (uint64_t)ctidPtr;
1304
1305    ctc->clearArchRegs();
1306
1307#if THE_ISA == ALPHA_ISA
1308    TheISA::copyMiscRegs(tc, ctc);
1309#elif THE_ISA == SPARC_ISA
1310    TheISA::copyRegs(tc, ctc);
1311    ctc->setIntReg(TheISA::NumIntArchRegs + 6, 0);
1312    ctc->setIntReg(TheISA::NumIntArchRegs + 4, 0);
1313    ctc->setIntReg(TheISA::NumIntArchRegs + 3, TheISA::NWindows - 2);
1314    ctc->setIntReg(TheISA::NumIntArchRegs + 5, TheISA::NWindows);
1315    ctc->setMiscReg(TheISA::MISCREG_CWP, 0);
1316    ctc->setIntReg(TheISA::NumIntArchRegs + 7, 0);
1317    ctc->setMiscRegNoEffect(TheISA::MISCREG_TL, 0);
1318    ctc->setMiscReg(TheISA::MISCREG_ASI, TheISA::ASI_PRIMARY);
1319    for (int y = 8; y < 32; y++)
1320        ctc->setIntReg(y, tc->readIntReg(y));
1321#elif THE_ISA == ARM_ISA or THE_ISA == X86_ISA
1322    TheISA::copyRegs(tc, ctc);
1323#endif
1324
1325#if THE_ISA == X86_ISA
1326    if (flags & OS::TGT_CLONE_SETTLS) {
1327        ctc->setMiscRegNoEffect(TheISA::MISCREG_FS_BASE, tlsPtr);
1328        ctc->setMiscRegNoEffect(TheISA::MISCREG_FS_EFF_BASE, tlsPtr);
1329    }
1330#endif
1331
1332    if (newStack)
1333        ctc->setIntReg(TheISA::StackPointerReg, newStack);
1334
1335    cp->setSyscallReturn(ctc, 0);
1336
1337#if THE_ISA == ALPHA_ISA
1338    ctc->setIntReg(TheISA::SyscallSuccessReg, 0);
1339#elif THE_ISA == SPARC_ISA
1340    tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1341    ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1342#endif
1343
1344    ctc->pcState(tc->nextInstAddr());
1345    ctc->activate();
1346
1347    return cp->pid();
1348}
1349
1350/// Target fstatfs() handler.
1351template <class OS>
1352SyscallReturn
1353fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1354{
1355    int index = 0;
1356    int tgt_fd = p->getSyscallArg(tc, index);
1357    Addr bufPtr = p->getSyscallArg(tc, index);
1358
1359    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1360    if (!ffdp)
1361        return -EBADF;
1362    int sim_fd = ffdp->getSimFD();
1363
1364    struct statfs hostBuf;
1365    int result = fstatfs(sim_fd, &hostBuf);
1366
1367    if (result < 0)
1368        return -errno;
1369
1370    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1371
1372    return 0;
1373}
1374
1375
1376/// Target writev() handler.
1377template <class OS>
1378SyscallReturn
1379writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1380{
1381    int index = 0;
1382    int tgt_fd = p->getSyscallArg(tc, index);
1383
1384    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1385    if (!hbfdp)
1386        return -EBADF;
1387    int sim_fd = hbfdp->getSimFD();
1388
1389    SETranslatingPortProxy &prox = tc->getMemProxy();
1390    uint64_t tiov_base = p->getSyscallArg(tc, index);
1391    size_t count = p->getSyscallArg(tc, index);
1392    struct iovec hiov[count];
1393    for (size_t i = 0; i < count; ++i) {
1394        typename OS::tgt_iovec tiov;
1395
1396        prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1397                      (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1398        hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1399        hiov[i].iov_base = new char [hiov[i].iov_len];
1400        prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1401                      hiov[i].iov_len);
1402    }
1403
1404    int result = writev(sim_fd, hiov, count);
1405
1406    for (size_t i = 0; i < count; ++i)
1407        delete [] (char *)hiov[i].iov_base;
1408
1409    if (result < 0)
1410        return -errno;
1411
1412    return result;
1413}
1414
1415/// Real mmap handler.
1416template <class OS>
1417SyscallReturn
1418mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1419         bool is_mmap2)
1420{
1421    int index = 0;
1422    Addr start = p->getSyscallArg(tc, index);
1423    uint64_t length = p->getSyscallArg(tc, index);
1424    int prot = p->getSyscallArg(tc, index);
1425    int tgt_flags = p->getSyscallArg(tc, index);
1426    int tgt_fd = p->getSyscallArg(tc, index);
1427    int offset = p->getSyscallArg(tc, index);
1428
1429    if (is_mmap2)
1430        offset *= TheISA::PageBytes;
1431
1432    if (start & (TheISA::PageBytes - 1) ||
1433        offset & (TheISA::PageBytes - 1) ||
1434        (tgt_flags & OS::TGT_MAP_PRIVATE &&
1435         tgt_flags & OS::TGT_MAP_SHARED) ||
1436        (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1437         !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1438        !length) {
1439        return -EINVAL;
1440    }
1441
1442    if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1443        // With shared mmaps, there are two cases to consider:
1444        // 1) anonymous: writes should modify the mapping and this should be
1445        // visible to observers who share the mapping. Currently, it's
1446        // difficult to update the shared mapping because there's no
1447        // structure which maintains information about the which virtual
1448        // memory areas are shared. If that structure existed, it would be
1449        // possible to make the translations point to the same frames.
1450        // 2) file-backed: writes should modify the mapping and the file
1451        // which is backed by the mapping. The shared mapping problem is the
1452        // same as what was mentioned about the anonymous mappings. For
1453        // file-backed mappings, the writes to the file are difficult
1454        // because it requires syncing what the mapping holds with the file
1455        // that resides on the host system. So, any write on a real system
1456        // would cause the change to be propagated to the file mapping at
1457        // some point in the future (the inode is tracked along with the
1458        // mapping). This isn't guaranteed to always happen, but it usually
1459        // works well enough. The guarantee is provided by the msync system
1460        // call. We could force the change through with shared mappings with
1461        // a call to msync, but that again would require more information
1462        // than we currently maintain.
1463        warn("mmap: writing to shared mmap region is currently "
1464             "unsupported. The write succeeds on the target, but it "
1465             "will not be propagated to the host or shared mappings");
1466    }
1467
1468    length = roundUp(length, TheISA::PageBytes);
1469
1470    int sim_fd = -1;
1471    uint8_t *pmap = nullptr;
1472    if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1473        std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1474
1475        auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1476        if (dfdp) {
1477            EmulatedDriver *emul_driver = dfdp->getDriver();
1478            return emul_driver->mmap(p, tc, start, length, prot,
1479                                     tgt_flags, tgt_fd, offset);
1480        }
1481
1482        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1483        if (!ffdp)
1484            return -EBADF;
1485        sim_fd = ffdp->getSimFD();
1486
1487        pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1488                                    sim_fd, offset);
1489
1490        if (pmap == (decltype(pmap))-1) {
1491            warn("mmap: failed to map file into host address space");
1492            return -errno;
1493        }
1494    }
1495
1496    // Extend global mmap region if necessary. Note that we ignore the
1497    // start address unless MAP_FIXED is specified.
1498    if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1499        std::shared_ptr<MemState> mem_state = p->memState;
1500        Addr mmap_end = mem_state->getMmapEnd();
1501
1502        start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1503        mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1504
1505        mem_state->setMmapEnd(mmap_end);
1506    }
1507
1508    DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1509                    start, start + length - 1);
1510
1511    // We only allow mappings to overwrite existing mappings if
1512    // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1513    // because we ignore the start hint if TGT_MAP_FIXED is not set.
1514    int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1515    if (clobber) {
1516        for (auto tc : p->system->threadContexts) {
1517            // If we might be overwriting old mappings, we need to
1518            // invalidate potentially stale mappings out of the TLBs.
1519            tc->getDTBPtr()->flushAll();
1520            tc->getITBPtr()->flushAll();
1521        }
1522    }
1523
1524    // Allocate physical memory and map it in. If the page table is already
1525    // mapped and clobber is not set, the simulator will issue throw a
1526    // fatal and bail out of the simulation.
1527    p->allocateMem(start, length, clobber);
1528
1529    // Transfer content into target address space.
1530    SETranslatingPortProxy &tp = tc->getMemProxy();
1531    if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1532        // In general, we should zero the mapped area for anonymous mappings,
1533        // with something like:
1534        //     tp.memsetBlob(start, 0, length);
1535        // However, given that we don't support sparse mappings, and
1536        // some applications can map a couple of gigabytes of space
1537        // (intending sparse usage), that can get painfully expensive.
1538        // Fortunately, since we don't properly implement munmap either,
1539        // there's no danger of remapping used memory, so for now all
1540        // newly mapped memory should already be zeroed so we can skip it.
1541    } else {
1542        // It is possible to mmap an area larger than a file, however
1543        // accessing unmapped portions the system triggers a "Bus error"
1544        // on the host. We must know when to stop copying the file from
1545        // the host into the target address space.
1546        struct stat file_stat;
1547        if (fstat(sim_fd, &file_stat) > 0)
1548            fatal("mmap: cannot stat file");
1549
1550        // Copy the portion of the file that is resident. This requires
1551        // checking both the mmap size and the filesize that we are
1552        // trying to mmap into this space; the mmap size also depends
1553        // on the specified offset into the file.
1554        uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1555                                 length);
1556        tp.writeBlob(start, pmap, size);
1557
1558        // Cleanup the mmap region before exiting this function.
1559        munmap(pmap, length);
1560
1561        // Maintain the symbol table for dynamic executables.
1562        // The loader will call mmap to map the images into its address
1563        // space and we intercept that here. We can verify that we are
1564        // executing inside the loader by checking the program counter value.
1565        // XXX: with multiprogrammed workloads or multi-node configurations,
1566        // this will not work since there is a single global symbol table.
1567        ObjectFile *interpreter = p->getInterpreter();
1568        if (interpreter) {
1569            Addr text_start = interpreter->textBase();
1570            Addr text_end = text_start + interpreter->textSize();
1571
1572            Addr pc = tc->pcState().pc();
1573
1574            if (pc >= text_start && pc < text_end) {
1575                std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1576                auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1577                ObjectFile *lib = createObjectFile(ffdp->getFileName());
1578
1579                if (lib) {
1580                    lib->loadAllSymbols(debugSymbolTable,
1581                                        lib->textBase(), start);
1582                }
1583            }
1584        }
1585
1586        // Note that we do not zero out the remainder of the mapping. This
1587        // is done by a real system, but it probably will not affect
1588        // execution (hopefully).
1589    }
1590
1591    return start;
1592}
1593
1594template <class OS>
1595SyscallReturn
1596pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1597{
1598    int index = 0;
1599    int tgt_fd = p->getSyscallArg(tc, index);
1600    Addr bufPtr = p->getSyscallArg(tc, index);
1601    int nbytes = p->getSyscallArg(tc, index);
1602    int offset = p->getSyscallArg(tc, index);
1603
1604    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1605    if (!ffdp)
1606        return -EBADF;
1607    int sim_fd = ffdp->getSimFD();
1608
1609    BufferArg bufArg(bufPtr, nbytes);
1610    bufArg.copyIn(tc->getMemProxy());
1611
1612    int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1613
1614    return (bytes_written == -1) ? -errno : bytes_written;
1615}
1616
1617/// Target mmap() handler.
1618template <class OS>
1619SyscallReturn
1620mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1621{
1622    return mmapImpl<OS>(desc, num, p, tc, false);
1623}
1624
1625/// Target mmap2() handler.
1626template <class OS>
1627SyscallReturn
1628mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1629{
1630    return mmapImpl<OS>(desc, num, p, tc, true);
1631}
1632
1633/// Target getrlimit() handler.
1634template <class OS>
1635SyscallReturn
1636getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1637              ThreadContext *tc)
1638{
1639    int index = 0;
1640    unsigned resource = process->getSyscallArg(tc, index);
1641    TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1642
1643    switch (resource) {
1644      case OS::TGT_RLIMIT_STACK:
1645        // max stack size in bytes: make up a number (8MB for now)
1646        rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1647        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1648        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1649        break;
1650
1651      case OS::TGT_RLIMIT_DATA:
1652        // max data segment size in bytes: make up a number
1653        rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1654        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1655        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1656        break;
1657
1658      default:
1659        warn("getrlimit: unimplemented resource %d", resource);
1660        return -EINVAL;
1661        break;
1662    }
1663
1664    rlp.copyOut(tc->getMemProxy());
1665    return 0;
1666}
1667
1668/// Target clock_gettime() function.
1669template <class OS>
1670SyscallReturn
1671clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1672{
1673    int index = 1;
1674    //int clk_id = p->getSyscallArg(tc, index);
1675    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1676
1677    getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1678    tp->tv_sec += seconds_since_epoch;
1679    tp->tv_sec = TheISA::htog(tp->tv_sec);
1680    tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1681
1682    tp.copyOut(tc->getMemProxy());
1683
1684    return 0;
1685}
1686
1687/// Target clock_getres() function.
1688template <class OS>
1689SyscallReturn
1690clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1691{
1692    int index = 1;
1693    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1694
1695    // Set resolution at ns, which is what clock_gettime() returns
1696    tp->tv_sec = 0;
1697    tp->tv_nsec = 1;
1698
1699    tp.copyOut(tc->getMemProxy());
1700
1701    return 0;
1702}
1703
1704/// Target gettimeofday() handler.
1705template <class OS>
1706SyscallReturn
1707gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1708                 ThreadContext *tc)
1709{
1710    int index = 0;
1711    TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1712
1713    getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1714    tp->tv_sec += seconds_since_epoch;
1715    tp->tv_sec = TheISA::htog(tp->tv_sec);
1716    tp->tv_usec = TheISA::htog(tp->tv_usec);
1717
1718    tp.copyOut(tc->getMemProxy());
1719
1720    return 0;
1721}
1722
1723
1724/// Target utimes() handler.
1725template <class OS>
1726SyscallReturn
1727utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1728           ThreadContext *tc)
1729{
1730    std::string path;
1731
1732    int index = 0;
1733    if (!tc->getMemProxy().tryReadString(path,
1734                process->getSyscallArg(tc, index))) {
1735        return -EFAULT;
1736    }
1737
1738    TypedBufferArg<typename OS::timeval [2]>
1739        tp(process->getSyscallArg(tc, index));
1740    tp.copyIn(tc->getMemProxy());
1741
1742    struct timeval hostTimeval[2];
1743    for (int i = 0; i < 2; ++i) {
1744        hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1745        hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1746    }
1747
1748    // Adjust path for current working directory
1749    path = process->fullPath(path);
1750
1751    int result = utimes(path.c_str(), hostTimeval);
1752
1753    if (result < 0)
1754        return -errno;
1755
1756    return 0;
1757}
1758
1759template <class OS>
1760SyscallReturn
1761execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1762{
1763    desc->setFlags(0);
1764
1765    int index = 0;
1766    std::string path;
1767    SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
1768    if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
1769        return -EFAULT;
1770
1771    if (access(path.c_str(), F_OK) == -1)
1772        return -EACCES;
1773
1774    auto read_in = [](std::vector<std::string> & vect,
1775                      SETranslatingPortProxy & mem_proxy,
1776                      Addr mem_loc)
1777    {
1778        for (int inc = 0; ; inc++) {
1779            BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
1780            b.copyIn(mem_proxy);
1781
1782            if (!*(Addr*)b.bufferPtr())
1783                break;
1784
1785            vect.push_back(std::string());
1786            mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
1787        }
1788    };
1789
1790    /**
1791     * Note that ProcessParams is generated by swig and there are no other
1792     * examples of how to create anything but this default constructor. The
1793     * fields are manually initialized instead of passing parameters to the
1794     * constructor.
1795     */
1796    ProcessParams *pp = new ProcessParams();
1797    pp->executable = path;
1798    Addr argv_mem_loc = p->getSyscallArg(tc, index);
1799    read_in(pp->cmd, mem_proxy, argv_mem_loc);
1800    Addr envp_mem_loc = p->getSyscallArg(tc, index);
1801    read_in(pp->env, mem_proxy, envp_mem_loc);
1802    pp->uid = p->uid();
1803    pp->egid = p->egid();
1804    pp->euid = p->euid();
1805    pp->gid = p->gid();
1806    pp->ppid = p->ppid();
1807    pp->pid = p->pid();
1808    pp->input.assign("cin");
1809    pp->output.assign("cout");
1810    pp->errout.assign("cerr");
1811    pp->cwd.assign(p->getcwd());
1812    pp->system = p->system;
1813    /**
1814     * Prevent process object creation with identical PIDs (which will trip
1815     * a fatal check in Process constructor). The execve call is supposed to
1816     * take over the currently executing process' identity but replace
1817     * whatever it is doing with a new process image. Instead of hijacking
1818     * the process object in the simulator, we create a new process object
1819     * and bind to the previous process' thread below (hijacking the thread).
1820     */
1821    p->system->PIDs.erase(p->pid());
1822    Process *new_p = pp->create();
1823    delete pp;
1824
1825    /**
1826     * Work through the file descriptor array and close any files marked
1827     * close-on-exec.
1828     */
1829    new_p->fds = p->fds;
1830    for (int i = 0; i < new_p->fds->getSize(); i++) {
1831        std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
1832        if (fdep && fdep->getCOE())
1833            new_p->fds->closeFDEntry(i);
1834    }
1835
1836    *new_p->sigchld = true;
1837
1838    delete p;
1839    tc->clearArchRegs();
1840    tc->setProcessPtr(new_p);
1841    new_p->assignThreadContext(tc->contextId());
1842    new_p->initState();
1843    tc->activate();
1844    TheISA::PCState pcState = tc->pcState();
1845    tc->setNPC(pcState.instAddr());
1846
1847    desc->setFlags(SyscallDesc::SuppressReturnValue);
1848    return 0;
1849}
1850
1851/// Target getrusage() function.
1852template <class OS>
1853SyscallReturn
1854getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
1855              ThreadContext *tc)
1856{
1857    int index = 0;
1858    int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
1859    TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
1860
1861    rup->ru_utime.tv_sec = 0;
1862    rup->ru_utime.tv_usec = 0;
1863    rup->ru_stime.tv_sec = 0;
1864    rup->ru_stime.tv_usec = 0;
1865    rup->ru_maxrss = 0;
1866    rup->ru_ixrss = 0;
1867    rup->ru_idrss = 0;
1868    rup->ru_isrss = 0;
1869    rup->ru_minflt = 0;
1870    rup->ru_majflt = 0;
1871    rup->ru_nswap = 0;
1872    rup->ru_inblock = 0;
1873    rup->ru_oublock = 0;
1874    rup->ru_msgsnd = 0;
1875    rup->ru_msgrcv = 0;
1876    rup->ru_nsignals = 0;
1877    rup->ru_nvcsw = 0;
1878    rup->ru_nivcsw = 0;
1879
1880    switch (who) {
1881      case OS::TGT_RUSAGE_SELF:
1882        getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
1883        rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
1884        rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
1885        break;
1886
1887      case OS::TGT_RUSAGE_CHILDREN:
1888        // do nothing.  We have no child processes, so they take no time.
1889        break;
1890
1891      default:
1892        // don't really handle THREAD or CHILDREN, but just warn and
1893        // plow ahead
1894        warn("getrusage() only supports RUSAGE_SELF.  Parameter %d ignored.",
1895             who);
1896    }
1897
1898    rup.copyOut(tc->getMemProxy());
1899
1900    return 0;
1901}
1902
1903/// Target times() function.
1904template <class OS>
1905SyscallReturn
1906timesFunc(SyscallDesc *desc, int callnum, Process *process,
1907          ThreadContext *tc)
1908{
1909    int index = 0;
1910    TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
1911
1912    // Fill in the time structure (in clocks)
1913    int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
1914    bufp->tms_utime = clocks;
1915    bufp->tms_stime = 0;
1916    bufp->tms_cutime = 0;
1917    bufp->tms_cstime = 0;
1918
1919    // Convert to host endianness
1920    bufp->tms_utime = TheISA::htog(bufp->tms_utime);
1921
1922    // Write back
1923    bufp.copyOut(tc->getMemProxy());
1924
1925    // Return clock ticks since system boot
1926    return clocks;
1927}
1928
1929/// Target time() function.
1930template <class OS>
1931SyscallReturn
1932timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
1933{
1934    typename OS::time_t sec, usec;
1935    getElapsedTimeMicro(sec, usec);
1936    sec += seconds_since_epoch;
1937
1938    int index = 0;
1939    Addr taddr = (Addr)process->getSyscallArg(tc, index);
1940    if (taddr != 0) {
1941        typename OS::time_t t = sec;
1942        t = TheISA::htog(t);
1943        SETranslatingPortProxy &p = tc->getMemProxy();
1944        p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
1945    }
1946    return sec;
1947}
1948
1949template <class OS>
1950SyscallReturn
1951tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
1952{
1953    int index = 0;
1954    int tgid = process->getSyscallArg(tc, index);
1955    int tid = process->getSyscallArg(tc, index);
1956    int sig = process->getSyscallArg(tc, index);
1957
1958    /**
1959     * This system call is intended to allow killing a specific thread
1960     * within an arbitrary thread group if sanctioned with permission checks.
1961     * It's usually true that threads share the termination signal as pointed
1962     * out by the pthread_kill man page and this seems to be the intended
1963     * usage. Due to this being an emulated environment, assume the following:
1964     * Threads are allowed to call tgkill because the EUID for all threads
1965     * should be the same. There is no signal handling mechanism for kernel
1966     * registration of signal handlers since signals are poorly supported in
1967     * emulation mode. Since signal handlers cannot be registered, all
1968     * threads within in a thread group must share the termination signal.
1969     * We never exhaust PIDs so there's no chance of finding the wrong one
1970     * due to PID rollover.
1971     */
1972
1973    System *sys = tc->getSystemPtr();
1974    Process *tgt_proc = nullptr;
1975    for (int i = 0; i < sys->numContexts(); i++) {
1976        Process *temp = sys->threadContexts[i]->getProcessPtr();
1977        if (temp->pid() == tid) {
1978            tgt_proc = temp;
1979            break;
1980        }
1981    }
1982
1983    if (sig != 0 || sig != OS::TGT_SIGABRT)
1984        return -EINVAL;
1985
1986    if (tgt_proc == nullptr)
1987        return -ESRCH;
1988
1989    if (tgid != -1 && tgt_proc->tgid() != tgid)
1990        return -ESRCH;
1991
1992    if (sig == OS::TGT_SIGABRT)
1993        exitGroupFunc(desc, 252, process, tc);
1994
1995    return 0;
1996}
1997
1998
1999#endif // __SIM_SYSCALL_EMUL_HH__
2000