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