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