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