syscall_emul.hh revision 13936
1360SN/A/*
21458SN/A * Copyright (c) 2012-2013, 2015 ARM Limited
3360SN/A * Copyright (c) 2015 Advanced Micro Devices, Inc.
4360SN/A * All rights reserved
5360SN/A *
6360SN/A * The license below extends only to copyright in the software and shall
7360SN/A * not be construed as granting a license to any other intellectual
8360SN/A * property including but not limited to intellectual property relating
9360SN/A * to a hardware implementation of the functionality of the software
10360SN/A * licensed hereunder.  You may use the software subject to the license
11360SN/A * terms below provided that you ensure that this notice is replicated
12360SN/A * unmodified and in its entirety in all distributions of the software,
13360SN/A * modified or unmodified, in source code or in binary form.
14360SN/A *
15360SN/A * Copyright (c) 2003-2005 The Regents of The University of Michigan
16360SN/A * All rights reserved.
17360SN/A *
18360SN/A * Redistribution and use in source and binary forms, with or without
19360SN/A * modification, are permitted provided that the following conditions are
20360SN/A * met: redistributions of source code must retain the above copyright
21360SN/A * notice, this list of conditions and the following disclaimer;
22360SN/A * redistributions in binary form must reproduce the above copyright
23360SN/A * notice, this list of conditions and the following disclaimer in the
24360SN/A * documentation and/or other materials provided with the distribution;
25360SN/A * neither the name of the copyright holders nor the names of its
26360SN/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
30360SN/A * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31360SN/A * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
321354SN/A * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
331354SN/A * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34360SN/A * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
352764Sstever@eecs.umich.edu * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
362764Sstever@eecs.umich.edu * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
372064SN/A * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38360SN/A * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39360SN/A * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40360SN/A *
41360SN/A * Authors: Steve Reinhardt
42360SN/A *          Kevin Lim
43360SN/A */
441809SN/A
455543Ssaidi@eecs.umich.edu#ifndef __SIM_SYSCALL_EMUL_HH__
461809SN/A#define __SIM_SYSCALL_EMUL_HH__
473113Sgblack@eecs.umich.edu
487075Snate@binkert.org#if (defined(__APPLE__) || defined(__OpenBSD__) ||      \
493113Sgblack@eecs.umich.edu     defined(__FreeBSD__) || defined(__CYGWIN__) ||     \
501999SN/A     defined(__NetBSD__))
517075Snate@binkert.org#define NO_STAT64 1
527075Snate@binkert.org#else
537075Snate@binkert.org#define NO_STAT64 0
54360SN/A#endif
552474SN/A
565543Ssaidi@eecs.umich.edu///
572462SN/A/// @file syscall_emul.hh
581354SN/A///
596216Snate@binkert.org/// This file defines objects used to emulate syscalls from the target
606658Snate@binkert.org/// application on the host machine.
612474SN/A
622680Sktlim@umich.edu#if defined(__linux__)
632474SN/A#include <sys/eventfd.h>
642474SN/A#include <sys/statfs.h>
656640Svince@csl.cornell.edu
661354SN/A#else
67360SN/A#include <sys/mount.h>
68360SN/A
69360SN/A#endif
70360SN/A
71360SN/A#ifdef __CYGWIN32__
72360SN/A#include <sys/fcntl.h>
73360SN/A
74360SN/A#endif
75378SN/A#include <fcntl.h>
761450SN/A#include <net/if.h>
773114Sgblack@eecs.umich.edu#include <poll.h>
78360SN/A#include <sys/ioctl.h>
795543Ssaidi@eecs.umich.edu#include <sys/mman.h>
805543Ssaidi@eecs.umich.edu#include <sys/socket.h>
815543Ssaidi@eecs.umich.edu#include <sys/stat.h>
82360SN/A#include <sys/time.h>
83360SN/A#include <sys/types.h>
84360SN/A#include <sys/uio.h>
85360SN/A#include <unistd.h>
86360SN/A
872680Sktlim@umich.edu#include <cerrno>
88360SN/A#include <memory>
89360SN/A#include <string>
90360SN/A
91360SN/A#include "arch/generic/tlb.hh"
92360SN/A#include "arch/utility.hh"
93360SN/A#include "base/intmath.hh"
94360SN/A#include "base/loader/object_file.hh"
95360SN/A#include "base/logging.hh"
96360SN/A#include "base/trace.hh"
97360SN/A#include "base/types.hh"
98360SN/A#include "config/the_isa.hh"
993114Sgblack@eecs.umich.edu#include "cpu/base.hh"
100360SN/A#include "cpu/thread_context.hh"
101360SN/A#include "mem/page_table.hh"
102360SN/A#include "params/Process.hh"
103360SN/A#include "sim/emul_driver.hh"
104360SN/A#include "sim/futex_map.hh"
105360SN/A#include "sim/process.hh"
106360SN/A#include "sim/syscall_debug_macros.hh"
107360SN/A#include "sim/syscall_desc.hh"
108360SN/A#include "sim/syscall_emul_buf.hh"
109360SN/A#include "sim/syscall_return.hh"
110360SN/A
111360SN/A#if defined(__APPLE__) && defined(__MACH__) && !defined(CMSG_ALIGN)
112360SN/A#define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & ~(sizeof(size_t) - 1))
113360SN/A#endif
114360SN/A
115360SN/A//////////////////////////////////////////////////////////////////////
116360SN/A//
117360SN/A// The following emulation functions are generic enough that they
118360SN/A// don't need to be recompiled for different emulated OS's.  They are
119360SN/A// defined in sim/syscall_emul.cc.
120360SN/A//
1212400SN/A//////////////////////////////////////////////////////////////////////
122360SN/A
1232461SN/Avoid warnUnsupportedOS(std::string syscall_name);
1245543Ssaidi@eecs.umich.edu
125360SN/A/// Handler for unimplemented syscalls that we haven't thought about.
126360SN/ASyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
127360SN/A                                Process *p, ThreadContext *tc);
128360SN/A
129360SN/A/// Handler for unimplemented syscalls that we never intend to
1302400SN/A/// implement (signal handling, etc.) and should not affect the correct
131360SN/A/// behavior of the program.  Print a warning only if the appropriate
1322461SN/A/// trace flag is enabled.  Return success to the target program.
1335543Ssaidi@eecs.umich.eduSyscallReturn ignoreFunc(SyscallDesc *desc, int num,
134360SN/A                         Process *p, ThreadContext *tc);
135360SN/A
136360SN/A// Target fallocateFunc() handler.
137360SN/ASyscallReturn fallocateFunc(SyscallDesc *desc, int num,
138360SN/A                            Process *p, ThreadContext *tc);
139360SN/A
140360SN/A/// Target exit() handler: terminate current context.
141360SN/ASyscallReturn exitFunc(SyscallDesc *desc, int num,
142360SN/A                       Process *p, ThreadContext *tc);
143360SN/A
144360SN/A/// Target exit_group() handler: terminate simulation. (exit all threads)
145360SN/ASyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
146360SN/A                       Process *p, ThreadContext *tc);
1475543Ssaidi@eecs.umich.edu
148360SN/A/// Target set_tid_address() handler.
149360SN/ASyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
150360SN/A                                Process *p, ThreadContext *tc);
151360SN/A
152360SN/A/// Target getpagesize() handler.
153360SN/ASyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
154360SN/A                              Process *p, ThreadContext *tc);
155360SN/A
156360SN/A/// Target brk() handler: set brk address.
157360SN/ASyscallReturn brkFunc(SyscallDesc *desc, int num,
158360SN/A                      Process *p, ThreadContext *tc);
159360SN/A
160360SN/A/// Target close() handler.
161360SN/ASyscallReturn closeFunc(SyscallDesc *desc, int num,
162360SN/A                        Process *p, ThreadContext *tc);
163360SN/A
164360SN/A/// Target lseek() handler.
1655543Ssaidi@eecs.umich.eduSyscallReturn lseekFunc(SyscallDesc *desc, int num,
1665543Ssaidi@eecs.umich.edu                        Process *p, ThreadContext *tc);
167502SN/A
168360SN/A/// Target _llseek() handler.
169360SN/ASyscallReturn _llseekFunc(SyscallDesc *desc, int num,
170360SN/A                          Process *p, ThreadContext *tc);
171360SN/A
172360SN/A/// Target munmap() handler.
173360SN/ASyscallReturn munmapFunc(SyscallDesc *desc, int num,
174360SN/A                         Process *p, ThreadContext *tc);
175360SN/A
176360SN/A/// Target shutdown() handler.
177360SN/ASyscallReturn shutdownFunc(SyscallDesc *desc, int num,
178360SN/A                           Process *p, ThreadContext *tc);
179378SN/A
1801706SN/A/// Target gethostname() handler.
1813114Sgblack@eecs.umich.eduSyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
182378SN/A                              Process *p, ThreadContext *tc);
183378SN/A
184378SN/A/// Target getcwd() handler.
185378SN/ASyscallReturn getcwdFunc(SyscallDesc *desc, int num,
186378SN/A                         Process *p, ThreadContext *tc);
1871706SN/A
1883114Sgblack@eecs.umich.edu/// Target readlink() handler.
189360SN/ASyscallReturn readlinkFunc(SyscallDesc *desc, int num,
1906109Ssanchezd@stanford.edu                           Process *p, ThreadContext *tc,
1911706SN/A                           int index = 0);
1923114Sgblack@eecs.umich.eduSyscallReturn readlinkFunc(SyscallDesc *desc, int num,
193378SN/A                           Process *p, ThreadContext *tc);
1946109Ssanchezd@stanford.edu
1956109Ssanchezd@stanford.edu/// Target unlink() handler.
1966109Ssanchezd@stanford.eduSyscallReturn unlinkHelper(SyscallDesc *desc, int num,
1976109Ssanchezd@stanford.edu                           Process *p, ThreadContext *tc,
198378SN/A                           int index);
1991706SN/ASyscallReturn unlinkFunc(SyscallDesc *desc, int num,
2003114Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
201378SN/A
2025748SSteve.Reinhardt@amd.com/// Target link() handler
2035748SSteve.Reinhardt@amd.comSyscallReturn linkFunc(SyscallDesc *desc, int num, Process *p,
2045748SSteve.Reinhardt@amd.com                       ThreadContext *tc);
205378SN/A
206378SN/A/// Target symlink() handler.
2071706SN/ASyscallReturn symlinkFunc(SyscallDesc *desc, int num, Process *p,
2083114Sgblack@eecs.umich.edu                          ThreadContext *tc);
209378SN/A
210378SN/A/// Target mkdir() handler.
2111706SN/ASyscallReturn mkdirFunc(SyscallDesc *desc, int num,
2123114Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
213378SN/A
214378SN/A/// Target mknod() handler.
2151706SN/ASyscallReturn mknodFunc(SyscallDesc *desc, int num,
2163114Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
217378SN/A
218378SN/A/// Target chdir() handler.
2191706SN/ASyscallReturn chdirFunc(SyscallDesc *desc, int num,
2203114Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
221378SN/A
2224118Sgblack@eecs.umich.edu// Target rmdir() handler.
2234118Sgblack@eecs.umich.eduSyscallReturn rmdirFunc(SyscallDesc *desc, int num,
2244118Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
2254118Sgblack@eecs.umich.edu
226378SN/A/// Target rename() handler.
2271706SN/ASyscallReturn renameFunc(SyscallDesc *desc, int num,
2283114Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
229378SN/A
230378SN/A
2311706SN/A/// Target truncate() handler.
2323114Sgblack@eecs.umich.eduSyscallReturn truncateFunc(SyscallDesc *desc, int num,
233360SN/A                           Process *p, ThreadContext *tc);
2345513SMichael.Adler@intel.com
2355513SMichael.Adler@intel.com
2365513SMichael.Adler@intel.com/// Target ftruncate() handler.
2375513SMichael.Adler@intel.comSyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
2385513SMichael.Adler@intel.com                            Process *p, ThreadContext *tc);
2395513SMichael.Adler@intel.com
2405513SMichael.Adler@intel.com
2415513SMichael.Adler@intel.com/// Target truncate64() handler.
242511SN/ASyscallReturn truncate64Func(SyscallDesc *desc, int num,
2431706SN/A                             Process *p, ThreadContext *tc);
2443114Sgblack@eecs.umich.edu
245511SN/A/// Target ftruncate64() handler.
2465513SMichael.Adler@intel.comSyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
2475513SMichael.Adler@intel.com                              Process *p, ThreadContext *tc);
2485513SMichael.Adler@intel.com
2495513SMichael.Adler@intel.com
250511SN/A/// Target umask() handler.
2511706SN/ASyscallReturn umaskFunc(SyscallDesc *desc, int num,
2523114Sgblack@eecs.umich.edu                        Process *p, ThreadContext *tc);
2531706SN/A
2541706SN/A/// Target gettid() handler.
2551706SN/ASyscallReturn gettidFunc(SyscallDesc *desc, int num,
2561706SN/A                         Process *p, ThreadContext *tc);
2573114Sgblack@eecs.umich.edu
2581706SN/A/// Target chown() handler.
2591706SN/ASyscallReturn chownFunc(SyscallDesc *desc, int num,
2601706SN/A                        Process *p, ThreadContext *tc);
2611706SN/A
2623114Sgblack@eecs.umich.edu/// Target setpgid() handler.
2631706SN/ASyscallReturn setpgidFunc(SyscallDesc *desc, int num,
264511SN/A                          Process *p, ThreadContext *tc);
2656703Svince@csl.cornell.edu
2666703Svince@csl.cornell.edu/// Target fchown() handler.
2676703Svince@csl.cornell.eduSyscallReturn fchownFunc(SyscallDesc *desc, int num,
2686703Svince@csl.cornell.edu                         Process *p, ThreadContext *tc);
2696685Stjones1@inf.ed.ac.uk
2706685Stjones1@inf.ed.ac.uk/// Target dup() handler.
2716685Stjones1@inf.ed.ac.ukSyscallReturn dupFunc(SyscallDesc *desc, int num,
2726685Stjones1@inf.ed.ac.uk                      Process *process, ThreadContext *tc);
2736685Stjones1@inf.ed.ac.uk
2745513SMichael.Adler@intel.com/// Target dup2() handler.
2755513SMichael.Adler@intel.comSyscallReturn dup2Func(SyscallDesc *desc, int num,
2765513SMichael.Adler@intel.com                       Process *process, ThreadContext *tc);
2775513SMichael.Adler@intel.com
2785513SMichael.Adler@intel.com/// Target fcntl() handler.
2791999SN/ASyscallReturn fcntlFunc(SyscallDesc *desc, int num,
2801999SN/A                        Process *process, ThreadContext *tc);
2813114Sgblack@eecs.umich.edu
2821999SN/A/// Target fcntl64() handler.
2831999SN/ASyscallReturn fcntl64Func(SyscallDesc *desc, int num,
2841999SN/A                          Process *process, ThreadContext *tc);
2851999SN/A
2863114Sgblack@eecs.umich.edu/// Target setuid() handler.
2871999SN/ASyscallReturn setuidFunc(SyscallDesc *desc, int num,
2883079Sstever@eecs.umich.edu                         Process *p, ThreadContext *tc);
2893079Sstever@eecs.umich.edu
2903114Sgblack@eecs.umich.edu/// Target pipe() handler.
2913079Sstever@eecs.umich.eduSyscallReturn pipeFunc(SyscallDesc *desc, int num,
2922093SN/A                       Process *p, ThreadContext *tc);
2932093SN/A
2943114Sgblack@eecs.umich.edu/// Internal pipe() handler.
2952093SN/ASyscallReturn pipeImpl(SyscallDesc *desc, int num, Process *p,
2962687Sksewell@umich.edu                       ThreadContext *tc, bool pseudoPipe);
2972687Sksewell@umich.edu
2983114Sgblack@eecs.umich.edu/// Target getpid() handler.
2992687Sksewell@umich.eduSyscallReturn getpidFunc(SyscallDesc *desc, int num,
3002238SN/A                         Process *p, ThreadContext *tc);
3012238SN/A
3023114Sgblack@eecs.umich.edu// Target getpeername() handler.
3032238SN/ASyscallReturn getpeernameFunc(SyscallDesc *desc, int num,
3042238SN/A                              Process *p, ThreadContext *tc);
3052238SN/A
3063114Sgblack@eecs.umich.edu// Target bind() handler.
3072238SN/ASyscallReturn bindFunc(SyscallDesc *desc, int num,
3082238SN/A                       Process *p, ThreadContext *tc);
3092238SN/A
3103114Sgblack@eecs.umich.edu// Target listen() handler.
3112238SN/ASyscallReturn listenFunc(SyscallDesc *desc, int num,
3122238SN/A                         Process *p, ThreadContext *tc);
3132238SN/A
3143114Sgblack@eecs.umich.edu// Target connect() handler.
3152238SN/ASyscallReturn connectFunc(SyscallDesc *desc, int num,
3162238SN/A                          Process *p, ThreadContext *tc);
3172238SN/A
3183114Sgblack@eecs.umich.edu#if defined(SYS_getdents)
3192238SN/A// Target getdents() handler.
3202238SN/ASyscallReturn getdentsFunc(SyscallDesc *desc, int num,
3212238SN/A                           Process *p, ThreadContext *tc);
3223114Sgblack@eecs.umich.edu#endif
3232238SN/A
3242238SN/A#if defined(SYS_getdents64)
3252238SN/A// Target getdents() handler.
3263114Sgblack@eecs.umich.eduSyscallReturn getdents64Func(SyscallDesc *desc, int num,
3272238SN/A                           Process *p, ThreadContext *tc);
3286109Ssanchezd@stanford.edu#endif
3296109Ssanchezd@stanford.edu
3306109Ssanchezd@stanford.edu// Target sendto() handler.
3312238SN/ASyscallReturn sendtoFunc(SyscallDesc *desc, int num,
3322238SN/A                         Process *p, ThreadContext *tc);
3332238SN/A
3342238SN/A// Target recvfrom() handler.
3352238SN/ASyscallReturn recvfromFunc(SyscallDesc *desc, int num,
3363114Sgblack@eecs.umich.edu                           Process *p, ThreadContext *tc);
3372238SN/A
3382238SN/A// Target recvmsg() handler.
3392238SN/ASyscallReturn recvmsgFunc(SyscallDesc *desc, int num,
3403114Sgblack@eecs.umich.edu                          Process *p, ThreadContext *tc);
3412238SN/A
3422238SN/A// Target sendmsg() handler.
3432238SN/ASyscallReturn sendmsgFunc(SyscallDesc *desc, int num,
3443114Sgblack@eecs.umich.edu                          Process *p, ThreadContext *tc);
3452238SN/A
3462238SN/A// Target getuid() handler.
3472238SN/ASyscallReturn getuidFunc(SyscallDesc *desc, int num,
3483114Sgblack@eecs.umich.edu                         Process *p, ThreadContext *tc);
3492238SN/A
3502238SN/A/// Target getgid() handler.
3511354SN/ASyscallReturn getgidFunc(SyscallDesc *desc, int num,
3521354SN/A                         Process *p, ThreadContext *tc);
3531354SN/A
3541354SN/A/// Target getppid() handler.
3551354SN/ASyscallReturn getppidFunc(SyscallDesc *desc, int num,
3561354SN/A                          Process *p, ThreadContext *tc);
3571354SN/A
3581354SN/A/// Target geteuid() handler.
3591354SN/ASyscallReturn geteuidFunc(SyscallDesc *desc, int num,
3601354SN/A                          Process *p, ThreadContext *tc);
3611354SN/A
3621354SN/A/// Target getegid() handler.
3631354SN/ASyscallReturn getegidFunc(SyscallDesc *desc, int num,
3641354SN/A                          Process *p, ThreadContext *tc);
3657064Snate@binkert.org
3661354SN/A/// Target access() handler
3671354SN/ASyscallReturn accessFunc(SyscallDesc *desc, int num,
3681354SN/A                         Process *p, ThreadContext *tc);
3691354SN/ASyscallReturn accessFunc(SyscallDesc *desc, int num,
370360SN/A                         Process *p, ThreadContext *tc,
371360SN/A                         int index);
372360SN/A
373360SN/A// Target getsockopt() handler.
374360SN/ASyscallReturn getsockoptFunc(SyscallDesc *desc, int num,
375360SN/A                             Process *p, ThreadContext *tc);
376360SN/A
3773113Sgblack@eecs.umich.edu// Target setsockopt() handler.
3783113Sgblack@eecs.umich.eduSyscallReturn setsockoptFunc(SyscallDesc *desc, int num,
3793113Sgblack@eecs.umich.edu                             Process *p, ThreadContext *tc);
3803113Sgblack@eecs.umich.edu
3813113Sgblack@eecs.umich.edu// Target getsockname() handler.
3823113Sgblack@eecs.umich.eduSyscallReturn getsocknameFunc(SyscallDesc *desc, int num,
3833113Sgblack@eecs.umich.edu                              Process *p, ThreadContext *tc);
3843113Sgblack@eecs.umich.edu
3853113Sgblack@eecs.umich.edu/// Futex system call
3863113Sgblack@eecs.umich.edu/// Implemented by Daniel Sanchez
3873113Sgblack@eecs.umich.edu/// Used by printf's in multi-threaded apps
3883113Sgblack@eecs.umich.edutemplate <class OS>
3893113Sgblack@eecs.umich.eduSyscallReturn
3903113Sgblack@eecs.umich.edufutexFunc(SyscallDesc *desc, int callnum, Process *process,
3913113Sgblack@eecs.umich.edu          ThreadContext *tc)
3923113Sgblack@eecs.umich.edu{
3934189Sgblack@eecs.umich.edu    using namespace std;
3944189Sgblack@eecs.umich.edu
3953113Sgblack@eecs.umich.edu    int index = 0;
3963113Sgblack@eecs.umich.edu    Addr uaddr = process->getSyscallArg(tc, index);
3973113Sgblack@eecs.umich.edu    int op = process->getSyscallArg(tc, index);
3983113Sgblack@eecs.umich.edu    int val = process->getSyscallArg(tc, index);
3993113Sgblack@eecs.umich.edu    int timeout M5_VAR_USED = process->getSyscallArg(tc, index);
4003113Sgblack@eecs.umich.edu    Addr uaddr2 M5_VAR_USED = process->getSyscallArg(tc, index);
4013113Sgblack@eecs.umich.edu    int val3 = process->getSyscallArg(tc, index);
4023277Sgblack@eecs.umich.edu
4035515SMichael.Adler@intel.com    /*
4045515SMichael.Adler@intel.com     * Unsupported option that does not affect the correctness of the
4055515SMichael.Adler@intel.com     * application. This is a performance optimization utilized by Linux.
4065515SMichael.Adler@intel.com     */
4075515SMichael.Adler@intel.com    op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
4083277Sgblack@eecs.umich.edu    op &= ~OS::TGT_FUTEX_CLOCK_REALTIME_FLAG;
4093277Sgblack@eecs.umich.edu
4103277Sgblack@eecs.umich.edu    FutexMap &futex_map = tc->getSystemPtr()->futexMap;
4113277Sgblack@eecs.umich.edu
4123277Sgblack@eecs.umich.edu    if (OS::TGT_FUTEX_WAIT == op || OS::TGT_FUTEX_WAIT_BITSET == op) {
4133277Sgblack@eecs.umich.edu        // Ensure futex system call accessed atomically.
4143277Sgblack@eecs.umich.edu        BufferArg buf(uaddr, sizeof(int));
4153113Sgblack@eecs.umich.edu        buf.copyIn(tc->getMemProxy());
4163113Sgblack@eecs.umich.edu        int mem_val = *(int*)buf.bufferPtr();
4173113Sgblack@eecs.umich.edu
4183113Sgblack@eecs.umich.edu        /*
4193113Sgblack@eecs.umich.edu         * The value in memory at uaddr is not equal with the expected val
4203113Sgblack@eecs.umich.edu         * (a different thread must have changed it before the system call was
4213113Sgblack@eecs.umich.edu         * invoked). In this case, we need to throw an error.
4223114Sgblack@eecs.umich.edu         */
4233113Sgblack@eecs.umich.edu        if (val != mem_val)
4243114Sgblack@eecs.umich.edu            return -OS::TGT_EWOULDBLOCK;
4253113Sgblack@eecs.umich.edu
4263114Sgblack@eecs.umich.edu        if (OS::TGT_FUTEX_WAIT) {
4273113Sgblack@eecs.umich.edu            futex_map.suspend(uaddr, process->tgid(), tc);
4284061Sgblack@eecs.umich.edu        } else {
4294061Sgblack@eecs.umich.edu            futex_map.suspend_bitset(uaddr, process->tgid(), tc, val3);
4304061Sgblack@eecs.umich.edu        }
4313113Sgblack@eecs.umich.edu
4323113Sgblack@eecs.umich.edu        return 0;
4333113Sgblack@eecs.umich.edu    } else if (OS::TGT_FUTEX_WAKE == op) {
4343113Sgblack@eecs.umich.edu        return futex_map.wakeup(uaddr, process->tgid(), val);
4353113Sgblack@eecs.umich.edu    } else if (OS::TGT_FUTEX_WAKE_BITSET == op) {
4363113Sgblack@eecs.umich.edu        return futex_map.wakeup_bitset(uaddr, process->tgid(), val3);
4373113Sgblack@eecs.umich.edu    } else if (OS::TGT_FUTEX_REQUEUE == op ||
4383113Sgblack@eecs.umich.edu               OS::TGT_FUTEX_CMP_REQUEUE == op) {
4393113Sgblack@eecs.umich.edu
4403113Sgblack@eecs.umich.edu        // Ensure futex system call accessed atomically.
4413113Sgblack@eecs.umich.edu        BufferArg buf(uaddr, sizeof(int));
4424189Sgblack@eecs.umich.edu        buf.copyIn(tc->getMemProxy());
4434189Sgblack@eecs.umich.edu        int mem_val = *(int*)buf.bufferPtr();
4443113Sgblack@eecs.umich.edu        /*
4453113Sgblack@eecs.umich.edu         * For CMP_REQUEUE, the whole operation is only started only if
4463113Sgblack@eecs.umich.edu         * val3 is still the value of the futex pointed to by uaddr.
4473113Sgblack@eecs.umich.edu         */
4483113Sgblack@eecs.umich.edu        if (OS::TGT_FUTEX_CMP_REQUEUE && val3 != mem_val)
4493113Sgblack@eecs.umich.edu            return -OS::TGT_EWOULDBLOCK;
4503113Sgblack@eecs.umich.edu        return futex_map.requeue(uaddr, process->tgid(), val, timeout, uaddr2);
4513113Sgblack@eecs.umich.edu    } else if (OS::TGT_FUTEX_WAKE_OP == op) {
4523113Sgblack@eecs.umich.edu        /*
4533113Sgblack@eecs.umich.edu         * The FUTEX_WAKE_OP operation is equivalent to executing the
4543113Sgblack@eecs.umich.edu         * following code atomically and totally ordered with respect to
4553113Sgblack@eecs.umich.edu         * other futex operations on any of the two supplied futex words:
4563113Sgblack@eecs.umich.edu         *
4573113Sgblack@eecs.umich.edu         *   int oldval = *(int *) addr2;
4583113Sgblack@eecs.umich.edu         *   *(int *) addr2 = oldval op oparg;
4593113Sgblack@eecs.umich.edu         *   futex(addr1, FUTEX_WAKE, val, 0, 0, 0);
4603113Sgblack@eecs.umich.edu         *   if (oldval cmp cmparg)
4613113Sgblack@eecs.umich.edu         *        futex(addr2, FUTEX_WAKE, val2, 0, 0, 0);
4623113Sgblack@eecs.umich.edu         *
4633113Sgblack@eecs.umich.edu         * (op, oparg, cmp, cmparg are encoded in val3)
4643113Sgblack@eecs.umich.edu         *
4653113Sgblack@eecs.umich.edu         * +---+---+-----------+-----------+
4663113Sgblack@eecs.umich.edu         * |op |cmp|   oparg   |  cmparg   |
4673113Sgblack@eecs.umich.edu         * +---+---+-----------+-----------+
4683113Sgblack@eecs.umich.edu         *   4   4       12          12    <== # of bits
4693113Sgblack@eecs.umich.edu         *
4703113Sgblack@eecs.umich.edu         * reference: http://man7.org/linux/man-pages/man2/futex.2.html
4713113Sgblack@eecs.umich.edu         *
4723113Sgblack@eecs.umich.edu         */
4733113Sgblack@eecs.umich.edu        // get value from simulated-space
4743113Sgblack@eecs.umich.edu        BufferArg buf(uaddr2, sizeof(int));
4753113Sgblack@eecs.umich.edu        buf.copyIn(tc->getMemProxy());
4763113Sgblack@eecs.umich.edu        int oldval = *(int*)buf.bufferPtr();
4773113Sgblack@eecs.umich.edu        int newval = oldval;
4786686Stjones1@inf.ed.ac.uk        // extract op, oparg, cmp, cmparg from val3
4793113Sgblack@eecs.umich.edu        int wake_cmparg =  val3 & 0xfff;
4803113Sgblack@eecs.umich.edu        int wake_oparg  = (val3 & 0xfff000)   >> 12;
4813113Sgblack@eecs.umich.edu        int wake_cmp    = (val3 & 0xf000000)  >> 24;
482378SN/A        int wake_op     = (val3 & 0xf0000000) >> 28;
483378SN/A        if ((wake_op & OS::TGT_FUTEX_OP_ARG_SHIFT) >> 3 == 1)
484378SN/A            wake_oparg = (1 << wake_oparg);
485360SN/A        wake_op &= ~OS::TGT_FUTEX_OP_ARG_SHIFT;
4861450SN/A        // perform operation on the value of the second futex
4873114Sgblack@eecs.umich.edu        if (wake_op == OS::TGT_FUTEX_OP_SET)
4882680Sktlim@umich.edu            newval = wake_oparg;
489360SN/A        else if (wake_op == OS::TGT_FUTEX_OP_ADD)
4906701Sgblack@eecs.umich.edu            newval += wake_oparg;
4916701Sgblack@eecs.umich.edu        else if (wake_op == OS::TGT_FUTEX_OP_OR)
4926701Sgblack@eecs.umich.edu            newval |= wake_oparg;
493360SN/A        else if (wake_op == OS::TGT_FUTEX_OP_ANDN)
4941969SN/A            newval &= ~wake_oparg;
495360SN/A        else if (wake_op == OS::TGT_FUTEX_OP_XOR)
496360SN/A            newval ^= wake_oparg;
497360SN/A        // copy updated value back to simulated-space
4981458SN/A        *(int*)buf.bufferPtr() = newval;
499360SN/A        buf.copyOut(tc->getMemProxy());
500360SN/A        // perform the first wake-up
501360SN/A        int woken1 = futex_map.wakeup(uaddr, process->tgid(), val);
5024131Sbinkertn@umich.edu        int woken2 = 0;
5034131Sbinkertn@umich.edu        // calculate the condition of the second wake-up
5044131Sbinkertn@umich.edu        bool is_wake2 = false;
5054131Sbinkertn@umich.edu        if (wake_cmp == OS::TGT_FUTEX_OP_CMP_EQ)
5064131Sbinkertn@umich.edu            is_wake2 = oldval == wake_cmparg;
5074131Sbinkertn@umich.edu        else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_NE)
5084131Sbinkertn@umich.edu            is_wake2 = oldval != wake_cmparg;
5094131Sbinkertn@umich.edu        else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LT)
5106689Stjones1@inf.ed.ac.uk            is_wake2 = oldval < wake_cmparg;
5111458SN/A        else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LE)
512360SN/A            is_wake2 = oldval <= wake_cmparg;
513360SN/A        else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GT)
5141706SN/A            is_wake2 = oldval > wake_cmparg;
5152680Sktlim@umich.edu        else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GE)
516360SN/A            is_wake2 = oldval >= wake_cmparg;
517360SN/A        // perform the second wake-up
518360SN/A        if (is_wake2)
519378SN/A            woken2 = futex_map.wakeup(uaddr2, process->tgid(), timeout);
520360SN/A
5211450SN/A        return woken1 + woken2;
5223114Sgblack@eecs.umich.edu    }
5232680Sktlim@umich.edu    warn("futex: op %d not implemented; ignoring.", op);
524360SN/A    return -ENOSYS;
525360SN/A}
526360SN/A
5276701Sgblack@eecs.umich.edu
5286701Sgblack@eecs.umich.edu/// Pseudo Funcs  - These functions use a different return convension,
5296701Sgblack@eecs.umich.edu/// returning a second value in a register other than the normal return register
5301458SN/ASyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
531360SN/A                             Process *process, ThreadContext *tc);
532360SN/A
533360SN/A/// Target getpidPseudo() handler.
534360SN/ASyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
5351706SN/A                               Process *p, ThreadContext *tc);
5361458SN/A
537360SN/A/// Target getuidPseudo() handler.
538360SN/ASyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
5396701Sgblack@eecs.umich.edu                               Process *p, ThreadContext *tc);
5406701Sgblack@eecs.umich.edu
541360SN/A/// Target getgidPseudo() handler.
542360SN/ASyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
543360SN/A                               Process *p, ThreadContext *tc);
544360SN/A
545360SN/A
546360SN/A/// A readable name for 1,000,000, for converting microseconds to seconds.
547360SN/Aconst int one_million = 1000000;
548360SN/A/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
549360SN/Aconst int one_billion = 1000000000;
550360SN/A
551360SN/A/// Approximate seconds since the epoch (1/1/1970).  About a billion,
552360SN/A/// by my reckoning.  We want to keep this a constant (not use the
5531706SN/A/// real-world time) to keep simulations repeatable.
554360SN/Aconst unsigned seconds_since_epoch = 1000000000;
555360SN/A
556360SN/A/// Helper function to convert current elapsed time to seconds and
557360SN/A/// microseconds.
558360SN/Atemplate <class T1, class T2>
5593669Sbinkertn@umich.eduvoid
5603669Sbinkertn@umich.edugetElapsedTimeMicro(T1 &sec, T2 &usec)
5613669Sbinkertn@umich.edu{
5621706SN/A    uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
5631706SN/A    sec = elapsed_usecs / one_million;
5645795Ssaidi@eecs.umich.edu    usec = elapsed_usecs % one_million;
5655795Ssaidi@eecs.umich.edu}
5665795Ssaidi@eecs.umich.edu
5675795Ssaidi@eecs.umich.edu/// Helper function to convert current elapsed time to seconds and
5685795Ssaidi@eecs.umich.edu/// nanoseconds.
5695795Ssaidi@eecs.umich.edutemplate <class T1, class T2>
5705795Ssaidi@eecs.umich.eduvoid
5715795Ssaidi@eecs.umich.edugetElapsedTimeNano(T1 &sec, T2 &nsec)
5725795Ssaidi@eecs.umich.edu{
5735795Ssaidi@eecs.umich.edu    uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
5745795Ssaidi@eecs.umich.edu    sec = elapsed_nsecs / one_billion;
575360SN/A    nsec = elapsed_nsecs % one_billion;
576360SN/A}
577360SN/A
5786640Svince@csl.cornell.edu//////////////////////////////////////////////////////////////////////
5796640Svince@csl.cornell.edu//
5806640Svince@csl.cornell.edu// The following emulation functions are generic, but need to be
5816640Svince@csl.cornell.edu// templated to account for differences in types, constants, etc.
5826640Svince@csl.cornell.edu//
5836640Svince@csl.cornell.edu//////////////////////////////////////////////////////////////////////
5846640Svince@csl.cornell.edu
5856701Sgblack@eecs.umich.edu    typedef struct statfs hst_statfs;
5866701Sgblack@eecs.umich.edu#if NO_STAT64
5876701Sgblack@eecs.umich.edu    typedef struct stat hst_stat;
5886640Svince@csl.cornell.edu    typedef struct stat hst_stat64;
5896701Sgblack@eecs.umich.edu#else
5906701Sgblack@eecs.umich.edu    typedef struct stat hst_stat;
5916640Svince@csl.cornell.edu    typedef struct stat64 hst_stat64;
5926701Sgblack@eecs.umich.edu#endif
5936640Svince@csl.cornell.edu
5946701Sgblack@eecs.umich.edu//// Helper function to convert a host stat buffer to a target stat
5956640Svince@csl.cornell.edu//// buffer.  Also copies the target buffer out to the simulated
596360SN/A//// memory space.  Used by stat(), fstat(), and lstat().
5971999SN/A
5981999SN/Atemplate <typename target_stat, typename host_stat>
5991999SN/Avoid
6003114Sgblack@eecs.umich.educonvertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
6012680Sktlim@umich.edu{
6021999SN/A    using namespace TheISA;
6031999SN/A
6041999SN/A    if (fakeTTY)
6056701Sgblack@eecs.umich.edu        tgt->st_dev = 0xA;
6066701Sgblack@eecs.umich.edu    else
6076701Sgblack@eecs.umich.edu        tgt->st_dev = host->st_dev;
6081999SN/A    tgt->st_dev = TheISA::htog(tgt->st_dev);
6096701Sgblack@eecs.umich.edu    tgt->st_ino = host->st_ino;
6101999SN/A    tgt->st_ino = TheISA::htog(tgt->st_ino);
6116701Sgblack@eecs.umich.edu    tgt->st_mode = host->st_mode;
6121999SN/A    if (fakeTTY) {
6131999SN/A        // Claim to be a character device
6141999SN/A        tgt->st_mode &= ~S_IFMT;    // Clear S_IFMT
6151999SN/A        tgt->st_mode |= S_IFCHR;    // Set S_IFCHR
6161999SN/A    }
6173669Sbinkertn@umich.edu    tgt->st_mode = TheISA::htog(tgt->st_mode);
6183669Sbinkertn@umich.edu    tgt->st_nlink = host->st_nlink;
6193669Sbinkertn@umich.edu    tgt->st_nlink = TheISA::htog(tgt->st_nlink);
6201999SN/A    tgt->st_uid = host->st_uid;
6211999SN/A    tgt->st_uid = TheISA::htog(tgt->st_uid);
6221999SN/A    tgt->st_gid = host->st_gid;
6232218SN/A    tgt->st_gid = TheISA::htog(tgt->st_gid);
6241999SN/A    if (fakeTTY)
6251999SN/A        tgt->st_rdev = 0x880d;
6261999SN/A    else
6271999SN/A        tgt->st_rdev = host->st_rdev;
6281999SN/A    tgt->st_rdev = TheISA::htog(tgt->st_rdev);
6291999SN/A    tgt->st_size = host->st_size;
6301999SN/A    tgt->st_size = TheISA::htog(tgt->st_size);
6311999SN/A    tgt->st_atimeX = host->st_atime;
6323114Sgblack@eecs.umich.edu    tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
6332680Sktlim@umich.edu    tgt->st_mtimeX = host->st_mtime;
6341999SN/A    tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
6356701Sgblack@eecs.umich.edu    tgt->st_ctimeX = host->st_ctime;
6366701Sgblack@eecs.umich.edu    tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
6371999SN/A    // Force the block size to be 8KB. This helps to ensure buffered io works
6381999SN/A    // consistently across different hosts.
6391999SN/A    tgt->st_blksize = 0x2000;
6401999SN/A    tgt->st_blksize = TheISA::htog(tgt->st_blksize);
6411999SN/A    tgt->st_blocks = host->st_blocks;
6426701Sgblack@eecs.umich.edu    tgt->st_blocks = TheISA::htog(tgt->st_blocks);
6431999SN/A}
6441999SN/A
6451999SN/A// Same for stat64
6461999SN/A
6471999SN/Atemplate <typename target_stat, typename host_stat64>
6481999SN/Avoid
6491999SN/AconvertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
6501999SN/A{
6512218SN/A    using namespace TheISA;
6521999SN/A
6531999SN/A    convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
6541999SN/A#if defined(STAT_HAVE_NSEC)
6551999SN/A    tgt->st_atime_nsec = host->st_atime_nsec;
6565877Shsul@eecs.umich.edu    tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
6575877Shsul@eecs.umich.edu    tgt->st_mtime_nsec = host->st_mtime_nsec;
6585877Shsul@eecs.umich.edu    tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
6595877Shsul@eecs.umich.edu    tgt->st_ctime_nsec = host->st_ctime_nsec;
6605877Shsul@eecs.umich.edu    tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
6616701Sgblack@eecs.umich.edu#else
6626701Sgblack@eecs.umich.edu    tgt->st_atime_nsec = 0;
6636701Sgblack@eecs.umich.edu    tgt->st_mtime_nsec = 0;
6646701Sgblack@eecs.umich.edu    tgt->st_ctime_nsec = 0;
6656701Sgblack@eecs.umich.edu#endif
6665877Shsul@eecs.umich.edu}
6675877Shsul@eecs.umich.edu
6685877Shsul@eecs.umich.edu// Here are a couple of convenience functions
6695877Shsul@eecs.umich.edutemplate<class OS>
6705877Shsul@eecs.umich.eduvoid
6715877Shsul@eecs.umich.educopyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
6725877Shsul@eecs.umich.edu               hst_stat *host, bool fakeTTY = false)
6735877Shsul@eecs.umich.edu{
6745877Shsul@eecs.umich.edu    typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
6755877Shsul@eecs.umich.edu    tgt_stat_buf tgt(addr);
6765877Shsul@eecs.umich.edu    convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
6775877Shsul@eecs.umich.edu    tgt.copyOut(mem);
6785877Shsul@eecs.umich.edu}
6795877Shsul@eecs.umich.edu
6805877Shsul@eecs.umich.edutemplate<class OS>
6815877Shsul@eecs.umich.eduvoid
6825877Shsul@eecs.umich.educopyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
6835877Shsul@eecs.umich.edu                 hst_stat64 *host, bool fakeTTY = false)
6845877Shsul@eecs.umich.edu{
6855877Shsul@eecs.umich.edu    typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
6865877Shsul@eecs.umich.edu    tgt_stat_buf tgt(addr);
6875877Shsul@eecs.umich.edu    convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
6885877Shsul@eecs.umich.edu    tgt.copyOut(mem);
6895877Shsul@eecs.umich.edu}
6905877Shsul@eecs.umich.edu
6915877Shsul@eecs.umich.edutemplate <class OS>
6925877Shsul@eecs.umich.eduvoid
6935877Shsul@eecs.umich.educopyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
6945877Shsul@eecs.umich.edu                 hst_statfs *host)
6955877Shsul@eecs.umich.edu{
6965877Shsul@eecs.umich.edu    TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
6975877Shsul@eecs.umich.edu
6985877Shsul@eecs.umich.edu    tgt->f_type = TheISA::htog(host->f_type);
6995877Shsul@eecs.umich.edu#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
7005877Shsul@eecs.umich.edu    tgt->f_bsize = TheISA::htog(host->f_iosize);
7015877Shsul@eecs.umich.edu#else
7021999SN/A    tgt->f_bsize = TheISA::htog(host->f_bsize);
703378SN/A#endif
704360SN/A    tgt->f_blocks = TheISA::htog(host->f_blocks);
7051450SN/A    tgt->f_bfree = TheISA::htog(host->f_bfree);
7063114Sgblack@eecs.umich.edu    tgt->f_bavail = TheISA::htog(host->f_bavail);
7072680Sktlim@umich.edu    tgt->f_files = TheISA::htog(host->f_files);
708360SN/A    tgt->f_ffree = TheISA::htog(host->f_ffree);
709360SN/A    memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
710360SN/A#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
7116701Sgblack@eecs.umich.edu    tgt->f_namelen = TheISA::htog(host->f_namemax);
7126701Sgblack@eecs.umich.edu    tgt->f_frsize = TheISA::htog(host->f_bsize);
7136701Sgblack@eecs.umich.edu#elif defined(__APPLE__)
7146701Sgblack@eecs.umich.edu    tgt->f_namelen = 0;
7156701Sgblack@eecs.umich.edu    tgt->f_frsize = 0;
7166701Sgblack@eecs.umich.edu#else
717360SN/A    tgt->f_namelen = TheISA::htog(host->f_namelen);
7183669Sbinkertn@umich.edu    tgt->f_frsize = TheISA::htog(host->f_frsize);
7193669Sbinkertn@umich.edu#endif
7203669Sbinkertn@umich.edu#if defined(__linux__)
721360SN/A    memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
722360SN/A#else
723360SN/A    /*
724360SN/A     * The fields are different sizes per OS. Don't bother with
7252218SN/A     * f_spare or f_reserved on non-Linux for now.
726360SN/A     */
7276701Sgblack@eecs.umich.edu    memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
728360SN/A#endif
7291458SN/A
730360SN/A    tgt.copyOut(mem);
731360SN/A}
732360SN/A
7335074Ssaidi@eecs.umich.edu/// Target ioctl() handler.  For the most part, programs call ioctl()
7345074Ssaidi@eecs.umich.edu/// only to find out if their stdout is a tty, to determine whether to
7355074Ssaidi@eecs.umich.edu/// do line or block buffering.  We always claim that output fds are
7365074Ssaidi@eecs.umich.edu/// not TTYs to provide repeatable results.
7375074Ssaidi@eecs.umich.edutemplate <class OS>
7385074Ssaidi@eecs.umich.eduSyscallReturn
7395074Ssaidi@eecs.umich.eduioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
7405074Ssaidi@eecs.umich.edu{
7416701Sgblack@eecs.umich.edu    int index = 0;
7426701Sgblack@eecs.umich.edu    int tgt_fd = p->getSyscallArg(tc, index);
7436701Sgblack@eecs.umich.edu    unsigned req = p->getSyscallArg(tc, index);
7445074Ssaidi@eecs.umich.edu
7456701Sgblack@eecs.umich.edu    DPRINTF_SYSCALL(Verbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
7465074Ssaidi@eecs.umich.edu
7475074Ssaidi@eecs.umich.edu    if (OS::isTtyReq(req))
7485074Ssaidi@eecs.umich.edu        return -ENOTTY;
7495074Ssaidi@eecs.umich.edu
7505208Ssaidi@eecs.umich.edu    auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
7515208Ssaidi@eecs.umich.edu    if (dfdp) {
7525208Ssaidi@eecs.umich.edu        EmulatedDriver *emul_driver = dfdp->getDriver();
7535208Ssaidi@eecs.umich.edu        if (emul_driver)
7545074Ssaidi@eecs.umich.edu            return emul_driver->ioctl(p, tc, req);
7555074Ssaidi@eecs.umich.edu    }
7565208Ssaidi@eecs.umich.edu
7575074Ssaidi@eecs.umich.edu    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
7585074Ssaidi@eecs.umich.edu    if (sfdp) {
7595074Ssaidi@eecs.umich.edu        int status;
7605074Ssaidi@eecs.umich.edu
7616701Sgblack@eecs.umich.edu        switch (req) {
7625074Ssaidi@eecs.umich.edu          case SIOCGIFCONF: {
7635074Ssaidi@eecs.umich.edu            Addr conf_addr = p->getSyscallArg(tc, index);
7645074Ssaidi@eecs.umich.edu            BufferArg conf_arg(conf_addr, sizeof(ifconf));
7655074Ssaidi@eecs.umich.edu            conf_arg.copyIn(tc->getMemProxy());
7665074Ssaidi@eecs.umich.edu
7671999SN/A            ifconf *conf = (ifconf*)conf_arg.bufferPtr();
7681999SN/A            Addr ifc_buf_addr = (Addr)conf->ifc_buf;
7691999SN/A            BufferArg ifc_buf_arg(ifc_buf_addr, conf->ifc_len);
7703114Sgblack@eecs.umich.edu            ifc_buf_arg.copyIn(tc->getMemProxy());
7712680Sktlim@umich.edu
7721999SN/A            conf->ifc_buf = (char*)ifc_buf_arg.bufferPtr();
7736701Sgblack@eecs.umich.edu
7746701Sgblack@eecs.umich.edu            status = ioctl(sfdp->getSimFD(), req, conf_arg.bufferPtr());
7756701Sgblack@eecs.umich.edu            if (status != -1) {
7761999SN/A                conf->ifc_buf = (char*)ifc_buf_addr;
7771999SN/A                ifc_buf_arg.copyOut(tc->getMemProxy());
7781999SN/A                conf_arg.copyOut(tc->getMemProxy());
7791999SN/A            }
7801999SN/A
7812764Sstever@eecs.umich.edu            return status;
7822064SN/A          }
7832064SN/A          case SIOCGIFFLAGS:
7842064SN/A#if defined(__linux__)
7852064SN/A          case SIOCGIFINDEX:
7861999SN/A#endif
7872064SN/A          case SIOCGIFNETMASK:
7881999SN/A          case SIOCGIFADDR:
7891999SN/A#if defined(__linux__)
7902218SN/A          case SIOCGIFHWADDR:
7911999SN/A#endif
7926701Sgblack@eecs.umich.edu          case SIOCGIFMTU: {
7931999SN/A            Addr req_addr = p->getSyscallArg(tc, index);
7941999SN/A            BufferArg req_arg(req_addr, sizeof(ifreq));
7951999SN/A            req_arg.copyIn(tc->getMemProxy());
7961999SN/A
7971999SN/A            status = ioctl(sfdp->getSimFD(), req, req_arg.bufferPtr());
798378SN/A            if (status != -1)
799360SN/A                req_arg.copyOut(tc->getMemProxy());
8001450SN/A            return status;
8013114Sgblack@eecs.umich.edu          }
8022680Sktlim@umich.edu        }
803360SN/A    }
804360SN/A
805360SN/A    /**
8066701Sgblack@eecs.umich.edu     * For lack of a better return code, return ENOTTY. Ideally, we should
8076701Sgblack@eecs.umich.edu     * return something better here, but at least we issue the warning.
8086701Sgblack@eecs.umich.edu     */
8096701Sgblack@eecs.umich.edu    warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
8106701Sgblack@eecs.umich.edu         tgt_fd, req, tc->pcState());
8116701Sgblack@eecs.umich.edu    return -ENOTTY;
812360SN/A}
8133669Sbinkertn@umich.edu
8143669Sbinkertn@umich.edutemplate <class OS>
8153669Sbinkertn@umich.eduSyscallReturn
816360SN/AopenImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
817360SN/A         bool isopenat)
818360SN/A{
819360SN/A    int index = 0;
8201458SN/A    int tgt_dirfd = -1;
821360SN/A
8226701Sgblack@eecs.umich.edu    /**
823360SN/A     * If using the openat variant, read in the target directory file
8241458SN/A     * descriptor from the simulated process.
825360SN/A     */
826360SN/A    if (isopenat)
8271999SN/A        tgt_dirfd = p->getSyscallArg(tc, index);
8281999SN/A
8291999SN/A    /**
8303114Sgblack@eecs.umich.edu     * Retrieve the simulated process' memory proxy and then read in the path
8312680Sktlim@umich.edu     * string from that memory space into the host's working memory space.
8321999SN/A     */
8331999SN/A    std::string path;
8341999SN/A    if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
8356701Sgblack@eecs.umich.edu        return -EFAULT;
8366701Sgblack@eecs.umich.edu
8376701Sgblack@eecs.umich.edu#ifdef __CYGWIN32__
8386701Sgblack@eecs.umich.edu    int host_flags = O_BINARY;
8396701Sgblack@eecs.umich.edu#else
8406701Sgblack@eecs.umich.edu    int host_flags = 0;
8411999SN/A#endif
8423669Sbinkertn@umich.edu    /**
8433669Sbinkertn@umich.edu     * Translate target flags into host flags. Flags exist which are not
8443669Sbinkertn@umich.edu     * ported between architectures which can cause check failures.
8452764Sstever@eecs.umich.edu     */
8462064SN/A    int tgt_flags = p->getSyscallArg(tc, index);
8472064SN/A    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
8482064SN/A        if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
8491999SN/A            tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
8501999SN/A            host_flags |= OS::openFlagTable[i].hostFlag;
8512064SN/A        }
8521999SN/A    }
8531999SN/A    if (tgt_flags) {
8541999SN/A        warn("open%s: cannot decode flags 0x%x",
8551999SN/A             isopenat ? "at" : "", tgt_flags);
8566701Sgblack@eecs.umich.edu    }
8571999SN/A#ifdef __CYGWIN32__
8581999SN/A    host_flags |= O_BINARY;
8591999SN/A#endif
8601999SN/A
861378SN/A    int mode = p->getSyscallArg(tc, index);
862360SN/A
8631450SN/A    /**
8643114Sgblack@eecs.umich.edu     * If the simulated process called open or openat with AT_FDCWD specified,
8652680Sktlim@umich.edu     * take the current working directory value which was passed into the
866360SN/A     * process class as a Python parameter and append the current path to
8676701Sgblack@eecs.umich.edu     * create a full path.
8686701Sgblack@eecs.umich.edu     * Otherwise, openat with a valid target directory file descriptor has
8696701Sgblack@eecs.umich.edu     * been called. If the path option, which was passed in as a parameter,
870360SN/A     * is not absolute, retrieve the directory file descriptor's path and
8711969SN/A     * prepend it to the path passed in as a parameter.
872360SN/A     * In every case, we should have a full path (which is relevant to the
873360SN/A     * host) to work with after this block has been passed.
8741458SN/A     */
875360SN/A    std::string redir_path = path;
876360SN/A    std::string abs_path = path;
877360SN/A    if (!isopenat || tgt_dirfd == OS::TGT_AT_FDCWD) {
878360SN/A        abs_path = p->absolutePath(path, true);
879360SN/A        redir_path = p->checkPathRedirect(path);
8801458SN/A    } else if (!startswith(path, "/")) {
881360SN/A        std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
8826701Sgblack@eecs.umich.edu        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
8832021SN/A        if (!ffdp)
8841458SN/A            return -EBADF;
885360SN/A        abs_path = ffdp->getFileName() + path;
886360SN/A        redir_path = p->checkPathRedirect(abs_path);
887360SN/A    }
8881706SN/A
8891706SN/A    /**
8901706SN/A     * Since this is an emulated environment, we create pseudo file
8913114Sgblack@eecs.umich.edu     * descriptors for device requests that have been registered with
8922680Sktlim@umich.edu     * the process class through Python; this allows us to create a file
8931706SN/A     * descriptor for subsequent ioctl or mmap calls.
8941706SN/A     */
8951706SN/A    if (startswith(abs_path, "/dev/")) {
8966701Sgblack@eecs.umich.edu        std::string filename = abs_path.substr(strlen("/dev/"));
8976701Sgblack@eecs.umich.edu        EmulatedDriver *drv = p->findDriver(filename);
8986701Sgblack@eecs.umich.edu        if (drv) {
8996701Sgblack@eecs.umich.edu            DPRINTF_SYSCALL(Verbose, "open%s: passing call to "
9006701Sgblack@eecs.umich.edu                            "driver open with path[%s]\n",
9016701Sgblack@eecs.umich.edu                            isopenat ? "at" : "", abs_path.c_str());
9021706SN/A            return drv->open(p, tc, mode, host_flags);
9033669Sbinkertn@umich.edu        }
9043669Sbinkertn@umich.edu        /**
9053669Sbinkertn@umich.edu         * Fall through here for pass through to host devices, such
9061706SN/A         * as /dev/zero
9071706SN/A         */
9081706SN/A    }
9091706SN/A
9102218SN/A    /**
9111706SN/A     * We make several attempts resolve a call to open.
9126701Sgblack@eecs.umich.edu     *
9131706SN/A     * 1) Resolve any path redirection before hand. This will set the path
9141706SN/A     * up with variable 'redir_path' which may contain a modified path or
9151706SN/A     * the original path value. This should already be done in prior code.
9161706SN/A     * 2) Try to handle the access using 'special_paths'. Some special_paths
9171706SN/A     * and files cannot be called on the host and need to be handled as
9181706SN/A     * special cases inside the simulator. These special_paths are handled by
9191706SN/A     * C++ routines to provide output back to userspace.
9201706SN/A     * 3) If the full path that was created above does not match any of the
9213114Sgblack@eecs.umich.edu     * special cases, pass it through to the open call on the __HOST__ to let
9222680Sktlim@umich.edu     * the host open the file on our behalf. Again, the openImpl tries to
9231706SN/A     * USE_THE_HOST_FILESYSTEM_OPEN (with a possible redirection to the
9246701Sgblack@eecs.umich.edu     * faux-filesystem files). The faux-filesystem is dynamically created
9256701Sgblack@eecs.umich.edu     * during simulator configuration using Python functions.
9266701Sgblack@eecs.umich.edu     * 4) If the host cannot open the file, the open attempt failed in "3)".
9271706SN/A     * Return the host's error code back through the system call to the
9281706SN/A     * simulated process. If running a debug trace, also notify the user that
9291706SN/A     * the open call failed.
9301706SN/A     *
9311706SN/A     * Any success will set sim_fd to something other than -1 and skip the
9321706SN/A     * next conditions effectively bypassing them.
9331706SN/A     */
9341706SN/A    int sim_fd = -1;
9352218SN/A    std::string used_path;
9361706SN/A    std::vector<std::string> special_paths =
9376701Sgblack@eecs.umich.edu            { "/proc/meminfo/", "/system/", "/sys/", "/platform/",
9381706SN/A              "/etc/passwd" };
9391706SN/A    for (auto entry : special_paths) {
9401706SN/A        if (startswith(path, entry)) {
9411706SN/A            sim_fd = OS::openSpecialFile(abs_path, p, tc);
9421706SN/A            used_path = abs_path;
9431999SN/A        }
9441999SN/A    }
9451999SN/A    if (sim_fd == -1) {
9463114Sgblack@eecs.umich.edu        sim_fd = open(redir_path.c_str(), host_flags, mode);
9472680Sktlim@umich.edu        used_path = redir_path;
9481999SN/A    }
9496701Sgblack@eecs.umich.edu    if (sim_fd == -1) {
9506701Sgblack@eecs.umich.edu        int local = -errno;
9511999SN/A        DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s "
9521999SN/A                        "(inferred from:%s)\n", isopenat ? "at" : "",
9531999SN/A                        used_path.c_str(), path.c_str());
9541999SN/A        return local;
9551999SN/A    }
9562680Sktlim@umich.edu
9576701Sgblack@eecs.umich.edu    /**
9586701Sgblack@eecs.umich.edu     * The file was opened successfully and needs to be recorded in the
9591999SN/A     * process' file descriptor array so that it can be retrieved later.
9606227Snate@binkert.org     * The target file descriptor that is chosen will be the lowest unused
9611999SN/A     * file descriptor.
9622461SN/A     * Return the indirect target file descriptor back to the simulated
9632461SN/A     * process to act as a handle for the opened file.
9642461SN/A     */
9652091SN/A    auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
9661999SN/A    int tgt_fd = p->fds->allocFD(ffdp);
9672461SN/A    DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n"
9682461SN/A                    "(inferred from:%s)\n", isopenat ? "at" : "",
9691999SN/A                    sim_fd, tgt_fd, used_path.c_str(), path.c_str());
9701999SN/A    return tgt_fd;
9711999SN/A}
9721999SN/A
9736227Snate@binkert.org/// Target open() handler.
9741999SN/Atemplate <class OS>
9751999SN/ASyscallReturn
9761999SN/AopenFunc(SyscallDesc *desc, int callnum, Process *process,
9772218SN/A         ThreadContext *tc)
9781999SN/A{
9791999SN/A    return openImpl<OS>(desc, callnum, process, tc, false);
9801999SN/A}
9811999SN/A
9821999SN/A/// Target openat() handler.
983378SN/Atemplate <class OS>
984378SN/ASyscallReturn
985378SN/AopenatFunc(SyscallDesc *desc, int callnum, Process *process,
986378SN/A           ThreadContext *tc)
987378SN/A{
988378SN/A    return openImpl<OS>(desc, callnum, process, tc, true);
989378SN/A}
990378SN/A
991360SN/A/// Target unlinkat() handler.
992378SN/Atemplate <class OS>
993378SN/ASyscallReturn
994378SN/AunlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
995360SN/A             ThreadContext *tc)
9961450SN/A{
9973114Sgblack@eecs.umich.edu    int index = 0;
998360SN/A    int dirfd = process->getSyscallArg(tc, index);
9996701Sgblack@eecs.umich.edu    if (dirfd != OS::TGT_AT_FDCWD)
10006701Sgblack@eecs.umich.edu        warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
10016701Sgblack@eecs.umich.edu
10026701Sgblack@eecs.umich.edu    return unlinkHelper(desc, callnum, process, tc, 1);
10036701Sgblack@eecs.umich.edu}
10046701Sgblack@eecs.umich.edu
10056701Sgblack@eecs.umich.edu/// Target facessat() handler
1006360SN/Atemplate <class OS>
10075877Shsul@eecs.umich.eduSyscallReturn
10082544SN/AfaccessatFunc(SyscallDesc *desc, int callnum, Process *process,
10092544SN/A              ThreadContext *tc)
10102544SN/A{
10112544SN/A    int index = 0;
10122544SN/A    int dirfd = process->getSyscallArg(tc, index);
10132544SN/A    if (dirfd != OS::TGT_AT_FDCWD)
1014360SN/A        warn("faccessat: first argument not AT_FDCWD; unlikely to work");
1015360SN/A    return accessFunc(desc, callnum, process, tc, 1);
10162544SN/A}
10172544SN/A
10182544SN/A/// Target readlinkat() handler
10192544SN/Atemplate <class OS>
10202544SN/ASyscallReturn
10212544SN/AreadlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
10226672Sgblack@eecs.umich.edu               ThreadContext *tc)
10236672Sgblack@eecs.umich.edu{
10246672Sgblack@eecs.umich.edu    int index = 0;
10256672Sgblack@eecs.umich.edu    int dirfd = process->getSyscallArg(tc, index);
10266672Sgblack@eecs.umich.edu    if (dirfd != OS::TGT_AT_FDCWD)
10276672Sgblack@eecs.umich.edu        warn("openat: first argument not AT_FDCWD; unlikely to work");
10286672Sgblack@eecs.umich.edu    return readlinkFunc(desc, callnum, process, tc, 1);
10292544SN/A}
10302544SN/A
10312553SN/A/// Target renameat() handler.
10321969SN/Atemplate <class OS>
10336701Sgblack@eecs.umich.eduSyscallReturn
1034360SN/ArenameatFunc(SyscallDesc *desc, int callnum, Process *process,
1035360SN/A             ThreadContext *tc)
10361458SN/A{
1037360SN/A    int index = 0;
1038360SN/A
1039378SN/A    int olddirfd = process->getSyscallArg(tc, index);
1040360SN/A    if (olddirfd != OS::TGT_AT_FDCWD)
10411450SN/A        warn("renameat: first argument not AT_FDCWD; unlikely to work");
10423114Sgblack@eecs.umich.edu
10432680Sktlim@umich.edu    std::string old_name;
1044360SN/A
10456701Sgblack@eecs.umich.edu    if (!tc->getMemProxy().tryReadString(old_name,
10466701Sgblack@eecs.umich.edu                                         process->getSyscallArg(tc, index)))
10476701Sgblack@eecs.umich.edu        return -EFAULT;
1048360SN/A
1049360SN/A    int newdirfd = process->getSyscallArg(tc, index);
10502064SN/A    if (newdirfd != OS::TGT_AT_FDCWD)
10515877Shsul@eecs.umich.edu        warn("renameat: third argument not AT_FDCWD; unlikely to work");
10522064SN/A
10532091SN/A    std::string new_name;
10542091SN/A
10552064SN/A    if (!tc->getMemProxy().tryReadString(new_name,
1056360SN/A                                         process->getSyscallArg(tc, index)))
10575877Shsul@eecs.umich.edu        return -EFAULT;
10585877Shsul@eecs.umich.edu
10595877Shsul@eecs.umich.edu    // Adjust path for cwd and redirection
10605877Shsul@eecs.umich.edu    old_name = process->checkPathRedirect(old_name);
10615877Shsul@eecs.umich.edu    new_name = process->checkPathRedirect(new_name);
10625877Shsul@eecs.umich.edu
10635877Shsul@eecs.umich.edu    int result = rename(old_name.c_str(), new_name.c_str());
10642064SN/A    return (result == -1) ? -errno : result;
10652064SN/A}
10662064SN/A
10672064SN/A/// Target sysinfo() handler.
10682064SN/Atemplate <class OS>
1069360SN/ASyscallReturn
1070360SN/AsysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
10712680Sktlim@umich.edu            ThreadContext *tc)
10721458SN/A{
1073360SN/A
1074360SN/A    int index = 0;
1075378SN/A    TypedBufferArg<typename OS::tgt_sysinfo>
1076360SN/A        sysinfo(process->getSyscallArg(tc, index));
10771450SN/A
10783114Sgblack@eecs.umich.edu    sysinfo->uptime = seconds_since_epoch;
10792680Sktlim@umich.edu    sysinfo->totalram = process->system->memSize();
1080360SN/A    sysinfo->mem_unit = 1;
10816701Sgblack@eecs.umich.edu
10826701Sgblack@eecs.umich.edu    sysinfo.copyOut(tc->getMemProxy());
1083360SN/A
1084360SN/A    return 0;
1085360SN/A}
10866109Ssanchezd@stanford.edu
10876109Ssanchezd@stanford.edu/// Target chmod() handler.
1088360SN/Atemplate <class OS>
10892680Sktlim@umich.eduSyscallReturn
1090360SN/AchmodFunc(SyscallDesc *desc, int callnum, Process *process,
10911458SN/A          ThreadContext *tc)
1092360SN/A{
1093360SN/A    std::string path;
1094360SN/A
10951999SN/A    int index = 0;
10961999SN/A    if (!tc->getMemProxy().tryReadString(path,
10971999SN/A                process->getSyscallArg(tc, index))) {
10983114Sgblack@eecs.umich.edu        return -EFAULT;
10992680Sktlim@umich.edu    }
11001999SN/A
11011999SN/A    uint32_t mode = process->getSyscallArg(tc, index);
11021999SN/A    mode_t hostMode = 0;
11036701Sgblack@eecs.umich.edu
11046701Sgblack@eecs.umich.edu    // XXX translate mode flags via OS::something???
11056701Sgblack@eecs.umich.edu    hostMode = mode;
11066701Sgblack@eecs.umich.edu
11076701Sgblack@eecs.umich.edu    // Adjust path for cwd and redirection
11081999SN/A    path = process->checkPathRedirect(path);
11096701Sgblack@eecs.umich.edu
11106701Sgblack@eecs.umich.edu    // do the chmod
11112680Sktlim@umich.edu    int result = chmod(path.c_str(), hostMode);
11121999SN/A    if (result < 0)
11131999SN/A        return -errno;
11141999SN/A
11151999SN/A    return 0;
11162091SN/A}
11172091SN/A
11181999SN/Atemplate <class OS>
11193669Sbinkertn@umich.eduSyscallReturn
11203669Sbinkertn@umich.edupollFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
11213669Sbinkertn@umich.edu{
11223669Sbinkertn@umich.edu    int index = 0;
11231999SN/A    Addr fdsPtr = p->getSyscallArg(tc, index);
11241999SN/A    int nfds = p->getSyscallArg(tc, index);
11251999SN/A    int tmout = p->getSyscallArg(tc, index);
11261999SN/A
11271999SN/A    BufferArg fdsBuf(fdsPtr, sizeof(struct pollfd) * nfds);
11281999SN/A    fdsBuf.copyIn(tc->getMemProxy());
11291999SN/A
1130378SN/A    /**
1131360SN/A     * Record the target file descriptors in a local variable. We need to
11321450SN/A     * replace them with host file descriptors but we need a temporary copy
11333114Sgblack@eecs.umich.edu     * for later. Afterwards, replace each target file descriptor in the
11342680Sktlim@umich.edu     * poll_fd array with its host_fd.
1135360SN/A     */
11366701Sgblack@eecs.umich.edu    int temp_tgt_fds[nfds];
11376701Sgblack@eecs.umich.edu    for (index = 0; index < nfds; index++) {
11386701Sgblack@eecs.umich.edu        temp_tgt_fds[index] = ((struct pollfd *)fdsBuf.bufferPtr())[index].fd;
1139360SN/A        auto tgt_fd = temp_tgt_fds[index];
11403670Sbinkertn@umich.edu        auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
11413670Sbinkertn@umich.edu        if (!hbfdp)
1142360SN/A            return -EBADF;
1143360SN/A        auto host_fd = hbfdp->getSimFD();
1144360SN/A        ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = host_fd;
1145360SN/A    }
1146360SN/A
1147360SN/A    /**
1148360SN/A     * We cannot allow an infinite poll to occur or it will inevitably cause
1149360SN/A     * a deadlock in the gem5 simulator with clone. We must pass in tmout with
1150360SN/A     * a non-negative value, however it also makes no sense to poll on the
1151360SN/A     * underlying host for any other time than tmout a zero timeout.
1152360SN/A     */
1153360SN/A    int status;
1154360SN/A    if (tmout < 0) {
1155360SN/A        status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1156360SN/A        if (status == 0) {
1157360SN/A            /**
1158360SN/A             * If blocking indefinitely, check the signal list to see if a
11593670Sbinkertn@umich.edu             * signal would break the poll out of the retry cycle and try
11603670Sbinkertn@umich.edu             * to return the signal interrupt instead.
11613670Sbinkertn@umich.edu             */
11623670Sbinkertn@umich.edu            System *sysh = tc->getSystemPtr();
11633670Sbinkertn@umich.edu            std::list<BasicSignal>::iterator it;
11643670Sbinkertn@umich.edu            for (it=sysh->signalList.begin(); it!=sysh->signalList.end(); it++)
11653670Sbinkertn@umich.edu                if (it->receiver == p)
11663670Sbinkertn@umich.edu                    return -EINTR;
11673670Sbinkertn@umich.edu            return SyscallReturn::retry();
11683670Sbinkertn@umich.edu        }
11693670Sbinkertn@umich.edu    } else
11703670Sbinkertn@umich.edu        status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
11713670Sbinkertn@umich.edu
11723670Sbinkertn@umich.edu    if (status == -1)
11733670Sbinkertn@umich.edu        return -errno;
11743670Sbinkertn@umich.edu
11753670Sbinkertn@umich.edu    /**
11763670Sbinkertn@umich.edu     * Replace each host_fd in the returned poll_fd array with its original
11772680Sktlim@umich.edu     * target file descriptor.
1178360SN/A     */
11791458SN/A    for (index = 0; index < nfds; index++) {
1180360SN/A        auto tgt_fd = temp_tgt_fds[index];
1181360SN/A        ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = tgt_fd;
11826683Stjones1@inf.ed.ac.uk    }
11836683Stjones1@inf.ed.ac.uk
11846683Stjones1@inf.ed.ac.uk    /**
11856683Stjones1@inf.ed.ac.uk     * Copy out the pollfd struct because the host may have updated fields
11866683Stjones1@inf.ed.ac.uk     * in the structure.
11876683Stjones1@inf.ed.ac.uk     */
11886701Sgblack@eecs.umich.edu    fdsBuf.copyOut(tc->getMemProxy());
11896701Sgblack@eecs.umich.edu
11906683Stjones1@inf.ed.ac.uk    return status;
11916683Stjones1@inf.ed.ac.uk}
11927064Snate@binkert.org
11936683Stjones1@inf.ed.ac.uk/// Target fchmod() handler.
11946683Stjones1@inf.ed.ac.uktemplate <class OS>
11956683Stjones1@inf.ed.ac.ukSyscallReturn
11966683Stjones1@inf.ed.ac.ukfchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
11976683Stjones1@inf.ed.ac.uk{
11986683Stjones1@inf.ed.ac.uk    int index = 0;
11996683Stjones1@inf.ed.ac.uk    int tgt_fd = p->getSyscallArg(tc, index);
12006683Stjones1@inf.ed.ac.uk    uint32_t mode = p->getSyscallArg(tc, index);
12016683Stjones1@inf.ed.ac.uk
12026683Stjones1@inf.ed.ac.uk    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
12036683Stjones1@inf.ed.ac.uk    if (!ffdp)
12046683Stjones1@inf.ed.ac.uk        return -EBADF;
12056683Stjones1@inf.ed.ac.uk    int sim_fd = ffdp->getSimFD();
12066683Stjones1@inf.ed.ac.uk
12072553SN/A    mode_t hostMode = mode;
12086684Stjones1@inf.ed.ac.uk
12096684Stjones1@inf.ed.ac.uk    int result = fchmod(sim_fd, hostMode);
12106684Stjones1@inf.ed.ac.uk
12116684Stjones1@inf.ed.ac.uk    return (result < 0) ? -errno : 0;
12126684Stjones1@inf.ed.ac.uk}
12136684Stjones1@inf.ed.ac.uk
12146684Stjones1@inf.ed.ac.uk/// Target mremap() handler.
12156684Stjones1@inf.ed.ac.uktemplate <class OS>
12166684Stjones1@inf.ed.ac.ukSyscallReturn
12176684Stjones1@inf.ed.ac.ukmremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
12186701Sgblack@eecs.umich.edu{
12196701Sgblack@eecs.umich.edu    int index = 0;
12206684Stjones1@inf.ed.ac.uk    Addr start = process->getSyscallArg(tc, index);
12216684Stjones1@inf.ed.ac.uk    uint64_t old_length = process->getSyscallArg(tc, index);
12226684Stjones1@inf.ed.ac.uk    uint64_t new_length = process->getSyscallArg(tc, index);
12236684Stjones1@inf.ed.ac.uk    uint64_t flags = process->getSyscallArg(tc, index);
12246684Stjones1@inf.ed.ac.uk    uint64_t provided_address = 0;
12256684Stjones1@inf.ed.ac.uk    bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
12266684Stjones1@inf.ed.ac.uk
12276684Stjones1@inf.ed.ac.uk    if (use_provided_address)
12282553SN/A        provided_address = process->getSyscallArg(tc, index);
12292553SN/A
12301354SN/A    if ((start % TheISA::PageBytes != 0) ||
1231        (provided_address % TheISA::PageBytes != 0)) {
1232        warn("mremap failing: arguments not page aligned");
1233        return -EINVAL;
1234    }
1235
1236    new_length = roundUp(new_length, TheISA::PageBytes);
1237
1238    if (new_length > old_length) {
1239        std::shared_ptr<MemState> mem_state = process->memState;
1240        Addr mmap_end = mem_state->getMmapEnd();
1241
1242        if ((start + old_length) == mmap_end &&
1243            (!use_provided_address || provided_address == start)) {
1244            // This case cannot occur when growing downward, as
1245            // start is greater than or equal to mmap_end.
1246            uint64_t diff = new_length - old_length;
1247            process->allocateMem(mmap_end, diff);
1248            mem_state->setMmapEnd(mmap_end + diff);
1249            return start;
1250        } else {
1251            if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
1252                warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
1253                return -ENOMEM;
1254            } else {
1255                uint64_t new_start = provided_address;
1256                if (!use_provided_address) {
1257                    new_start = process->mmapGrowsDown() ?
1258                                mmap_end - new_length : mmap_end;
1259                    mmap_end = process->mmapGrowsDown() ?
1260                               new_start : mmap_end + new_length;
1261                    mem_state->setMmapEnd(mmap_end);
1262                }
1263
1264                process->pTable->remap(start, old_length, new_start);
1265                warn("mremapping to new vaddr %08p-%08p, adding %d\n",
1266                     new_start, new_start + new_length,
1267                     new_length - old_length);
1268                // add on the remaining unallocated pages
1269                process->allocateMem(new_start + old_length,
1270                                     new_length - old_length,
1271                                     use_provided_address /* clobber */);
1272                if (use_provided_address &&
1273                    ((new_start + new_length > mem_state->getMmapEnd() &&
1274                      !process->mmapGrowsDown()) ||
1275                    (new_start < mem_state->getMmapEnd() &&
1276                      process->mmapGrowsDown()))) {
1277                    // something fishy going on here, at least notify the user
1278                    // @todo: increase mmap_end?
1279                    warn("mmap region limit exceeded with MREMAP_FIXED\n");
1280                }
1281                warn("returning %08p as start\n", new_start);
1282                return new_start;
1283            }
1284        }
1285    } else {
1286        if (use_provided_address && provided_address != start)
1287            process->pTable->remap(start, new_length, provided_address);
1288        process->pTable->unmap(start + new_length, old_length - new_length);
1289        return use_provided_address ? provided_address : start;
1290    }
1291}
1292
1293/// Target stat() handler.
1294template <class OS>
1295SyscallReturn
1296statFunc(SyscallDesc *desc, int callnum, Process *process,
1297         ThreadContext *tc)
1298{
1299    std::string path;
1300
1301    int index = 0;
1302    if (!tc->getMemProxy().tryReadString(path,
1303                process->getSyscallArg(tc, index))) {
1304        return -EFAULT;
1305    }
1306    Addr bufPtr = process->getSyscallArg(tc, index);
1307
1308    // Adjust path for cwd and redirection
1309    path = process->checkPathRedirect(path);
1310
1311    struct stat hostBuf;
1312    int result = stat(path.c_str(), &hostBuf);
1313
1314    if (result < 0)
1315        return -errno;
1316
1317    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1318
1319    return 0;
1320}
1321
1322
1323/// Target stat64() handler.
1324template <class OS>
1325SyscallReturn
1326stat64Func(SyscallDesc *desc, int callnum, Process *process,
1327           ThreadContext *tc)
1328{
1329    std::string path;
1330
1331    int index = 0;
1332    if (!tc->getMemProxy().tryReadString(path,
1333                process->getSyscallArg(tc, index)))
1334        return -EFAULT;
1335    Addr bufPtr = process->getSyscallArg(tc, index);
1336
1337    // Adjust path for cwd and redirection
1338    path = process->checkPathRedirect(path);
1339
1340#if NO_STAT64
1341    struct stat  hostBuf;
1342    int result = stat(path.c_str(), &hostBuf);
1343#else
1344    struct stat64 hostBuf;
1345    int result = stat64(path.c_str(), &hostBuf);
1346#endif
1347
1348    if (result < 0)
1349        return -errno;
1350
1351    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1352
1353    return 0;
1354}
1355
1356
1357/// Target fstatat64() handler.
1358template <class OS>
1359SyscallReturn
1360fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
1361              ThreadContext *tc)
1362{
1363    int index = 0;
1364    int dirfd = process->getSyscallArg(tc, index);
1365    if (dirfd != OS::TGT_AT_FDCWD)
1366        warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1367
1368    std::string path;
1369    if (!tc->getMemProxy().tryReadString(path,
1370                process->getSyscallArg(tc, index)))
1371        return -EFAULT;
1372    Addr bufPtr = process->getSyscallArg(tc, index);
1373
1374    // Adjust path for cwd and redirection
1375    path = process->checkPathRedirect(path);
1376
1377#if NO_STAT64
1378    struct stat  hostBuf;
1379    int result = stat(path.c_str(), &hostBuf);
1380#else
1381    struct stat64 hostBuf;
1382    int result = stat64(path.c_str(), &hostBuf);
1383#endif
1384
1385    if (result < 0)
1386        return -errno;
1387
1388    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1389
1390    return 0;
1391}
1392
1393
1394/// Target fstat64() handler.
1395template <class OS>
1396SyscallReturn
1397fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1398{
1399    int index = 0;
1400    int tgt_fd = p->getSyscallArg(tc, index);
1401    Addr bufPtr = p->getSyscallArg(tc, index);
1402
1403    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1404    if (!ffdp)
1405        return -EBADF;
1406    int sim_fd = ffdp->getSimFD();
1407
1408#if NO_STAT64
1409    struct stat  hostBuf;
1410    int result = fstat(sim_fd, &hostBuf);
1411#else
1412    struct stat64  hostBuf;
1413    int result = fstat64(sim_fd, &hostBuf);
1414#endif
1415
1416    if (result < 0)
1417        return -errno;
1418
1419    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1420
1421    return 0;
1422}
1423
1424
1425/// Target lstat() handler.
1426template <class OS>
1427SyscallReturn
1428lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1429          ThreadContext *tc)
1430{
1431    std::string path;
1432
1433    int index = 0;
1434    if (!tc->getMemProxy().tryReadString(path,
1435                process->getSyscallArg(tc, index))) {
1436        return -EFAULT;
1437    }
1438    Addr bufPtr = process->getSyscallArg(tc, index);
1439
1440    // Adjust path for cwd and redirection
1441    path = process->checkPathRedirect(path);
1442
1443    struct stat hostBuf;
1444    int result = lstat(path.c_str(), &hostBuf);
1445
1446    if (result < 0)
1447        return -errno;
1448
1449    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1450
1451    return 0;
1452}
1453
1454/// Target lstat64() handler.
1455template <class OS>
1456SyscallReturn
1457lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1458            ThreadContext *tc)
1459{
1460    std::string path;
1461
1462    int index = 0;
1463    if (!tc->getMemProxy().tryReadString(path,
1464                process->getSyscallArg(tc, index))) {
1465        return -EFAULT;
1466    }
1467    Addr bufPtr = process->getSyscallArg(tc, index);
1468
1469    // Adjust path for cwd and redirection
1470    path = process->checkPathRedirect(path);
1471
1472#if NO_STAT64
1473    struct stat hostBuf;
1474    int result = lstat(path.c_str(), &hostBuf);
1475#else
1476    struct stat64 hostBuf;
1477    int result = lstat64(path.c_str(), &hostBuf);
1478#endif
1479
1480    if (result < 0)
1481        return -errno;
1482
1483    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1484
1485    return 0;
1486}
1487
1488/// Target fstat() handler.
1489template <class OS>
1490SyscallReturn
1491fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1492{
1493    int index = 0;
1494    int tgt_fd = p->getSyscallArg(tc, index);
1495    Addr bufPtr = p->getSyscallArg(tc, index);
1496
1497    DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1498
1499    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1500    if (!ffdp)
1501        return -EBADF;
1502    int sim_fd = ffdp->getSimFD();
1503
1504    struct stat hostBuf;
1505    int result = fstat(sim_fd, &hostBuf);
1506
1507    if (result < 0)
1508        return -errno;
1509
1510    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1511
1512    return 0;
1513}
1514
1515/// Target statfs() handler.
1516template <class OS>
1517SyscallReturn
1518statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1519           ThreadContext *tc)
1520{
1521#if defined(__linux__)
1522    std::string path;
1523
1524    int index = 0;
1525    if (!tc->getMemProxy().tryReadString(path,
1526                process->getSyscallArg(tc, index))) {
1527        return -EFAULT;
1528    }
1529    Addr bufPtr = process->getSyscallArg(tc, index);
1530
1531    // Adjust path for cwd and redirection
1532    path = process->checkPathRedirect(path);
1533
1534    struct statfs hostBuf;
1535    int result = statfs(path.c_str(), &hostBuf);
1536
1537    if (result < 0)
1538        return -errno;
1539
1540    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1541    return 0;
1542#else
1543    warnUnsupportedOS("statfs");
1544    return -1;
1545#endif
1546}
1547
1548template <class OS>
1549SyscallReturn
1550cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1551{
1552    int index = 0;
1553
1554    RegVal flags = p->getSyscallArg(tc, index);
1555    RegVal newStack = p->getSyscallArg(tc, index);
1556    Addr ptidPtr = p->getSyscallArg(tc, index);
1557
1558#if THE_ISA == RISCV_ISA or THE_ISA == ARM_ISA
1559    /**
1560     * Linux sets CLONE_BACKWARDS flag for RISC-V and Arm.
1561     * The flag defines the list of clone() arguments in the following
1562     * order: flags -> newStack -> ptidPtr -> tlsPtr -> ctidPtr
1563     */
1564    Addr tlsPtr = p->getSyscallArg(tc, index);
1565    Addr ctidPtr = p->getSyscallArg(tc, index);
1566#else
1567    Addr ctidPtr = p->getSyscallArg(tc, index);
1568    Addr tlsPtr = p->getSyscallArg(tc, index);
1569#endif
1570
1571    if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1572        ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1573        ((flags & OS::TGT_CLONE_FS)     &&  (flags & OS::TGT_CLONE_NEWNS)) ||
1574        ((flags & OS::TGT_CLONE_NEWIPC) &&  (flags & OS::TGT_CLONE_SYSVSEM)) ||
1575        ((flags & OS::TGT_CLONE_NEWPID) &&  (flags & OS::TGT_CLONE_THREAD)) ||
1576        ((flags & OS::TGT_CLONE_VM)     && !(newStack)))
1577        return -EINVAL;
1578
1579    ThreadContext *ctc;
1580    if (!(ctc = p->findFreeContext())) {
1581        DPRINTF_SYSCALL(Verbose, "clone: no spare thread context in system"
1582                        "[cpu %d, thread %d]", tc->cpuId(), tc->threadId());
1583        return -EAGAIN;
1584    }
1585
1586    /**
1587     * Note that ProcessParams is generated by swig and there are no other
1588     * examples of how to create anything but this default constructor. The
1589     * fields are manually initialized instead of passing parameters to the
1590     * constructor.
1591     */
1592    ProcessParams *pp = new ProcessParams();
1593    pp->executable.assign(*(new std::string(p->progName())));
1594    pp->cmd.push_back(*(new std::string(p->progName())));
1595    pp->system = p->system;
1596    pp->cwd.assign(p->tgtCwd);
1597    pp->input.assign("stdin");
1598    pp->output.assign("stdout");
1599    pp->errout.assign("stderr");
1600    pp->uid = p->uid();
1601    pp->euid = p->euid();
1602    pp->gid = p->gid();
1603    pp->egid = p->egid();
1604
1605    /* Find the first free PID that's less than the maximum */
1606    std::set<int> const& pids = p->system->PIDs;
1607    int temp_pid = *pids.begin();
1608    do {
1609        temp_pid++;
1610    } while (pids.find(temp_pid) != pids.end());
1611    if (temp_pid >= System::maxPID)
1612        fatal("temp_pid is too large: %d", temp_pid);
1613
1614    pp->pid = temp_pid;
1615    pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1616    pp->useArchPT = p->useArchPT;
1617    pp->kvmInSE = p->kvmInSE;
1618    Process *cp = pp->create();
1619    delete pp;
1620
1621    Process *owner = ctc->getProcessPtr();
1622    ctc->setProcessPtr(cp);
1623    cp->assignThreadContext(ctc->contextId());
1624    owner->revokeThreadContext(ctc->contextId());
1625
1626    if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1627        BufferArg ptidBuf(ptidPtr, sizeof(long));
1628        long *ptid = (long *)ptidBuf.bufferPtr();
1629        *ptid = cp->pid();
1630        ptidBuf.copyOut(tc->getMemProxy());
1631    }
1632
1633    if (flags & OS::TGT_CLONE_THREAD) {
1634        cp->pTable->shared = true;
1635        cp->useForClone = true;
1636    }
1637    cp->initState();
1638    p->clone(tc, ctc, cp, flags);
1639
1640    if (flags & OS::TGT_CLONE_THREAD) {
1641        delete cp->sigchld;
1642        cp->sigchld = p->sigchld;
1643    } else if (flags & OS::TGT_SIGCHLD) {
1644        *cp->sigchld = true;
1645    }
1646
1647    if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1648        BufferArg ctidBuf(ctidPtr, sizeof(long));
1649        long *ctid = (long *)ctidBuf.bufferPtr();
1650        *ctid = cp->pid();
1651        ctidBuf.copyOut(ctc->getMemProxy());
1652    }
1653
1654    if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1655        cp->childClearTID = (uint64_t)ctidPtr;
1656
1657    ctc->clearArchRegs();
1658
1659    OS::archClone(flags, p, cp, tc, ctc, newStack, tlsPtr);
1660
1661    cp->setSyscallReturn(ctc, 0);
1662
1663#if THE_ISA == ALPHA_ISA
1664    ctc->setIntReg(TheISA::SyscallSuccessReg, 0);
1665#elif THE_ISA == SPARC_ISA
1666    tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1667    ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1668#endif
1669
1670    if (p->kvmInSE) {
1671#if THE_ISA == X86_ISA
1672        ctc->pcState(tc->readIntReg(TheISA::INTREG_RCX));
1673#else
1674        panic("KVM CPU model is not supported for this ISA");
1675#endif
1676    } else {
1677        TheISA::PCState cpc = tc->pcState();
1678        cpc.advance();
1679        ctc->pcState(cpc);
1680    }
1681    ctc->activate();
1682
1683    return cp->pid();
1684}
1685
1686/// Target fstatfs() handler.
1687template <class OS>
1688SyscallReturn
1689fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1690{
1691    int index = 0;
1692    int tgt_fd = p->getSyscallArg(tc, index);
1693    Addr bufPtr = p->getSyscallArg(tc, index);
1694
1695    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1696    if (!ffdp)
1697        return -EBADF;
1698    int sim_fd = ffdp->getSimFD();
1699
1700    struct statfs hostBuf;
1701    int result = fstatfs(sim_fd, &hostBuf);
1702
1703    if (result < 0)
1704        return -errno;
1705
1706    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1707
1708    return 0;
1709}
1710
1711/// Target readv() handler.
1712template <class OS>
1713SyscallReturn
1714readvFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1715{
1716    int index = 0;
1717    int tgt_fd = p->getSyscallArg(tc, index);
1718
1719    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1720    if (!ffdp)
1721        return -EBADF;
1722    int sim_fd = ffdp->getSimFD();
1723
1724    SETranslatingPortProxy &prox = tc->getMemProxy();
1725    uint64_t tiov_base = p->getSyscallArg(tc, index);
1726    size_t count = p->getSyscallArg(tc, index);
1727    typename OS::tgt_iovec tiov[count];
1728    struct iovec hiov[count];
1729    for (size_t i = 0; i < count; ++i) {
1730        prox.readBlob(tiov_base + (i * sizeof(typename OS::tgt_iovec)),
1731                      (uint8_t*)&tiov[i], sizeof(typename OS::tgt_iovec));
1732        hiov[i].iov_len = TheISA::gtoh(tiov[i].iov_len);
1733        hiov[i].iov_base = new char [hiov[i].iov_len];
1734    }
1735
1736    int result = readv(sim_fd, hiov, count);
1737    int local_errno = errno;
1738
1739    for (size_t i = 0; i < count; ++i) {
1740        if (result != -1) {
1741            prox.writeBlob(TheISA::htog(tiov[i].iov_base),
1742                           (uint8_t*)hiov[i].iov_base, hiov[i].iov_len);
1743        }
1744        delete [] (char *)hiov[i].iov_base;
1745    }
1746
1747    return (result == -1) ? -local_errno : result;
1748}
1749
1750/// Target writev() handler.
1751template <class OS>
1752SyscallReturn
1753writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1754{
1755    int index = 0;
1756    int tgt_fd = p->getSyscallArg(tc, index);
1757
1758    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1759    if (!hbfdp)
1760        return -EBADF;
1761    int sim_fd = hbfdp->getSimFD();
1762
1763    SETranslatingPortProxy &prox = tc->getMemProxy();
1764    uint64_t tiov_base = p->getSyscallArg(tc, index);
1765    size_t count = p->getSyscallArg(tc, index);
1766    struct iovec hiov[count];
1767    for (size_t i = 0; i < count; ++i) {
1768        typename OS::tgt_iovec tiov;
1769
1770        prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1771                      (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1772        hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1773        hiov[i].iov_base = new char [hiov[i].iov_len];
1774        prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1775                      hiov[i].iov_len);
1776    }
1777
1778    int result = writev(sim_fd, hiov, count);
1779
1780    for (size_t i = 0; i < count; ++i)
1781        delete [] (char *)hiov[i].iov_base;
1782
1783    return (result == -1) ? -errno : result;
1784}
1785
1786/// Real mmap handler.
1787template <class OS>
1788SyscallReturn
1789mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1790         bool is_mmap2)
1791{
1792    int index = 0;
1793    Addr start = p->getSyscallArg(tc, index);
1794    uint64_t length = p->getSyscallArg(tc, index);
1795    int prot = p->getSyscallArg(tc, index);
1796    int tgt_flags = p->getSyscallArg(tc, index);
1797    int tgt_fd = p->getSyscallArg(tc, index);
1798    int offset = p->getSyscallArg(tc, index);
1799
1800    if (is_mmap2)
1801        offset *= TheISA::PageBytes;
1802
1803    if (start & (TheISA::PageBytes - 1) ||
1804        offset & (TheISA::PageBytes - 1) ||
1805        (tgt_flags & OS::TGT_MAP_PRIVATE &&
1806         tgt_flags & OS::TGT_MAP_SHARED) ||
1807        (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1808         !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1809        !length) {
1810        return -EINVAL;
1811    }
1812
1813    if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1814        // With shared mmaps, there are two cases to consider:
1815        // 1) anonymous: writes should modify the mapping and this should be
1816        // visible to observers who share the mapping. Currently, it's
1817        // difficult to update the shared mapping because there's no
1818        // structure which maintains information about the which virtual
1819        // memory areas are shared. If that structure existed, it would be
1820        // possible to make the translations point to the same frames.
1821        // 2) file-backed: writes should modify the mapping and the file
1822        // which is backed by the mapping. The shared mapping problem is the
1823        // same as what was mentioned about the anonymous mappings. For
1824        // file-backed mappings, the writes to the file are difficult
1825        // because it requires syncing what the mapping holds with the file
1826        // that resides on the host system. So, any write on a real system
1827        // would cause the change to be propagated to the file mapping at
1828        // some point in the future (the inode is tracked along with the
1829        // mapping). This isn't guaranteed to always happen, but it usually
1830        // works well enough. The guarantee is provided by the msync system
1831        // call. We could force the change through with shared mappings with
1832        // a call to msync, but that again would require more information
1833        // than we currently maintain.
1834        warn("mmap: writing to shared mmap region is currently "
1835             "unsupported. The write succeeds on the target, but it "
1836             "will not be propagated to the host or shared mappings");
1837    }
1838
1839    length = roundUp(length, TheISA::PageBytes);
1840
1841    int sim_fd = -1;
1842    uint8_t *pmap = nullptr;
1843    if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1844        std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1845
1846        auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1847        if (dfdp) {
1848            EmulatedDriver *emul_driver = dfdp->getDriver();
1849            return emul_driver->mmap(p, tc, start, length, prot,
1850                                     tgt_flags, tgt_fd, offset);
1851        }
1852
1853        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1854        if (!ffdp)
1855            return -EBADF;
1856        sim_fd = ffdp->getSimFD();
1857
1858        pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1859                                    sim_fd, offset);
1860
1861        if (pmap == (decltype(pmap))-1) {
1862            warn("mmap: failed to map file into host address space");
1863            return -errno;
1864        }
1865    }
1866
1867    // Extend global mmap region if necessary. Note that we ignore the
1868    // start address unless MAP_FIXED is specified.
1869    if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1870        std::shared_ptr<MemState> mem_state = p->memState;
1871        Addr mmap_end = mem_state->getMmapEnd();
1872
1873        start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1874        mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1875
1876        mem_state->setMmapEnd(mmap_end);
1877    }
1878
1879    DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1880                    start, start + length - 1);
1881
1882    // We only allow mappings to overwrite existing mappings if
1883    // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1884    // because we ignore the start hint if TGT_MAP_FIXED is not set.
1885    int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1886    if (clobber) {
1887        for (auto tc : p->system->threadContexts) {
1888            // If we might be overwriting old mappings, we need to
1889            // invalidate potentially stale mappings out of the TLBs.
1890            tc->getDTBPtr()->flushAll();
1891            tc->getITBPtr()->flushAll();
1892        }
1893    }
1894
1895    // Allocate physical memory and map it in. If the page table is already
1896    // mapped and clobber is not set, the simulator will issue throw a
1897    // fatal and bail out of the simulation.
1898    p->allocateMem(start, length, clobber);
1899
1900    // Transfer content into target address space.
1901    SETranslatingPortProxy &tp = tc->getMemProxy();
1902    if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1903        // In general, we should zero the mapped area for anonymous mappings,
1904        // with something like:
1905        //     tp.memsetBlob(start, 0, length);
1906        // However, given that we don't support sparse mappings, and
1907        // some applications can map a couple of gigabytes of space
1908        // (intending sparse usage), that can get painfully expensive.
1909        // Fortunately, since we don't properly implement munmap either,
1910        // there's no danger of remapping used memory, so for now all
1911        // newly mapped memory should already be zeroed so we can skip it.
1912    } else {
1913        // It is possible to mmap an area larger than a file, however
1914        // accessing unmapped portions the system triggers a "Bus error"
1915        // on the host. We must know when to stop copying the file from
1916        // the host into the target address space.
1917        struct stat file_stat;
1918        if (fstat(sim_fd, &file_stat) > 0)
1919            fatal("mmap: cannot stat file");
1920
1921        // Copy the portion of the file that is resident. This requires
1922        // checking both the mmap size and the filesize that we are
1923        // trying to mmap into this space; the mmap size also depends
1924        // on the specified offset into the file.
1925        uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1926                                 length);
1927        tp.writeBlob(start, pmap, size);
1928
1929        // Cleanup the mmap region before exiting this function.
1930        munmap(pmap, length);
1931
1932        // Maintain the symbol table for dynamic executables.
1933        // The loader will call mmap to map the images into its address
1934        // space and we intercept that here. We can verify that we are
1935        // executing inside the loader by checking the program counter value.
1936        // XXX: with multiprogrammed workloads or multi-node configurations,
1937        // this will not work since there is a single global symbol table.
1938        ObjectFile *interpreter = p->getInterpreter();
1939        if (interpreter) {
1940            Addr text_start = interpreter->textBase();
1941            Addr text_end = text_start + interpreter->textSize();
1942
1943            Addr pc = tc->pcState().pc();
1944
1945            if (pc >= text_start && pc < text_end) {
1946                std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1947                auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1948                ObjectFile *lib = createObjectFile(ffdp->getFileName());
1949
1950                if (lib) {
1951                    lib->loadAllSymbols(debugSymbolTable,
1952                                        lib->textBase(), start);
1953                }
1954            }
1955        }
1956
1957        // Note that we do not zero out the remainder of the mapping. This
1958        // is done by a real system, but it probably will not affect
1959        // execution (hopefully).
1960    }
1961
1962    return start;
1963}
1964
1965template <class OS>
1966SyscallReturn
1967pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1968{
1969    int index = 0;
1970    int tgt_fd = p->getSyscallArg(tc, index);
1971    Addr bufPtr = p->getSyscallArg(tc, index);
1972    int nbytes = p->getSyscallArg(tc, index);
1973    int offset = p->getSyscallArg(tc, index);
1974
1975    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1976    if (!ffdp)
1977        return -EBADF;
1978    int sim_fd = ffdp->getSimFD();
1979
1980    BufferArg bufArg(bufPtr, nbytes);
1981    bufArg.copyIn(tc->getMemProxy());
1982
1983    int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1984
1985    return (bytes_written == -1) ? -errno : bytes_written;
1986}
1987
1988/// Target mmap() handler.
1989template <class OS>
1990SyscallReturn
1991mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1992{
1993    return mmapImpl<OS>(desc, num, p, tc, false);
1994}
1995
1996/// Target mmap2() handler.
1997template <class OS>
1998SyscallReturn
1999mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2000{
2001    return mmapImpl<OS>(desc, num, p, tc, true);
2002}
2003
2004/// Target getrlimit() handler.
2005template <class OS>
2006SyscallReturn
2007getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
2008              ThreadContext *tc)
2009{
2010    int index = 0;
2011    unsigned resource = process->getSyscallArg(tc, index);
2012    TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
2013
2014    switch (resource) {
2015      case OS::TGT_RLIMIT_STACK:
2016        // max stack size in bytes: make up a number (8MB for now)
2017        rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
2018        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
2019        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
2020        break;
2021
2022      case OS::TGT_RLIMIT_DATA:
2023        // max data segment size in bytes: make up a number
2024        rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
2025        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
2026        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
2027        break;
2028
2029      default:
2030        warn("getrlimit: unimplemented resource %d", resource);
2031        return -EINVAL;
2032        break;
2033    }
2034
2035    rlp.copyOut(tc->getMemProxy());
2036    return 0;
2037}
2038
2039template <class OS>
2040SyscallReturn
2041prlimitFunc(SyscallDesc *desc, int callnum, Process *process,
2042            ThreadContext *tc)
2043{
2044    int index = 0;
2045    if (process->getSyscallArg(tc, index) != 0)
2046    {
2047        warn("prlimit: ignoring rlimits for nonzero pid");
2048        return -EPERM;
2049    }
2050    int resource = process->getSyscallArg(tc, index);
2051    Addr n = process->getSyscallArg(tc, index);
2052    if (n != 0)
2053        warn("prlimit: ignoring new rlimit");
2054    Addr o = process->getSyscallArg(tc, index);
2055    if (o != 0)
2056    {
2057        TypedBufferArg<typename OS::rlimit> rlp(o);
2058        switch (resource) {
2059          case OS::TGT_RLIMIT_STACK:
2060            // max stack size in bytes: make up a number (8MB for now)
2061            rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
2062            rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
2063            rlp->rlim_max = TheISA::htog(rlp->rlim_max);
2064            break;
2065          case OS::TGT_RLIMIT_DATA:
2066            // max data segment size in bytes: make up a number
2067            rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
2068            rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
2069            rlp->rlim_max = TheISA::htog(rlp->rlim_max);
2070            break;
2071          default:
2072            warn("prlimit: unimplemented resource %d", resource);
2073            return -EINVAL;
2074            break;
2075        }
2076        rlp.copyOut(tc->getMemProxy());
2077    }
2078    return 0;
2079}
2080
2081/// Target clock_gettime() function.
2082template <class OS>
2083SyscallReturn
2084clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2085{
2086    int index = 1;
2087    //int clk_id = p->getSyscallArg(tc, index);
2088    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
2089
2090    getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
2091    tp->tv_sec += seconds_since_epoch;
2092    tp->tv_sec = TheISA::htog(tp->tv_sec);
2093    tp->tv_nsec = TheISA::htog(tp->tv_nsec);
2094
2095    tp.copyOut(tc->getMemProxy());
2096
2097    return 0;
2098}
2099
2100/// Target clock_getres() function.
2101template <class OS>
2102SyscallReturn
2103clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2104{
2105    int index = 1;
2106    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
2107
2108    // Set resolution at ns, which is what clock_gettime() returns
2109    tp->tv_sec = 0;
2110    tp->tv_nsec = 1;
2111
2112    tp.copyOut(tc->getMemProxy());
2113
2114    return 0;
2115}
2116
2117/// Target gettimeofday() handler.
2118template <class OS>
2119SyscallReturn
2120gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
2121                 ThreadContext *tc)
2122{
2123    int index = 0;
2124    TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
2125
2126    getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
2127    tp->tv_sec += seconds_since_epoch;
2128    tp->tv_sec = TheISA::htog(tp->tv_sec);
2129    tp->tv_usec = TheISA::htog(tp->tv_usec);
2130
2131    tp.copyOut(tc->getMemProxy());
2132
2133    return 0;
2134}
2135
2136
2137/// Target utimes() handler.
2138template <class OS>
2139SyscallReturn
2140utimesFunc(SyscallDesc *desc, int callnum, Process *process,
2141           ThreadContext *tc)
2142{
2143    std::string path;
2144
2145    int index = 0;
2146    if (!tc->getMemProxy().tryReadString(path,
2147                process->getSyscallArg(tc, index))) {
2148        return -EFAULT;
2149    }
2150
2151    TypedBufferArg<typename OS::timeval [2]>
2152        tp(process->getSyscallArg(tc, index));
2153    tp.copyIn(tc->getMemProxy());
2154
2155    struct timeval hostTimeval[2];
2156    for (int i = 0; i < 2; ++i) {
2157        hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
2158        hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
2159    }
2160
2161    // Adjust path for cwd and redirection
2162    path = process->checkPathRedirect(path);
2163
2164    int result = utimes(path.c_str(), hostTimeval);
2165
2166    if (result < 0)
2167        return -errno;
2168
2169    return 0;
2170}
2171
2172template <class OS>
2173SyscallReturn
2174execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
2175{
2176    desc->setFlags(0);
2177
2178    int index = 0;
2179    std::string path;
2180    SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
2181    if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
2182        return -EFAULT;
2183
2184    if (access(path.c_str(), F_OK) == -1)
2185        return -EACCES;
2186
2187    auto read_in = [](std::vector<std::string> & vect,
2188                      SETranslatingPortProxy & mem_proxy,
2189                      Addr mem_loc)
2190    {
2191        for (int inc = 0; ; inc++) {
2192            BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
2193            b.copyIn(mem_proxy);
2194
2195            if (!*(Addr*)b.bufferPtr())
2196                break;
2197
2198            vect.push_back(std::string());
2199            mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
2200        }
2201    };
2202
2203    /**
2204     * Note that ProcessParams is generated by swig and there are no other
2205     * examples of how to create anything but this default constructor. The
2206     * fields are manually initialized instead of passing parameters to the
2207     * constructor.
2208     */
2209    ProcessParams *pp = new ProcessParams();
2210    pp->executable = path;
2211    Addr argv_mem_loc = p->getSyscallArg(tc, index);
2212    read_in(pp->cmd, mem_proxy, argv_mem_loc);
2213    Addr envp_mem_loc = p->getSyscallArg(tc, index);
2214    read_in(pp->env, mem_proxy, envp_mem_loc);
2215    pp->uid = p->uid();
2216    pp->egid = p->egid();
2217    pp->euid = p->euid();
2218    pp->gid = p->gid();
2219    pp->ppid = p->ppid();
2220    pp->pid = p->pid();
2221    pp->input.assign("cin");
2222    pp->output.assign("cout");
2223    pp->errout.assign("cerr");
2224    pp->cwd.assign(p->tgtCwd);
2225    pp->system = p->system;
2226    /**
2227     * Prevent process object creation with identical PIDs (which will trip
2228     * a fatal check in Process constructor). The execve call is supposed to
2229     * take over the currently executing process' identity but replace
2230     * whatever it is doing with a new process image. Instead of hijacking
2231     * the process object in the simulator, we create a new process object
2232     * and bind to the previous process' thread below (hijacking the thread).
2233     */
2234    p->system->PIDs.erase(p->pid());
2235    Process *new_p = pp->create();
2236    delete pp;
2237
2238    /**
2239     * Work through the file descriptor array and close any files marked
2240     * close-on-exec.
2241     */
2242    new_p->fds = p->fds;
2243    for (int i = 0; i < new_p->fds->getSize(); i++) {
2244        std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
2245        if (fdep && fdep->getCOE())
2246            new_p->fds->closeFDEntry(i);
2247    }
2248
2249    *new_p->sigchld = true;
2250
2251    delete p;
2252    tc->clearArchRegs();
2253    tc->setProcessPtr(new_p);
2254    new_p->assignThreadContext(tc->contextId());
2255    new_p->initState();
2256    tc->activate();
2257    TheISA::PCState pcState = tc->pcState();
2258    tc->setNPC(pcState.instAddr());
2259
2260    desc->setFlags(SyscallDesc::SuppressReturnValue);
2261    return 0;
2262}
2263
2264/// Target getrusage() function.
2265template <class OS>
2266SyscallReturn
2267getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
2268              ThreadContext *tc)
2269{
2270    int index = 0;
2271    int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
2272    TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
2273
2274    rup->ru_utime.tv_sec = 0;
2275    rup->ru_utime.tv_usec = 0;
2276    rup->ru_stime.tv_sec = 0;
2277    rup->ru_stime.tv_usec = 0;
2278    rup->ru_maxrss = 0;
2279    rup->ru_ixrss = 0;
2280    rup->ru_idrss = 0;
2281    rup->ru_isrss = 0;
2282    rup->ru_minflt = 0;
2283    rup->ru_majflt = 0;
2284    rup->ru_nswap = 0;
2285    rup->ru_inblock = 0;
2286    rup->ru_oublock = 0;
2287    rup->ru_msgsnd = 0;
2288    rup->ru_msgrcv = 0;
2289    rup->ru_nsignals = 0;
2290    rup->ru_nvcsw = 0;
2291    rup->ru_nivcsw = 0;
2292
2293    switch (who) {
2294      case OS::TGT_RUSAGE_SELF:
2295        getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
2296        rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
2297        rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
2298        break;
2299
2300      case OS::TGT_RUSAGE_CHILDREN:
2301        // do nothing.  We have no child processes, so they take no time.
2302        break;
2303
2304      default:
2305        // don't really handle THREAD or CHILDREN, but just warn and
2306        // plow ahead
2307        warn("getrusage() only supports RUSAGE_SELF.  Parameter %d ignored.",
2308             who);
2309    }
2310
2311    rup.copyOut(tc->getMemProxy());
2312
2313    return 0;
2314}
2315
2316/// Target times() function.
2317template <class OS>
2318SyscallReturn
2319timesFunc(SyscallDesc *desc, int callnum, Process *process,
2320          ThreadContext *tc)
2321{
2322    int index = 0;
2323    TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
2324
2325    // Fill in the time structure (in clocks)
2326    int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
2327    bufp->tms_utime = clocks;
2328    bufp->tms_stime = 0;
2329    bufp->tms_cutime = 0;
2330    bufp->tms_cstime = 0;
2331
2332    // Convert to host endianness
2333    bufp->tms_utime = TheISA::htog(bufp->tms_utime);
2334
2335    // Write back
2336    bufp.copyOut(tc->getMemProxy());
2337
2338    // Return clock ticks since system boot
2339    return clocks;
2340}
2341
2342/// Target time() function.
2343template <class OS>
2344SyscallReturn
2345timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
2346{
2347    typename OS::time_t sec, usec;
2348    getElapsedTimeMicro(sec, usec);
2349    sec += seconds_since_epoch;
2350
2351    int index = 0;
2352    Addr taddr = (Addr)process->getSyscallArg(tc, index);
2353    if (taddr != 0) {
2354        typename OS::time_t t = sec;
2355        t = TheISA::htog(t);
2356        SETranslatingPortProxy &p = tc->getMemProxy();
2357        p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
2358    }
2359    return sec;
2360}
2361
2362template <class OS>
2363SyscallReturn
2364tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
2365{
2366    int index = 0;
2367    int tgid = process->getSyscallArg(tc, index);
2368    int tid = process->getSyscallArg(tc, index);
2369    int sig = process->getSyscallArg(tc, index);
2370
2371    /**
2372     * This system call is intended to allow killing a specific thread
2373     * within an arbitrary thread group if sanctioned with permission checks.
2374     * It's usually true that threads share the termination signal as pointed
2375     * out by the pthread_kill man page and this seems to be the intended
2376     * usage. Due to this being an emulated environment, assume the following:
2377     * Threads are allowed to call tgkill because the EUID for all threads
2378     * should be the same. There is no signal handling mechanism for kernel
2379     * registration of signal handlers since signals are poorly supported in
2380     * emulation mode. Since signal handlers cannot be registered, all
2381     * threads within in a thread group must share the termination signal.
2382     * We never exhaust PIDs so there's no chance of finding the wrong one
2383     * due to PID rollover.
2384     */
2385
2386    System *sys = tc->getSystemPtr();
2387    Process *tgt_proc = nullptr;
2388    for (int i = 0; i < sys->numContexts(); i++) {
2389        Process *temp = sys->threadContexts[i]->getProcessPtr();
2390        if (temp->pid() == tid) {
2391            tgt_proc = temp;
2392            break;
2393        }
2394    }
2395
2396    if (sig != 0 || sig != OS::TGT_SIGABRT)
2397        return -EINVAL;
2398
2399    if (tgt_proc == nullptr)
2400        return -ESRCH;
2401
2402    if (tgid != -1 && tgt_proc->tgid() != tgid)
2403        return -ESRCH;
2404
2405    if (sig == OS::TGT_SIGABRT)
2406        exitGroupFunc(desc, 252, process, tc);
2407
2408    return 0;
2409}
2410
2411template <class OS>
2412SyscallReturn
2413socketFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2414{
2415    int index = 0;
2416    int domain = p->getSyscallArg(tc, index);
2417    int type = p->getSyscallArg(tc, index);
2418    int prot = p->getSyscallArg(tc, index);
2419
2420    int sim_fd = socket(domain, type, prot);
2421    if (sim_fd == -1)
2422        return -errno;
2423
2424    auto sfdp = std::make_shared<SocketFDEntry>(sim_fd, domain, type, prot);
2425    int tgt_fd = p->fds->allocFD(sfdp);
2426
2427    return tgt_fd;
2428}
2429
2430template <class OS>
2431SyscallReturn
2432socketpairFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2433{
2434    int index = 0;
2435    int domain = p->getSyscallArg(tc, index);
2436    int type = p->getSyscallArg(tc, index);
2437    int prot = p->getSyscallArg(tc, index);
2438    Addr svPtr = p->getSyscallArg(tc, index);
2439
2440    BufferArg svBuf((Addr)svPtr, 2 * sizeof(int));
2441    int status = socketpair(domain, type, prot, (int *)svBuf.bufferPtr());
2442    if (status == -1)
2443        return -errno;
2444
2445    int *fds = (int *)svBuf.bufferPtr();
2446
2447    auto sfdp1 = std::make_shared<SocketFDEntry>(fds[0], domain, type, prot);
2448    fds[0] = p->fds->allocFD(sfdp1);
2449    auto sfdp2 = std::make_shared<SocketFDEntry>(fds[1], domain, type, prot);
2450    fds[1] = p->fds->allocFD(sfdp2);
2451    svBuf.copyOut(tc->getMemProxy());
2452
2453    return status;
2454}
2455
2456template <class OS>
2457SyscallReturn
2458selectFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
2459{
2460    int retval;
2461
2462    int index = 0;
2463    int nfds_t = p->getSyscallArg(tc, index);
2464    Addr fds_read_ptr = p->getSyscallArg(tc, index);
2465    Addr fds_writ_ptr = p->getSyscallArg(tc, index);
2466    Addr fds_excp_ptr = p->getSyscallArg(tc, index);
2467    Addr time_val_ptr = p->getSyscallArg(tc, index);
2468
2469    TypedBufferArg<typename OS::fd_set> rd_t(fds_read_ptr);
2470    TypedBufferArg<typename OS::fd_set> wr_t(fds_writ_ptr);
2471    TypedBufferArg<typename OS::fd_set> ex_t(fds_excp_ptr);
2472    TypedBufferArg<typename OS::timeval> tp(time_val_ptr);
2473
2474    /**
2475     * Host fields. Notice that these use the definitions from the system
2476     * headers instead of the gem5 headers and libraries. If the host and
2477     * target have different header file definitions, this will not work.
2478     */
2479    fd_set rd_h;
2480    FD_ZERO(&rd_h);
2481    fd_set wr_h;
2482    FD_ZERO(&wr_h);
2483    fd_set ex_h;
2484    FD_ZERO(&ex_h);
2485
2486    /**
2487     * Copy in the fd_set from the target.
2488     */
2489    if (fds_read_ptr)
2490        rd_t.copyIn(tc->getMemProxy());
2491    if (fds_writ_ptr)
2492        wr_t.copyIn(tc->getMemProxy());
2493    if (fds_excp_ptr)
2494        ex_t.copyIn(tc->getMemProxy());
2495
2496    /**
2497     * We need to translate the target file descriptor set into a host file
2498     * descriptor set. This involves both our internal process fd array
2499     * and the fd_set defined in Linux header files. The nfds field also
2500     * needs to be updated as it will be only target specific after
2501     * retrieving it from the target; the nfds value is expected to be the
2502     * highest file descriptor that needs to be checked, so we need to extend
2503     * it out for nfds_h when we do the update.
2504     */
2505    int nfds_h = 0;
2506    std::map<int, int> trans_map;
2507    auto try_add_host_set = [&](fd_set *tgt_set_entry,
2508                                fd_set *hst_set_entry,
2509                                int iter) -> bool
2510    {
2511        /**
2512         * By this point, we know that we are looking at a valid file
2513         * descriptor set on the target. We need to check if the target file
2514         * descriptor value passed in as iter is part of the set.
2515         */
2516        if (FD_ISSET(iter, tgt_set_entry)) {
2517            /**
2518             * We know that the target file descriptor belongs to the set,
2519             * but we do not yet know if the file descriptor is valid or
2520             * that we have a host mapping. Check that now.
2521             */
2522            auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[iter]);
2523            if (!hbfdp)
2524                return true;
2525            auto sim_fd = hbfdp->getSimFD();
2526
2527            /**
2528             * Add the sim_fd to tgt_fd translation into trans_map for use
2529             * later when we need to zero the target fd_set structures and
2530             * then update them with hits returned from the host select call.
2531             */
2532            trans_map[sim_fd] = iter;
2533
2534            /**
2535             * We know that the host file descriptor exists so now we check
2536             * if we need to update the max count for nfds_h before passing
2537             * the duplicated structure into the host.
2538             */
2539            nfds_h = std::max(nfds_h - 1, sim_fd + 1);
2540
2541            /**
2542             * Add the host file descriptor to the set that we are going to
2543             * pass into the host.
2544             */
2545            FD_SET(sim_fd, hst_set_entry);
2546        }
2547        return false;
2548    };
2549
2550    for (int i = 0; i < nfds_t; i++) {
2551        if (fds_read_ptr) {
2552            bool ebadf = try_add_host_set((fd_set*)&*rd_t, &rd_h, i);
2553            if (ebadf) return -EBADF;
2554        }
2555        if (fds_writ_ptr) {
2556            bool ebadf = try_add_host_set((fd_set*)&*wr_t, &wr_h, i);
2557            if (ebadf) return -EBADF;
2558        }
2559        if (fds_excp_ptr) {
2560            bool ebadf = try_add_host_set((fd_set*)&*ex_t, &ex_h, i);
2561            if (ebadf) return -EBADF;
2562        }
2563    }
2564
2565    if (time_val_ptr) {
2566        /**
2567         * It might be possible to decrement the timeval based on some
2568         * derivation of wall clock determined from elapsed simulator ticks
2569         * but that seems like overkill. Rather, we just set the timeval with
2570         * zero timeout. (There is no reason to block during the simulation
2571         * as it only decreases simulator performance.)
2572         */
2573        tp->tv_sec = 0;
2574        tp->tv_usec = 0;
2575
2576        retval = select(nfds_h,
2577                        fds_read_ptr ? &rd_h : nullptr,
2578                        fds_writ_ptr ? &wr_h : nullptr,
2579                        fds_excp_ptr ? &ex_h : nullptr,
2580                        (timeval*)&*tp);
2581    } else {
2582        /**
2583         * If the timeval pointer is null, setup a new timeval structure to
2584         * pass into the host select call. Unfortunately, we will need to
2585         * manually check the return value and throw a retry fault if the
2586         * return value is zero. Allowing the system call to block will
2587         * likely deadlock the event queue.
2588         */
2589        struct timeval tv = { 0, 0 };
2590
2591        retval = select(nfds_h,
2592                        fds_read_ptr ? &rd_h : nullptr,
2593                        fds_writ_ptr ? &wr_h : nullptr,
2594                        fds_excp_ptr ? &ex_h : nullptr,
2595                        &tv);
2596
2597        if (retval == 0) {
2598            /**
2599             * If blocking indefinitely, check the signal list to see if a
2600             * signal would break the poll out of the retry cycle and try to
2601             * return the signal interrupt instead.
2602             */
2603            for (auto sig : tc->getSystemPtr()->signalList)
2604                if (sig.receiver == p)
2605                    return -EINTR;
2606            return SyscallReturn::retry();
2607        }
2608    }
2609
2610    if (retval == -1)
2611        return -errno;
2612
2613    FD_ZERO((fd_set*)&*rd_t);
2614    FD_ZERO((fd_set*)&*wr_t);
2615    FD_ZERO((fd_set*)&*ex_t);
2616
2617    /**
2618     * We need to translate the host file descriptor set into a target file
2619     * descriptor set. This involves both our internal process fd array
2620     * and the fd_set defined in header files.
2621     */
2622    for (int i = 0; i < nfds_h; i++) {
2623        if (fds_read_ptr) {
2624            if (FD_ISSET(i, &rd_h))
2625                FD_SET(trans_map[i], (fd_set*)&*rd_t);
2626        }
2627
2628        if (fds_writ_ptr) {
2629            if (FD_ISSET(i, &wr_h))
2630                FD_SET(trans_map[i], (fd_set*)&*wr_t);
2631        }
2632
2633        if (fds_excp_ptr) {
2634            if (FD_ISSET(i, &ex_h))
2635                FD_SET(trans_map[i], (fd_set*)&*ex_t);
2636        }
2637    }
2638
2639    if (fds_read_ptr)
2640        rd_t.copyOut(tc->getMemProxy());
2641    if (fds_writ_ptr)
2642        wr_t.copyOut(tc->getMemProxy());
2643    if (fds_excp_ptr)
2644        ex_t.copyOut(tc->getMemProxy());
2645    if (time_val_ptr)
2646        tp.copyOut(tc->getMemProxy());
2647
2648    return retval;
2649}
2650
2651template <class OS>
2652SyscallReturn
2653readFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2654{
2655    int index = 0;
2656    int tgt_fd = p->getSyscallArg(tc, index);
2657    Addr buf_ptr = p->getSyscallArg(tc, index);
2658    int nbytes = p->getSyscallArg(tc, index);
2659
2660    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2661    if (!hbfdp)
2662        return -EBADF;
2663    int sim_fd = hbfdp->getSimFD();
2664
2665    struct pollfd pfd;
2666    pfd.fd = sim_fd;
2667    pfd.events = POLLIN | POLLPRI;
2668    if ((poll(&pfd, 1, 0) == 0)
2669        && !(hbfdp->getFlags() & OS::TGT_O_NONBLOCK))
2670        return SyscallReturn::retry();
2671
2672    BufferArg buf_arg(buf_ptr, nbytes);
2673    int bytes_read = read(sim_fd, buf_arg.bufferPtr(), nbytes);
2674
2675    if (bytes_read > 0)
2676        buf_arg.copyOut(tc->getMemProxy());
2677
2678    return (bytes_read == -1) ? -errno : bytes_read;
2679}
2680
2681template <class OS>
2682SyscallReturn
2683writeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2684{
2685    int index = 0;
2686    int tgt_fd = p->getSyscallArg(tc, index);
2687    Addr buf_ptr = p->getSyscallArg(tc, index);
2688    int nbytes = p->getSyscallArg(tc, index);
2689
2690    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2691    if (!hbfdp)
2692        return -EBADF;
2693    int sim_fd = hbfdp->getSimFD();
2694
2695    BufferArg buf_arg(buf_ptr, nbytes);
2696    buf_arg.copyIn(tc->getMemProxy());
2697
2698    struct pollfd pfd;
2699    pfd.fd = sim_fd;
2700    pfd.events = POLLOUT;
2701
2702    /**
2703     * We don't want to poll on /dev/random. The kernel will not enable the
2704     * file descriptor for writing unless the entropy in the system falls
2705     * below write_wakeup_threshold. This is not guaranteed to happen
2706     * depending on host settings.
2707     */
2708    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(hbfdp);
2709    if (ffdp && (ffdp->getFileName() != "/dev/random")) {
2710        if (!poll(&pfd, 1, 0) && !(ffdp->getFlags() & OS::TGT_O_NONBLOCK))
2711            return SyscallReturn::retry();
2712    }
2713
2714    int bytes_written = write(sim_fd, buf_arg.bufferPtr(), nbytes);
2715
2716    if (bytes_written != -1)
2717        fsync(sim_fd);
2718
2719    return (bytes_written == -1) ? -errno : bytes_written;
2720}
2721
2722template <class OS>
2723SyscallReturn
2724wait4Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2725{
2726    int index = 0;
2727    pid_t pid = p->getSyscallArg(tc, index);
2728    Addr statPtr = p->getSyscallArg(tc, index);
2729    int options = p->getSyscallArg(tc, index);
2730    Addr rusagePtr = p->getSyscallArg(tc, index);
2731
2732    if (rusagePtr)
2733        DPRINTF_SYSCALL(Verbose, "wait4: rusage pointer provided %lx, however "
2734                 "functionality not supported. Ignoring rusage pointer.\n",
2735                 rusagePtr);
2736
2737    /**
2738     * Currently, wait4 is only implemented so that it will wait for children
2739     * exit conditions which are denoted by a SIGCHLD signals posted into the
2740     * system signal list. We return no additional information via any of the
2741     * parameters supplied to wait4. If nothing is found in the system signal
2742     * list, we will wait indefinitely for SIGCHLD to post by retrying the
2743     * call.
2744     */
2745    System *sysh = tc->getSystemPtr();
2746    std::list<BasicSignal>::iterator iter;
2747    for (iter=sysh->signalList.begin(); iter!=sysh->signalList.end(); iter++) {
2748        if (iter->receiver == p) {
2749            if (pid < -1) {
2750                if ((iter->sender->pgid() == -pid)
2751                    && (iter->signalValue == OS::TGT_SIGCHLD))
2752                    goto success;
2753            } else if (pid == -1) {
2754                if (iter->signalValue == OS::TGT_SIGCHLD)
2755                    goto success;
2756            } else if (pid == 0) {
2757                if ((iter->sender->pgid() == p->pgid())
2758                    && (iter->signalValue == OS::TGT_SIGCHLD))
2759                    goto success;
2760            } else {
2761                if ((iter->sender->pid() == pid)
2762                    && (iter->signalValue == OS::TGT_SIGCHLD))
2763                    goto success;
2764            }
2765        }
2766    }
2767
2768    return (options & OS::TGT_WNOHANG) ? 0 : SyscallReturn::retry();
2769
2770success:
2771    // Set status to EXITED for WIFEXITED evaluations.
2772    const int EXITED = 0;
2773    BufferArg statusBuf(statPtr, sizeof(int));
2774    *(int *)statusBuf.bufferPtr() = EXITED;
2775    statusBuf.copyOut(tc->getMemProxy());
2776
2777    // Return the child PID.
2778    pid_t retval = iter->sender->pid();
2779    sysh->signalList.erase(iter);
2780    return retval;
2781}
2782
2783template <class OS>
2784SyscallReturn
2785acceptFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2786{
2787    struct sockaddr sa;
2788    socklen_t addrLen;
2789    int host_fd;
2790    int index = 0;
2791    int tgt_fd = p->getSyscallArg(tc, index);
2792    Addr addrPtr = p->getSyscallArg(tc, index);
2793    Addr lenPtr = p->getSyscallArg(tc, index);
2794
2795    BufferArg *lenBufPtr = nullptr;
2796    BufferArg *addrBufPtr = nullptr;
2797
2798    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
2799    if (!sfdp)
2800        return -EBADF;
2801    int sim_fd = sfdp->getSimFD();
2802
2803    /**
2804     * We poll the socket file descriptor first to guarantee that we do not
2805     * block on our accept call. The socket can be opened without the
2806     * non-blocking flag (it blocks). This will cause deadlocks between
2807     * communicating processes.
2808     */
2809    struct pollfd pfd;
2810    pfd.fd = sim_fd;
2811    pfd.events = POLLIN | POLLPRI;
2812    if ((poll(&pfd, 1, 0) == 0)
2813        && !(sfdp->getFlags() & OS::TGT_O_NONBLOCK))
2814        return SyscallReturn::retry();
2815
2816    if (lenPtr) {
2817        lenBufPtr = new BufferArg(lenPtr, sizeof(socklen_t));
2818        lenBufPtr->copyIn(tc->getMemProxy());
2819        memcpy(&addrLen, (socklen_t *)lenBufPtr->bufferPtr(),
2820               sizeof(socklen_t));
2821    }
2822
2823    if (addrPtr) {
2824        addrBufPtr = new BufferArg(addrPtr, sizeof(struct sockaddr));
2825        addrBufPtr->copyIn(tc->getMemProxy());
2826        memcpy(&sa, (struct sockaddr *)addrBufPtr->bufferPtr(),
2827               sizeof(struct sockaddr));
2828    }
2829
2830    host_fd = accept(sim_fd, &sa, &addrLen);
2831
2832    if (host_fd == -1)
2833        return -errno;
2834
2835    if (addrPtr) {
2836        memcpy(addrBufPtr->bufferPtr(), &sa, sizeof(sa));
2837        addrBufPtr->copyOut(tc->getMemProxy());
2838        delete(addrBufPtr);
2839    }
2840
2841    if (lenPtr) {
2842        *(socklen_t *)lenBufPtr->bufferPtr() = addrLen;
2843        lenBufPtr->copyOut(tc->getMemProxy());
2844        delete(lenBufPtr);
2845    }
2846
2847    auto afdp = std::make_shared<SocketFDEntry>(host_fd, sfdp->_domain,
2848                                                sfdp->_type, sfdp->_protocol);
2849    return p->fds->allocFD(afdp);
2850}
2851
2852/// Target eventfd() function.
2853template <class OS>
2854SyscallReturn
2855eventfdFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2856{
2857#if defined(__linux__)
2858    int index = 0;
2859    unsigned initval = p->getSyscallArg(tc, index);
2860    int in_flags = p->getSyscallArg(tc, index);
2861
2862    int sim_fd = eventfd(initval, in_flags);
2863    if (sim_fd == -1)
2864        return -errno;
2865
2866    bool cloexec = in_flags & OS::TGT_O_CLOEXEC;
2867
2868    int flags = cloexec ? OS::TGT_O_CLOEXEC : 0;
2869    flags |= (in_flags & OS::TGT_O_NONBLOCK) ? OS::TGT_O_NONBLOCK : 0;
2870
2871    auto hbfdp = std::make_shared<HBFDEntry>(flags, sim_fd, cloexec);
2872    int tgt_fd = p->fds->allocFD(hbfdp);
2873    return tgt_fd;
2874#else
2875    warnUnsupportedOS("eventfd");
2876    return -1;
2877#endif
2878}
2879
2880#endif // __SIM_SYSCALL_EMUL_HH__
2881