syscall_emul.hh revision 13534:6068637fc0c0
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    ctc->pcState(tc->nextInstAddr());
1406    ctc->activate();
1407
1408    return cp->pid();
1409}
1410
1411/// Target fstatfs() handler.
1412template <class OS>
1413SyscallReturn
1414fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1415{
1416    int index = 0;
1417    int tgt_fd = p->getSyscallArg(tc, index);
1418    Addr bufPtr = p->getSyscallArg(tc, index);
1419
1420    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1421    if (!ffdp)
1422        return -EBADF;
1423    int sim_fd = ffdp->getSimFD();
1424
1425    struct statfs hostBuf;
1426    int result = fstatfs(sim_fd, &hostBuf);
1427
1428    if (result < 0)
1429        return -errno;
1430
1431    copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1432
1433    return 0;
1434}
1435
1436
1437/// Target writev() handler.
1438template <class OS>
1439SyscallReturn
1440writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1441{
1442    int index = 0;
1443    int tgt_fd = p->getSyscallArg(tc, index);
1444
1445    auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1446    if (!hbfdp)
1447        return -EBADF;
1448    int sim_fd = hbfdp->getSimFD();
1449
1450    SETranslatingPortProxy &prox = tc->getMemProxy();
1451    uint64_t tiov_base = p->getSyscallArg(tc, index);
1452    size_t count = p->getSyscallArg(tc, index);
1453    struct iovec hiov[count];
1454    for (size_t i = 0; i < count; ++i) {
1455        typename OS::tgt_iovec tiov;
1456
1457        prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1458                      (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1459        hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1460        hiov[i].iov_base = new char [hiov[i].iov_len];
1461        prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1462                      hiov[i].iov_len);
1463    }
1464
1465    int result = writev(sim_fd, hiov, count);
1466
1467    for (size_t i = 0; i < count; ++i)
1468        delete [] (char *)hiov[i].iov_base;
1469
1470    if (result < 0)
1471        return -errno;
1472
1473    return result;
1474}
1475
1476/// Real mmap handler.
1477template <class OS>
1478SyscallReturn
1479mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1480         bool is_mmap2)
1481{
1482    int index = 0;
1483    Addr start = p->getSyscallArg(tc, index);
1484    uint64_t length = p->getSyscallArg(tc, index);
1485    int prot = p->getSyscallArg(tc, index);
1486    int tgt_flags = p->getSyscallArg(tc, index);
1487    int tgt_fd = p->getSyscallArg(tc, index);
1488    int offset = p->getSyscallArg(tc, index);
1489
1490    if (is_mmap2)
1491        offset *= TheISA::PageBytes;
1492
1493    if (start & (TheISA::PageBytes - 1) ||
1494        offset & (TheISA::PageBytes - 1) ||
1495        (tgt_flags & OS::TGT_MAP_PRIVATE &&
1496         tgt_flags & OS::TGT_MAP_SHARED) ||
1497        (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1498         !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1499        !length) {
1500        return -EINVAL;
1501    }
1502
1503    if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1504        // With shared mmaps, there are two cases to consider:
1505        // 1) anonymous: writes should modify the mapping and this should be
1506        // visible to observers who share the mapping. Currently, it's
1507        // difficult to update the shared mapping because there's no
1508        // structure which maintains information about the which virtual
1509        // memory areas are shared. If that structure existed, it would be
1510        // possible to make the translations point to the same frames.
1511        // 2) file-backed: writes should modify the mapping and the file
1512        // which is backed by the mapping. The shared mapping problem is the
1513        // same as what was mentioned about the anonymous mappings. For
1514        // file-backed mappings, the writes to the file are difficult
1515        // because it requires syncing what the mapping holds with the file
1516        // that resides on the host system. So, any write on a real system
1517        // would cause the change to be propagated to the file mapping at
1518        // some point in the future (the inode is tracked along with the
1519        // mapping). This isn't guaranteed to always happen, but it usually
1520        // works well enough. The guarantee is provided by the msync system
1521        // call. We could force the change through with shared mappings with
1522        // a call to msync, but that again would require more information
1523        // than we currently maintain.
1524        warn("mmap: writing to shared mmap region is currently "
1525             "unsupported. The write succeeds on the target, but it "
1526             "will not be propagated to the host or shared mappings");
1527    }
1528
1529    length = roundUp(length, TheISA::PageBytes);
1530
1531    int sim_fd = -1;
1532    uint8_t *pmap = nullptr;
1533    if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1534        std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1535
1536        auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1537        if (dfdp) {
1538            EmulatedDriver *emul_driver = dfdp->getDriver();
1539            return emul_driver->mmap(p, tc, start, length, prot,
1540                                     tgt_flags, tgt_fd, offset);
1541        }
1542
1543        auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1544        if (!ffdp)
1545            return -EBADF;
1546        sim_fd = ffdp->getSimFD();
1547
1548        pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1549                                    sim_fd, offset);
1550
1551        if (pmap == (decltype(pmap))-1) {
1552            warn("mmap: failed to map file into host address space");
1553            return -errno;
1554        }
1555    }
1556
1557    // Extend global mmap region if necessary. Note that we ignore the
1558    // start address unless MAP_FIXED is specified.
1559    if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1560        std::shared_ptr<MemState> mem_state = p->memState;
1561        Addr mmap_end = mem_state->getMmapEnd();
1562
1563        start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1564        mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1565
1566        mem_state->setMmapEnd(mmap_end);
1567    }
1568
1569    DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1570                    start, start + length - 1);
1571
1572    // We only allow mappings to overwrite existing mappings if
1573    // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1574    // because we ignore the start hint if TGT_MAP_FIXED is not set.
1575    int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1576    if (clobber) {
1577        for (auto tc : p->system->threadContexts) {
1578            // If we might be overwriting old mappings, we need to
1579            // invalidate potentially stale mappings out of the TLBs.
1580            tc->getDTBPtr()->flushAll();
1581            tc->getITBPtr()->flushAll();
1582        }
1583    }
1584
1585    // Allocate physical memory and map it in. If the page table is already
1586    // mapped and clobber is not set, the simulator will issue throw a
1587    // fatal and bail out of the simulation.
1588    p->allocateMem(start, length, clobber);
1589
1590    // Transfer content into target address space.
1591    SETranslatingPortProxy &tp = tc->getMemProxy();
1592    if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1593        // In general, we should zero the mapped area for anonymous mappings,
1594        // with something like:
1595        //     tp.memsetBlob(start, 0, length);
1596        // However, given that we don't support sparse mappings, and
1597        // some applications can map a couple of gigabytes of space
1598        // (intending sparse usage), that can get painfully expensive.
1599        // Fortunately, since we don't properly implement munmap either,
1600        // there's no danger of remapping used memory, so for now all
1601        // newly mapped memory should already be zeroed so we can skip it.
1602    } else {
1603        // It is possible to mmap an area larger than a file, however
1604        // accessing unmapped portions the system triggers a "Bus error"
1605        // on the host. We must know when to stop copying the file from
1606        // the host into the target address space.
1607        struct stat file_stat;
1608        if (fstat(sim_fd, &file_stat) > 0)
1609            fatal("mmap: cannot stat file");
1610
1611        // Copy the portion of the file that is resident. This requires
1612        // checking both the mmap size and the filesize that we are
1613        // trying to mmap into this space; the mmap size also depends
1614        // on the specified offset into the file.
1615        uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1616                                 length);
1617        tp.writeBlob(start, pmap, size);
1618
1619        // Cleanup the mmap region before exiting this function.
1620        munmap(pmap, length);
1621
1622        // Maintain the symbol table for dynamic executables.
1623        // The loader will call mmap to map the images into its address
1624        // space and we intercept that here. We can verify that we are
1625        // executing inside the loader by checking the program counter value.
1626        // XXX: with multiprogrammed workloads or multi-node configurations,
1627        // this will not work since there is a single global symbol table.
1628        ObjectFile *interpreter = p->getInterpreter();
1629        if (interpreter) {
1630            Addr text_start = interpreter->textBase();
1631            Addr text_end = text_start + interpreter->textSize();
1632
1633            Addr pc = tc->pcState().pc();
1634
1635            if (pc >= text_start && pc < text_end) {
1636                std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1637                auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1638                ObjectFile *lib = createObjectFile(ffdp->getFileName());
1639
1640                if (lib) {
1641                    lib->loadAllSymbols(debugSymbolTable,
1642                                        lib->textBase(), start);
1643                }
1644            }
1645        }
1646
1647        // Note that we do not zero out the remainder of the mapping. This
1648        // is done by a real system, but it probably will not affect
1649        // execution (hopefully).
1650    }
1651
1652    return start;
1653}
1654
1655template <class OS>
1656SyscallReturn
1657pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1658{
1659    int index = 0;
1660    int tgt_fd = p->getSyscallArg(tc, index);
1661    Addr bufPtr = p->getSyscallArg(tc, index);
1662    int nbytes = p->getSyscallArg(tc, index);
1663    int offset = p->getSyscallArg(tc, index);
1664
1665    auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1666    if (!ffdp)
1667        return -EBADF;
1668    int sim_fd = ffdp->getSimFD();
1669
1670    BufferArg bufArg(bufPtr, nbytes);
1671    bufArg.copyIn(tc->getMemProxy());
1672
1673    int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1674
1675    return (bytes_written == -1) ? -errno : bytes_written;
1676}
1677
1678/// Target mmap() handler.
1679template <class OS>
1680SyscallReturn
1681mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1682{
1683    return mmapImpl<OS>(desc, num, p, tc, false);
1684}
1685
1686/// Target mmap2() handler.
1687template <class OS>
1688SyscallReturn
1689mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1690{
1691    return mmapImpl<OS>(desc, num, p, tc, true);
1692}
1693
1694/// Target getrlimit() handler.
1695template <class OS>
1696SyscallReturn
1697getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1698              ThreadContext *tc)
1699{
1700    int index = 0;
1701    unsigned resource = process->getSyscallArg(tc, index);
1702    TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1703
1704    switch (resource) {
1705      case OS::TGT_RLIMIT_STACK:
1706        // max stack size in bytes: make up a number (8MB for now)
1707        rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1708        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1709        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1710        break;
1711
1712      case OS::TGT_RLIMIT_DATA:
1713        // max data segment size in bytes: make up a number
1714        rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1715        rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1716        rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1717        break;
1718
1719      default:
1720        warn("getrlimit: unimplemented resource %d", resource);
1721        return -EINVAL;
1722        break;
1723    }
1724
1725    rlp.copyOut(tc->getMemProxy());
1726    return 0;
1727}
1728
1729template <class OS>
1730SyscallReturn
1731prlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1732            ThreadContext *tc)
1733{
1734    int index = 0;
1735    if (process->getSyscallArg(tc, index) != 0)
1736    {
1737        warn("prlimit: ignoring rlimits for nonzero pid");
1738        return -EPERM;
1739    }
1740    int resource = process->getSyscallArg(tc, index);
1741    Addr n = process->getSyscallArg(tc, index);
1742    if (n != 0)
1743        warn("prlimit: ignoring new rlimit");
1744    Addr o = process->getSyscallArg(tc, index);
1745    if (o != 0)
1746    {
1747        TypedBufferArg<typename OS::rlimit> rlp(o);
1748        switch (resource) {
1749          case OS::TGT_RLIMIT_STACK:
1750            // max stack size in bytes: make up a number (8MB for now)
1751            rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1752            rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1753            rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1754            break;
1755          case OS::TGT_RLIMIT_DATA:
1756            // max data segment size in bytes: make up a number
1757            rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
1758            rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1759            rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1760            break;
1761          default:
1762            warn("prlimit: unimplemented resource %d", resource);
1763            return -EINVAL;
1764            break;
1765        }
1766        rlp.copyOut(tc->getMemProxy());
1767    }
1768    return 0;
1769}
1770
1771/// Target clock_gettime() function.
1772template <class OS>
1773SyscallReturn
1774clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1775{
1776    int index = 1;
1777    //int clk_id = p->getSyscallArg(tc, index);
1778    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1779
1780    getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1781    tp->tv_sec += seconds_since_epoch;
1782    tp->tv_sec = TheISA::htog(tp->tv_sec);
1783    tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1784
1785    tp.copyOut(tc->getMemProxy());
1786
1787    return 0;
1788}
1789
1790/// Target clock_getres() function.
1791template <class OS>
1792SyscallReturn
1793clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1794{
1795    int index = 1;
1796    TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1797
1798    // Set resolution at ns, which is what clock_gettime() returns
1799    tp->tv_sec = 0;
1800    tp->tv_nsec = 1;
1801
1802    tp.copyOut(tc->getMemProxy());
1803
1804    return 0;
1805}
1806
1807/// Target gettimeofday() handler.
1808template <class OS>
1809SyscallReturn
1810gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1811                 ThreadContext *tc)
1812{
1813    int index = 0;
1814    TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1815
1816    getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1817    tp->tv_sec += seconds_since_epoch;
1818    tp->tv_sec = TheISA::htog(tp->tv_sec);
1819    tp->tv_usec = TheISA::htog(tp->tv_usec);
1820
1821    tp.copyOut(tc->getMemProxy());
1822
1823    return 0;
1824}
1825
1826
1827/// Target utimes() handler.
1828template <class OS>
1829SyscallReturn
1830utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1831           ThreadContext *tc)
1832{
1833    std::string path;
1834
1835    int index = 0;
1836    if (!tc->getMemProxy().tryReadString(path,
1837                process->getSyscallArg(tc, index))) {
1838        return -EFAULT;
1839    }
1840
1841    TypedBufferArg<typename OS::timeval [2]>
1842        tp(process->getSyscallArg(tc, index));
1843    tp.copyIn(tc->getMemProxy());
1844
1845    struct timeval hostTimeval[2];
1846    for (int i = 0; i < 2; ++i) {
1847        hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1848        hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1849    }
1850
1851    // Adjust path for current working directory
1852    path = process->fullPath(path);
1853
1854    int result = utimes(path.c_str(), hostTimeval);
1855
1856    if (result < 0)
1857        return -errno;
1858
1859    return 0;
1860}
1861
1862template <class OS>
1863SyscallReturn
1864execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1865{
1866    desc->setFlags(0);
1867
1868    int index = 0;
1869    std::string path;
1870    SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
1871    if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
1872        return -EFAULT;
1873
1874    if (access(path.c_str(), F_OK) == -1)
1875        return -EACCES;
1876
1877    auto read_in = [](std::vector<std::string> & vect,
1878                      SETranslatingPortProxy & mem_proxy,
1879                      Addr mem_loc)
1880    {
1881        for (int inc = 0; ; inc++) {
1882            BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
1883            b.copyIn(mem_proxy);
1884
1885            if (!*(Addr*)b.bufferPtr())
1886                break;
1887
1888            vect.push_back(std::string());
1889            mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
1890        }
1891    };
1892
1893    /**
1894     * Note that ProcessParams is generated by swig and there are no other
1895     * examples of how to create anything but this default constructor. The
1896     * fields are manually initialized instead of passing parameters to the
1897     * constructor.
1898     */
1899    ProcessParams *pp = new ProcessParams();
1900    pp->executable = path;
1901    Addr argv_mem_loc = p->getSyscallArg(tc, index);
1902    read_in(pp->cmd, mem_proxy, argv_mem_loc);
1903    Addr envp_mem_loc = p->getSyscallArg(tc, index);
1904    read_in(pp->env, mem_proxy, envp_mem_loc);
1905    pp->uid = p->uid();
1906    pp->egid = p->egid();
1907    pp->euid = p->euid();
1908    pp->gid = p->gid();
1909    pp->ppid = p->ppid();
1910    pp->pid = p->pid();
1911    pp->input.assign("cin");
1912    pp->output.assign("cout");
1913    pp->errout.assign("cerr");
1914    pp->cwd.assign(p->getcwd());
1915    pp->system = p->system;
1916    /**
1917     * Prevent process object creation with identical PIDs (which will trip
1918     * a fatal check in Process constructor). The execve call is supposed to
1919     * take over the currently executing process' identity but replace
1920     * whatever it is doing with a new process image. Instead of hijacking
1921     * the process object in the simulator, we create a new process object
1922     * and bind to the previous process' thread below (hijacking the thread).
1923     */
1924    p->system->PIDs.erase(p->pid());
1925    Process *new_p = pp->create();
1926    delete pp;
1927
1928    /**
1929     * Work through the file descriptor array and close any files marked
1930     * close-on-exec.
1931     */
1932    new_p->fds = p->fds;
1933    for (int i = 0; i < new_p->fds->getSize(); i++) {
1934        std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
1935        if (fdep && fdep->getCOE())
1936            new_p->fds->closeFDEntry(i);
1937    }
1938
1939    *new_p->sigchld = true;
1940
1941    delete p;
1942    tc->clearArchRegs();
1943    tc->setProcessPtr(new_p);
1944    new_p->assignThreadContext(tc->contextId());
1945    new_p->initState();
1946    tc->activate();
1947    TheISA::PCState pcState = tc->pcState();
1948    tc->setNPC(pcState.instAddr());
1949
1950    desc->setFlags(SyscallDesc::SuppressReturnValue);
1951    return 0;
1952}
1953
1954/// Target getrusage() function.
1955template <class OS>
1956SyscallReturn
1957getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
1958              ThreadContext *tc)
1959{
1960    int index = 0;
1961    int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
1962    TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
1963
1964    rup->ru_utime.tv_sec = 0;
1965    rup->ru_utime.tv_usec = 0;
1966    rup->ru_stime.tv_sec = 0;
1967    rup->ru_stime.tv_usec = 0;
1968    rup->ru_maxrss = 0;
1969    rup->ru_ixrss = 0;
1970    rup->ru_idrss = 0;
1971    rup->ru_isrss = 0;
1972    rup->ru_minflt = 0;
1973    rup->ru_majflt = 0;
1974    rup->ru_nswap = 0;
1975    rup->ru_inblock = 0;
1976    rup->ru_oublock = 0;
1977    rup->ru_msgsnd = 0;
1978    rup->ru_msgrcv = 0;
1979    rup->ru_nsignals = 0;
1980    rup->ru_nvcsw = 0;
1981    rup->ru_nivcsw = 0;
1982
1983    switch (who) {
1984      case OS::TGT_RUSAGE_SELF:
1985        getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
1986        rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
1987        rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
1988        break;
1989
1990      case OS::TGT_RUSAGE_CHILDREN:
1991        // do nothing.  We have no child processes, so they take no time.
1992        break;
1993
1994      default:
1995        // don't really handle THREAD or CHILDREN, but just warn and
1996        // plow ahead
1997        warn("getrusage() only supports RUSAGE_SELF.  Parameter %d ignored.",
1998             who);
1999    }
2000
2001    rup.copyOut(tc->getMemProxy());
2002
2003    return 0;
2004}
2005
2006/// Target times() function.
2007template <class OS>
2008SyscallReturn
2009timesFunc(SyscallDesc *desc, int callnum, Process *process,
2010          ThreadContext *tc)
2011{
2012    int index = 0;
2013    TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
2014
2015    // Fill in the time structure (in clocks)
2016    int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
2017    bufp->tms_utime = clocks;
2018    bufp->tms_stime = 0;
2019    bufp->tms_cutime = 0;
2020    bufp->tms_cstime = 0;
2021
2022    // Convert to host endianness
2023    bufp->tms_utime = TheISA::htog(bufp->tms_utime);
2024
2025    // Write back
2026    bufp.copyOut(tc->getMemProxy());
2027
2028    // Return clock ticks since system boot
2029    return clocks;
2030}
2031
2032/// Target time() function.
2033template <class OS>
2034SyscallReturn
2035timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
2036{
2037    typename OS::time_t sec, usec;
2038    getElapsedTimeMicro(sec, usec);
2039    sec += seconds_since_epoch;
2040
2041    int index = 0;
2042    Addr taddr = (Addr)process->getSyscallArg(tc, index);
2043    if (taddr != 0) {
2044        typename OS::time_t t = sec;
2045        t = TheISA::htog(t);
2046        SETranslatingPortProxy &p = tc->getMemProxy();
2047        p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
2048    }
2049    return sec;
2050}
2051
2052template <class OS>
2053SyscallReturn
2054tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
2055{
2056    int index = 0;
2057    int tgid = process->getSyscallArg(tc, index);
2058    int tid = process->getSyscallArg(tc, index);
2059    int sig = process->getSyscallArg(tc, index);
2060
2061    /**
2062     * This system call is intended to allow killing a specific thread
2063     * within an arbitrary thread group if sanctioned with permission checks.
2064     * It's usually true that threads share the termination signal as pointed
2065     * out by the pthread_kill man page and this seems to be the intended
2066     * usage. Due to this being an emulated environment, assume the following:
2067     * Threads are allowed to call tgkill because the EUID for all threads
2068     * should be the same. There is no signal handling mechanism for kernel
2069     * registration of signal handlers since signals are poorly supported in
2070     * emulation mode. Since signal handlers cannot be registered, all
2071     * threads within in a thread group must share the termination signal.
2072     * We never exhaust PIDs so there's no chance of finding the wrong one
2073     * due to PID rollover.
2074     */
2075
2076    System *sys = tc->getSystemPtr();
2077    Process *tgt_proc = nullptr;
2078    for (int i = 0; i < sys->numContexts(); i++) {
2079        Process *temp = sys->threadContexts[i]->getProcessPtr();
2080        if (temp->pid() == tid) {
2081            tgt_proc = temp;
2082            break;
2083        }
2084    }
2085
2086    if (sig != 0 || sig != OS::TGT_SIGABRT)
2087        return -EINVAL;
2088
2089    if (tgt_proc == nullptr)
2090        return -ESRCH;
2091
2092    if (tgid != -1 && tgt_proc->tgid() != tgid)
2093        return -ESRCH;
2094
2095    if (sig == OS::TGT_SIGABRT)
2096        exitGroupFunc(desc, 252, process, tc);
2097
2098    return 0;
2099}
2100
2101
2102#endif // __SIM_SYSCALL_EMUL_HH__
2103