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