2 * Copyright (c) 2012-2013, 2015 ARM Limited
3 * Copyright (c) 2015 Advanced Micro Devices, Inc.
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.
15 * Copyright (c) 2003-2005 The Regents of The University of Michigan
16 * All rights reserved.
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.
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.
41 * Authors: Steve Reinhardt
45 #ifndef __SIM_SYSCALL_EMUL_HH__
46 #define __SIM_SYSCALL_EMUL_HH__
48 #define NO_STAT64 (defined(__APPLE__) || defined(__OpenBSD__) || \
49 defined(__FreeBSD__) || defined(__CYGWIN__) || \
52 #define NO_STATFS (defined(__APPLE__) || defined(__OpenBSD__) || \
53 defined(__FreeBSD__) || defined(__NetBSD__))
55 #define NO_FALLOCATE (defined(__APPLE__) || defined(__OpenBSD__) || \
56 defined(__FreeBSD__) || defined(__NetBSD__))
59 /// @file syscall_emul.hh
61 /// This file defines objects used to emulate syscalls from the target
62 /// application on the host machine.
65 #include <sys/fcntl.h>
72 #include <sys/statfs.h>
74 #include <sys/mount.h>
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"
103 //////////////////////////////////////////////////////////////////////
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.
109 //////////////////////////////////////////////////////////////////////
112 /// Handler for unimplemented syscalls that we haven't thought about.
113 SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
114 Process *p, ThreadContext *tc);
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.
120 SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
121 Process *p, ThreadContext *tc);
123 // Target fallocateFunc() handler.
124 SyscallReturn fallocateFunc(SyscallDesc *desc, int num,
125 Process *p, ThreadContext *tc);
127 /// Target exit() handler: terminate current context.
128 SyscallReturn exitFunc(SyscallDesc *desc, int num,
129 Process *p, ThreadContext *tc);
131 /// Target exit_group() handler: terminate simulation. (exit all threads)
132 SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
133 Process *p, ThreadContext *tc);
135 /// Target set_tid_address() handler.
136 SyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
137 Process *p, ThreadContext *tc);
139 /// Target getpagesize() handler.
140 SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
141 Process *p, ThreadContext *tc);
143 /// Target brk() handler: set brk address.
144 SyscallReturn brkFunc(SyscallDesc *desc, int num,
145 Process *p, ThreadContext *tc);
147 /// Target close() handler.
148 SyscallReturn closeFunc(SyscallDesc *desc, int num,
149 Process *p, ThreadContext *tc);
151 // Target read() handler.
152 SyscallReturn readFunc(SyscallDesc *desc, int num,
153 Process *p, ThreadContext *tc);
155 /// Target write() handler.
156 SyscallReturn writeFunc(SyscallDesc *desc, int num,
157 Process *p, ThreadContext *tc);
159 /// Target lseek() handler.
160 SyscallReturn lseekFunc(SyscallDesc *desc, int num,
161 Process *p, ThreadContext *tc);
163 /// Target _llseek() handler.
164 SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
165 Process *p, ThreadContext *tc);
167 /// Target munmap() handler.
168 SyscallReturn munmapFunc(SyscallDesc *desc, int num,
169 Process *p, ThreadContext *tc);
171 /// Target gethostname() handler.
172 SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
173 Process *p, ThreadContext *tc);
175 /// Target getcwd() handler.
176 SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
177 Process *p, ThreadContext *tc);
179 /// Target readlink() handler.
180 SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
181 Process *p, ThreadContext *tc,
183 SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
184 Process *p, ThreadContext *tc);
186 /// Target unlink() handler.
187 SyscallReturn unlinkHelper(SyscallDesc *desc, int num,
188 Process *p, ThreadContext *tc,
190 SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
191 Process *p, ThreadContext *tc);
193 /// Target mkdir() handler.
194 SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
195 Process *p, ThreadContext *tc);
197 /// Target rename() handler.
198 SyscallReturn renameFunc(SyscallDesc *desc, int num,
199 Process *p, ThreadContext *tc);
202 /// Target truncate() handler.
203 SyscallReturn truncateFunc(SyscallDesc *desc, int num,
204 Process *p, ThreadContext *tc);
207 /// Target ftruncate() handler.
208 SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
209 Process *p, ThreadContext *tc);
212 /// Target truncate64() handler.
213 SyscallReturn truncate64Func(SyscallDesc *desc, int num,
214 Process *p, ThreadContext *tc);
216 /// Target ftruncate64() handler.
217 SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
218 Process *p, ThreadContext *tc);
221 /// Target umask() handler.
222 SyscallReturn umaskFunc(SyscallDesc *desc, int num,
223 Process *p, ThreadContext *tc);
225 /// Target gettid() handler.
226 SyscallReturn gettidFunc(SyscallDesc *desc, int num,
227 Process *p, ThreadContext *tc);
229 /// Target chown() handler.
230 SyscallReturn chownFunc(SyscallDesc *desc, int num,
231 Process *p, ThreadContext *tc);
233 /// Target setpgid() handler.
234 SyscallReturn setpgidFunc(SyscallDesc *desc, int num,
235 Process *p, ThreadContext *tc);
237 /// Target fchown() handler.
238 SyscallReturn fchownFunc(SyscallDesc *desc, int num,
239 Process *p, ThreadContext *tc);
241 /// Target dup() handler.
242 SyscallReturn dupFunc(SyscallDesc *desc, int num,
243 Process *process, ThreadContext *tc);
245 /// Target dup2() handler.
246 SyscallReturn dup2Func(SyscallDesc *desc, int num,
247 Process *process, ThreadContext *tc);
249 /// Target fcntl() handler.
250 SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
251 Process *process, ThreadContext *tc);
253 /// Target fcntl64() handler.
254 SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
255 Process *process, ThreadContext *tc);
257 /// Target setuid() handler.
258 SyscallReturn setuidFunc(SyscallDesc *desc, int num,
259 Process *p, ThreadContext *tc);
261 /// Target pipe() handler.
262 SyscallReturn pipeFunc(SyscallDesc *desc, int num,
263 Process *p, ThreadContext *tc);
265 /// Internal pipe() handler.
266 SyscallReturn pipeImpl(SyscallDesc *desc, int num, Process *p,
267 ThreadContext *tc, bool pseudoPipe);
269 /// Target getpid() handler.
270 SyscallReturn getpidFunc(SyscallDesc *desc, int num,
271 Process *p, ThreadContext *tc);
273 /// Target getuid() handler.
274 SyscallReturn getuidFunc(SyscallDesc *desc, int num,
275 Process *p, ThreadContext *tc);
277 /// Target getgid() handler.
278 SyscallReturn getgidFunc(SyscallDesc *desc, int num,
279 Process *p, ThreadContext *tc);
281 /// Target getppid() handler.
282 SyscallReturn getppidFunc(SyscallDesc *desc, int num,
283 Process *p, ThreadContext *tc);
285 /// Target geteuid() handler.
286 SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
287 Process *p, ThreadContext *tc);
289 /// Target getegid() handler.
290 SyscallReturn getegidFunc(SyscallDesc *desc, int num,
291 Process *p, ThreadContext *tc);
293 /// Target access() handler
294 SyscallReturn accessFunc(SyscallDesc *desc, int num,
295 Process *p, ThreadContext *tc);
296 SyscallReturn accessFunc(SyscallDesc *desc, int num,
297 Process *p, ThreadContext *tc,
300 /// Futex system call
301 /// Implemented by Daniel Sanchez
302 /// Used by printf's in multi-threaded apps
305 futexFunc(SyscallDesc *desc, int callnum, Process *process,
311 Addr uaddr = process->getSyscallArg(tc, index);
312 int op = process->getSyscallArg(tc, index);
313 int val = process->getSyscallArg(tc, index);
316 * Unsupported option that does not affect the correctness of the
317 * application. This is a performance optimization utilized by Linux.
319 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
321 FutexMap &futex_map = tc->getSystemPtr()->futexMap;
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();
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.
335 return -OS::TGT_EWOULDBLOCK;
337 futex_map.suspend(uaddr, process->tgid(), tc);
340 } else if (OS::TGT_FUTEX_WAKE == op) {
341 return futex_map.wakeup(uaddr, process->tgid(), val);
344 warn("futex: op %d not implemented; ignoring.", op);
349 /// Pseudo Funcs - These functions use a different return convension,
350 /// returning a second value in a register other than the normal return register
351 SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
352 Process *process, ThreadContext *tc);
354 /// Target getpidPseudo() handler.
355 SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
356 Process *p, ThreadContext *tc);
358 /// Target getuidPseudo() handler.
359 SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
360 Process *p, ThreadContext *tc);
362 /// Target getgidPseudo() handler.
363 SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
364 Process *p, ThreadContext *tc);
367 /// A readable name for 1,000,000, for converting microseconds to seconds.
368 const int one_million = 1000000;
369 /// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
370 const int one_billion = 1000000000;
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.
375 const unsigned seconds_since_epoch = 1000000000;
377 /// Helper function to convert current elapsed time to seconds and
379 template <class T1, class T2>
381 getElapsedTimeMicro(T1 &sec, T2 &usec)
383 uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
384 sec = elapsed_usecs / one_million;
385 usec = elapsed_usecs % one_million;
388 /// Helper function to convert current elapsed time to seconds and
390 template <class T1, class T2>
392 getElapsedTimeNano(T1 &sec, T2 &nsec)
394 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
395 sec = elapsed_nsecs / one_billion;
396 nsec = elapsed_nsecs % one_billion;
399 //////////////////////////////////////////////////////////////////////
401 // The following emulation functions are generic, but need to be
402 // templated to account for differences in types, constants, etc.
404 //////////////////////////////////////////////////////////////////////
406 typedef struct statfs hst_statfs;
408 typedef struct stat hst_stat;
409 typedef struct stat hst_stat64;
411 typedef struct stat hst_stat;
412 typedef struct stat64 hst_stat64;
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().
419 template <typename target_stat, typename host_stat>
421 convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
423 using namespace TheISA;
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;
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
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);
446 tgt->st_rdev = 0x880d;
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);
468 template <typename target_stat, typename host_stat64>
470 convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
472 using namespace TheISA;
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);
483 tgt->st_atime_nsec = 0;
484 tgt->st_mtime_nsec = 0;
485 tgt->st_ctime_nsec = 0;
489 // Here are a couple of convenience functions
492 copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
493 hst_stat *host, bool fakeTTY = false)
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);
503 copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
504 hst_stat64 *host, bool fakeTTY = false)
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);
514 copyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
517 TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
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);
523 tgt->f_bsize = TheISA::htog(host->f_bsize);
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__)
538 tgt->f_namelen = TheISA::htog(host->f_namelen);
539 tgt->f_frsize = TheISA::htog(host->f_frsize);
541 #if defined(__linux__)
542 memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
545 * The fields are different sizes per OS. Don't bother with
546 * f_spare or f_reserved on non-Linux for now.
548 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
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.
560 ioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
563 int tgt_fd = p->getSyscallArg(tc, index);
564 unsigned req = p->getSyscallArg(tc, index);
566 DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
568 if (OS::isTtyReq(req))
571 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
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.
580 EmulatedDriver *emul_driver = dfdp->getDriver();
582 return emul_driver->ioctl(p, tc, req);
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.
588 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
589 tgt_fd, req, tc->pcState());
595 openImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
602 * If using the openat variant, read in the target directory file
603 * descriptor from the simulated process.
606 tgt_dirfd = p->getSyscallArg(tc, index);
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.
613 if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
617 int host_flags = O_BINARY;
622 * Translate target flags into host flags. Flags exist which are not
623 * ported between architectures which can cause check failures.
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;
633 warn("open%s: cannot decode flags 0x%x",
634 isopenat ? "at" : "", tgt_flags);
637 host_flags |= O_BINARY;
640 int mode = p->getSyscallArg(tc, index);
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.
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);
661 path.insert(0, ffdp->getFileName());
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.
670 if (startswith(path, "/dev/")) {
671 std::string filename = path.substr(strlen("/dev/"));
672 EmulatedDriver *drv = p->findDriver(filename);
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);
680 * Fall through here for pass through to host devices, such
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.
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);
702 sim_fd = open(path.c_str(), host_flags, mode);
706 DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s\n",
707 isopenat ? "at" : "", path.c_str());
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
716 * Return the indirect target file descriptor back to the simulated
717 * process to act as a handle for the opened file.
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());
726 /// Target open() handler.
729 openFunc(SyscallDesc *desc, int callnum, Process *process,
732 return openImpl<OS>(desc, callnum, process, tc, false);
735 /// Target openat() handler.
738 openatFunc(SyscallDesc *desc, int callnum, Process *process,
741 return openImpl<OS>(desc, callnum, process, tc, true);
744 /// Target unlinkat() handler.
747 unlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
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");
755 return unlinkHelper(desc, callnum, process, tc, 1);
758 /// Target facessat() handler
761 faccessatFunc(SyscallDesc *desc, int callnum, Process *process,
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);
771 /// Target readlinkat() handler
774 readlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
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);
784 /// Target renameat() handler.
787 renameatFunc(SyscallDesc *desc, int callnum, Process *process,
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");
796 std::string old_name;
798 if (!tc->getMemProxy().tryReadString(old_name,
799 process->getSyscallArg(tc, index)))
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");
806 std::string new_name;
808 if (!tc->getMemProxy().tryReadString(new_name,
809 process->getSyscallArg(tc, index)))
812 // Adjust path for current working directory
813 old_name = process->fullPath(old_name);
814 new_name = process->fullPath(new_name);
816 int result = rename(old_name.c_str(), new_name.c_str());
817 return (result == -1) ? -errno : result;
820 /// Target sysinfo() handler.
823 sysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
828 TypedBufferArg<typename OS::tgt_sysinfo>
829 sysinfo(process->getSyscallArg(tc, index));
831 sysinfo->uptime = seconds_since_epoch;
832 sysinfo->totalram = process->system->memSize();
833 sysinfo->mem_unit = 1;
835 sysinfo.copyOut(tc->getMemProxy());
840 /// Target chmod() handler.
843 chmodFunc(SyscallDesc *desc, int callnum, Process *process,
849 if (!tc->getMemProxy().tryReadString(path,
850 process->getSyscallArg(tc, index))) {
854 uint32_t mode = process->getSyscallArg(tc, index);
857 // XXX translate mode flags via OS::something???
860 // Adjust path for current working directory
861 path = process->fullPath(path);
864 int result = chmod(path.c_str(), hostMode);
872 /// Target fchmod() handler.
875 fchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
878 int tgt_fd = p->getSyscallArg(tc, index);
879 uint32_t mode = p->getSyscallArg(tc, index);
881 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
884 int sim_fd = ffdp->getSimFD();
886 mode_t hostMode = mode;
888 int result = fchmod(sim_fd, hostMode);
890 return (result < 0) ? -errno : 0;
893 /// Target mremap() handler.
896 mremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
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;
906 if (use_provided_address)
907 provided_address = process->getSyscallArg(tc, index);
909 if ((start % TheISA::PageBytes != 0) ||
910 (provided_address % TheISA::PageBytes != 0)) {
911 warn("mremap failing: arguments not page aligned");
915 new_length = roundUp(new_length, TheISA::PageBytes);
917 if (new_length > old_length) {
918 std::shared_ptr<MemState> mem_state = process->memState;
919 Addr mmap_end = mem_state->getMmapEnd();
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);
928 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
929 warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
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");
950 warn("returning %08p as start\n", new_start);
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;
962 /// Target stat() handler.
965 statFunc(SyscallDesc *desc, int callnum, Process *process,
971 if (!tc->getMemProxy().tryReadString(path,
972 process->getSyscallArg(tc, index))) {
975 Addr bufPtr = process->getSyscallArg(tc, index);
977 // Adjust path for current working directory
978 path = process->fullPath(path);
981 int result = stat(path.c_str(), &hostBuf);
986 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
992 /// Target stat64() handler.
995 stat64Func(SyscallDesc *desc, int callnum, Process *process,
1001 if (!tc->getMemProxy().tryReadString(path,
1002 process->getSyscallArg(tc, index)))
1004 Addr bufPtr = process->getSyscallArg(tc, index);
1006 // Adjust path for current working directory
1007 path = process->fullPath(path);
1010 struct stat hostBuf;
1011 int result = stat(path.c_str(), &hostBuf);
1013 struct stat64 hostBuf;
1014 int result = stat64(path.c_str(), &hostBuf);
1020 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1026 /// Target fstatat64() handler.
1029 fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
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");
1038 if (!tc->getMemProxy().tryReadString(path,
1039 process->getSyscallArg(tc, index)))
1041 Addr bufPtr = process->getSyscallArg(tc, index);
1043 // Adjust path for current working directory
1044 path = process->fullPath(path);
1047 struct stat hostBuf;
1048 int result = stat(path.c_str(), &hostBuf);
1050 struct stat64 hostBuf;
1051 int result = stat64(path.c_str(), &hostBuf);
1057 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1063 /// Target fstat64() handler.
1066 fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1069 int tgt_fd = p->getSyscallArg(tc, index);
1070 Addr bufPtr = p->getSyscallArg(tc, index);
1072 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1075 int sim_fd = ffdp->getSimFD();
1078 struct stat hostBuf;
1079 int result = fstat(sim_fd, &hostBuf);
1081 struct stat64 hostBuf;
1082 int result = fstat64(sim_fd, &hostBuf);
1088 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1094 /// Target lstat() handler.
1097 lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1103 if (!tc->getMemProxy().tryReadString(path,
1104 process->getSyscallArg(tc, index))) {
1107 Addr bufPtr = process->getSyscallArg(tc, index);
1109 // Adjust path for current working directory
1110 path = process->fullPath(path);
1112 struct stat hostBuf;
1113 int result = lstat(path.c_str(), &hostBuf);
1118 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1123 /// Target lstat64() handler.
1126 lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1132 if (!tc->getMemProxy().tryReadString(path,
1133 process->getSyscallArg(tc, index))) {
1136 Addr bufPtr = process->getSyscallArg(tc, index);
1138 // Adjust path for current working directory
1139 path = process->fullPath(path);
1142 struct stat hostBuf;
1143 int result = lstat(path.c_str(), &hostBuf);
1145 struct stat64 hostBuf;
1146 int result = lstat64(path.c_str(), &hostBuf);
1152 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1157 /// Target fstat() handler.
1160 fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1163 int tgt_fd = p->getSyscallArg(tc, index);
1164 Addr bufPtr = p->getSyscallArg(tc, index);
1166 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1168 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1171 int sim_fd = ffdp->getSimFD();
1173 struct stat hostBuf;
1174 int result = fstat(sim_fd, &hostBuf);
1179 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1185 /// Target statfs() handler.
1188 statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1192 warn("Host OS cannot support calls to statfs. Ignoring syscall");
1197 if (!tc->getMemProxy().tryReadString(path,
1198 process->getSyscallArg(tc, index))) {
1201 Addr bufPtr = process->getSyscallArg(tc, index);
1203 // Adjust path for current working directory
1204 path = process->fullPath(path);
1206 struct statfs hostBuf;
1207 int result = statfs(path.c_str(), &hostBuf);
1212 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1219 cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
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);
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)))
1237 if (!(ctc = p->findFreeContext()))
1238 fatal("clone: no spare thread context in system");
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
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");
1255 pp->euid = p->euid();
1257 pp->egid = p->egid();
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();
1264 } while (pids.find(temp_pid) != pids.end());
1265 if (temp_pid >= System::maxPID)
1266 fatal("temp_pid is too large: %d", temp_pid);
1269 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1270 Process *cp = pp->create();
1273 Process *owner = ctc->getProcessPtr();
1274 ctc->setProcessPtr(cp);
1275 cp->assignThreadContext(ctc->contextId());
1276 owner->revokeThreadContext(ctc->contextId());
1278 if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1279 BufferArg ptidBuf(ptidPtr, sizeof(long));
1280 long *ptid = (long *)ptidBuf.bufferPtr();
1282 ptidBuf.copyOut(tc->getMemProxy());
1286 p->clone(tc, ctc, cp, flags);
1288 if (flags & OS::TGT_CLONE_THREAD) {
1290 cp->sigchld = p->sigchld;
1291 } else if (flags & OS::TGT_SIGCHLD) {
1292 *cp->sigchld = true;
1295 if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1296 BufferArg ctidBuf(ctidPtr, sizeof(long));
1297 long *ctid = (long *)ctidBuf.bufferPtr();
1299 ctidBuf.copyOut(ctc->getMemProxy());
1302 if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1303 cp->childClearTID = (uint64_t)ctidPtr;
1305 ctc->clearArchRegs();
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);
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);
1333 ctc->setIntReg(TheISA::StackPointerReg, newStack);
1335 cp->setSyscallReturn(ctc, 0);
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);
1344 ctc->pcState(tc->nextInstAddr());
1350 /// Target fstatfs() handler.
1353 fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1356 int tgt_fd = p->getSyscallArg(tc, index);
1357 Addr bufPtr = p->getSyscallArg(tc, index);
1359 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1362 int sim_fd = ffdp->getSimFD();
1364 struct statfs hostBuf;
1365 int result = fstatfs(sim_fd, &hostBuf);
1370 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1376 /// Target writev() handler.
1379 writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1382 int tgt_fd = p->getSyscallArg(tc, index);
1384 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1387 int sim_fd = hbfdp->getSimFD();
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;
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,
1404 int result = writev(sim_fd, hiov, count);
1406 for (size_t i = 0; i < count; ++i)
1407 delete [] (char *)hiov[i].iov_base;
1415 /// Real mmap handler.
1418 mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
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);
1430 offset *= TheISA::PageBytes;
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)) ||
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");
1468 length = roundUp(length, TheISA::PageBytes);
1471 uint8_t *pmap = nullptr;
1472 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1473 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1475 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1477 EmulatedDriver *emul_driver = dfdp->getDriver();
1478 return emul_driver->mmap(p, tc, start, length, prot,
1479 tgt_flags, tgt_fd, offset);
1482 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1485 sim_fd = ffdp->getSimFD();
1487 pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1490 if (pmap == (decltype(pmap))-1) {
1491 warn("mmap: failed to map file into host address space");
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();
1502 start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1503 mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1505 mem_state->setMmapEnd(mmap_end);
1508 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1509 start, start + length - 1);
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;
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();
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);
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.
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");
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,
1556 tp.writeBlob(start, pmap, size);
1558 // Cleanup the mmap region before exiting this function.
1559 munmap(pmap, length);
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();
1569 Addr text_start = interpreter->textBase();
1570 Addr text_end = text_start + interpreter->textSize();
1572 Addr pc = tc->pcState().pc();
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());
1580 lib->loadAllSymbols(debugSymbolTable,
1581 lib->textBase(), start);
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).
1596 pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
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);
1604 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1607 int sim_fd = ffdp->getSimFD();
1609 BufferArg bufArg(bufPtr, nbytes);
1610 bufArg.copyIn(tc->getMemProxy());
1612 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1614 return (bytes_written == -1) ? -errno : bytes_written;
1617 /// Target mmap() handler.
1620 mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1622 return mmapImpl<OS>(desc, num, p, tc, false);
1625 /// Target mmap2() handler.
1628 mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1630 return mmapImpl<OS>(desc, num, p, tc, true);
1633 /// Target getrlimit() handler.
1636 getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1640 unsigned resource = process->getSyscallArg(tc, index);
1641 TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
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);
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);
1659 warn("getrlimit: unimplemented resource %d", resource);
1664 rlp.copyOut(tc->getMemProxy());
1668 /// Target clock_gettime() function.
1671 clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1674 //int clk_id = p->getSyscallArg(tc, index);
1675 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
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);
1682 tp.copyOut(tc->getMemProxy());
1687 /// Target clock_getres() function.
1690 clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1693 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1695 // Set resolution at ns, which is what clock_gettime() returns
1699 tp.copyOut(tc->getMemProxy());
1704 /// Target gettimeofday() handler.
1707 gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1711 TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
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);
1718 tp.copyOut(tc->getMemProxy());
1724 /// Target utimes() handler.
1727 utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1733 if (!tc->getMemProxy().tryReadString(path,
1734 process->getSyscallArg(tc, index))) {
1738 TypedBufferArg<typename OS::timeval [2]>
1739 tp(process->getSyscallArg(tc, index));
1740 tp.copyIn(tc->getMemProxy());
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);
1748 // Adjust path for current working directory
1749 path = process->fullPath(path);
1751 int result = utimes(path.c_str(), hostTimeval);
1761 execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1767 SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
1768 if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
1771 if (access(path.c_str(), F_OK) == -1)
1774 auto read_in = [](std::vector<std::string> & vect,
1775 SETranslatingPortProxy & mem_proxy,
1778 for (int inc = 0; ; inc++) {
1779 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
1780 b.copyIn(mem_proxy);
1782 if (!*(Addr*)b.bufferPtr())
1785 vect.push_back(std::string());
1786 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
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
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);
1803 pp->egid = p->egid();
1804 pp->euid = p->euid();
1806 pp->ppid = p->ppid();
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;
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).
1821 p->system->PIDs.erase(p->pid());
1822 Process *new_p = pp->create();
1826 * Work through the file descriptor array and close any files marked
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);
1836 *new_p->sigchld = true;
1839 tc->clearArchRegs();
1840 tc->setProcessPtr(new_p);
1841 new_p->assignThreadContext(tc->contextId());
1844 TheISA::PCState pcState = tc->pcState();
1845 tc->setNPC(pcState.instAddr());
1847 desc->setFlags(SyscallDesc::SuppressReturnValue);
1851 /// Target getrusage() function.
1854 getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
1858 int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
1859 TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
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;
1872 rup->ru_inblock = 0;
1873 rup->ru_oublock = 0;
1876 rup->ru_nsignals = 0;
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);
1887 case OS::TGT_RUSAGE_CHILDREN:
1888 // do nothing. We have no child processes, so they take no time.
1892 // don't really handle THREAD or CHILDREN, but just warn and
1894 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
1898 rup.copyOut(tc->getMemProxy());
1903 /// Target times() function.
1906 timesFunc(SyscallDesc *desc, int callnum, Process *process,
1910 TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
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;
1919 // Convert to host endianness
1920 bufp->tms_utime = TheISA::htog(bufp->tms_utime);
1923 bufp.copyOut(tc->getMemProxy());
1925 // Return clock ticks since system boot
1929 /// Target time() function.
1932 timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
1934 typename OS::time_t sec, usec;
1935 getElapsedTimeMicro(sec, usec);
1936 sec += seconds_since_epoch;
1939 Addr taddr = (Addr)process->getSyscallArg(tc, index);
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));
1951 tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
1954 int tgid = process->getSyscallArg(tc, index);
1955 int tid = process->getSyscallArg(tc, index);
1956 int sig = process->getSyscallArg(tc, index);
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.
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) {
1983 if (sig != 0 || sig != OS::TGT_SIGABRT)
1986 if (tgt_proc == nullptr)
1989 if (tgid != -1 && tgt_proc->tgid() != tgid)
1992 if (sig == OS::TGT_SIGABRT)
1993 exitGroupFunc(desc, 252, process, tc);
1999 #endif // __SIM_SYSCALL_EMUL_HH__