syscall_emul.hh revision 13649
1/*
2 * Copyright (c) 2012-2013, 2015 ARM Limited
3 * Copyright (c) 2015 Advanced Micro Devices, Inc.
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder.  You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2003-2005 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Steve Reinhardt
42 *          Kevin Lim
43 */
44
45#ifndef __SIM_SYSCALL_EMUL_HH__
46#define __SIM_SYSCALL_EMUL_HH__
47
48#if (defined(__APPLE__) || defined(__OpenBSD__) ||      \
49     defined(__FreeBSD__) || defined(__CYGWIN__) ||     \
50     defined(__NetBSD__))
51#define NO_STAT64 1
52#else
53#define NO_STAT64 0
54#endif
55
56#if (defined(__APPLE__) || defined(__OpenBSD__) ||      \
57     defined(__FreeBSD__) || defined(__NetBSD__))
58#define NO_STATFS 1
59#else
60#define NO_STATFS 0
61#endif
62
63#if (defined(__APPLE__) || defined(__OpenBSD__) ||      \
64     defined(__FreeBSD__) || defined(__NetBSD__))
65#define NO_FALLOCATE 1
66#else
67#define NO_FALLOCATE 0
68#endif
69
70///
71/// @file syscall_emul.hh
72///
73/// This file defines objects used to emulate syscalls from the target
74/// application on the host machine.
75
76#ifdef __CYGWIN32__
77#include <sys/fcntl.h>
78
79#endif
80#include <fcntl.h>
81#include <poll.h>
82#include <sys/mman.h>
83#include <sys/socket.h>
84#include <sys/stat.h>
85#if (NO_STATFS == 0)
86#include <sys/statfs.h>
87#else
88#include <sys/mount.h>
89#endif
90#include <sys/time.h>
91#include <sys/types.h>
92#include <sys/uio.h>
93#include <unistd.h>
94
95#include <cerrno>
96#include <memory>
97#include <string>
98
99#include "arch/generic/tlb.hh"
100#include "arch/utility.hh"
101#include "base/intmath.hh"
102#include "base/loader/object_file.hh"
103#include "base/logging.hh"
104#include "base/trace.hh"
105#include "base/types.hh"
106#include "config/the_isa.hh"
107#include "cpu/base.hh"
108#include "cpu/thread_context.hh"
109#include "mem/page_table.hh"
110#include "params/Process.hh"
111#include "sim/emul_driver.hh"
112#include "sim/futex_map.hh"
113#include "sim/process.hh"
114#include "sim/syscall_debug_macros.hh"
115#include "sim/syscall_desc.hh"
116#include "sim/syscall_emul_buf.hh"
117#include "sim/syscall_return.hh"
118
119#if defined(__APPLE__) && defined(__MACH__) && !defined(CMSG_ALIGN)
120#define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & ~(sizeof(size_t) - 1))
121#endif
122
123//////////////////////////////////////////////////////////////////////
124//
125// The following emulation functions are generic enough that they
126// don't need to be recompiled for different emulated OS's.  They are
127// defined in sim/syscall_emul.cc.
128//
129//////////////////////////////////////////////////////////////////////
130
131
132/// Handler for unimplemented syscalls that we haven't thought about.
133SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
134                                Process *p, ThreadContext *tc);
135
136/// Handler for unimplemented syscalls that we never intend to
137/// implement (signal handling, etc.) and should not affect the correct
138/// behavior of the program.  Print a warning only if the appropriate
139/// trace flag is enabled.  Return success to the target program.
140SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
141                         Process *p, ThreadContext *tc);
142
143// Target fallocateFunc() handler.
144SyscallReturn fallocateFunc(SyscallDesc *desc, int num,
145                            Process *p, ThreadContext *tc);
146
147/// Target exit() handler: terminate current context.
148SyscallReturn exitFunc(SyscallDesc *desc, int num,
149                       Process *p, ThreadContext *tc);
150
151/// Target exit_group() handler: terminate simulation. (exit all threads)
152SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
153                       Process *p, ThreadContext *tc);
154
155/// Target set_tid_address() handler.
156SyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
157                                Process *p, ThreadContext *tc);
158
159/// Target getpagesize() handler.
160SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
161                              Process *p, ThreadContext *tc);
162
163/// Target brk() handler: set brk address.
164SyscallReturn brkFunc(SyscallDesc *desc, int num,
165                      Process *p, ThreadContext *tc);
166
167/// Target close() handler.
168SyscallReturn closeFunc(SyscallDesc *desc, int num,
169                        Process *p, ThreadContext *tc);
170
171/// Target lseek() handler.
172SyscallReturn lseekFunc(SyscallDesc *desc, int num,
173                        Process *p, ThreadContext *tc);
174
175/// Target _llseek() handler.
176SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
177                          Process *p, ThreadContext *tc);
178
179/// Target munmap() handler.
180SyscallReturn munmapFunc(SyscallDesc *desc, int num,
181                         Process *p, ThreadContext *tc);
182
183/// Target shutdown() handler.
184SyscallReturn shutdownFunc(SyscallDesc *desc, int num,
185                           Process *p, ThreadContext *tc);
186
187/// Target gethostname() handler.
188SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
189                              Process *p, ThreadContext *tc);
190
191/// Target getcwd() handler.
192SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
193                         Process *p, ThreadContext *tc);
194
195/// Target readlink() handler.
196SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
197                           Process *p, ThreadContext *tc,
198                           int index = 0);
199SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
200                           Process *p, ThreadContext *tc);
201
202/// Target unlink() handler.
203SyscallReturn unlinkHelper(SyscallDesc *desc, int num,
204                           Process *p, ThreadContext *tc,
205                           int index);
206SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
207                         Process *p, ThreadContext *tc);
208
209/// Target link() handler
210SyscallReturn linkFunc(SyscallDesc *desc, int num, Process *p,
211                       ThreadContext *tc);
212
213/// Target symlink() handler.
214SyscallReturn symlinkFunc(SyscallDesc *desc, int num, Process *p,
215                          ThreadContext *tc);
216
217/// Target mkdir() handler.
218SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
219                        Process *p, ThreadContext *tc);
220
221/// Target mknod() handler.
222SyscallReturn mknodFunc(SyscallDesc *desc, int num,
223                        Process *p, ThreadContext *tc);
224
225/// Target chdir() handler.
226SyscallReturn chdirFunc(SyscallDesc *desc, int num,
227                        Process *p, ThreadContext *tc);
228
229// Target rmdir() handler.
230SyscallReturn rmdirFunc(SyscallDesc *desc, int num,
231                        Process *p, ThreadContext *tc);
232
233/// Target rename() handler.
234SyscallReturn renameFunc(SyscallDesc *desc, int num,
235                         Process *p, ThreadContext *tc);
236
237
238/// Target truncate() handler.
239SyscallReturn truncateFunc(SyscallDesc *desc, int num,
240                           Process *p, ThreadContext *tc);
241
242
243/// Target ftruncate() handler.
244SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
245                            Process *p, ThreadContext *tc);
246
247
248/// Target truncate64() handler.
249SyscallReturn truncate64Func(SyscallDesc *desc, int num,
250                             Process *p, ThreadContext *tc);
251
252/// Target ftruncate64() handler.
253SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
254                              Process *p, ThreadContext *tc);
255
256
257/// Target umask() handler.
258SyscallReturn umaskFunc(SyscallDesc *desc, int num,
259                        Process *p, ThreadContext *tc);
260
261/// Target gettid() handler.
262SyscallReturn gettidFunc(SyscallDesc *desc, int num,
263                         Process *p, ThreadContext *tc);
264
265/// Target chown() handler.
266SyscallReturn chownFunc(SyscallDesc *desc, int num,
267                        Process *p, ThreadContext *tc);
268
269/// Target setpgid() handler.
270SyscallReturn setpgidFunc(SyscallDesc *desc, int num,
271                          Process *p, ThreadContext *tc);
272
273/// Target fchown() handler.
274SyscallReturn fchownFunc(SyscallDesc *desc, int num,
275                         Process *p, ThreadContext *tc);
276
277/// Target dup() handler.
278SyscallReturn dupFunc(SyscallDesc *desc, int num,
279                      Process *process, ThreadContext *tc);
280
281/// Target dup2() handler.
282SyscallReturn dup2Func(SyscallDesc *desc, int num,
283                       Process *process, ThreadContext *tc);
284
285/// Target fcntl() handler.
286SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
287                        Process *process, ThreadContext *tc);
288
289/// Target fcntl64() handler.
290SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
291                          Process *process, ThreadContext *tc);
292
293/// Target setuid() handler.
294SyscallReturn setuidFunc(SyscallDesc *desc, int num,
295                         Process *p, ThreadContext *tc);
296
297/// Target pipe() handler.
298SyscallReturn pipeFunc(SyscallDesc *desc, int num,
299                       Process *p, ThreadContext *tc);
300
301/// Internal pipe() handler.
302SyscallReturn pipeImpl(SyscallDesc *desc, int num, Process *p,
303                       ThreadContext *tc, bool pseudoPipe);
304
305/// Target getpid() handler.
306SyscallReturn getpidFunc(SyscallDesc *desc, int num,
307                         Process *p, ThreadContext *tc);
308
309// Target getpeername() handler.
310SyscallReturn getpeernameFunc(SyscallDesc *desc, int num,
311                              Process *p, ThreadContext *tc);
312
313// Target bind() handler.
314SyscallReturn bindFunc(SyscallDesc *desc, int num,
315                       Process *p, ThreadContext *tc);
316
317// Target listen() handler.
318SyscallReturn listenFunc(SyscallDesc *desc, int num,
319                         Process *p, ThreadContext *tc);
320
321// Target connect() handler.
322SyscallReturn connectFunc(SyscallDesc *desc, int num,
323                          Process *p, ThreadContext *tc);
324
325#if defined(SYS_getdents)
326// Target getdents() handler.
327SyscallReturn getdentsFunc(SyscallDesc *desc, int num,
328                           Process *p, ThreadContext *tc);
329#endif
330
331#if defined(SYS_getdents64)
332// Target getdents() handler.
333SyscallReturn getdents64Func(SyscallDesc *desc, int num,
334                           Process *p, ThreadContext *tc);
335#endif
336
337// Target sendto() handler.
338SyscallReturn sendtoFunc(SyscallDesc *desc, int num,
339                         Process *p, ThreadContext *tc);
340
341// Target recvfrom() handler.
342SyscallReturn recvfromFunc(SyscallDesc *desc, int num,
343                           Process *p, ThreadContext *tc);
344
345// Target recvmsg() handler.
346SyscallReturn recvmsgFunc(SyscallDesc *desc, int num,
347                          Process *p, ThreadContext *tc);
348
349// Target sendmsg() handler.
350SyscallReturn sendmsgFunc(SyscallDesc *desc, int num,
351                          Process *p, ThreadContext *tc);
352
353// Target getuid() handler.
354SyscallReturn getuidFunc(SyscallDesc *desc, int num,
355                         Process *p, ThreadContext *tc);
356
357/// Target getgid() handler.
358SyscallReturn getgidFunc(SyscallDesc *desc, int num,
359                         Process *p, ThreadContext *tc);
360
361/// Target getppid() handler.
362SyscallReturn getppidFunc(SyscallDesc *desc, int num,
363                          Process *p, ThreadContext *tc);
364
365/// Target geteuid() handler.
366SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
367                          Process *p, ThreadContext *tc);
368
369/// Target getegid() handler.
370SyscallReturn getegidFunc(SyscallDesc *desc, int num,
371                          Process *p, ThreadContext *tc);
372
373/// Target access() handler
374SyscallReturn accessFunc(SyscallDesc *desc, int num,
375                         Process *p, ThreadContext *tc);
376SyscallReturn accessFunc(SyscallDesc *desc, int num,
377                         Process *p, ThreadContext *tc,
378                         int index);
379
380// Target getsockopt() handler.
381SyscallReturn getsockoptFunc(SyscallDesc *desc, int num,
382                             Process *p, ThreadContext *tc);
383
384// Target setsockopt() handler.
385SyscallReturn setsockoptFunc(SyscallDesc *desc, int num,
386                             Process *p, ThreadContext *tc);
387
388// Target getsockname() handler.
389SyscallReturn getsocknameFunc(SyscallDesc *desc, int num,
390                              Process *p, ThreadContext *tc);
391
392/// Futex system call
393/// Implemented by Daniel Sanchez
394/// Used by printf's in multi-threaded apps
395template <class OS>
396SyscallReturn
397futexFunc(SyscallDesc *desc, int callnum, Process *process,
398          ThreadContext *tc)
399{
400    using namespace std;
401
402    int index = 0;
403    Addr uaddr = process->getSyscallArg(tc, index);
404    int op = process->getSyscallArg(tc, index);
405    int val = process->getSyscallArg(tc, index);
406    int timeout M5_VAR_USED = process->getSyscallArg(tc, index);
407    Addr uaddr2 M5_VAR_USED = process->getSyscallArg(tc, index);
408    int val3 = process->getSyscallArg(tc, index);
409
410    /*
411     * Unsupported option that does not affect the correctness of the
412     * application. This is a performance optimization utilized by Linux.
413     */
414    op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
415    op &= ~OS::TGT_FUTEX_CLOCK_REALTIME_FLAG;
416
417    FutexMap &futex_map = tc->getSystemPtr()->futexMap;
418
419    if (OS::TGT_FUTEX_WAIT == op || OS::TGT_FUTEX_WAIT_BITSET == op) {
420        // Ensure futex system call accessed atomically.
421        BufferArg buf(uaddr, sizeof(int));
422        buf.copyIn(tc->getMemProxy());
423        int mem_val = *(int*)buf.bufferPtr();
424
425        /*
426         * The value in memory at uaddr is not equal with the expected val
427         * (a different thread must have changed it before the system call was
428         * invoked). In this case, we need to throw an error.
429         */
430        if (val != mem_val)
431            return -OS::TGT_EWOULDBLOCK;
432
433        if (OS::TGT_FUTEX_WAIT) {
434            futex_map.suspend(uaddr, process->tgid(), tc);
435        } else {
436            futex_map.suspend_bitset(uaddr, process->tgid(), tc, val3);
437        }
438
439        return 0;
440    } else if (OS::TGT_FUTEX_WAKE == op) {
441        return futex_map.wakeup(uaddr, process->tgid(), val);
442    } else if (OS::TGT_FUTEX_WAKE_BITSET == op) {
443        return futex_map.wakeup_bitset(uaddr, process->tgid(), val3);
444    }
445
446    warn("futex: op %d not implemented; ignoring.", op);
447    return -ENOSYS;
448}
449
450
451/// Pseudo Funcs  - These functions use a different return convension,
452/// returning a second value in a register other than the normal return register
453SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
454                             Process *process, ThreadContext *tc);
455
456/// Target getpidPseudo() handler.
457SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
458                               Process *p, ThreadContext *tc);
459
460/// Target getuidPseudo() handler.
461SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
462                               Process *p, ThreadContext *tc);
463
464/// Target getgidPseudo() handler.
465SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
466                               Process *p, ThreadContext *tc);
467
468
469/// A readable name for 1,000,000, for converting microseconds to seconds.
470const int one_million = 1000000;
471/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
472const int one_billion = 1000000000;
473
474/// Approximate seconds since the epoch (1/1/1970).  About a billion,
475/// by my reckoning.  We want to keep this a constant (not use the
476/// real-world time) to keep simulations repeatable.
477const unsigned seconds_since_epoch = 1000000000;
478
479/// Helper function to convert current elapsed time to seconds and
480/// microseconds.
481template <class T1, class T2>
482void
483getElapsedTimeMicro(T1 &sec, T2 &usec)
484{
485    uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
486    sec = elapsed_usecs / one_million;
487    usec = elapsed_usecs % one_million;
488}
489
490/// Helper function to convert current elapsed time to seconds and
491/// nanoseconds.
492template <class T1, class T2>
493void
494getElapsedTimeNano(T1 &sec, T2 &nsec)
495{
496    uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
497    sec = elapsed_nsecs / one_billion;
498    nsec = elapsed_nsecs % one_billion;
499}
500
501//////////////////////////////////////////////////////////////////////
502//
503// The following emulation functions are generic, but need to be
504// templated to account for differences in types, constants, etc.
505//
506//////////////////////////////////////////////////////////////////////
507
508    typedef struct statfs hst_statfs;
509#if NO_STAT64
510    typedef struct stat hst_stat;
511    typedef struct stat hst_stat64;
512#else
513    typedef struct stat hst_stat;
514    typedef struct stat64 hst_stat64;
515#endif
516
517//// Helper function to convert a host stat buffer to a target stat
518//// buffer.  Also copies the target buffer out to the simulated
519//// memory space.  Used by stat(), fstat(), and lstat().
520
521template <typename target_stat, typename host_stat>
522void
523convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
524{
525    using namespace TheISA;
526
527    if (fakeTTY)
528        tgt->st_dev = 0xA;
529    else
530        tgt->st_dev = host->st_dev;
531    tgt->st_dev = TheISA::htog(tgt->st_dev);
532    tgt->st_ino = host->st_ino;
533    tgt->st_ino = TheISA::htog(tgt->st_ino);
534    tgt->st_mode = host->st_mode;
535    if (fakeTTY) {
536        // Claim to be a character device
537        tgt->st_mode &= ~S_IFMT;    // Clear S_IFMT
538        tgt->st_mode |= S_IFCHR;    // Set S_IFCHR
539    }
540    tgt->st_mode = TheISA::htog(tgt->st_mode);
541    tgt->st_nlink = host->st_nlink;
542    tgt->st_nlink = TheISA::htog(tgt->st_nlink);
543    tgt->st_uid = host->st_uid;
544    tgt->st_uid = TheISA::htog(tgt->st_uid);
545    tgt->st_gid = host->st_gid;
546    tgt->st_gid = TheISA::htog(tgt->st_gid);
547    if (fakeTTY)
548        tgt->st_rdev = 0x880d;
549    else
550        tgt->st_rdev = host->st_rdev;
551    tgt->st_rdev = TheISA::htog(tgt->st_rdev);
552    tgt->st_size = host->st_size;
553    tgt->st_size = TheISA::htog(tgt->st_size);
554    tgt->st_atimeX = host->st_atime;
555    tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
556    tgt->st_mtimeX = host->st_mtime;
557    tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
558    tgt->st_ctimeX = host->st_ctime;
559    tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
560    // Force the block size to be 8KB. This helps to ensure buffered io works
561    // consistently across different hosts.
562    tgt->st_blksize = 0x2000;
563    tgt->st_blksize = TheISA::htog(tgt->st_blksize);
564    tgt->st_blocks = host->st_blocks;
565    tgt->st_blocks = TheISA::htog(tgt->st_blocks);
566}
567
568// Same for stat64
569
570template <typename target_stat, typename host_stat64>
571void
572convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
573{
574    using namespace TheISA;
575
576    convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
577#if defined(STAT_HAVE_NSEC)
578    tgt->st_atime_nsec = host->st_atime_nsec;
579    tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
580    tgt->st_mtime_nsec = host->st_mtime_nsec;
581    tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
582    tgt->st_ctime_nsec = host->st_ctime_nsec;
583    tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
584#else
585    tgt->st_atime_nsec = 0;
586    tgt->st_mtime_nsec = 0;
587    tgt->st_ctime_nsec = 0;
588#endif
589}
590
591// Here are a couple of convenience functions
592template<class OS>
593void
594copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
595               hst_stat *host, bool fakeTTY = false)
596{
597    typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
598    tgt_stat_buf tgt(addr);
599    convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
600    tgt.copyOut(mem);
601}
602
603template<class OS>
604void
605copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
606                 hst_stat64 *host, bool fakeTTY = false)
607{
608    typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
609    tgt_stat_buf tgt(addr);
610    convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
611    tgt.copyOut(mem);
612}
613
614template <class OS>
615void
616copyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
617                 hst_statfs *host)
618{
619    TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
620
621    tgt->f_type = TheISA::htog(host->f_type);
622#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
623    tgt->f_bsize = TheISA::htog(host->f_iosize);
624#else
625    tgt->f_bsize = TheISA::htog(host->f_bsize);
626#endif
627    tgt->f_blocks = TheISA::htog(host->f_blocks);
628    tgt->f_bfree = TheISA::htog(host->f_bfree);
629    tgt->f_bavail = TheISA::htog(host->f_bavail);
630    tgt->f_files = TheISA::htog(host->f_files);
631    tgt->f_ffree = TheISA::htog(host->f_ffree);
632    memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
633#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
634    tgt->f_namelen = TheISA::htog(host->f_namemax);
635    tgt->f_frsize = TheISA::htog(host->f_bsize);
636#elif defined(__APPLE__)
637    tgt->f_namelen = 0;
638    tgt->f_frsize = 0;
639#else
640    tgt->f_namelen = TheISA::htog(host->f_namelen);
641    tgt->f_frsize = TheISA::htog(host->f_frsize);
642#endif
643#if defined(__linux__)
644    memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
645#else
646    /*
647     * The fields are different sizes per OS. Don't bother with
648     * f_spare or f_reserved on non-Linux for now.
649     */
650    memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
651#endif
652
653    tgt.copyOut(mem);
654}
655
656/// Target ioctl() handler.  For the most part, programs call ioctl()
657/// only to find out if their stdout is a tty, to determine whether to
658/// do line or block buffering.  We always claim that output fds are
659/// not TTYs to provide repeatable results.
660template <class OS>
661SyscallReturn
662ioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
663{
664    int index = 0;
665    int tgt_fd = p->getSyscallArg(tc, index);
666    unsigned req = p->getSyscallArg(tc, index);
667
668    DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
669
670    if (OS::isTtyReq(req))
671        return -ENOTTY;
672
673    auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
674    if (!dfdp)
675        return -EBADF;
676
677    /**
678     * If the driver is valid, issue the ioctl through it. Otherwise,
679     * there's an implicit assumption that the device is a TTY type and we
680     * return that we do not have a valid TTY.
681     */
682    EmulatedDriver *emul_driver = dfdp->getDriver();
683    if (emul_driver)
684        return emul_driver->ioctl(p, tc, req);
685
686    /**
687     * For lack of a better return code, return ENOTTY. Ideally, we should
688     * return something better here, but at least we issue the warning.
689     */
690    warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
691         tgt_fd, req, tc->pcState());
692    return -ENOTTY;
693}
694
695template <class OS>
696SyscallReturn
697openImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
698         bool isopenat)
699{
700    int index = 0;
701    int tgt_dirfd = -1;
702
703    /**
704     * If using the openat variant, read in the target directory file
705     * descriptor from the simulated process.
706     */
707    if (isopenat)
708        tgt_dirfd = p->getSyscallArg(tc, index);
709
710    /**
711     * Retrieve the simulated process' memory proxy and then read in the path
712     * string from that memory space into the host's working memory space.
713     */
714    std::string path;
715    if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
716        return -EFAULT;
717
718#ifdef __CYGWIN32__
719    int host_flags = O_BINARY;
720#else
721    int host_flags = 0;
722#endif
723    /**
724     * Translate target flags into host flags. Flags exist which are not
725     * ported between architectures which can cause check failures.
726     */
727    int tgt_flags = p->getSyscallArg(tc, index);
728    for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
729        if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
730            tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
731            host_flags |= OS::openFlagTable[i].hostFlag;
732        }
733    }
734    if (tgt_flags) {
735        warn("open%s: cannot decode flags 0x%x",
736             isopenat ? "at" : "", tgt_flags);
737    }
738#ifdef __CYGWIN32__
739    host_flags |= O_BINARY;
740#endif
741
742    int mode = p->getSyscallArg(tc, index);
743
744    /**
745     * If the simulated process called open or openat with AT_FDCWD specified,
746     * take the current working directory value which was passed into the
747     * process class as a Python parameter and append the current path to
748     * create a full path.
749     * Otherwise, openat with a valid target directory file descriptor has
750     * been called. If the path option, which was passed in as a parameter,
751     * is not absolute, retrieve the directory file descriptor's path and
752     * prepend it to the path passed in as a parameter.
753     * In every case, we should have a full path (which is relevant to the
754     * host) to work with after this block has been passed.
755     */
756    if (!isopenat || (isopenat && tgt_dirfd == OS::TGT_AT_FDCWD)) {
757        path = p->fullPath(path);
758    } else if (!startswith(path, "/")) {
759        std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
760        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
761        if (!ffdp)
762            return -EBADF;
763        path.insert(0, ffdp->getFileName() + "/");
764    }
765
766    /**
767     * Since this is an emulated environment, we create pseudo file
768     * descriptors for device requests that have been registered with
769     * the process class through Python; this allows us to create a file
770     * descriptor for subsequent ioctl or mmap calls.
771     */
772    if (startswith(path, "/dev/")) {
773        std::string filename = path.substr(strlen("/dev/"));
774        EmulatedDriver *drv = p->findDriver(filename);
775        if (drv) {
776            DPRINTF_SYSCALL(Verbose, "open%s: passing call to "
777                            "driver open with path[%s]\n",
778                            isopenat ? "at" : "", path.c_str());
779            return drv->open(p, tc, mode, host_flags);
780        }
781        /**
782         * Fall through here for pass through to host devices, such
783         * as /dev/zero
784         */
785    }
786
787    /**
788     * Some special paths and files cannot be called on the host and need
789     * to be handled as special cases inside the simulator.
790     * If the full path that was created above does not match any of the
791     * special cases, pass it through to the open call on the host to let
792     * the host open the file on our behalf.
793     * If the host cannot open the file, return the host's error code back
794     * through the system call to the simulated process.
795     */
796    int sim_fd = -1;
797    std::vector<std::string> special_paths =
798            { "/proc/", "/system/", "/sys/", "/platform/", "/etc/passwd" };
799    for (auto entry : special_paths) {
800        if (startswith(path, entry))
801            sim_fd = OS::openSpecialFile(path, p, tc);
802    }
803    if (sim_fd == -1) {
804        sim_fd = open(path.c_str(), host_flags, mode);
805    }
806    if (sim_fd == -1) {
807        int local = -errno;
808        DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s\n",
809                        isopenat ? "at" : "", path.c_str());
810        return local;
811    }
812
813    /**
814     * The file was opened successfully and needs to be recorded in the
815     * process' file descriptor array so that it can be retrieved later.
816     * The target file descriptor that is chosen will be the lowest unused
817     * file descriptor.
818     * Return the indirect target file descriptor back to the simulated
819     * process to act as a handle for the opened file.
820     */
821    auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
822    int tgt_fd = p->fds->allocFD(ffdp);
823    DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n",
824                    isopenat ? "at" : "", sim_fd, tgt_fd, path.c_str());
825    return tgt_fd;
826}
827
828/// Target open() handler.
829template <class OS>
830SyscallReturn
831openFunc(SyscallDesc *desc, int callnum, Process *process,
832         ThreadContext *tc)
833{
834    return openImpl<OS>(desc, callnum, process, tc, false);
835}
836
837/// Target openat() handler.
838template <class OS>
839SyscallReturn
840openatFunc(SyscallDesc *desc, int callnum, Process *process,
841           ThreadContext *tc)
842{
843    return openImpl<OS>(desc, callnum, process, tc, true);
844}
845
846/// Target unlinkat() handler.
847template <class OS>
848SyscallReturn
849unlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
850             ThreadContext *tc)
851{
852    int index = 0;
853    int dirfd = process->getSyscallArg(tc, index);
854    if (dirfd != OS::TGT_AT_FDCWD)
855        warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
856
857    return unlinkHelper(desc, callnum, process, tc, 1);
858}
859
860/// Target facessat() handler
861template <class OS>
862SyscallReturn
863faccessatFunc(SyscallDesc *desc, int callnum, Process *process,
864              ThreadContext *tc)
865{
866    int index = 0;
867    int dirfd = process->getSyscallArg(tc, index);
868    if (dirfd != OS::TGT_AT_FDCWD)
869        warn("faccessat: first argument not AT_FDCWD; unlikely to work");
870    return accessFunc(desc, callnum, process, tc, 1);
871}
872
873/// Target readlinkat() handler
874template <class OS>
875SyscallReturn
876readlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
877               ThreadContext *tc)
878{
879    int index = 0;
880    int dirfd = process->getSyscallArg(tc, index);
881    if (dirfd != OS::TGT_AT_FDCWD)
882        warn("openat: first argument not AT_FDCWD; unlikely to work");
883    return readlinkFunc(desc, callnum, process, tc, 1);
884}
885
886/// Target renameat() handler.
887template <class OS>
888SyscallReturn
889renameatFunc(SyscallDesc *desc, int callnum, Process *process,
890             ThreadContext *tc)
891{
892    int index = 0;
893
894    int olddirfd = process->getSyscallArg(tc, index);
895    if (olddirfd != OS::TGT_AT_FDCWD)
896        warn("renameat: first argument not AT_FDCWD; unlikely to work");
897
898    std::string old_name;
899
900    if (!tc->getMemProxy().tryReadString(old_name,
901                                         process->getSyscallArg(tc, index)))
902        return -EFAULT;
903
904    int newdirfd = process->getSyscallArg(tc, index);
905    if (newdirfd != OS::TGT_AT_FDCWD)
906        warn("renameat: third argument not AT_FDCWD; unlikely to work");
907
908    std::string new_name;
909
910    if (!tc->getMemProxy().tryReadString(new_name,
911                                         process->getSyscallArg(tc, index)))
912        return -EFAULT;
913
914    // Adjust path for current working directory
915    old_name = process->fullPath(old_name);
916    new_name = process->fullPath(new_name);
917
918    int result = rename(old_name.c_str(), new_name.c_str());
919    return (result == -1) ? -errno : result;
920}
921
922/// Target sysinfo() handler.
923template <class OS>
924SyscallReturn
925sysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
926            ThreadContext *tc)
927{
928
929    int index = 0;
930    TypedBufferArg<typename OS::tgt_sysinfo>
931        sysinfo(process->getSyscallArg(tc, index));
932
933    sysinfo->uptime = seconds_since_epoch;
934    sysinfo->totalram = process->system->memSize();
935    sysinfo->mem_unit = 1;
936
937    sysinfo.copyOut(tc->getMemProxy());
938
939    return 0;
940}
941
942/// Target chmod() handler.
943template <class OS>
944SyscallReturn
945chmodFunc(SyscallDesc *desc, int callnum, Process *process,
946          ThreadContext *tc)
947{
948    std::string path;
949
950    int index = 0;
951    if (!tc->getMemProxy().tryReadString(path,
952                process->getSyscallArg(tc, index))) {
953        return -EFAULT;
954    }
955
956    uint32_t mode = process->getSyscallArg(tc, index);
957    mode_t hostMode = 0;
958
959    // XXX translate mode flags via OS::something???
960    hostMode = mode;
961
962    // Adjust path for current working directory
963    path = process->fullPath(path);
964
965    // do the chmod
966    int result = chmod(path.c_str(), hostMode);
967    if (result < 0)
968        return -errno;
969
970    return 0;
971}
972
973template <class OS>
974SyscallReturn
975pollFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
976{
977    int index = 0;
978    Addr fdsPtr = p->getSyscallArg(tc, index);
979    int nfds = p->getSyscallArg(tc, index);
980    int tmout = p->getSyscallArg(tc, index);
981
982    BufferArg fdsBuf(fdsPtr, sizeof(struct pollfd) * nfds);
983    fdsBuf.copyIn(tc->getMemProxy());
984
985    /**
986     * Record the target file descriptors in a local variable. We need to
987     * replace them with host file descriptors but we need a temporary copy
988     * for later. Afterwards, replace each target file descriptor in the
989     * poll_fd array with its host_fd.
990     */
991    int temp_tgt_fds[nfds];
992    for (index = 0; index < nfds; index++) {
993        temp_tgt_fds[index] = ((struct pollfd *)fdsBuf.bufferPtr())[index].fd;
994        auto tgt_fd = temp_tgt_fds[index];
995        auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
996        if (!hbfdp)
997            return -EBADF;
998        auto host_fd = hbfdp->getSimFD();
999        ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = host_fd;
1000    }
1001
1002    /**
1003     * We cannot allow an infinite poll to occur or it will inevitably cause
1004     * a deadlock in the gem5 simulator with clone. We must pass in tmout with
1005     * a non-negative value, however it also makes no sense to poll on the
1006     * underlying host for any other time than tmout a zero timeout.
1007     */
1008    int status;
1009    if (tmout < 0) {
1010        status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1011        if (status == 0) {
1012            /**
1013             * If blocking indefinitely, check the signal list to see if a
1014             * signal would break the poll out of the retry cycle and try
1015             * to return the signal interrupt instead.
1016             */
1017            System *sysh = tc->getSystemPtr();
1018            std::list<BasicSignal>::iterator it;
1019            for (it=sysh->signalList.begin(); it!=sysh->signalList.end(); it++)
1020                if (it->receiver == p)
1021                    return -EINTR;
1022            return SyscallReturn::retry();
1023        }
1024    } else
1025        status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1026
1027    if (status == -1)
1028        return -errno;
1029
1030    /**
1031     * Replace each host_fd in the returned poll_fd array with its original
1032     * target file descriptor.
1033     */
1034    for (index = 0; index < nfds; index++) {
1035        auto tgt_fd = temp_tgt_fds[index];
1036        ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = tgt_fd;
1037    }
1038
1039    /**
1040     * Copy out the pollfd struct because the host may have updated fields
1041     * in the structure.
1042     */
1043    fdsBuf.copyOut(tc->getMemProxy());
1044
1045    return status;
1046}
1047
1048/// Target fchmod() handler.
1049template <class OS>
1050SyscallReturn
1051fchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1052{
1053    int index = 0;
1054    int tgt_fd = p->getSyscallArg(tc, index);
1055    uint32_t mode = p->getSyscallArg(tc, index);
1056
1057    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1058    if (!ffdp)
1059        return -EBADF;
1060    int sim_fd = ffdp->getSimFD();
1061
1062    mode_t hostMode = mode;
1063
1064    int result = fchmod(sim_fd, hostMode);
1065
1066    return (result < 0) ? -errno : 0;
1067}
1068
1069/// Target mremap() handler.
1070template <class OS>
1071SyscallReturn
1072mremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
1073{
1074    int index = 0;
1075    Addr start = process->getSyscallArg(tc, index);
1076    uint64_t old_length = process->getSyscallArg(tc, index);
1077    uint64_t new_length = process->getSyscallArg(tc, index);
1078    uint64_t flags = process->getSyscallArg(tc, index);
1079    uint64_t provided_address = 0;
1080    bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
1081
1082    if (use_provided_address)
1083        provided_address = process->getSyscallArg(tc, index);
1084
1085    if ((start % TheISA::PageBytes != 0) ||
1086        (provided_address % TheISA::PageBytes != 0)) {
1087        warn("mremap failing: arguments not page aligned");
1088        return -EINVAL;
1089    }
1090
1091    new_length = roundUp(new_length, TheISA::PageBytes);
1092
1093    if (new_length > old_length) {
1094        std::shared_ptr<MemState> mem_state = process->memState;
1095        Addr mmap_end = mem_state->getMmapEnd();
1096
1097        if ((start + old_length) == mmap_end &&
1098            (!use_provided_address || provided_address == start)) {
1099            // This case cannot occur when growing downward, as
1100            // start is greater than or equal to mmap_end.
1101            uint64_t diff = new_length - old_length;
1102            process->allocateMem(mmap_end, diff);
1103            mem_state->setMmapEnd(mmap_end + diff);
1104            return start;
1105        } else {
1106            if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
1107                warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
1108                return -ENOMEM;
1109            } else {
1110                uint64_t new_start = provided_address;
1111                if (!use_provided_address) {
1112                    new_start = process->mmapGrowsDown() ?
1113                                mmap_end - new_length : mmap_end;
1114                    mmap_end = process->mmapGrowsDown() ?
1115                               new_start : mmap_end + new_length;
1116                    mem_state->setMmapEnd(mmap_end);
1117                }
1118
1119                process->pTable->remap(start, old_length, new_start);
1120                warn("mremapping to new vaddr %08p-%08p, adding %d\n",
1121                     new_start, new_start + new_length,
1122                     new_length - old_length);
1123                // add on the remaining unallocated pages
1124                process->allocateMem(new_start + old_length,
1125                                     new_length - old_length,
1126                                     use_provided_address /* clobber */);
1127                if (use_provided_address &&
1128                    ((new_start + new_length > mem_state->getMmapEnd() &&
1129                      !process->mmapGrowsDown()) ||
1130                    (new_start < mem_state->getMmapEnd() &&
1131                      process->mmapGrowsDown()))) {
1132                    // something fishy going on here, at least notify the user
1133                    // @todo: increase mmap_end?
1134                    warn("mmap region limit exceeded with MREMAP_FIXED\n");
1135                }
1136                warn("returning %08p as start\n", new_start);
1137                return new_start;
1138            }
1139        }
1140    } else {
1141        if (use_provided_address && provided_address != start)
1142            process->pTable->remap(start, new_length, provided_address);
1143        process->pTable->unmap(start + new_length, old_length - new_length);
1144        return use_provided_address ? provided_address : start;
1145    }
1146}
1147
1148/// Target stat() handler.
1149template <class OS>
1150SyscallReturn
1151statFunc(SyscallDesc *desc, int callnum, Process *process,
1152         ThreadContext *tc)
1153{
1154    std::string path;
1155
1156    int index = 0;
1157    if (!tc->getMemProxy().tryReadString(path,
1158                process->getSyscallArg(tc, index))) {
1159        return -EFAULT;
1160    }
1161    Addr bufPtr = process->getSyscallArg(tc, index);
1162
1163    // Adjust path for current working directory
1164    path = process->fullPath(path);
1165
1166    struct stat hostBuf;
1167    int result = stat(path.c_str(), &hostBuf);
1168
1169    if (result < 0)
1170        return -errno;
1171
1172    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1173
1174    return 0;
1175}
1176
1177
1178/// Target stat64() handler.
1179template <class OS>
1180SyscallReturn
1181stat64Func(SyscallDesc *desc, int callnum, Process *process,
1182           ThreadContext *tc)
1183{
1184    std::string path;
1185
1186    int index = 0;
1187    if (!tc->getMemProxy().tryReadString(path,
1188                process->getSyscallArg(tc, index)))
1189        return -EFAULT;
1190    Addr bufPtr = process->getSyscallArg(tc, index);
1191
1192    // Adjust path for current working directory
1193    path = process->fullPath(path);
1194
1195#if NO_STAT64
1196    struct stat  hostBuf;
1197    int result = stat(path.c_str(), &hostBuf);
1198#else
1199    struct stat64 hostBuf;
1200    int result = stat64(path.c_str(), &hostBuf);
1201#endif
1202
1203    if (result < 0)
1204        return -errno;
1205
1206    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1207
1208    return 0;
1209}
1210
1211
1212/// Target fstatat64() handler.
1213template <class OS>
1214SyscallReturn
1215fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
1216              ThreadContext *tc)
1217{
1218    int index = 0;
1219    int dirfd = process->getSyscallArg(tc, index);
1220    if (dirfd != OS::TGT_AT_FDCWD)
1221        warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1222
1223    std::string path;
1224    if (!tc->getMemProxy().tryReadString(path,
1225                process->getSyscallArg(tc, index)))
1226        return -EFAULT;
1227    Addr bufPtr = process->getSyscallArg(tc, index);
1228
1229    // Adjust path for current working directory
1230    path = process->fullPath(path);
1231
1232#if NO_STAT64
1233    struct stat  hostBuf;
1234    int result = stat(path.c_str(), &hostBuf);
1235#else
1236    struct stat64 hostBuf;
1237    int result = stat64(path.c_str(), &hostBuf);
1238#endif
1239
1240    if (result < 0)
1241        return -errno;
1242
1243    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1244
1245    return 0;
1246}
1247
1248
1249/// Target fstat64() handler.
1250template <class OS>
1251SyscallReturn
1252fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1253{
1254    int index = 0;
1255    int tgt_fd = p->getSyscallArg(tc, index);
1256    Addr bufPtr = p->getSyscallArg(tc, index);
1257
1258    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1259    if (!ffdp)
1260        return -EBADF;
1261    int sim_fd = ffdp->getSimFD();
1262
1263#if NO_STAT64
1264    struct stat  hostBuf;
1265    int result = fstat(sim_fd, &hostBuf);
1266#else
1267    struct stat64  hostBuf;
1268    int result = fstat64(sim_fd, &hostBuf);
1269#endif
1270
1271    if (result < 0)
1272        return -errno;
1273
1274    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1275
1276    return 0;
1277}
1278
1279
1280/// Target lstat() handler.
1281template <class OS>
1282SyscallReturn
1283lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1284          ThreadContext *tc)
1285{
1286    std::string path;
1287
1288    int index = 0;
1289    if (!tc->getMemProxy().tryReadString(path,
1290                process->getSyscallArg(tc, index))) {
1291        return -EFAULT;
1292    }
1293    Addr bufPtr = process->getSyscallArg(tc, index);
1294
1295    // Adjust path for current working directory
1296    path = process->fullPath(path);
1297
1298    struct stat hostBuf;
1299    int result = lstat(path.c_str(), &hostBuf);
1300
1301    if (result < 0)
1302        return -errno;
1303
1304    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1305
1306    return 0;
1307}
1308
1309/// Target lstat64() handler.
1310template <class OS>
1311SyscallReturn
1312lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1313            ThreadContext *tc)
1314{
1315    std::string path;
1316
1317    int index = 0;
1318    if (!tc->getMemProxy().tryReadString(path,
1319                process->getSyscallArg(tc, index))) {
1320        return -EFAULT;
1321    }
1322    Addr bufPtr = process->getSyscallArg(tc, index);
1323
1324    // Adjust path for current working directory
1325    path = process->fullPath(path);
1326
1327#if NO_STAT64
1328    struct stat hostBuf;
1329    int result = lstat(path.c_str(), &hostBuf);
1330#else
1331    struct stat64 hostBuf;
1332    int result = lstat64(path.c_str(), &hostBuf);
1333#endif
1334
1335    if (result < 0)
1336        return -errno;
1337
1338    copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1339
1340    return 0;
1341}
1342
1343/// Target fstat() handler.
1344template <class OS>
1345SyscallReturn
1346fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1347{
1348    int index = 0;
1349    int tgt_fd = p->getSyscallArg(tc, index);
1350    Addr bufPtr = p->getSyscallArg(tc, index);
1351
1352    DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1353
1354    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1355    if (!ffdp)
1356        return -EBADF;
1357    int sim_fd = ffdp->getSimFD();
1358
1359    struct stat hostBuf;
1360    int result = fstat(sim_fd, &hostBuf);
1361
1362    if (result < 0)
1363        return -errno;
1364
1365    copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1366
1367    return 0;
1368}
1369
1370/// Target statfs() handler.
1371template <class OS>
1372SyscallReturn
1373statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1374           ThreadContext *tc)
1375{
1376#if NO_STATFS
1377    warn("Host OS cannot support calls to statfs. Ignoring syscall");
1378#else
1379    std::string path;
1380
1381    int index = 0;
1382    if (!tc->getMemProxy().tryReadString(path,
1383                process->getSyscallArg(tc, index))) {
1384        return -EFAULT;
1385    }
1386    Addr bufPtr = process->getSyscallArg(tc, index);
1387
1388    // Adjust path for current working directory
1389    path = process->fullPath(path);
1390
1391    struct statfs hostBuf;
1392    int result = statfs(path.c_str(), &hostBuf);
1393
1394    if (result < 0)
1395        return -errno;
1396
1397    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1398#endif
1399    return 0;
1400}
1401
1402template <class OS>
1403SyscallReturn
1404cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1405{
1406    int index = 0;
1407
1408    RegVal flags = p->getSyscallArg(tc, index);
1409    RegVal newStack = p->getSyscallArg(tc, index);
1410    Addr ptidPtr = p->getSyscallArg(tc, index);
1411
1412#if THE_ISA == RISCV_ISA or THE_ISA == ARM_ISA
1413    /**
1414     * Linux sets CLONE_BACKWARDS flag for RISC-V and Arm.
1415     * The flag defines the list of clone() arguments in the following
1416     * order: flags -> newStack -> ptidPtr -> tlsPtr -> ctidPtr
1417     */
1418    Addr tlsPtr = p->getSyscallArg(tc, index);
1419    Addr ctidPtr = p->getSyscallArg(tc, index);
1420#else
1421    Addr ctidPtr = p->getSyscallArg(tc, index);
1422    Addr tlsPtr = p->getSyscallArg(tc, index);
1423#endif
1424
1425    if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1426        ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1427        ((flags & OS::TGT_CLONE_FS)     &&  (flags & OS::TGT_CLONE_NEWNS)) ||
1428        ((flags & OS::TGT_CLONE_NEWIPC) &&  (flags & OS::TGT_CLONE_SYSVSEM)) ||
1429        ((flags & OS::TGT_CLONE_NEWPID) &&  (flags & OS::TGT_CLONE_THREAD)) ||
1430        ((flags & OS::TGT_CLONE_VM)     && !(newStack)))
1431        return -EINVAL;
1432
1433    ThreadContext *ctc;
1434    if (!(ctc = p->findFreeContext())) {
1435        DPRINTF_SYSCALL(Verbose, "clone: no spare thread context in system"
1436                        "[cpu %d, thread %d]", tc->cpuId(), tc->threadId());
1437        return -EAGAIN;
1438    }
1439
1440    /**
1441     * Note that ProcessParams is generated by swig and there are no other
1442     * examples of how to create anything but this default constructor. The
1443     * fields are manually initialized instead of passing parameters to the
1444     * constructor.
1445     */
1446    ProcessParams *pp = new ProcessParams();
1447    pp->executable.assign(*(new std::string(p->progName())));
1448    pp->cmd.push_back(*(new std::string(p->progName())));
1449    pp->system = p->system;
1450    pp->cwd.assign(p->getcwd());
1451    pp->input.assign("stdin");
1452    pp->output.assign("stdout");
1453    pp->errout.assign("stderr");
1454    pp->uid = p->uid();
1455    pp->euid = p->euid();
1456    pp->gid = p->gid();
1457    pp->egid = p->egid();
1458
1459    /* Find the first free PID that's less than the maximum */
1460    std::set<int> const& pids = p->system->PIDs;
1461    int temp_pid = *pids.begin();
1462    do {
1463        temp_pid++;
1464    } while (pids.find(temp_pid) != pids.end());
1465    if (temp_pid >= System::maxPID)
1466        fatal("temp_pid is too large: %d", temp_pid);
1467
1468    pp->pid = temp_pid;
1469    pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1470    Process *cp = pp->create();
1471    delete pp;
1472
1473    Process *owner = ctc->getProcessPtr();
1474    ctc->setProcessPtr(cp);
1475    cp->assignThreadContext(ctc->contextId());
1476    owner->revokeThreadContext(ctc->contextId());
1477
1478    if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1479        BufferArg ptidBuf(ptidPtr, sizeof(long));
1480        long *ptid = (long *)ptidBuf.bufferPtr();
1481        *ptid = cp->pid();
1482        ptidBuf.copyOut(tc->getMemProxy());
1483    }
1484
1485    cp->initState();
1486    p->clone(tc, ctc, cp, flags);
1487
1488    if (flags & OS::TGT_CLONE_THREAD) {
1489        delete cp->sigchld;
1490        cp->sigchld = p->sigchld;
1491    } else if (flags & OS::TGT_SIGCHLD) {
1492        *cp->sigchld = true;
1493    }
1494
1495    if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1496        BufferArg ctidBuf(ctidPtr, sizeof(long));
1497        long *ctid = (long *)ctidBuf.bufferPtr();
1498        *ctid = cp->pid();
1499        ctidBuf.copyOut(ctc->getMemProxy());
1500    }
1501
1502    if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1503        cp->childClearTID = (uint64_t)ctidPtr;
1504
1505    ctc->clearArchRegs();
1506
1507    OS::archClone(flags, p, cp, tc, ctc, newStack, tlsPtr);
1508
1509    cp->setSyscallReturn(ctc, 0);
1510
1511#if THE_ISA == ALPHA_ISA
1512    ctc->setIntReg(TheISA::SyscallSuccessReg, 0);
1513#elif THE_ISA == SPARC_ISA
1514    tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1515    ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1516#endif
1517
1518    TheISA::PCState cpc = tc->pcState();
1519    cpc.advance();
1520    ctc->pcState(cpc);
1521    ctc->activate();
1522
1523    return cp->pid();
1524}
1525
1526/// Target fstatfs() handler.
1527template <class OS>
1528SyscallReturn
1529fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1530{
1531    int index = 0;
1532    int tgt_fd = p->getSyscallArg(tc, index);
1533    Addr bufPtr = p->getSyscallArg(tc, index);
1534
1535    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1536    if (!ffdp)
1537        return -EBADF;
1538    int sim_fd = ffdp->getSimFD();
1539
1540    struct statfs hostBuf;
1541    int result = fstatfs(sim_fd, &hostBuf);
1542
1543    if (result < 0)
1544        return -errno;
1545
1546    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1547
1548    return 0;
1549}
1550
1551/// Target readv() handler.
1552template <class OS>
1553SyscallReturn
1554readvFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1555{
1556    int index = 0;
1557    int tgt_fd = p->getSyscallArg(tc, index);
1558
1559    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1560    if (!ffdp)
1561        return -EBADF;
1562    int sim_fd = ffdp->getSimFD();
1563
1564    SETranslatingPortProxy &prox = tc->getMemProxy();
1565    uint64_t tiov_base = p->getSyscallArg(tc, index);
1566    size_t count = p->getSyscallArg(tc, index);
1567    typename OS::tgt_iovec tiov[count];
1568    struct iovec hiov[count];
1569    for (size_t i = 0; i < count; ++i) {
1570        prox.readBlob(tiov_base + (i * sizeof(typename OS::tgt_iovec)),
1571                      (uint8_t*)&tiov[i], sizeof(typename OS::tgt_iovec));
1572        hiov[i].iov_len = TheISA::gtoh(tiov[i].iov_len);
1573        hiov[i].iov_base = new char [hiov[i].iov_len];
1574    }
1575
1576    int result = readv(sim_fd, hiov, count);
1577    int local_errno = errno;
1578
1579    for (size_t i = 0; i < count; ++i) {
1580        if (result != -1) {
1581            prox.writeBlob(TheISA::htog(tiov[i].iov_base),
1582                           (uint8_t*)hiov[i].iov_base, hiov[i].iov_len);
1583        }
1584        delete [] (char *)hiov[i].iov_base;
1585    }
1586
1587    return (result == -1) ? -local_errno : result;
1588}
1589
1590/// Target writev() handler.
1591template <class OS>
1592SyscallReturn
1593writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1594{
1595    int index = 0;
1596    int tgt_fd = p->getSyscallArg(tc, index);
1597
1598    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1599    if (!hbfdp)
1600        return -EBADF;
1601    int sim_fd = hbfdp->getSimFD();
1602
1603    SETranslatingPortProxy &prox = tc->getMemProxy();
1604    uint64_t tiov_base = p->getSyscallArg(tc, index);
1605    size_t count = p->getSyscallArg(tc, index);
1606    struct iovec hiov[count];
1607    for (size_t i = 0; i < count; ++i) {
1608        typename OS::tgt_iovec tiov;
1609
1610        prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1611                      (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1612        hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1613        hiov[i].iov_base = new char [hiov[i].iov_len];
1614        prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1615                      hiov[i].iov_len);
1616    }
1617
1618    int result = writev(sim_fd, hiov, count);
1619
1620    for (size_t i = 0; i < count; ++i)
1621        delete [] (char *)hiov[i].iov_base;
1622
1623    return (result == -1) ? -errno : result;
1624}
1625
1626/// Real mmap handler.
1627template <class OS>
1628SyscallReturn
1629mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1630         bool is_mmap2)
1631{
1632    int index = 0;
1633    Addr start = p->getSyscallArg(tc, index);
1634    uint64_t length = p->getSyscallArg(tc, index);
1635    int prot = p->getSyscallArg(tc, index);
1636    int tgt_flags = p->getSyscallArg(tc, index);
1637    int tgt_fd = p->getSyscallArg(tc, index);
1638    int offset = p->getSyscallArg(tc, index);
1639
1640    if (is_mmap2)
1641        offset *= TheISA::PageBytes;
1642
1643    if (start & (TheISA::PageBytes - 1) ||
1644        offset & (TheISA::PageBytes - 1) ||
1645        (tgt_flags & OS::TGT_MAP_PRIVATE &&
1646         tgt_flags & OS::TGT_MAP_SHARED) ||
1647        (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1648         !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1649        !length) {
1650        return -EINVAL;
1651    }
1652
1653    if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1654        // With shared mmaps, there are two cases to consider:
1655        // 1) anonymous: writes should modify the mapping and this should be
1656        // visible to observers who share the mapping. Currently, it's
1657        // difficult to update the shared mapping because there's no
1658        // structure which maintains information about the which virtual
1659        // memory areas are shared. If that structure existed, it would be
1660        // possible to make the translations point to the same frames.
1661        // 2) file-backed: writes should modify the mapping and the file
1662        // which is backed by the mapping. The shared mapping problem is the
1663        // same as what was mentioned about the anonymous mappings. For
1664        // file-backed mappings, the writes to the file are difficult
1665        // because it requires syncing what the mapping holds with the file
1666        // that resides on the host system. So, any write on a real system
1667        // would cause the change to be propagated to the file mapping at
1668        // some point in the future (the inode is tracked along with the
1669        // mapping). This isn't guaranteed to always happen, but it usually
1670        // works well enough. The guarantee is provided by the msync system
1671        // call. We could force the change through with shared mappings with
1672        // a call to msync, but that again would require more information
1673        // than we currently maintain.
1674        warn("mmap: writing to shared mmap region is currently "
1675             "unsupported. The write succeeds on the target, but it "
1676             "will not be propagated to the host or shared mappings");
1677    }
1678
1679    length = roundUp(length, TheISA::PageBytes);
1680
1681    int sim_fd = -1;
1682    uint8_t *pmap = nullptr;
1683    if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1684        std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1685
1686        auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1687        if (dfdp) {
1688            EmulatedDriver *emul_driver = dfdp->getDriver();
1689            return emul_driver->mmap(p, tc, start, length, prot,
1690                                     tgt_flags, tgt_fd, offset);
1691        }
1692
1693        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1694        if (!ffdp)
1695            return -EBADF;
1696        sim_fd = ffdp->getSimFD();
1697
1698        pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1699                                    sim_fd, offset);
1700
1701        if (pmap == (decltype(pmap))-1) {
1702            warn("mmap: failed to map file into host address space");
1703            return -errno;
1704        }
1705    }
1706
1707    // Extend global mmap region if necessary. Note that we ignore the
1708    // start address unless MAP_FIXED is specified.
1709    if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1710        std::shared_ptr<MemState> mem_state = p->memState;
1711        Addr mmap_end = mem_state->getMmapEnd();
1712
1713        start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1714        mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1715
1716        mem_state->setMmapEnd(mmap_end);
1717    }
1718
1719    DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1720                    start, start + length - 1);
1721
1722    // We only allow mappings to overwrite existing mappings if
1723    // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1724    // because we ignore the start hint if TGT_MAP_FIXED is not set.
1725    int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1726    if (clobber) {
1727        for (auto tc : p->system->threadContexts) {
1728            // If we might be overwriting old mappings, we need to
1729            // invalidate potentially stale mappings out of the TLBs.
1730            tc->getDTBPtr()->flushAll();
1731            tc->getITBPtr()->flushAll();
1732        }
1733    }
1734
1735    // Allocate physical memory and map it in. If the page table is already
1736    // mapped and clobber is not set, the simulator will issue throw a
1737    // fatal and bail out of the simulation.
1738    p->allocateMem(start, length, clobber);
1739
1740    // Transfer content into target address space.
1741    SETranslatingPortProxy &tp = tc->getMemProxy();
1742    if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1743        // In general, we should zero the mapped area for anonymous mappings,
1744        // with something like:
1745        //     tp.memsetBlob(start, 0, length);
1746        // However, given that we don't support sparse mappings, and
1747        // some applications can map a couple of gigabytes of space
1748        // (intending sparse usage), that can get painfully expensive.
1749        // Fortunately, since we don't properly implement munmap either,
1750        // there's no danger of remapping used memory, so for now all
1751        // newly mapped memory should already be zeroed so we can skip it.
1752    } else {
1753        // It is possible to mmap an area larger than a file, however
1754        // accessing unmapped portions the system triggers a "Bus error"
1755        // on the host. We must know when to stop copying the file from
1756        // the host into the target address space.
1757        struct stat file_stat;
1758        if (fstat(sim_fd, &file_stat) > 0)
1759            fatal("mmap: cannot stat file");
1760
1761        // Copy the portion of the file that is resident. This requires
1762        // checking both the mmap size and the filesize that we are
1763        // trying to mmap into this space; the mmap size also depends
1764        // on the specified offset into the file.
1765        uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1766                                 length);
1767        tp.writeBlob(start, pmap, size);
1768
1769        // Cleanup the mmap region before exiting this function.
1770        munmap(pmap, length);
1771
1772        // Maintain the symbol table for dynamic executables.
1773        // The loader will call mmap to map the images into its address
1774        // space and we intercept that here. We can verify that we are
1775        // executing inside the loader by checking the program counter value.
1776        // XXX: with multiprogrammed workloads or multi-node configurations,
1777        // this will not work since there is a single global symbol table.
1778        ObjectFile *interpreter = p->getInterpreter();
1779        if (interpreter) {
1780            Addr text_start = interpreter->textBase();
1781            Addr text_end = text_start + interpreter->textSize();
1782
1783            Addr pc = tc->pcState().pc();
1784
1785            if (pc >= text_start && pc < text_end) {
1786                std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1787                auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1788                ObjectFile *lib = createObjectFile(ffdp->getFileName());
1789
1790                if (lib) {
1791                    lib->loadAllSymbols(debugSymbolTable,
1792                                        lib->textBase(), start);
1793                }
1794            }
1795        }
1796
1797        // Note that we do not zero out the remainder of the mapping. This
1798        // is done by a real system, but it probably will not affect
1799        // execution (hopefully).
1800    }
1801
1802    return start;
1803}
1804
1805template <class OS>
1806SyscallReturn
1807pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1808{
1809    int index = 0;
1810    int tgt_fd = p->getSyscallArg(tc, index);
1811    Addr bufPtr = p->getSyscallArg(tc, index);
1812    int nbytes = p->getSyscallArg(tc, index);
1813    int offset = p->getSyscallArg(tc, index);
1814
1815    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1816    if (!ffdp)
1817        return -EBADF;
1818    int sim_fd = ffdp->getSimFD();
1819
1820    BufferArg bufArg(bufPtr, nbytes);
1821    bufArg.copyIn(tc->getMemProxy());
1822
1823    int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1824
1825    return (bytes_written == -1) ? -errno : bytes_written;
1826}
1827
1828/// Target mmap() handler.
1829template <class OS>
1830SyscallReturn
1831mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1832{
1833    return mmapImpl<OS>(desc, num, p, tc, false);
1834}
1835
1836/// Target mmap2() handler.
1837template <class OS>
1838SyscallReturn
1839mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1840{
1841    return mmapImpl<OS>(desc, num, p, tc, true);
1842}
1843
1844/// Target getrlimit() handler.
1845template <class OS>
1846SyscallReturn
1847getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1848              ThreadContext *tc)
1849{
1850    int index = 0;
1851    unsigned resource = process->getSyscallArg(tc, index);
1852    TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1853
1854    switch (resource) {
1855      case OS::TGT_RLIMIT_STACK:
1856        // max stack size in bytes: make up a number (8MB for now)
1857        rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1858        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1859        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1860        break;
1861
1862      case OS::TGT_RLIMIT_DATA:
1863        // max data segment size in bytes: make up a number
1864        rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1865        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1866        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1867        break;
1868
1869      default:
1870        warn("getrlimit: unimplemented resource %d", resource);
1871        return -EINVAL;
1872        break;
1873    }
1874
1875    rlp.copyOut(tc->getMemProxy());
1876    return 0;
1877}
1878
1879template <class OS>
1880SyscallReturn
1881prlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1882            ThreadContext *tc)
1883{
1884    int index = 0;
1885    if (process->getSyscallArg(tc, index) != 0)
1886    {
1887        warn("prlimit: ignoring rlimits for nonzero pid");
1888        return -EPERM;
1889    }
1890    int resource = process->getSyscallArg(tc, index);
1891    Addr n = process->getSyscallArg(tc, index);
1892    if (n != 0)
1893        warn("prlimit: ignoring new rlimit");
1894    Addr o = process->getSyscallArg(tc, index);
1895    if (o != 0)
1896    {
1897        TypedBufferArg<typename OS::rlimit> rlp(o);
1898        switch (resource) {
1899          case OS::TGT_RLIMIT_STACK:
1900            // max stack size in bytes: make up a number (8MB for now)
1901            rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1902            rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1903            rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1904            break;
1905          case OS::TGT_RLIMIT_DATA:
1906            // max data segment size in bytes: make up a number
1907            rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
1908            rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1909            rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1910            break;
1911          default:
1912            warn("prlimit: unimplemented resource %d", resource);
1913            return -EINVAL;
1914            break;
1915        }
1916        rlp.copyOut(tc->getMemProxy());
1917    }
1918    return 0;
1919}
1920
1921/// Target clock_gettime() function.
1922template <class OS>
1923SyscallReturn
1924clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1925{
1926    int index = 1;
1927    //int clk_id = p->getSyscallArg(tc, index);
1928    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1929
1930    getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1931    tp->tv_sec += seconds_since_epoch;
1932    tp->tv_sec = TheISA::htog(tp->tv_sec);
1933    tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1934
1935    tp.copyOut(tc->getMemProxy());
1936
1937    return 0;
1938}
1939
1940/// Target clock_getres() function.
1941template <class OS>
1942SyscallReturn
1943clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1944{
1945    int index = 1;
1946    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1947
1948    // Set resolution at ns, which is what clock_gettime() returns
1949    tp->tv_sec = 0;
1950    tp->tv_nsec = 1;
1951
1952    tp.copyOut(tc->getMemProxy());
1953
1954    return 0;
1955}
1956
1957/// Target gettimeofday() handler.
1958template <class OS>
1959SyscallReturn
1960gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1961                 ThreadContext *tc)
1962{
1963    int index = 0;
1964    TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1965
1966    getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1967    tp->tv_sec += seconds_since_epoch;
1968    tp->tv_sec = TheISA::htog(tp->tv_sec);
1969    tp->tv_usec = TheISA::htog(tp->tv_usec);
1970
1971    tp.copyOut(tc->getMemProxy());
1972
1973    return 0;
1974}
1975
1976
1977/// Target utimes() handler.
1978template <class OS>
1979SyscallReturn
1980utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1981           ThreadContext *tc)
1982{
1983    std::string path;
1984
1985    int index = 0;
1986    if (!tc->getMemProxy().tryReadString(path,
1987                process->getSyscallArg(tc, index))) {
1988        return -EFAULT;
1989    }
1990
1991    TypedBufferArg<typename OS::timeval [2]>
1992        tp(process->getSyscallArg(tc, index));
1993    tp.copyIn(tc->getMemProxy());
1994
1995    struct timeval hostTimeval[2];
1996    for (int i = 0; i < 2; ++i) {
1997        hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1998        hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1999    }
2000
2001    // Adjust path for current working directory
2002    path = process->fullPath(path);
2003
2004    int result = utimes(path.c_str(), hostTimeval);
2005
2006    if (result < 0)
2007        return -errno;
2008
2009    return 0;
2010}
2011
2012template <class OS>
2013SyscallReturn
2014execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
2015{
2016    desc->setFlags(0);
2017
2018    int index = 0;
2019    std::string path;
2020    SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
2021    if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
2022        return -EFAULT;
2023
2024    if (access(path.c_str(), F_OK) == -1)
2025        return -EACCES;
2026
2027    auto read_in = [](std::vector<std::string> & vect,
2028                      SETranslatingPortProxy & mem_proxy,
2029                      Addr mem_loc)
2030    {
2031        for (int inc = 0; ; inc++) {
2032            BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
2033            b.copyIn(mem_proxy);
2034
2035            if (!*(Addr*)b.bufferPtr())
2036                break;
2037
2038            vect.push_back(std::string());
2039            mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
2040        }
2041    };
2042
2043    /**
2044     * Note that ProcessParams is generated by swig and there are no other
2045     * examples of how to create anything but this default constructor. The
2046     * fields are manually initialized instead of passing parameters to the
2047     * constructor.
2048     */
2049    ProcessParams *pp = new ProcessParams();
2050    pp->executable = path;
2051    Addr argv_mem_loc = p->getSyscallArg(tc, index);
2052    read_in(pp->cmd, mem_proxy, argv_mem_loc);
2053    Addr envp_mem_loc = p->getSyscallArg(tc, index);
2054    read_in(pp->env, mem_proxy, envp_mem_loc);
2055    pp->uid = p->uid();
2056    pp->egid = p->egid();
2057    pp->euid = p->euid();
2058    pp->gid = p->gid();
2059    pp->ppid = p->ppid();
2060    pp->pid = p->pid();
2061    pp->input.assign("cin");
2062    pp->output.assign("cout");
2063    pp->errout.assign("cerr");
2064    pp->cwd.assign(p->getcwd());
2065    pp->system = p->system;
2066    /**
2067     * Prevent process object creation with identical PIDs (which will trip
2068     * a fatal check in Process constructor). The execve call is supposed to
2069     * take over the currently executing process' identity but replace
2070     * whatever it is doing with a new process image. Instead of hijacking
2071     * the process object in the simulator, we create a new process object
2072     * and bind to the previous process' thread below (hijacking the thread).
2073     */
2074    p->system->PIDs.erase(p->pid());
2075    Process *new_p = pp->create();
2076    delete pp;
2077
2078    /**
2079     * Work through the file descriptor array and close any files marked
2080     * close-on-exec.
2081     */
2082    new_p->fds = p->fds;
2083    for (int i = 0; i < new_p->fds->getSize(); i++) {
2084        std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
2085        if (fdep && fdep->getCOE())
2086            new_p->fds->closeFDEntry(i);
2087    }
2088
2089    *new_p->sigchld = true;
2090
2091    delete p;
2092    tc->clearArchRegs();
2093    tc->setProcessPtr(new_p);
2094    new_p->assignThreadContext(tc->contextId());
2095    new_p->initState();
2096    tc->activate();
2097    TheISA::PCState pcState = tc->pcState();
2098    tc->setNPC(pcState.instAddr());
2099
2100    desc->setFlags(SyscallDesc::SuppressReturnValue);
2101    return 0;
2102}
2103
2104/// Target getrusage() function.
2105template <class OS>
2106SyscallReturn
2107getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
2108              ThreadContext *tc)
2109{
2110    int index = 0;
2111    int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
2112    TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
2113
2114    rup->ru_utime.tv_sec = 0;
2115    rup->ru_utime.tv_usec = 0;
2116    rup->ru_stime.tv_sec = 0;
2117    rup->ru_stime.tv_usec = 0;
2118    rup->ru_maxrss = 0;
2119    rup->ru_ixrss = 0;
2120    rup->ru_idrss = 0;
2121    rup->ru_isrss = 0;
2122    rup->ru_minflt = 0;
2123    rup->ru_majflt = 0;
2124    rup->ru_nswap = 0;
2125    rup->ru_inblock = 0;
2126    rup->ru_oublock = 0;
2127    rup->ru_msgsnd = 0;
2128    rup->ru_msgrcv = 0;
2129    rup->ru_nsignals = 0;
2130    rup->ru_nvcsw = 0;
2131    rup->ru_nivcsw = 0;
2132
2133    switch (who) {
2134      case OS::TGT_RUSAGE_SELF:
2135        getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
2136        rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
2137        rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
2138        break;
2139
2140      case OS::TGT_RUSAGE_CHILDREN:
2141        // do nothing.  We have no child processes, so they take no time.
2142        break;
2143
2144      default:
2145        // don't really handle THREAD or CHILDREN, but just warn and
2146        // plow ahead
2147        warn("getrusage() only supports RUSAGE_SELF.  Parameter %d ignored.",
2148             who);
2149    }
2150
2151    rup.copyOut(tc->getMemProxy());
2152
2153    return 0;
2154}
2155
2156/// Target times() function.
2157template <class OS>
2158SyscallReturn
2159timesFunc(SyscallDesc *desc, int callnum, Process *process,
2160          ThreadContext *tc)
2161{
2162    int index = 0;
2163    TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
2164
2165    // Fill in the time structure (in clocks)
2166    int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
2167    bufp->tms_utime = clocks;
2168    bufp->tms_stime = 0;
2169    bufp->tms_cutime = 0;
2170    bufp->tms_cstime = 0;
2171
2172    // Convert to host endianness
2173    bufp->tms_utime = TheISA::htog(bufp->tms_utime);
2174
2175    // Write back
2176    bufp.copyOut(tc->getMemProxy());
2177
2178    // Return clock ticks since system boot
2179    return clocks;
2180}
2181
2182/// Target time() function.
2183template <class OS>
2184SyscallReturn
2185timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
2186{
2187    typename OS::time_t sec, usec;
2188    getElapsedTimeMicro(sec, usec);
2189    sec += seconds_since_epoch;
2190
2191    int index = 0;
2192    Addr taddr = (Addr)process->getSyscallArg(tc, index);
2193    if (taddr != 0) {
2194        typename OS::time_t t = sec;
2195        t = TheISA::htog(t);
2196        SETranslatingPortProxy &p = tc->getMemProxy();
2197        p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
2198    }
2199    return sec;
2200}
2201
2202template <class OS>
2203SyscallReturn
2204tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
2205{
2206    int index = 0;
2207    int tgid = process->getSyscallArg(tc, index);
2208    int tid = process->getSyscallArg(tc, index);
2209    int sig = process->getSyscallArg(tc, index);
2210
2211    /**
2212     * This system call is intended to allow killing a specific thread
2213     * within an arbitrary thread group if sanctioned with permission checks.
2214     * It's usually true that threads share the termination signal as pointed
2215     * out by the pthread_kill man page and this seems to be the intended
2216     * usage. Due to this being an emulated environment, assume the following:
2217     * Threads are allowed to call tgkill because the EUID for all threads
2218     * should be the same. There is no signal handling mechanism for kernel
2219     * registration of signal handlers since signals are poorly supported in
2220     * emulation mode. Since signal handlers cannot be registered, all
2221     * threads within in a thread group must share the termination signal.
2222     * We never exhaust PIDs so there's no chance of finding the wrong one
2223     * due to PID rollover.
2224     */
2225
2226    System *sys = tc->getSystemPtr();
2227    Process *tgt_proc = nullptr;
2228    for (int i = 0; i < sys->numContexts(); i++) {
2229        Process *temp = sys->threadContexts[i]->getProcessPtr();
2230        if (temp->pid() == tid) {
2231            tgt_proc = temp;
2232            break;
2233        }
2234    }
2235
2236    if (sig != 0 || sig != OS::TGT_SIGABRT)
2237        return -EINVAL;
2238
2239    if (tgt_proc == nullptr)
2240        return -ESRCH;
2241
2242    if (tgid != -1 && tgt_proc->tgid() != tgid)
2243        return -ESRCH;
2244
2245    if (sig == OS::TGT_SIGABRT)
2246        exitGroupFunc(desc, 252, process, tc);
2247
2248    return 0;
2249}
2250
2251template <class OS>
2252SyscallReturn
2253socketFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2254{
2255    int index = 0;
2256    int domain = p->getSyscallArg(tc, index);
2257    int type = p->getSyscallArg(tc, index);
2258    int prot = p->getSyscallArg(tc, index);
2259
2260    int sim_fd = socket(domain, type, prot);
2261    if (sim_fd == -1)
2262        return -errno;
2263
2264    auto sfdp = std::make_shared<SocketFDEntry>(sim_fd, domain, type, prot);
2265    int tgt_fd = p->fds->allocFD(sfdp);
2266
2267    return tgt_fd;
2268}
2269
2270template <class OS>
2271SyscallReturn
2272socketpairFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2273{
2274    int index = 0;
2275    int domain = p->getSyscallArg(tc, index);
2276    int type = p->getSyscallArg(tc, index);
2277    int prot = p->getSyscallArg(tc, index);
2278    Addr svPtr = p->getSyscallArg(tc, index);
2279
2280    BufferArg svBuf((Addr)svPtr, 2 * sizeof(int));
2281    int status = socketpair(domain, type, prot, (int *)svBuf.bufferPtr());
2282    if (status == -1)
2283        return -errno;
2284
2285    int *fds = (int *)svBuf.bufferPtr();
2286
2287    auto sfdp1 = std::make_shared<SocketFDEntry>(fds[0], domain, type, prot);
2288    fds[0] = p->fds->allocFD(sfdp1);
2289    auto sfdp2 = std::make_shared<SocketFDEntry>(fds[1], domain, type, prot);
2290    fds[1] = p->fds->allocFD(sfdp2);
2291    svBuf.copyOut(tc->getMemProxy());
2292
2293    return status;
2294}
2295
2296template <class OS>
2297SyscallReturn
2298selectFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
2299{
2300    int retval;
2301
2302    int index = 0;
2303    int nfds_t = p->getSyscallArg(tc, index);
2304    Addr fds_read_ptr = p->getSyscallArg(tc, index);
2305    Addr fds_writ_ptr = p->getSyscallArg(tc, index);
2306    Addr fds_excp_ptr = p->getSyscallArg(tc, index);
2307    Addr time_val_ptr = p->getSyscallArg(tc, index);
2308
2309    TypedBufferArg<typename OS::fd_set> rd_t(fds_read_ptr);
2310    TypedBufferArg<typename OS::fd_set> wr_t(fds_writ_ptr);
2311    TypedBufferArg<typename OS::fd_set> ex_t(fds_excp_ptr);
2312    TypedBufferArg<typename OS::timeval> tp(time_val_ptr);
2313
2314    /**
2315     * Host fields. Notice that these use the definitions from the system
2316     * headers instead of the gem5 headers and libraries. If the host and
2317     * target have different header file definitions, this will not work.
2318     */
2319    fd_set rd_h;
2320    FD_ZERO(&rd_h);
2321    fd_set wr_h;
2322    FD_ZERO(&wr_h);
2323    fd_set ex_h;
2324    FD_ZERO(&ex_h);
2325
2326    /**
2327     * Copy in the fd_set from the target.
2328     */
2329    if (fds_read_ptr)
2330        rd_t.copyIn(tc->getMemProxy());
2331    if (fds_writ_ptr)
2332        wr_t.copyIn(tc->getMemProxy());
2333    if (fds_excp_ptr)
2334        ex_t.copyIn(tc->getMemProxy());
2335
2336    /**
2337     * We need to translate the target file descriptor set into a host file
2338     * descriptor set. This involves both our internal process fd array
2339     * and the fd_set defined in Linux header files. The nfds field also
2340     * needs to be updated as it will be only target specific after
2341     * retrieving it from the target; the nfds value is expected to be the
2342     * highest file descriptor that needs to be checked, so we need to extend
2343     * it out for nfds_h when we do the update.
2344     */
2345    int nfds_h = 0;
2346    std::map<int, int> trans_map;
2347    auto try_add_host_set = [&](fd_set *tgt_set_entry,
2348                                fd_set *hst_set_entry,
2349                                int iter) -> bool
2350    {
2351        /**
2352         * By this point, we know that we are looking at a valid file
2353         * descriptor set on the target. We need to check if the target file
2354         * descriptor value passed in as iter is part of the set.
2355         */
2356        if (FD_ISSET(iter, tgt_set_entry)) {
2357            /**
2358             * We know that the target file descriptor belongs to the set,
2359             * but we do not yet know if the file descriptor is valid or
2360             * that we have a host mapping. Check that now.
2361             */
2362            auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[iter]);
2363            if (!hbfdp)
2364                return true;
2365            auto sim_fd = hbfdp->getSimFD();
2366
2367            /**
2368             * Add the sim_fd to tgt_fd translation into trans_map for use
2369             * later when we need to zero the target fd_set structures and
2370             * then update them with hits returned from the host select call.
2371             */
2372            trans_map[sim_fd] = iter;
2373
2374            /**
2375             * We know that the host file descriptor exists so now we check
2376             * if we need to update the max count for nfds_h before passing
2377             * the duplicated structure into the host.
2378             */
2379            nfds_h = std::max(nfds_h - 1, sim_fd + 1);
2380
2381            /**
2382             * Add the host file descriptor to the set that we are going to
2383             * pass into the host.
2384             */
2385            FD_SET(sim_fd, hst_set_entry);
2386        }
2387        return false;
2388    };
2389
2390    for (int i = 0; i < nfds_t; i++) {
2391        if (fds_read_ptr) {
2392            bool ebadf = try_add_host_set((fd_set*)&*rd_t, &rd_h, i);
2393            if (ebadf) return -EBADF;
2394        }
2395        if (fds_writ_ptr) {
2396            bool ebadf = try_add_host_set((fd_set*)&*wr_t, &wr_h, i);
2397            if (ebadf) return -EBADF;
2398        }
2399        if (fds_excp_ptr) {
2400            bool ebadf = try_add_host_set((fd_set*)&*ex_t, &ex_h, i);
2401            if (ebadf) return -EBADF;
2402        }
2403    }
2404
2405    if (time_val_ptr) {
2406        /**
2407         * It might be possible to decrement the timeval based on some
2408         * derivation of wall clock determined from elapsed simulator ticks
2409         * but that seems like overkill. Rather, we just set the timeval with
2410         * zero timeout. (There is no reason to block during the simulation
2411         * as it only decreases simulator performance.)
2412         */
2413        tp->tv_sec = 0;
2414        tp->tv_usec = 0;
2415
2416        retval = select(nfds_h,
2417                        fds_read_ptr ? &rd_h : nullptr,
2418                        fds_writ_ptr ? &wr_h : nullptr,
2419                        fds_excp_ptr ? &ex_h : nullptr,
2420                        (timeval*)&*tp);
2421    } else {
2422        /**
2423         * If the timeval pointer is null, setup a new timeval structure to
2424         * pass into the host select call. Unfortunately, we will need to
2425         * manually check the return value and throw a retry fault if the
2426         * return value is zero. Allowing the system call to block will
2427         * likely deadlock the event queue.
2428         */
2429        struct timeval tv = { 0, 0 };
2430
2431        retval = select(nfds_h,
2432                        fds_read_ptr ? &rd_h : nullptr,
2433                        fds_writ_ptr ? &wr_h : nullptr,
2434                        fds_excp_ptr ? &ex_h : nullptr,
2435                        &tv);
2436
2437        if (retval == 0) {
2438            /**
2439             * If blocking indefinitely, check the signal list to see if a
2440             * signal would break the poll out of the retry cycle and try to
2441             * return the signal interrupt instead.
2442             */
2443            for (auto sig : tc->getSystemPtr()->signalList)
2444                if (sig.receiver == p)
2445                    return -EINTR;
2446            return SyscallReturn::retry();
2447        }
2448    }
2449
2450    if (retval == -1)
2451        return -errno;
2452
2453    FD_ZERO((fd_set*)&*rd_t);
2454    FD_ZERO((fd_set*)&*wr_t);
2455    FD_ZERO((fd_set*)&*ex_t);
2456
2457    /**
2458     * We need to translate the host file descriptor set into a target file
2459     * descriptor set. This involves both our internal process fd array
2460     * and the fd_set defined in header files.
2461     */
2462    for (int i = 0; i < nfds_h; i++) {
2463        if (fds_read_ptr) {
2464            if (FD_ISSET(i, &rd_h))
2465                FD_SET(trans_map[i], (fd_set*)&*rd_t);
2466        }
2467
2468        if (fds_writ_ptr) {
2469            if (FD_ISSET(i, &wr_h))
2470                FD_SET(trans_map[i], (fd_set*)&*wr_t);
2471        }
2472
2473        if (fds_excp_ptr) {
2474            if (FD_ISSET(i, &ex_h))
2475                FD_SET(trans_map[i], (fd_set*)&*ex_t);
2476        }
2477    }
2478
2479    if (fds_read_ptr)
2480        rd_t.copyOut(tc->getMemProxy());
2481    if (fds_writ_ptr)
2482        wr_t.copyOut(tc->getMemProxy());
2483    if (fds_excp_ptr)
2484        ex_t.copyOut(tc->getMemProxy());
2485    if (time_val_ptr)
2486        tp.copyOut(tc->getMemProxy());
2487
2488    return retval;
2489}
2490
2491template <class OS>
2492SyscallReturn
2493readFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2494{
2495    int index = 0;
2496    int tgt_fd = p->getSyscallArg(tc, index);
2497    Addr buf_ptr = p->getSyscallArg(tc, index);
2498    int nbytes = p->getSyscallArg(tc, index);
2499
2500    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2501    if (!hbfdp)
2502        return -EBADF;
2503    int sim_fd = hbfdp->getSimFD();
2504
2505    struct pollfd pfd;
2506    pfd.fd = sim_fd;
2507    pfd.events = POLLIN | POLLPRI;
2508    if ((poll(&pfd, 1, 0) == 0)
2509        && !(hbfdp->getFlags() & OS::TGT_O_NONBLOCK))
2510        return SyscallReturn::retry();
2511
2512    BufferArg buf_arg(buf_ptr, nbytes);
2513    int bytes_read = read(sim_fd, buf_arg.bufferPtr(), nbytes);
2514
2515    if (bytes_read > 0)
2516        buf_arg.copyOut(tc->getMemProxy());
2517
2518    return (bytes_read == -1) ? -errno : bytes_read;
2519}
2520
2521template <class OS>
2522SyscallReturn
2523writeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2524{
2525    int index = 0;
2526    int tgt_fd = p->getSyscallArg(tc, index);
2527    Addr buf_ptr = p->getSyscallArg(tc, index);
2528    int nbytes = p->getSyscallArg(tc, index);
2529
2530    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2531    if (!hbfdp)
2532        return -EBADF;
2533    int sim_fd = hbfdp->getSimFD();
2534
2535    BufferArg buf_arg(buf_ptr, nbytes);
2536    buf_arg.copyIn(tc->getMemProxy());
2537
2538    struct pollfd pfd;
2539    pfd.fd = sim_fd;
2540    pfd.events = POLLOUT;
2541
2542    /**
2543     * We don't want to poll on /dev/random. The kernel will not enable the
2544     * file descriptor for writing unless the entropy in the system falls
2545     * below write_wakeup_threshold. This is not guaranteed to happen
2546     * depending on host settings.
2547     */
2548    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(hbfdp);
2549    if (ffdp && (ffdp->getFileName() != "/dev/random")) {
2550        if (!poll(&pfd, 1, 0) && !(ffdp->getFlags() & OS::TGT_O_NONBLOCK))
2551            return SyscallReturn::retry();
2552    }
2553
2554    int bytes_written = write(sim_fd, buf_arg.bufferPtr(), nbytes);
2555
2556    if (bytes_written != -1)
2557        fsync(sim_fd);
2558
2559    return (bytes_written == -1) ? -errno : bytes_written;
2560}
2561
2562template <class OS>
2563SyscallReturn
2564wait4Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2565{
2566    int index = 0;
2567    pid_t pid = p->getSyscallArg(tc, index);
2568    Addr statPtr = p->getSyscallArg(tc, index);
2569    int options = p->getSyscallArg(tc, index);
2570    Addr rusagePtr = p->getSyscallArg(tc, index);
2571
2572    if (rusagePtr)
2573        DPRINTFR(SyscallVerbose,
2574                 "%d: %s: syscall wait4: rusage pointer provided however "
2575                 "functionality not supported. Ignoring rusage pointer.\n",
2576                 curTick(), tc->getCpuPtr()->name());
2577
2578    /**
2579     * Currently, wait4 is only implemented so that it will wait for children
2580     * exit conditions which are denoted by a SIGCHLD signals posted into the
2581     * system signal list. We return no additional information via any of the
2582     * parameters supplied to wait4. If nothing is found in the system signal
2583     * list, we will wait indefinitely for SIGCHLD to post by retrying the
2584     * call.
2585     */
2586    System *sysh = tc->getSystemPtr();
2587    std::list<BasicSignal>::iterator iter;
2588    for (iter=sysh->signalList.begin(); iter!=sysh->signalList.end(); iter++) {
2589        if (iter->receiver == p) {
2590            if (pid < -1) {
2591                if ((iter->sender->pgid() == -pid)
2592                    && (iter->signalValue == OS::TGT_SIGCHLD))
2593                    goto success;
2594            } else if (pid == -1) {
2595                if (iter->signalValue == OS::TGT_SIGCHLD)
2596                    goto success;
2597            } else if (pid == 0) {
2598                if ((iter->sender->pgid() == p->pgid())
2599                    && (iter->signalValue == OS::TGT_SIGCHLD))
2600                    goto success;
2601            } else {
2602                if ((iter->sender->pid() == pid)
2603                    && (iter->signalValue == OS::TGT_SIGCHLD))
2604                    goto success;
2605            }
2606        }
2607    }
2608
2609    return (options & OS::TGT_WNOHANG) ? 0 : SyscallReturn::retry();
2610
2611success:
2612    // Set status to EXITED for WIFEXITED evaluations.
2613    const int EXITED = 0;
2614    BufferArg statusBuf(statPtr, sizeof(int));
2615    *(int *)statusBuf.bufferPtr() = EXITED;
2616    statusBuf.copyOut(tc->getMemProxy());
2617
2618    // Return the child PID.
2619    pid_t retval = iter->sender->pid();
2620    sysh->signalList.erase(iter);
2621    return retval;
2622}
2623
2624template <class OS>
2625SyscallReturn
2626acceptFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2627{
2628    struct sockaddr sa;
2629    socklen_t addrLen;
2630    int host_fd;
2631    int index = 0;
2632    int tgt_fd = p->getSyscallArg(tc, index);
2633    Addr addrPtr = p->getSyscallArg(tc, index);
2634    Addr lenPtr = p->getSyscallArg(tc, index);
2635
2636    BufferArg *lenBufPtr = nullptr;
2637    BufferArg *addrBufPtr = nullptr;
2638
2639    auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
2640    if (!sfdp)
2641        return -EBADF;
2642    int sim_fd = sfdp->getSimFD();
2643
2644    /**
2645     * We poll the socket file descriptor first to guarantee that we do not
2646     * block on our accept call. The socket can be opened without the
2647     * non-blocking flag (it blocks). This will cause deadlocks between
2648     * communicating processes.
2649     */
2650    struct pollfd pfd;
2651    pfd.fd = sim_fd;
2652    pfd.events = POLLIN | POLLPRI;
2653    if ((poll(&pfd, 1, 0) == 0)
2654        && !(sfdp->getFlags() & OS::TGT_O_NONBLOCK))
2655        return SyscallReturn::retry();
2656
2657    if (lenPtr) {
2658        lenBufPtr = new BufferArg(lenPtr, sizeof(socklen_t));
2659        lenBufPtr->copyIn(tc->getMemProxy());
2660        memcpy(&addrLen, (socklen_t *)lenBufPtr->bufferPtr(),
2661               sizeof(socklen_t));
2662    }
2663
2664    if (addrPtr) {
2665        addrBufPtr = new BufferArg(addrPtr, sizeof(struct sockaddr));
2666        addrBufPtr->copyIn(tc->getMemProxy());
2667        memcpy(&sa, (struct sockaddr *)addrBufPtr->bufferPtr(),
2668               sizeof(struct sockaddr));
2669    }
2670
2671    host_fd = accept(sim_fd, &sa, &addrLen);
2672
2673    if (host_fd == -1)
2674        return -errno;
2675
2676    if (addrPtr) {
2677        memcpy(addrBufPtr->bufferPtr(), &sa, sizeof(sa));
2678        addrBufPtr->copyOut(tc->getMemProxy());
2679        delete(addrBufPtr);
2680    }
2681
2682    if (lenPtr) {
2683        *(socklen_t *)lenBufPtr->bufferPtr() = addrLen;
2684        lenBufPtr->copyOut(tc->getMemProxy());
2685        delete(lenBufPtr);
2686    }
2687
2688    auto afdp = std::make_shared<SocketFDEntry>(host_fd, sfdp->_domain,
2689                                                sfdp->_type, sfdp->_protocol);
2690    return p->fds->allocFD(afdp);
2691}
2692
2693#endif // __SIM_SYSCALL_EMUL_HH__
2694