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