syscall_emul.hh (13571:a320800ceccf) syscall_emul.hh (13572:14ddf44aaebc)
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 <poll.h>
82#include <sys/mman.h>
83#include <sys/socket.h>
84#include <sys/stat.h>
85#if (NO_STATFS == 0)
86#include <sys/statfs.h>
87#else
88#include <sys/mount.h>
89#endif
90#include <sys/time.h>
91#include <sys/types.h>
92#include <sys/uio.h>
93#include <unistd.h>
94
95#include <cerrno>
96#include <memory>
97#include <string>
98
99#include "arch/generic/tlb.hh"
100#include "arch/utility.hh"
101#include "base/intmath.hh"
102#include "base/loader/object_file.hh"
103#include "base/logging.hh"
104#include "base/trace.hh"
105#include "base/types.hh"
106#include "config/the_isa.hh"
107#include "cpu/base.hh"
108#include "cpu/thread_context.hh"
109#include "mem/page_table.hh"
110#include "params/Process.hh"
111#include "sim/emul_driver.hh"
112#include "sim/futex_map.hh"
113#include "sim/process.hh"
114#include "sim/syscall_debug_macros.hh"
115#include "sim/syscall_desc.hh"
116#include "sim/syscall_emul_buf.hh"
117#include "sim/syscall_return.hh"
118
119//////////////////////////////////////////////////////////////////////
120//
121// The following emulation functions are generic enough that they
122// don't need to be recompiled for different emulated OS's. They are
123// defined in sim/syscall_emul.cc.
124//
125//////////////////////////////////////////////////////////////////////
126
127
128/// Handler for unimplemented syscalls that we haven't thought about.
129SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
130 Process *p, ThreadContext *tc);
131
132/// Handler for unimplemented syscalls that we never intend to
133/// implement (signal handling, etc.) and should not affect the correct
134/// behavior of the program. Print a warning only if the appropriate
135/// trace flag is enabled. Return success to the target program.
136SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
137 Process *p, ThreadContext *tc);
138
139// Target fallocateFunc() handler.
140SyscallReturn fallocateFunc(SyscallDesc *desc, int num,
141 Process *p, ThreadContext *tc);
142
143/// Target exit() handler: terminate current context.
144SyscallReturn exitFunc(SyscallDesc *desc, int num,
145 Process *p, ThreadContext *tc);
146
147/// Target exit_group() handler: terminate simulation. (exit all threads)
148SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
149 Process *p, ThreadContext *tc);
150
151/// Target set_tid_address() handler.
152SyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
153 Process *p, ThreadContext *tc);
154
155/// Target getpagesize() handler.
156SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
157 Process *p, ThreadContext *tc);
158
159/// Target brk() handler: set brk address.
160SyscallReturn brkFunc(SyscallDesc *desc, int num,
161 Process *p, ThreadContext *tc);
162
163/// Target close() handler.
164SyscallReturn closeFunc(SyscallDesc *desc, int num,
165 Process *p, ThreadContext *tc);
166
167/// Target lseek() handler.
168SyscallReturn lseekFunc(SyscallDesc *desc, int num,
169 Process *p, ThreadContext *tc);
170
171/// Target _llseek() handler.
172SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
173 Process *p, ThreadContext *tc);
174
175/// Target munmap() handler.
176SyscallReturn munmapFunc(SyscallDesc *desc, int num,
177 Process *p, ThreadContext *tc);
178
179/// Target shutdown() handler.
180SyscallReturn shutdownFunc(SyscallDesc *desc, int num,
181 Process *p, ThreadContext *tc);
182
183/// Target gethostname() handler.
184SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
185 Process *p, ThreadContext *tc);
186
187/// Target getcwd() handler.
188SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
189 Process *p, ThreadContext *tc);
190
191/// Target readlink() handler.
192SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
193 Process *p, ThreadContext *tc,
194 int index = 0);
195SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
196 Process *p, ThreadContext *tc);
197
198/// Target unlink() handler.
199SyscallReturn unlinkHelper(SyscallDesc *desc, int num,
200 Process *p, ThreadContext *tc,
201 int index);
202SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
203 Process *p, ThreadContext *tc);
204
205/// Target link() handler
206SyscallReturn linkFunc(SyscallDesc *desc, int num, Process *p,
207 ThreadContext *tc);
208
209/// Target symlink() handler.
210SyscallReturn symlinkFunc(SyscallDesc *desc, int num, Process *p,
211 ThreadContext *tc);
212
213/// Target mkdir() handler.
214SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
215 Process *p, ThreadContext *tc);
216
217/// Target mknod() handler.
218SyscallReturn mknodFunc(SyscallDesc *desc, int num,
219 Process *p, ThreadContext *tc);
220
221/// Target chdir() handler.
222SyscallReturn chdirFunc(SyscallDesc *desc, int num,
223 Process *p, ThreadContext *tc);
224
225// Target rmdir() handler.
226SyscallReturn rmdirFunc(SyscallDesc *desc, int num,
227 Process *p, ThreadContext *tc);
228
229/// Target rename() handler.
230SyscallReturn renameFunc(SyscallDesc *desc, int num,
231 Process *p, ThreadContext *tc);
232
233
234/// Target truncate() handler.
235SyscallReturn truncateFunc(SyscallDesc *desc, int num,
236 Process *p, ThreadContext *tc);
237
238
239/// Target ftruncate() handler.
240SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
241 Process *p, ThreadContext *tc);
242
243
244/// Target truncate64() handler.
245SyscallReturn truncate64Func(SyscallDesc *desc, int num,
246 Process *p, ThreadContext *tc);
247
248/// Target ftruncate64() handler.
249SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
250 Process *p, ThreadContext *tc);
251
252
253/// Target umask() handler.
254SyscallReturn umaskFunc(SyscallDesc *desc, int num,
255 Process *p, ThreadContext *tc);
256
257/// Target gettid() handler.
258SyscallReturn gettidFunc(SyscallDesc *desc, int num,
259 Process *p, ThreadContext *tc);
260
261/// Target chown() handler.
262SyscallReturn chownFunc(SyscallDesc *desc, int num,
263 Process *p, ThreadContext *tc);
264
265/// Target setpgid() handler.
266SyscallReturn setpgidFunc(SyscallDesc *desc, int num,
267 Process *p, ThreadContext *tc);
268
269/// Target fchown() handler.
270SyscallReturn fchownFunc(SyscallDesc *desc, int num,
271 Process *p, ThreadContext *tc);
272
273/// Target dup() handler.
274SyscallReturn dupFunc(SyscallDesc *desc, int num,
275 Process *process, ThreadContext *tc);
276
277/// Target dup2() handler.
278SyscallReturn dup2Func(SyscallDesc *desc, int num,
279 Process *process, ThreadContext *tc);
280
281/// Target fcntl() handler.
282SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
283 Process *process, ThreadContext *tc);
284
285/// Target fcntl64() handler.
286SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
287 Process *process, ThreadContext *tc);
288
289/// Target setuid() handler.
290SyscallReturn setuidFunc(SyscallDesc *desc, int num,
291 Process *p, ThreadContext *tc);
292
293/// Target pipe() handler.
294SyscallReturn pipeFunc(SyscallDesc *desc, int num,
295 Process *p, ThreadContext *tc);
296
297/// Internal pipe() handler.
298SyscallReturn pipeImpl(SyscallDesc *desc, int num, Process *p,
299 ThreadContext *tc, bool pseudoPipe);
300
301/// Target getpid() handler.
302SyscallReturn getpidFunc(SyscallDesc *desc, int num,
303 Process *p, ThreadContext *tc);
304
305// Target getpeername() handler.
306SyscallReturn getpeernameFunc(SyscallDesc *desc, int num,
307 Process *p, ThreadContext *tc);
308
309// Target bind() handler.
310SyscallReturn bindFunc(SyscallDesc *desc, int num,
311 Process *p, ThreadContext *tc);
312
313// Target listen() handler.
314SyscallReturn listenFunc(SyscallDesc *desc, int num,
315 Process *p, ThreadContext *tc);
316
317// Target connect() handler.
318SyscallReturn connectFunc(SyscallDesc *desc, int num,
319 Process *p, ThreadContext *tc);
320
321#if defined(SYS_getdents)
322// Target getdents() handler.
323SyscallReturn getdentsFunc(SyscallDesc *desc, int num,
324 Process *p, ThreadContext *tc);
325#endif
326
327#if defined(SYS_getdents64)
328// Target getdents() handler.
329SyscallReturn getdents64Func(SyscallDesc *desc, int num,
330 Process *p, ThreadContext *tc);
331#endif
332
333// Target sendto() handler.
334SyscallReturn sendtoFunc(SyscallDesc *desc, int num,
335 Process *p, ThreadContext *tc);
336
337// Target recvfrom() handler.
338SyscallReturn recvfromFunc(SyscallDesc *desc, int num,
339 Process *p, ThreadContext *tc);
340
341// Target recvmsg() handler.
342SyscallReturn recvmsgFunc(SyscallDesc *desc, int num,
343 Process *p, ThreadContext *tc);
344
345// Target sendmsg() handler.
346SyscallReturn sendmsgFunc(SyscallDesc *desc, int num,
347 Process *p, ThreadContext *tc);
348
349// Target getuid() handler.
350SyscallReturn getuidFunc(SyscallDesc *desc, int num,
351 Process *p, ThreadContext *tc);
352
353/// Target getgid() handler.
354SyscallReturn getgidFunc(SyscallDesc *desc, int num,
355 Process *p, ThreadContext *tc);
356
357/// Target getppid() handler.
358SyscallReturn getppidFunc(SyscallDesc *desc, int num,
359 Process *p, ThreadContext *tc);
360
361/// Target geteuid() handler.
362SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
363 Process *p, ThreadContext *tc);
364
365/// Target getegid() handler.
366SyscallReturn getegidFunc(SyscallDesc *desc, int num,
367 Process *p, ThreadContext *tc);
368
369/// Target access() handler
370SyscallReturn accessFunc(SyscallDesc *desc, int num,
371 Process *p, ThreadContext *tc);
372SyscallReturn accessFunc(SyscallDesc *desc, int num,
373 Process *p, ThreadContext *tc,
374 int index);
375
376// Target getsockopt() handler.
377SyscallReturn getsockoptFunc(SyscallDesc *desc, int num,
378 Process *p, ThreadContext *tc);
379
380// Target setsockopt() handler.
381SyscallReturn setsockoptFunc(SyscallDesc *desc, int num,
382 Process *p, ThreadContext *tc);
383
384// Target getsockname() handler.
385SyscallReturn getsocknameFunc(SyscallDesc *desc, int num,
386 Process *p, ThreadContext *tc);
387
388/// Futex system call
389/// Implemented by Daniel Sanchez
390/// Used by printf's in multi-threaded apps
391template <class OS>
392SyscallReturn
393futexFunc(SyscallDesc *desc, int callnum, Process *process,
394 ThreadContext *tc)
395{
396 using namespace std;
397
398 int index = 0;
399 Addr uaddr = process->getSyscallArg(tc, index);
400 int op = process->getSyscallArg(tc, index);
401 int val = process->getSyscallArg(tc, index);
402
403 /*
404 * Unsupported option that does not affect the correctness of the
405 * application. This is a performance optimization utilized by Linux.
406 */
407 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
408
409 FutexMap &futex_map = tc->getSystemPtr()->futexMap;
410
411 if (OS::TGT_FUTEX_WAIT == op) {
412 // Ensure futex system call accessed atomically.
413 BufferArg buf(uaddr, sizeof(int));
414 buf.copyIn(tc->getMemProxy());
415 int mem_val = *(int*)buf.bufferPtr();
416
417 /*
418 * The value in memory at uaddr is not equal with the expected val
419 * (a different thread must have changed it before the system call was
420 * invoked). In this case, we need to throw an error.
421 */
422 if (val != mem_val)
423 return -OS::TGT_EWOULDBLOCK;
424
425 futex_map.suspend(uaddr, process->tgid(), tc);
426
427 return 0;
428 } else if (OS::TGT_FUTEX_WAKE == op) {
429 return futex_map.wakeup(uaddr, process->tgid(), val);
430 }
431
432 warn("futex: op %d not implemented; ignoring.", op);
433 return -ENOSYS;
434}
435
436
437/// Pseudo Funcs - These functions use a different return convension,
438/// returning a second value in a register other than the normal return register
439SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
440 Process *process, ThreadContext *tc);
441
442/// Target getpidPseudo() handler.
443SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
444 Process *p, ThreadContext *tc);
445
446/// Target getuidPseudo() handler.
447SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
448 Process *p, ThreadContext *tc);
449
450/// Target getgidPseudo() handler.
451SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
452 Process *p, ThreadContext *tc);
453
454
455/// A readable name for 1,000,000, for converting microseconds to seconds.
456const int one_million = 1000000;
457/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
458const int one_billion = 1000000000;
459
460/// Approximate seconds since the epoch (1/1/1970). About a billion,
461/// by my reckoning. We want to keep this a constant (not use the
462/// real-world time) to keep simulations repeatable.
463const unsigned seconds_since_epoch = 1000000000;
464
465/// Helper function to convert current elapsed time to seconds and
466/// microseconds.
467template <class T1, class T2>
468void
469getElapsedTimeMicro(T1 &sec, T2 &usec)
470{
471 uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
472 sec = elapsed_usecs / one_million;
473 usec = elapsed_usecs % one_million;
474}
475
476/// Helper function to convert current elapsed time to seconds and
477/// nanoseconds.
478template <class T1, class T2>
479void
480getElapsedTimeNano(T1 &sec, T2 &nsec)
481{
482 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
483 sec = elapsed_nsecs / one_billion;
484 nsec = elapsed_nsecs % one_billion;
485}
486
487//////////////////////////////////////////////////////////////////////
488//
489// The following emulation functions are generic, but need to be
490// templated to account for differences in types, constants, etc.
491//
492//////////////////////////////////////////////////////////////////////
493
494 typedef struct statfs hst_statfs;
495#if NO_STAT64
496 typedef struct stat hst_stat;
497 typedef struct stat hst_stat64;
498#else
499 typedef struct stat hst_stat;
500 typedef struct stat64 hst_stat64;
501#endif
502
503//// Helper function to convert a host stat buffer to a target stat
504//// buffer. Also copies the target buffer out to the simulated
505//// memory space. Used by stat(), fstat(), and lstat().
506
507template <typename target_stat, typename host_stat>
508void
509convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
510{
511 using namespace TheISA;
512
513 if (fakeTTY)
514 tgt->st_dev = 0xA;
515 else
516 tgt->st_dev = host->st_dev;
517 tgt->st_dev = TheISA::htog(tgt->st_dev);
518 tgt->st_ino = host->st_ino;
519 tgt->st_ino = TheISA::htog(tgt->st_ino);
520 tgt->st_mode = host->st_mode;
521 if (fakeTTY) {
522 // Claim to be a character device
523 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT
524 tgt->st_mode |= S_IFCHR; // Set S_IFCHR
525 }
526 tgt->st_mode = TheISA::htog(tgt->st_mode);
527 tgt->st_nlink = host->st_nlink;
528 tgt->st_nlink = TheISA::htog(tgt->st_nlink);
529 tgt->st_uid = host->st_uid;
530 tgt->st_uid = TheISA::htog(tgt->st_uid);
531 tgt->st_gid = host->st_gid;
532 tgt->st_gid = TheISA::htog(tgt->st_gid);
533 if (fakeTTY)
534 tgt->st_rdev = 0x880d;
535 else
536 tgt->st_rdev = host->st_rdev;
537 tgt->st_rdev = TheISA::htog(tgt->st_rdev);
538 tgt->st_size = host->st_size;
539 tgt->st_size = TheISA::htog(tgt->st_size);
540 tgt->st_atimeX = host->st_atime;
541 tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
542 tgt->st_mtimeX = host->st_mtime;
543 tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
544 tgt->st_ctimeX = host->st_ctime;
545 tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
546 // Force the block size to be 8KB. This helps to ensure buffered io works
547 // consistently across different hosts.
548 tgt->st_blksize = 0x2000;
549 tgt->st_blksize = TheISA::htog(tgt->st_blksize);
550 tgt->st_blocks = host->st_blocks;
551 tgt->st_blocks = TheISA::htog(tgt->st_blocks);
552}
553
554// Same for stat64
555
556template <typename target_stat, typename host_stat64>
557void
558convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
559{
560 using namespace TheISA;
561
562 convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
563#if defined(STAT_HAVE_NSEC)
564 tgt->st_atime_nsec = host->st_atime_nsec;
565 tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
566 tgt->st_mtime_nsec = host->st_mtime_nsec;
567 tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
568 tgt->st_ctime_nsec = host->st_ctime_nsec;
569 tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
570#else
571 tgt->st_atime_nsec = 0;
572 tgt->st_mtime_nsec = 0;
573 tgt->st_ctime_nsec = 0;
574#endif
575}
576
577// Here are a couple of convenience functions
578template<class OS>
579void
580copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
581 hst_stat *host, bool fakeTTY = false)
582{
583 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
584 tgt_stat_buf tgt(addr);
585 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
586 tgt.copyOut(mem);
587}
588
589template<class OS>
590void
591copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
592 hst_stat64 *host, bool fakeTTY = false)
593{
594 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
595 tgt_stat_buf tgt(addr);
596 convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
597 tgt.copyOut(mem);
598}
599
600template <class OS>
601void
602copyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
603 hst_statfs *host)
604{
605 TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
606
607 tgt->f_type = TheISA::htog(host->f_type);
608#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
609 tgt->f_bsize = TheISA::htog(host->f_iosize);
610#else
611 tgt->f_bsize = TheISA::htog(host->f_bsize);
612#endif
613 tgt->f_blocks = TheISA::htog(host->f_blocks);
614 tgt->f_bfree = TheISA::htog(host->f_bfree);
615 tgt->f_bavail = TheISA::htog(host->f_bavail);
616 tgt->f_files = TheISA::htog(host->f_files);
617 tgt->f_ffree = TheISA::htog(host->f_ffree);
618 memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
619#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
620 tgt->f_namelen = TheISA::htog(host->f_namemax);
621 tgt->f_frsize = TheISA::htog(host->f_bsize);
622#elif defined(__APPLE__)
623 tgt->f_namelen = 0;
624 tgt->f_frsize = 0;
625#else
626 tgt->f_namelen = TheISA::htog(host->f_namelen);
627 tgt->f_frsize = TheISA::htog(host->f_frsize);
628#endif
629#if defined(__linux__)
630 memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
631#else
632 /*
633 * The fields are different sizes per OS. Don't bother with
634 * f_spare or f_reserved on non-Linux for now.
635 */
636 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
637#endif
638
639 tgt.copyOut(mem);
640}
641
642/// Target ioctl() handler. For the most part, programs call ioctl()
643/// only to find out if their stdout is a tty, to determine whether to
644/// do line or block buffering. We always claim that output fds are
645/// not TTYs to provide repeatable results.
646template <class OS>
647SyscallReturn
648ioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
649{
650 int index = 0;
651 int tgt_fd = p->getSyscallArg(tc, index);
652 unsigned req = p->getSyscallArg(tc, index);
653
654 DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
655
656 if (OS::isTtyReq(req))
657 return -ENOTTY;
658
659 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
660 if (!dfdp)
661 return -EBADF;
662
663 /**
664 * If the driver is valid, issue the ioctl through it. Otherwise,
665 * there's an implicit assumption that the device is a TTY type and we
666 * return that we do not have a valid TTY.
667 */
668 EmulatedDriver *emul_driver = dfdp->getDriver();
669 if (emul_driver)
670 return emul_driver->ioctl(p, tc, req);
671
672 /**
673 * For lack of a better return code, return ENOTTY. Ideally, we should
674 * return something better here, but at least we issue the warning.
675 */
676 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
677 tgt_fd, req, tc->pcState());
678 return -ENOTTY;
679}
680
681template <class OS>
682SyscallReturn
683openImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
684 bool isopenat)
685{
686 int index = 0;
687 int tgt_dirfd = -1;
688
689 /**
690 * If using the openat variant, read in the target directory file
691 * descriptor from the simulated process.
692 */
693 if (isopenat)
694 tgt_dirfd = p->getSyscallArg(tc, index);
695
696 /**
697 * Retrieve the simulated process' memory proxy and then read in the path
698 * string from that memory space into the host's working memory space.
699 */
700 std::string path;
701 if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
702 return -EFAULT;
703
704#ifdef __CYGWIN32__
705 int host_flags = O_BINARY;
706#else
707 int host_flags = 0;
708#endif
709 /**
710 * Translate target flags into host flags. Flags exist which are not
711 * ported between architectures which can cause check failures.
712 */
713 int tgt_flags = p->getSyscallArg(tc, index);
714 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
715 if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
716 tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
717 host_flags |= OS::openFlagTable[i].hostFlag;
718 }
719 }
720 if (tgt_flags) {
721 warn("open%s: cannot decode flags 0x%x",
722 isopenat ? "at" : "", tgt_flags);
723 }
724#ifdef __CYGWIN32__
725 host_flags |= O_BINARY;
726#endif
727
728 int mode = p->getSyscallArg(tc, index);
729
730 /**
731 * If the simulated process called open or openat with AT_FDCWD specified,
732 * take the current working directory value which was passed into the
733 * process class as a Python parameter and append the current path to
734 * create a full path.
735 * Otherwise, openat with a valid target directory file descriptor has
736 * been called. If the path option, which was passed in as a parameter,
737 * is not absolute, retrieve the directory file descriptor's path and
738 * prepend it to the path passed in as a parameter.
739 * In every case, we should have a full path (which is relevant to the
740 * host) to work with after this block has been passed.
741 */
742 if (!isopenat || (isopenat && tgt_dirfd == OS::TGT_AT_FDCWD)) {
743 path = p->fullPath(path);
744 } else if (!startswith(path, "/")) {
745 std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
746 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
747 if (!ffdp)
748 return -EBADF;
749 path.insert(0, ffdp->getFileName() + "/");
750 }
751
752 /**
753 * Since this is an emulated environment, we create pseudo file
754 * descriptors for device requests that have been registered with
755 * the process class through Python; this allows us to create a file
756 * descriptor for subsequent ioctl or mmap calls.
757 */
758 if (startswith(path, "/dev/")) {
759 std::string filename = path.substr(strlen("/dev/"));
760 EmulatedDriver *drv = p->findDriver(filename);
761 if (drv) {
762 DPRINTF_SYSCALL(Verbose, "open%s: passing call to "
763 "driver open with path[%s]\n",
764 isopenat ? "at" : "", path.c_str());
765 return drv->open(p, tc, mode, host_flags);
766 }
767 /**
768 * Fall through here for pass through to host devices, such
769 * as /dev/zero
770 */
771 }
772
773 /**
774 * Some special paths and files cannot be called on the host and need
775 * to be handled as special cases inside the simulator.
776 * If the full path that was created above does not match any of the
777 * special cases, pass it through to the open call on the host to let
778 * the host open the file on our behalf.
779 * If the host cannot open the file, return the host's error code back
780 * through the system call to the simulated process.
781 */
782 int sim_fd = -1;
783 std::vector<std::string> special_paths =
784 { "/proc/", "/system/", "/sys/", "/platform/", "/etc/passwd" };
785 for (auto entry : special_paths) {
786 if (startswith(path, entry))
787 sim_fd = OS::openSpecialFile(path, p, tc);
788 }
789 if (sim_fd == -1) {
790 sim_fd = open(path.c_str(), host_flags, mode);
791 }
792 if (sim_fd == -1) {
793 int local = -errno;
794 DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s\n",
795 isopenat ? "at" : "", path.c_str());
796 return local;
797 }
798
799 /**
800 * The file was opened successfully and needs to be recorded in the
801 * process' file descriptor array so that it can be retrieved later.
802 * The target file descriptor that is chosen will be the lowest unused
803 * file descriptor.
804 * Return the indirect target file descriptor back to the simulated
805 * process to act as a handle for the opened file.
806 */
807 auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
808 int tgt_fd = p->fds->allocFD(ffdp);
809 DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n",
810 isopenat ? "at" : "", sim_fd, tgt_fd, path.c_str());
811 return tgt_fd;
812}
813
814/// Target open() handler.
815template <class OS>
816SyscallReturn
817openFunc(SyscallDesc *desc, int callnum, Process *process,
818 ThreadContext *tc)
819{
820 return openImpl<OS>(desc, callnum, process, tc, false);
821}
822
823/// Target openat() handler.
824template <class OS>
825SyscallReturn
826openatFunc(SyscallDesc *desc, int callnum, Process *process,
827 ThreadContext *tc)
828{
829 return openImpl<OS>(desc, callnum, process, tc, true);
830}
831
832/// Target unlinkat() handler.
833template <class OS>
834SyscallReturn
835unlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
836 ThreadContext *tc)
837{
838 int index = 0;
839 int dirfd = process->getSyscallArg(tc, index);
840 if (dirfd != OS::TGT_AT_FDCWD)
841 warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
842
843 return unlinkHelper(desc, callnum, process, tc, 1);
844}
845
846/// Target facessat() handler
847template <class OS>
848SyscallReturn
849faccessatFunc(SyscallDesc *desc, int callnum, Process *process,
850 ThreadContext *tc)
851{
852 int index = 0;
853 int dirfd = process->getSyscallArg(tc, index);
854 if (dirfd != OS::TGT_AT_FDCWD)
855 warn("faccessat: first argument not AT_FDCWD; unlikely to work");
856 return accessFunc(desc, callnum, process, tc, 1);
857}
858
859/// Target readlinkat() handler
860template <class OS>
861SyscallReturn
862readlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
863 ThreadContext *tc)
864{
865 int index = 0;
866 int dirfd = process->getSyscallArg(tc, index);
867 if (dirfd != OS::TGT_AT_FDCWD)
868 warn("openat: first argument not AT_FDCWD; unlikely to work");
869 return readlinkFunc(desc, callnum, process, tc, 1);
870}
871
872/// Target renameat() handler.
873template <class OS>
874SyscallReturn
875renameatFunc(SyscallDesc *desc, int callnum, Process *process,
876 ThreadContext *tc)
877{
878 int index = 0;
879
880 int olddirfd = process->getSyscallArg(tc, index);
881 if (olddirfd != OS::TGT_AT_FDCWD)
882 warn("renameat: first argument not AT_FDCWD; unlikely to work");
883
884 std::string old_name;
885
886 if (!tc->getMemProxy().tryReadString(old_name,
887 process->getSyscallArg(tc, index)))
888 return -EFAULT;
889
890 int newdirfd = process->getSyscallArg(tc, index);
891 if (newdirfd != OS::TGT_AT_FDCWD)
892 warn("renameat: third argument not AT_FDCWD; unlikely to work");
893
894 std::string new_name;
895
896 if (!tc->getMemProxy().tryReadString(new_name,
897 process->getSyscallArg(tc, index)))
898 return -EFAULT;
899
900 // Adjust path for current working directory
901 old_name = process->fullPath(old_name);
902 new_name = process->fullPath(new_name);
903
904 int result = rename(old_name.c_str(), new_name.c_str());
905 return (result == -1) ? -errno : result;
906}
907
908/// Target sysinfo() handler.
909template <class OS>
910SyscallReturn
911sysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
912 ThreadContext *tc)
913{
914
915 int index = 0;
916 TypedBufferArg<typename OS::tgt_sysinfo>
917 sysinfo(process->getSyscallArg(tc, index));
918
919 sysinfo->uptime = seconds_since_epoch;
920 sysinfo->totalram = process->system->memSize();
921 sysinfo->mem_unit = 1;
922
923 sysinfo.copyOut(tc->getMemProxy());
924
925 return 0;
926}
927
928/// Target chmod() handler.
929template <class OS>
930SyscallReturn
931chmodFunc(SyscallDesc *desc, int callnum, Process *process,
932 ThreadContext *tc)
933{
934 std::string path;
935
936 int index = 0;
937 if (!tc->getMemProxy().tryReadString(path,
938 process->getSyscallArg(tc, index))) {
939 return -EFAULT;
940 }
941
942 uint32_t mode = process->getSyscallArg(tc, index);
943 mode_t hostMode = 0;
944
945 // XXX translate mode flags via OS::something???
946 hostMode = mode;
947
948 // Adjust path for current working directory
949 path = process->fullPath(path);
950
951 // do the chmod
952 int result = chmod(path.c_str(), hostMode);
953 if (result < 0)
954 return -errno;
955
956 return 0;
957}
958
959template <class OS>
960SyscallReturn
961pollFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
962{
963 int index = 0;
964 Addr fdsPtr = p->getSyscallArg(tc, index);
965 int nfds = p->getSyscallArg(tc, index);
966 int tmout = p->getSyscallArg(tc, index);
967
968 BufferArg fdsBuf(fdsPtr, sizeof(struct pollfd) * nfds);
969 fdsBuf.copyIn(tc->getMemProxy());
970
971 /**
972 * Record the target file descriptors in a local variable. We need to
973 * replace them with host file descriptors but we need a temporary copy
974 * for later. Afterwards, replace each target file descriptor in the
975 * poll_fd array with its host_fd.
976 */
977 int temp_tgt_fds[nfds];
978 for (index = 0; index < nfds; index++) {
979 temp_tgt_fds[index] = ((struct pollfd *)fdsBuf.bufferPtr())[index].fd;
980 auto tgt_fd = temp_tgt_fds[index];
981 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
982 if (!hbfdp)
983 return -EBADF;
984 auto host_fd = hbfdp->getSimFD();
985 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = host_fd;
986 }
987
988 /**
989 * We cannot allow an infinite poll to occur or it will inevitably cause
990 * a deadlock in the gem5 simulator with clone. We must pass in tmout with
991 * a non-negative value, however it also makes no sense to poll on the
992 * underlying host for any other time than tmout a zero timeout.
993 */
994 int status;
995 if (tmout < 0) {
996 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
997 if (status == 0) {
998 /**
999 * If blocking indefinitely, check the signal list to see if a
1000 * signal would break the poll out of the retry cycle and try
1001 * to return the signal interrupt instead.
1002 */
1003 System *sysh = tc->getSystemPtr();
1004 std::list<BasicSignal>::iterator it;
1005 for (it=sysh->signalList.begin(); it!=sysh->signalList.end(); it++)
1006 if (it->receiver == p)
1007 return -EINTR;
1008 return SyscallReturn::retry();
1009 }
1010 } else
1011 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1012
1013 if (status == -1)
1014 return -errno;
1015
1016 /**
1017 * Replace each host_fd in the returned poll_fd array with its original
1018 * target file descriptor.
1019 */
1020 for (index = 0; index < nfds; index++) {
1021 auto tgt_fd = temp_tgt_fds[index];
1022 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = tgt_fd;
1023 }
1024
1025 /**
1026 * Copy out the pollfd struct because the host may have updated fields
1027 * in the structure.
1028 */
1029 fdsBuf.copyOut(tc->getMemProxy());
1030
1031 return status;
1032}
1033
1034/// Target fchmod() handler.
1035template <class OS>
1036SyscallReturn
1037fchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1038{
1039 int index = 0;
1040 int tgt_fd = p->getSyscallArg(tc, index);
1041 uint32_t mode = p->getSyscallArg(tc, index);
1042
1043 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1044 if (!ffdp)
1045 return -EBADF;
1046 int sim_fd = ffdp->getSimFD();
1047
1048 mode_t hostMode = mode;
1049
1050 int result = fchmod(sim_fd, hostMode);
1051
1052 return (result < 0) ? -errno : 0;
1053}
1054
1055/// Target mremap() handler.
1056template <class OS>
1057SyscallReturn
1058mremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
1059{
1060 int index = 0;
1061 Addr start = process->getSyscallArg(tc, index);
1062 uint64_t old_length = process->getSyscallArg(tc, index);
1063 uint64_t new_length = process->getSyscallArg(tc, index);
1064 uint64_t flags = process->getSyscallArg(tc, index);
1065 uint64_t provided_address = 0;
1066 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
1067
1068 if (use_provided_address)
1069 provided_address = process->getSyscallArg(tc, index);
1070
1071 if ((start % TheISA::PageBytes != 0) ||
1072 (provided_address % TheISA::PageBytes != 0)) {
1073 warn("mremap failing: arguments not page aligned");
1074 return -EINVAL;
1075 }
1076
1077 new_length = roundUp(new_length, TheISA::PageBytes);
1078
1079 if (new_length > old_length) {
1080 std::shared_ptr<MemState> mem_state = process->memState;
1081 Addr mmap_end = mem_state->getMmapEnd();
1082
1083 if ((start + old_length) == mmap_end &&
1084 (!use_provided_address || provided_address == start)) {
1085 // This case cannot occur when growing downward, as
1086 // start is greater than or equal to mmap_end.
1087 uint64_t diff = new_length - old_length;
1088 process->allocateMem(mmap_end, diff);
1089 mem_state->setMmapEnd(mmap_end + diff);
1090 return start;
1091 } else {
1092 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
1093 warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
1094 return -ENOMEM;
1095 } else {
1096 uint64_t new_start = provided_address;
1097 if (!use_provided_address) {
1098 new_start = process->mmapGrowsDown() ?
1099 mmap_end - new_length : mmap_end;
1100 mmap_end = process->mmapGrowsDown() ?
1101 new_start : mmap_end + new_length;
1102 mem_state->setMmapEnd(mmap_end);
1103 }
1104
1105 process->pTable->remap(start, old_length, new_start);
1106 warn("mremapping to new vaddr %08p-%08p, adding %d\n",
1107 new_start, new_start + new_length,
1108 new_length - old_length);
1109 // add on the remaining unallocated pages
1110 process->allocateMem(new_start + old_length,
1111 new_length - old_length,
1112 use_provided_address /* clobber */);
1113 if (use_provided_address &&
1114 ((new_start + new_length > mem_state->getMmapEnd() &&
1115 !process->mmapGrowsDown()) ||
1116 (new_start < mem_state->getMmapEnd() &&
1117 process->mmapGrowsDown()))) {
1118 // something fishy going on here, at least notify the user
1119 // @todo: increase mmap_end?
1120 warn("mmap region limit exceeded with MREMAP_FIXED\n");
1121 }
1122 warn("returning %08p as start\n", new_start);
1123 return new_start;
1124 }
1125 }
1126 } else {
1127 if (use_provided_address && provided_address != start)
1128 process->pTable->remap(start, new_length, provided_address);
1129 process->pTable->unmap(start + new_length, old_length - new_length);
1130 return use_provided_address ? provided_address : start;
1131 }
1132}
1133
1134/// Target stat() handler.
1135template <class OS>
1136SyscallReturn
1137statFunc(SyscallDesc *desc, int callnum, Process *process,
1138 ThreadContext *tc)
1139{
1140 std::string path;
1141
1142 int index = 0;
1143 if (!tc->getMemProxy().tryReadString(path,
1144 process->getSyscallArg(tc, index))) {
1145 return -EFAULT;
1146 }
1147 Addr bufPtr = process->getSyscallArg(tc, index);
1148
1149 // Adjust path for current working directory
1150 path = process->fullPath(path);
1151
1152 struct stat hostBuf;
1153 int result = stat(path.c_str(), &hostBuf);
1154
1155 if (result < 0)
1156 return -errno;
1157
1158 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1159
1160 return 0;
1161}
1162
1163
1164/// Target stat64() handler.
1165template <class OS>
1166SyscallReturn
1167stat64Func(SyscallDesc *desc, int callnum, Process *process,
1168 ThreadContext *tc)
1169{
1170 std::string path;
1171
1172 int index = 0;
1173 if (!tc->getMemProxy().tryReadString(path,
1174 process->getSyscallArg(tc, index)))
1175 return -EFAULT;
1176 Addr bufPtr = process->getSyscallArg(tc, index);
1177
1178 // Adjust path for current working directory
1179 path = process->fullPath(path);
1180
1181#if NO_STAT64
1182 struct stat hostBuf;
1183 int result = stat(path.c_str(), &hostBuf);
1184#else
1185 struct stat64 hostBuf;
1186 int result = stat64(path.c_str(), &hostBuf);
1187#endif
1188
1189 if (result < 0)
1190 return -errno;
1191
1192 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1193
1194 return 0;
1195}
1196
1197
1198/// Target fstatat64() handler.
1199template <class OS>
1200SyscallReturn
1201fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
1202 ThreadContext *tc)
1203{
1204 int index = 0;
1205 int dirfd = process->getSyscallArg(tc, index);
1206 if (dirfd != OS::TGT_AT_FDCWD)
1207 warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1208
1209 std::string path;
1210 if (!tc->getMemProxy().tryReadString(path,
1211 process->getSyscallArg(tc, index)))
1212 return -EFAULT;
1213 Addr bufPtr = process->getSyscallArg(tc, index);
1214
1215 // Adjust path for current working directory
1216 path = process->fullPath(path);
1217
1218#if NO_STAT64
1219 struct stat hostBuf;
1220 int result = stat(path.c_str(), &hostBuf);
1221#else
1222 struct stat64 hostBuf;
1223 int result = stat64(path.c_str(), &hostBuf);
1224#endif
1225
1226 if (result < 0)
1227 return -errno;
1228
1229 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1230
1231 return 0;
1232}
1233
1234
1235/// Target fstat64() handler.
1236template <class OS>
1237SyscallReturn
1238fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1239{
1240 int index = 0;
1241 int tgt_fd = p->getSyscallArg(tc, index);
1242 Addr bufPtr = p->getSyscallArg(tc, index);
1243
1244 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1245 if (!ffdp)
1246 return -EBADF;
1247 int sim_fd = ffdp->getSimFD();
1248
1249#if NO_STAT64
1250 struct stat hostBuf;
1251 int result = fstat(sim_fd, &hostBuf);
1252#else
1253 struct stat64 hostBuf;
1254 int result = fstat64(sim_fd, &hostBuf);
1255#endif
1256
1257 if (result < 0)
1258 return -errno;
1259
1260 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1261
1262 return 0;
1263}
1264
1265
1266/// Target lstat() handler.
1267template <class OS>
1268SyscallReturn
1269lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1270 ThreadContext *tc)
1271{
1272 std::string path;
1273
1274 int index = 0;
1275 if (!tc->getMemProxy().tryReadString(path,
1276 process->getSyscallArg(tc, index))) {
1277 return -EFAULT;
1278 }
1279 Addr bufPtr = process->getSyscallArg(tc, index);
1280
1281 // Adjust path for current working directory
1282 path = process->fullPath(path);
1283
1284 struct stat hostBuf;
1285 int result = lstat(path.c_str(), &hostBuf);
1286
1287 if (result < 0)
1288 return -errno;
1289
1290 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1291
1292 return 0;
1293}
1294
1295/// Target lstat64() handler.
1296template <class OS>
1297SyscallReturn
1298lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1299 ThreadContext *tc)
1300{
1301 std::string path;
1302
1303 int index = 0;
1304 if (!tc->getMemProxy().tryReadString(path,
1305 process->getSyscallArg(tc, index))) {
1306 return -EFAULT;
1307 }
1308 Addr bufPtr = process->getSyscallArg(tc, index);
1309
1310 // Adjust path for current working directory
1311 path = process->fullPath(path);
1312
1313#if NO_STAT64
1314 struct stat hostBuf;
1315 int result = lstat(path.c_str(), &hostBuf);
1316#else
1317 struct stat64 hostBuf;
1318 int result = lstat64(path.c_str(), &hostBuf);
1319#endif
1320
1321 if (result < 0)
1322 return -errno;
1323
1324 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1325
1326 return 0;
1327}
1328
1329/// Target fstat() handler.
1330template <class OS>
1331SyscallReturn
1332fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1333{
1334 int index = 0;
1335 int tgt_fd = p->getSyscallArg(tc, index);
1336 Addr bufPtr = p->getSyscallArg(tc, index);
1337
1338 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1339
1340 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1341 if (!ffdp)
1342 return -EBADF;
1343 int sim_fd = ffdp->getSimFD();
1344
1345 struct stat hostBuf;
1346 int result = fstat(sim_fd, &hostBuf);
1347
1348 if (result < 0)
1349 return -errno;
1350
1351 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1352
1353 return 0;
1354}
1355
1356/// Target statfs() handler.
1357template <class OS>
1358SyscallReturn
1359statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1360 ThreadContext *tc)
1361{
1362#if NO_STATFS
1363 warn("Host OS cannot support calls to statfs. Ignoring syscall");
1364#else
1365 std::string path;
1366
1367 int index = 0;
1368 if (!tc->getMemProxy().tryReadString(path,
1369 process->getSyscallArg(tc, index))) {
1370 return -EFAULT;
1371 }
1372 Addr bufPtr = process->getSyscallArg(tc, index);
1373
1374 // Adjust path for current working directory
1375 path = process->fullPath(path);
1376
1377 struct statfs hostBuf;
1378 int result = statfs(path.c_str(), &hostBuf);
1379
1380 if (result < 0)
1381 return -errno;
1382
1383 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1384#endif
1385 return 0;
1386}
1387
1388template <class OS>
1389SyscallReturn
1390cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1391{
1392 int index = 0;
1393
1394 RegVal flags = p->getSyscallArg(tc, index);
1395 RegVal newStack = p->getSyscallArg(tc, index);
1396 Addr ptidPtr = p->getSyscallArg(tc, index);
1397
1398#if THE_ISA == RISCV_ISA or THE_ISA == ARM_ISA
1399 /**
1400 * Linux sets CLONE_BACKWARDS flag for RISC-V and Arm.
1401 * The flag defines the list of clone() arguments in the following
1402 * order: flags -> newStack -> ptidPtr -> tlsPtr -> ctidPtr
1403 */
1404 Addr tlsPtr = p->getSyscallArg(tc, index);
1405 Addr ctidPtr = p->getSyscallArg(tc, index);
1406#else
1407 Addr ctidPtr = p->getSyscallArg(tc, index);
1408 Addr tlsPtr = p->getSyscallArg(tc, index);
1409#endif
1410
1411 if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1412 ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1413 ((flags & OS::TGT_CLONE_FS) && (flags & OS::TGT_CLONE_NEWNS)) ||
1414 ((flags & OS::TGT_CLONE_NEWIPC) && (flags & OS::TGT_CLONE_SYSVSEM)) ||
1415 ((flags & OS::TGT_CLONE_NEWPID) && (flags & OS::TGT_CLONE_THREAD)) ||
1416 ((flags & OS::TGT_CLONE_VM) && !(newStack)))
1417 return -EINVAL;
1418
1419 ThreadContext *ctc;
1420 if (!(ctc = p->findFreeContext()))
1421 fatal("clone: no spare thread context in system");
1422
1423 /**
1424 * Note that ProcessParams is generated by swig and there are no other
1425 * examples of how to create anything but this default constructor. The
1426 * fields are manually initialized instead of passing parameters to the
1427 * constructor.
1428 */
1429 ProcessParams *pp = new ProcessParams();
1430 pp->executable.assign(*(new std::string(p->progName())));
1431 pp->cmd.push_back(*(new std::string(p->progName())));
1432 pp->system = p->system;
1433 pp->cwd.assign(p->getcwd());
1434 pp->input.assign("stdin");
1435 pp->output.assign("stdout");
1436 pp->errout.assign("stderr");
1437 pp->uid = p->uid();
1438 pp->euid = p->euid();
1439 pp->gid = p->gid();
1440 pp->egid = p->egid();
1441
1442 /* Find the first free PID that's less than the maximum */
1443 std::set<int> const& pids = p->system->PIDs;
1444 int temp_pid = *pids.begin();
1445 do {
1446 temp_pid++;
1447 } while (pids.find(temp_pid) != pids.end());
1448 if (temp_pid >= System::maxPID)
1449 fatal("temp_pid is too large: %d", temp_pid);
1450
1451 pp->pid = temp_pid;
1452 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1453 Process *cp = pp->create();
1454 delete pp;
1455
1456 Process *owner = ctc->getProcessPtr();
1457 ctc->setProcessPtr(cp);
1458 cp->assignThreadContext(ctc->contextId());
1459 owner->revokeThreadContext(ctc->contextId());
1460
1461 if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1462 BufferArg ptidBuf(ptidPtr, sizeof(long));
1463 long *ptid = (long *)ptidBuf.bufferPtr();
1464 *ptid = cp->pid();
1465 ptidBuf.copyOut(tc->getMemProxy());
1466 }
1467
1468 cp->initState();
1469 p->clone(tc, ctc, cp, flags);
1470
1471 if (flags & OS::TGT_CLONE_THREAD) {
1472 delete cp->sigchld;
1473 cp->sigchld = p->sigchld;
1474 } else if (flags & OS::TGT_SIGCHLD) {
1475 *cp->sigchld = true;
1476 }
1477
1478 if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1479 BufferArg ctidBuf(ctidPtr, sizeof(long));
1480 long *ctid = (long *)ctidBuf.bufferPtr();
1481 *ctid = cp->pid();
1482 ctidBuf.copyOut(ctc->getMemProxy());
1483 }
1484
1485 if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1486 cp->childClearTID = (uint64_t)ctidPtr;
1487
1488 ctc->clearArchRegs();
1489
1490 OS::archClone(flags, p, cp, tc, ctc, newStack, tlsPtr);
1491
1492 cp->setSyscallReturn(ctc, 0);
1493
1494#if THE_ISA == ALPHA_ISA
1495 ctc->setIntReg(TheISA::SyscallSuccessReg, 0);
1496#elif THE_ISA == SPARC_ISA
1497 tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1498 ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1499#endif
1500
1501 TheISA::PCState cpc = tc->pcState();
1502 cpc.advance();
1503 ctc->pcState(cpc);
1504 ctc->activate();
1505
1506 return cp->pid();
1507}
1508
1509/// Target fstatfs() handler.
1510template <class OS>
1511SyscallReturn
1512fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1513{
1514 int index = 0;
1515 int tgt_fd = p->getSyscallArg(tc, index);
1516 Addr bufPtr = p->getSyscallArg(tc, index);
1517
1518 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1519 if (!ffdp)
1520 return -EBADF;
1521 int sim_fd = ffdp->getSimFD();
1522
1523 struct statfs hostBuf;
1524 int result = fstatfs(sim_fd, &hostBuf);
1525
1526 if (result < 0)
1527 return -errno;
1528
1529 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1530
1531 return 0;
1532}
1533
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 <poll.h>
82#include <sys/mman.h>
83#include <sys/socket.h>
84#include <sys/stat.h>
85#if (NO_STATFS == 0)
86#include <sys/statfs.h>
87#else
88#include <sys/mount.h>
89#endif
90#include <sys/time.h>
91#include <sys/types.h>
92#include <sys/uio.h>
93#include <unistd.h>
94
95#include <cerrno>
96#include <memory>
97#include <string>
98
99#include "arch/generic/tlb.hh"
100#include "arch/utility.hh"
101#include "base/intmath.hh"
102#include "base/loader/object_file.hh"
103#include "base/logging.hh"
104#include "base/trace.hh"
105#include "base/types.hh"
106#include "config/the_isa.hh"
107#include "cpu/base.hh"
108#include "cpu/thread_context.hh"
109#include "mem/page_table.hh"
110#include "params/Process.hh"
111#include "sim/emul_driver.hh"
112#include "sim/futex_map.hh"
113#include "sim/process.hh"
114#include "sim/syscall_debug_macros.hh"
115#include "sim/syscall_desc.hh"
116#include "sim/syscall_emul_buf.hh"
117#include "sim/syscall_return.hh"
118
119//////////////////////////////////////////////////////////////////////
120//
121// The following emulation functions are generic enough that they
122// don't need to be recompiled for different emulated OS's. They are
123// defined in sim/syscall_emul.cc.
124//
125//////////////////////////////////////////////////////////////////////
126
127
128/// Handler for unimplemented syscalls that we haven't thought about.
129SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
130 Process *p, ThreadContext *tc);
131
132/// Handler for unimplemented syscalls that we never intend to
133/// implement (signal handling, etc.) and should not affect the correct
134/// behavior of the program. Print a warning only if the appropriate
135/// trace flag is enabled. Return success to the target program.
136SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
137 Process *p, ThreadContext *tc);
138
139// Target fallocateFunc() handler.
140SyscallReturn fallocateFunc(SyscallDesc *desc, int num,
141 Process *p, ThreadContext *tc);
142
143/// Target exit() handler: terminate current context.
144SyscallReturn exitFunc(SyscallDesc *desc, int num,
145 Process *p, ThreadContext *tc);
146
147/// Target exit_group() handler: terminate simulation. (exit all threads)
148SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
149 Process *p, ThreadContext *tc);
150
151/// Target set_tid_address() handler.
152SyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
153 Process *p, ThreadContext *tc);
154
155/// Target getpagesize() handler.
156SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
157 Process *p, ThreadContext *tc);
158
159/// Target brk() handler: set brk address.
160SyscallReturn brkFunc(SyscallDesc *desc, int num,
161 Process *p, ThreadContext *tc);
162
163/// Target close() handler.
164SyscallReturn closeFunc(SyscallDesc *desc, int num,
165 Process *p, ThreadContext *tc);
166
167/// Target lseek() handler.
168SyscallReturn lseekFunc(SyscallDesc *desc, int num,
169 Process *p, ThreadContext *tc);
170
171/// Target _llseek() handler.
172SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
173 Process *p, ThreadContext *tc);
174
175/// Target munmap() handler.
176SyscallReturn munmapFunc(SyscallDesc *desc, int num,
177 Process *p, ThreadContext *tc);
178
179/// Target shutdown() handler.
180SyscallReturn shutdownFunc(SyscallDesc *desc, int num,
181 Process *p, ThreadContext *tc);
182
183/// Target gethostname() handler.
184SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
185 Process *p, ThreadContext *tc);
186
187/// Target getcwd() handler.
188SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
189 Process *p, ThreadContext *tc);
190
191/// Target readlink() handler.
192SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
193 Process *p, ThreadContext *tc,
194 int index = 0);
195SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
196 Process *p, ThreadContext *tc);
197
198/// Target unlink() handler.
199SyscallReturn unlinkHelper(SyscallDesc *desc, int num,
200 Process *p, ThreadContext *tc,
201 int index);
202SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
203 Process *p, ThreadContext *tc);
204
205/// Target link() handler
206SyscallReturn linkFunc(SyscallDesc *desc, int num, Process *p,
207 ThreadContext *tc);
208
209/// Target symlink() handler.
210SyscallReturn symlinkFunc(SyscallDesc *desc, int num, Process *p,
211 ThreadContext *tc);
212
213/// Target mkdir() handler.
214SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
215 Process *p, ThreadContext *tc);
216
217/// Target mknod() handler.
218SyscallReturn mknodFunc(SyscallDesc *desc, int num,
219 Process *p, ThreadContext *tc);
220
221/// Target chdir() handler.
222SyscallReturn chdirFunc(SyscallDesc *desc, int num,
223 Process *p, ThreadContext *tc);
224
225// Target rmdir() handler.
226SyscallReturn rmdirFunc(SyscallDesc *desc, int num,
227 Process *p, ThreadContext *tc);
228
229/// Target rename() handler.
230SyscallReturn renameFunc(SyscallDesc *desc, int num,
231 Process *p, ThreadContext *tc);
232
233
234/// Target truncate() handler.
235SyscallReturn truncateFunc(SyscallDesc *desc, int num,
236 Process *p, ThreadContext *tc);
237
238
239/// Target ftruncate() handler.
240SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
241 Process *p, ThreadContext *tc);
242
243
244/// Target truncate64() handler.
245SyscallReturn truncate64Func(SyscallDesc *desc, int num,
246 Process *p, ThreadContext *tc);
247
248/// Target ftruncate64() handler.
249SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
250 Process *p, ThreadContext *tc);
251
252
253/// Target umask() handler.
254SyscallReturn umaskFunc(SyscallDesc *desc, int num,
255 Process *p, ThreadContext *tc);
256
257/// Target gettid() handler.
258SyscallReturn gettidFunc(SyscallDesc *desc, int num,
259 Process *p, ThreadContext *tc);
260
261/// Target chown() handler.
262SyscallReturn chownFunc(SyscallDesc *desc, int num,
263 Process *p, ThreadContext *tc);
264
265/// Target setpgid() handler.
266SyscallReturn setpgidFunc(SyscallDesc *desc, int num,
267 Process *p, ThreadContext *tc);
268
269/// Target fchown() handler.
270SyscallReturn fchownFunc(SyscallDesc *desc, int num,
271 Process *p, ThreadContext *tc);
272
273/// Target dup() handler.
274SyscallReturn dupFunc(SyscallDesc *desc, int num,
275 Process *process, ThreadContext *tc);
276
277/// Target dup2() handler.
278SyscallReturn dup2Func(SyscallDesc *desc, int num,
279 Process *process, ThreadContext *tc);
280
281/// Target fcntl() handler.
282SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
283 Process *process, ThreadContext *tc);
284
285/// Target fcntl64() handler.
286SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
287 Process *process, ThreadContext *tc);
288
289/// Target setuid() handler.
290SyscallReturn setuidFunc(SyscallDesc *desc, int num,
291 Process *p, ThreadContext *tc);
292
293/// Target pipe() handler.
294SyscallReturn pipeFunc(SyscallDesc *desc, int num,
295 Process *p, ThreadContext *tc);
296
297/// Internal pipe() handler.
298SyscallReturn pipeImpl(SyscallDesc *desc, int num, Process *p,
299 ThreadContext *tc, bool pseudoPipe);
300
301/// Target getpid() handler.
302SyscallReturn getpidFunc(SyscallDesc *desc, int num,
303 Process *p, ThreadContext *tc);
304
305// Target getpeername() handler.
306SyscallReturn getpeernameFunc(SyscallDesc *desc, int num,
307 Process *p, ThreadContext *tc);
308
309// Target bind() handler.
310SyscallReturn bindFunc(SyscallDesc *desc, int num,
311 Process *p, ThreadContext *tc);
312
313// Target listen() handler.
314SyscallReturn listenFunc(SyscallDesc *desc, int num,
315 Process *p, ThreadContext *tc);
316
317// Target connect() handler.
318SyscallReturn connectFunc(SyscallDesc *desc, int num,
319 Process *p, ThreadContext *tc);
320
321#if defined(SYS_getdents)
322// Target getdents() handler.
323SyscallReturn getdentsFunc(SyscallDesc *desc, int num,
324 Process *p, ThreadContext *tc);
325#endif
326
327#if defined(SYS_getdents64)
328// Target getdents() handler.
329SyscallReturn getdents64Func(SyscallDesc *desc, int num,
330 Process *p, ThreadContext *tc);
331#endif
332
333// Target sendto() handler.
334SyscallReturn sendtoFunc(SyscallDesc *desc, int num,
335 Process *p, ThreadContext *tc);
336
337// Target recvfrom() handler.
338SyscallReturn recvfromFunc(SyscallDesc *desc, int num,
339 Process *p, ThreadContext *tc);
340
341// Target recvmsg() handler.
342SyscallReturn recvmsgFunc(SyscallDesc *desc, int num,
343 Process *p, ThreadContext *tc);
344
345// Target sendmsg() handler.
346SyscallReturn sendmsgFunc(SyscallDesc *desc, int num,
347 Process *p, ThreadContext *tc);
348
349// Target getuid() handler.
350SyscallReturn getuidFunc(SyscallDesc *desc, int num,
351 Process *p, ThreadContext *tc);
352
353/// Target getgid() handler.
354SyscallReturn getgidFunc(SyscallDesc *desc, int num,
355 Process *p, ThreadContext *tc);
356
357/// Target getppid() handler.
358SyscallReturn getppidFunc(SyscallDesc *desc, int num,
359 Process *p, ThreadContext *tc);
360
361/// Target geteuid() handler.
362SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
363 Process *p, ThreadContext *tc);
364
365/// Target getegid() handler.
366SyscallReturn getegidFunc(SyscallDesc *desc, int num,
367 Process *p, ThreadContext *tc);
368
369/// Target access() handler
370SyscallReturn accessFunc(SyscallDesc *desc, int num,
371 Process *p, ThreadContext *tc);
372SyscallReturn accessFunc(SyscallDesc *desc, int num,
373 Process *p, ThreadContext *tc,
374 int index);
375
376// Target getsockopt() handler.
377SyscallReturn getsockoptFunc(SyscallDesc *desc, int num,
378 Process *p, ThreadContext *tc);
379
380// Target setsockopt() handler.
381SyscallReturn setsockoptFunc(SyscallDesc *desc, int num,
382 Process *p, ThreadContext *tc);
383
384// Target getsockname() handler.
385SyscallReturn getsocknameFunc(SyscallDesc *desc, int num,
386 Process *p, ThreadContext *tc);
387
388/// Futex system call
389/// Implemented by Daniel Sanchez
390/// Used by printf's in multi-threaded apps
391template <class OS>
392SyscallReturn
393futexFunc(SyscallDesc *desc, int callnum, Process *process,
394 ThreadContext *tc)
395{
396 using namespace std;
397
398 int index = 0;
399 Addr uaddr = process->getSyscallArg(tc, index);
400 int op = process->getSyscallArg(tc, index);
401 int val = process->getSyscallArg(tc, index);
402
403 /*
404 * Unsupported option that does not affect the correctness of the
405 * application. This is a performance optimization utilized by Linux.
406 */
407 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
408
409 FutexMap &futex_map = tc->getSystemPtr()->futexMap;
410
411 if (OS::TGT_FUTEX_WAIT == op) {
412 // Ensure futex system call accessed atomically.
413 BufferArg buf(uaddr, sizeof(int));
414 buf.copyIn(tc->getMemProxy());
415 int mem_val = *(int*)buf.bufferPtr();
416
417 /*
418 * The value in memory at uaddr is not equal with the expected val
419 * (a different thread must have changed it before the system call was
420 * invoked). In this case, we need to throw an error.
421 */
422 if (val != mem_val)
423 return -OS::TGT_EWOULDBLOCK;
424
425 futex_map.suspend(uaddr, process->tgid(), tc);
426
427 return 0;
428 } else if (OS::TGT_FUTEX_WAKE == op) {
429 return futex_map.wakeup(uaddr, process->tgid(), val);
430 }
431
432 warn("futex: op %d not implemented; ignoring.", op);
433 return -ENOSYS;
434}
435
436
437/// Pseudo Funcs - These functions use a different return convension,
438/// returning a second value in a register other than the normal return register
439SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
440 Process *process, ThreadContext *tc);
441
442/// Target getpidPseudo() handler.
443SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
444 Process *p, ThreadContext *tc);
445
446/// Target getuidPseudo() handler.
447SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
448 Process *p, ThreadContext *tc);
449
450/// Target getgidPseudo() handler.
451SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
452 Process *p, ThreadContext *tc);
453
454
455/// A readable name for 1,000,000, for converting microseconds to seconds.
456const int one_million = 1000000;
457/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
458const int one_billion = 1000000000;
459
460/// Approximate seconds since the epoch (1/1/1970). About a billion,
461/// by my reckoning. We want to keep this a constant (not use the
462/// real-world time) to keep simulations repeatable.
463const unsigned seconds_since_epoch = 1000000000;
464
465/// Helper function to convert current elapsed time to seconds and
466/// microseconds.
467template <class T1, class T2>
468void
469getElapsedTimeMicro(T1 &sec, T2 &usec)
470{
471 uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
472 sec = elapsed_usecs / one_million;
473 usec = elapsed_usecs % one_million;
474}
475
476/// Helper function to convert current elapsed time to seconds and
477/// nanoseconds.
478template <class T1, class T2>
479void
480getElapsedTimeNano(T1 &sec, T2 &nsec)
481{
482 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
483 sec = elapsed_nsecs / one_billion;
484 nsec = elapsed_nsecs % one_billion;
485}
486
487//////////////////////////////////////////////////////////////////////
488//
489// The following emulation functions are generic, but need to be
490// templated to account for differences in types, constants, etc.
491//
492//////////////////////////////////////////////////////////////////////
493
494 typedef struct statfs hst_statfs;
495#if NO_STAT64
496 typedef struct stat hst_stat;
497 typedef struct stat hst_stat64;
498#else
499 typedef struct stat hst_stat;
500 typedef struct stat64 hst_stat64;
501#endif
502
503//// Helper function to convert a host stat buffer to a target stat
504//// buffer. Also copies the target buffer out to the simulated
505//// memory space. Used by stat(), fstat(), and lstat().
506
507template <typename target_stat, typename host_stat>
508void
509convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
510{
511 using namespace TheISA;
512
513 if (fakeTTY)
514 tgt->st_dev = 0xA;
515 else
516 tgt->st_dev = host->st_dev;
517 tgt->st_dev = TheISA::htog(tgt->st_dev);
518 tgt->st_ino = host->st_ino;
519 tgt->st_ino = TheISA::htog(tgt->st_ino);
520 tgt->st_mode = host->st_mode;
521 if (fakeTTY) {
522 // Claim to be a character device
523 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT
524 tgt->st_mode |= S_IFCHR; // Set S_IFCHR
525 }
526 tgt->st_mode = TheISA::htog(tgt->st_mode);
527 tgt->st_nlink = host->st_nlink;
528 tgt->st_nlink = TheISA::htog(tgt->st_nlink);
529 tgt->st_uid = host->st_uid;
530 tgt->st_uid = TheISA::htog(tgt->st_uid);
531 tgt->st_gid = host->st_gid;
532 tgt->st_gid = TheISA::htog(tgt->st_gid);
533 if (fakeTTY)
534 tgt->st_rdev = 0x880d;
535 else
536 tgt->st_rdev = host->st_rdev;
537 tgt->st_rdev = TheISA::htog(tgt->st_rdev);
538 tgt->st_size = host->st_size;
539 tgt->st_size = TheISA::htog(tgt->st_size);
540 tgt->st_atimeX = host->st_atime;
541 tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
542 tgt->st_mtimeX = host->st_mtime;
543 tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
544 tgt->st_ctimeX = host->st_ctime;
545 tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
546 // Force the block size to be 8KB. This helps to ensure buffered io works
547 // consistently across different hosts.
548 tgt->st_blksize = 0x2000;
549 tgt->st_blksize = TheISA::htog(tgt->st_blksize);
550 tgt->st_blocks = host->st_blocks;
551 tgt->st_blocks = TheISA::htog(tgt->st_blocks);
552}
553
554// Same for stat64
555
556template <typename target_stat, typename host_stat64>
557void
558convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
559{
560 using namespace TheISA;
561
562 convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
563#if defined(STAT_HAVE_NSEC)
564 tgt->st_atime_nsec = host->st_atime_nsec;
565 tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
566 tgt->st_mtime_nsec = host->st_mtime_nsec;
567 tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
568 tgt->st_ctime_nsec = host->st_ctime_nsec;
569 tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
570#else
571 tgt->st_atime_nsec = 0;
572 tgt->st_mtime_nsec = 0;
573 tgt->st_ctime_nsec = 0;
574#endif
575}
576
577// Here are a couple of convenience functions
578template<class OS>
579void
580copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
581 hst_stat *host, bool fakeTTY = false)
582{
583 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
584 tgt_stat_buf tgt(addr);
585 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
586 tgt.copyOut(mem);
587}
588
589template<class OS>
590void
591copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
592 hst_stat64 *host, bool fakeTTY = false)
593{
594 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
595 tgt_stat_buf tgt(addr);
596 convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
597 tgt.copyOut(mem);
598}
599
600template <class OS>
601void
602copyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
603 hst_statfs *host)
604{
605 TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
606
607 tgt->f_type = TheISA::htog(host->f_type);
608#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
609 tgt->f_bsize = TheISA::htog(host->f_iosize);
610#else
611 tgt->f_bsize = TheISA::htog(host->f_bsize);
612#endif
613 tgt->f_blocks = TheISA::htog(host->f_blocks);
614 tgt->f_bfree = TheISA::htog(host->f_bfree);
615 tgt->f_bavail = TheISA::htog(host->f_bavail);
616 tgt->f_files = TheISA::htog(host->f_files);
617 tgt->f_ffree = TheISA::htog(host->f_ffree);
618 memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
619#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
620 tgt->f_namelen = TheISA::htog(host->f_namemax);
621 tgt->f_frsize = TheISA::htog(host->f_bsize);
622#elif defined(__APPLE__)
623 tgt->f_namelen = 0;
624 tgt->f_frsize = 0;
625#else
626 tgt->f_namelen = TheISA::htog(host->f_namelen);
627 tgt->f_frsize = TheISA::htog(host->f_frsize);
628#endif
629#if defined(__linux__)
630 memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
631#else
632 /*
633 * The fields are different sizes per OS. Don't bother with
634 * f_spare or f_reserved on non-Linux for now.
635 */
636 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
637#endif
638
639 tgt.copyOut(mem);
640}
641
642/// Target ioctl() handler. For the most part, programs call ioctl()
643/// only to find out if their stdout is a tty, to determine whether to
644/// do line or block buffering. We always claim that output fds are
645/// not TTYs to provide repeatable results.
646template <class OS>
647SyscallReturn
648ioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
649{
650 int index = 0;
651 int tgt_fd = p->getSyscallArg(tc, index);
652 unsigned req = p->getSyscallArg(tc, index);
653
654 DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
655
656 if (OS::isTtyReq(req))
657 return -ENOTTY;
658
659 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
660 if (!dfdp)
661 return -EBADF;
662
663 /**
664 * If the driver is valid, issue the ioctl through it. Otherwise,
665 * there's an implicit assumption that the device is a TTY type and we
666 * return that we do not have a valid TTY.
667 */
668 EmulatedDriver *emul_driver = dfdp->getDriver();
669 if (emul_driver)
670 return emul_driver->ioctl(p, tc, req);
671
672 /**
673 * For lack of a better return code, return ENOTTY. Ideally, we should
674 * return something better here, but at least we issue the warning.
675 */
676 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
677 tgt_fd, req, tc->pcState());
678 return -ENOTTY;
679}
680
681template <class OS>
682SyscallReturn
683openImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
684 bool isopenat)
685{
686 int index = 0;
687 int tgt_dirfd = -1;
688
689 /**
690 * If using the openat variant, read in the target directory file
691 * descriptor from the simulated process.
692 */
693 if (isopenat)
694 tgt_dirfd = p->getSyscallArg(tc, index);
695
696 /**
697 * Retrieve the simulated process' memory proxy and then read in the path
698 * string from that memory space into the host's working memory space.
699 */
700 std::string path;
701 if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
702 return -EFAULT;
703
704#ifdef __CYGWIN32__
705 int host_flags = O_BINARY;
706#else
707 int host_flags = 0;
708#endif
709 /**
710 * Translate target flags into host flags. Flags exist which are not
711 * ported between architectures which can cause check failures.
712 */
713 int tgt_flags = p->getSyscallArg(tc, index);
714 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
715 if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
716 tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
717 host_flags |= OS::openFlagTable[i].hostFlag;
718 }
719 }
720 if (tgt_flags) {
721 warn("open%s: cannot decode flags 0x%x",
722 isopenat ? "at" : "", tgt_flags);
723 }
724#ifdef __CYGWIN32__
725 host_flags |= O_BINARY;
726#endif
727
728 int mode = p->getSyscallArg(tc, index);
729
730 /**
731 * If the simulated process called open or openat with AT_FDCWD specified,
732 * take the current working directory value which was passed into the
733 * process class as a Python parameter and append the current path to
734 * create a full path.
735 * Otherwise, openat with a valid target directory file descriptor has
736 * been called. If the path option, which was passed in as a parameter,
737 * is not absolute, retrieve the directory file descriptor's path and
738 * prepend it to the path passed in as a parameter.
739 * In every case, we should have a full path (which is relevant to the
740 * host) to work with after this block has been passed.
741 */
742 if (!isopenat || (isopenat && tgt_dirfd == OS::TGT_AT_FDCWD)) {
743 path = p->fullPath(path);
744 } else if (!startswith(path, "/")) {
745 std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
746 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
747 if (!ffdp)
748 return -EBADF;
749 path.insert(0, ffdp->getFileName() + "/");
750 }
751
752 /**
753 * Since this is an emulated environment, we create pseudo file
754 * descriptors for device requests that have been registered with
755 * the process class through Python; this allows us to create a file
756 * descriptor for subsequent ioctl or mmap calls.
757 */
758 if (startswith(path, "/dev/")) {
759 std::string filename = path.substr(strlen("/dev/"));
760 EmulatedDriver *drv = p->findDriver(filename);
761 if (drv) {
762 DPRINTF_SYSCALL(Verbose, "open%s: passing call to "
763 "driver open with path[%s]\n",
764 isopenat ? "at" : "", path.c_str());
765 return drv->open(p, tc, mode, host_flags);
766 }
767 /**
768 * Fall through here for pass through to host devices, such
769 * as /dev/zero
770 */
771 }
772
773 /**
774 * Some special paths and files cannot be called on the host and need
775 * to be handled as special cases inside the simulator.
776 * If the full path that was created above does not match any of the
777 * special cases, pass it through to the open call on the host to let
778 * the host open the file on our behalf.
779 * If the host cannot open the file, return the host's error code back
780 * through the system call to the simulated process.
781 */
782 int sim_fd = -1;
783 std::vector<std::string> special_paths =
784 { "/proc/", "/system/", "/sys/", "/platform/", "/etc/passwd" };
785 for (auto entry : special_paths) {
786 if (startswith(path, entry))
787 sim_fd = OS::openSpecialFile(path, p, tc);
788 }
789 if (sim_fd == -1) {
790 sim_fd = open(path.c_str(), host_flags, mode);
791 }
792 if (sim_fd == -1) {
793 int local = -errno;
794 DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s\n",
795 isopenat ? "at" : "", path.c_str());
796 return local;
797 }
798
799 /**
800 * The file was opened successfully and needs to be recorded in the
801 * process' file descriptor array so that it can be retrieved later.
802 * The target file descriptor that is chosen will be the lowest unused
803 * file descriptor.
804 * Return the indirect target file descriptor back to the simulated
805 * process to act as a handle for the opened file.
806 */
807 auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
808 int tgt_fd = p->fds->allocFD(ffdp);
809 DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n",
810 isopenat ? "at" : "", sim_fd, tgt_fd, path.c_str());
811 return tgt_fd;
812}
813
814/// Target open() handler.
815template <class OS>
816SyscallReturn
817openFunc(SyscallDesc *desc, int callnum, Process *process,
818 ThreadContext *tc)
819{
820 return openImpl<OS>(desc, callnum, process, tc, false);
821}
822
823/// Target openat() handler.
824template <class OS>
825SyscallReturn
826openatFunc(SyscallDesc *desc, int callnum, Process *process,
827 ThreadContext *tc)
828{
829 return openImpl<OS>(desc, callnum, process, tc, true);
830}
831
832/// Target unlinkat() handler.
833template <class OS>
834SyscallReturn
835unlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
836 ThreadContext *tc)
837{
838 int index = 0;
839 int dirfd = process->getSyscallArg(tc, index);
840 if (dirfd != OS::TGT_AT_FDCWD)
841 warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
842
843 return unlinkHelper(desc, callnum, process, tc, 1);
844}
845
846/// Target facessat() handler
847template <class OS>
848SyscallReturn
849faccessatFunc(SyscallDesc *desc, int callnum, Process *process,
850 ThreadContext *tc)
851{
852 int index = 0;
853 int dirfd = process->getSyscallArg(tc, index);
854 if (dirfd != OS::TGT_AT_FDCWD)
855 warn("faccessat: first argument not AT_FDCWD; unlikely to work");
856 return accessFunc(desc, callnum, process, tc, 1);
857}
858
859/// Target readlinkat() handler
860template <class OS>
861SyscallReturn
862readlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
863 ThreadContext *tc)
864{
865 int index = 0;
866 int dirfd = process->getSyscallArg(tc, index);
867 if (dirfd != OS::TGT_AT_FDCWD)
868 warn("openat: first argument not AT_FDCWD; unlikely to work");
869 return readlinkFunc(desc, callnum, process, tc, 1);
870}
871
872/// Target renameat() handler.
873template <class OS>
874SyscallReturn
875renameatFunc(SyscallDesc *desc, int callnum, Process *process,
876 ThreadContext *tc)
877{
878 int index = 0;
879
880 int olddirfd = process->getSyscallArg(tc, index);
881 if (olddirfd != OS::TGT_AT_FDCWD)
882 warn("renameat: first argument not AT_FDCWD; unlikely to work");
883
884 std::string old_name;
885
886 if (!tc->getMemProxy().tryReadString(old_name,
887 process->getSyscallArg(tc, index)))
888 return -EFAULT;
889
890 int newdirfd = process->getSyscallArg(tc, index);
891 if (newdirfd != OS::TGT_AT_FDCWD)
892 warn("renameat: third argument not AT_FDCWD; unlikely to work");
893
894 std::string new_name;
895
896 if (!tc->getMemProxy().tryReadString(new_name,
897 process->getSyscallArg(tc, index)))
898 return -EFAULT;
899
900 // Adjust path for current working directory
901 old_name = process->fullPath(old_name);
902 new_name = process->fullPath(new_name);
903
904 int result = rename(old_name.c_str(), new_name.c_str());
905 return (result == -1) ? -errno : result;
906}
907
908/// Target sysinfo() handler.
909template <class OS>
910SyscallReturn
911sysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
912 ThreadContext *tc)
913{
914
915 int index = 0;
916 TypedBufferArg<typename OS::tgt_sysinfo>
917 sysinfo(process->getSyscallArg(tc, index));
918
919 sysinfo->uptime = seconds_since_epoch;
920 sysinfo->totalram = process->system->memSize();
921 sysinfo->mem_unit = 1;
922
923 sysinfo.copyOut(tc->getMemProxy());
924
925 return 0;
926}
927
928/// Target chmod() handler.
929template <class OS>
930SyscallReturn
931chmodFunc(SyscallDesc *desc, int callnum, Process *process,
932 ThreadContext *tc)
933{
934 std::string path;
935
936 int index = 0;
937 if (!tc->getMemProxy().tryReadString(path,
938 process->getSyscallArg(tc, index))) {
939 return -EFAULT;
940 }
941
942 uint32_t mode = process->getSyscallArg(tc, index);
943 mode_t hostMode = 0;
944
945 // XXX translate mode flags via OS::something???
946 hostMode = mode;
947
948 // Adjust path for current working directory
949 path = process->fullPath(path);
950
951 // do the chmod
952 int result = chmod(path.c_str(), hostMode);
953 if (result < 0)
954 return -errno;
955
956 return 0;
957}
958
959template <class OS>
960SyscallReturn
961pollFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
962{
963 int index = 0;
964 Addr fdsPtr = p->getSyscallArg(tc, index);
965 int nfds = p->getSyscallArg(tc, index);
966 int tmout = p->getSyscallArg(tc, index);
967
968 BufferArg fdsBuf(fdsPtr, sizeof(struct pollfd) * nfds);
969 fdsBuf.copyIn(tc->getMemProxy());
970
971 /**
972 * Record the target file descriptors in a local variable. We need to
973 * replace them with host file descriptors but we need a temporary copy
974 * for later. Afterwards, replace each target file descriptor in the
975 * poll_fd array with its host_fd.
976 */
977 int temp_tgt_fds[nfds];
978 for (index = 0; index < nfds; index++) {
979 temp_tgt_fds[index] = ((struct pollfd *)fdsBuf.bufferPtr())[index].fd;
980 auto tgt_fd = temp_tgt_fds[index];
981 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
982 if (!hbfdp)
983 return -EBADF;
984 auto host_fd = hbfdp->getSimFD();
985 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = host_fd;
986 }
987
988 /**
989 * We cannot allow an infinite poll to occur or it will inevitably cause
990 * a deadlock in the gem5 simulator with clone. We must pass in tmout with
991 * a non-negative value, however it also makes no sense to poll on the
992 * underlying host for any other time than tmout a zero timeout.
993 */
994 int status;
995 if (tmout < 0) {
996 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
997 if (status == 0) {
998 /**
999 * If blocking indefinitely, check the signal list to see if a
1000 * signal would break the poll out of the retry cycle and try
1001 * to return the signal interrupt instead.
1002 */
1003 System *sysh = tc->getSystemPtr();
1004 std::list<BasicSignal>::iterator it;
1005 for (it=sysh->signalList.begin(); it!=sysh->signalList.end(); it++)
1006 if (it->receiver == p)
1007 return -EINTR;
1008 return SyscallReturn::retry();
1009 }
1010 } else
1011 status = poll((struct pollfd *)fdsBuf.bufferPtr(), nfds, 0);
1012
1013 if (status == -1)
1014 return -errno;
1015
1016 /**
1017 * Replace each host_fd in the returned poll_fd array with its original
1018 * target file descriptor.
1019 */
1020 for (index = 0; index < nfds; index++) {
1021 auto tgt_fd = temp_tgt_fds[index];
1022 ((struct pollfd *)fdsBuf.bufferPtr())[index].fd = tgt_fd;
1023 }
1024
1025 /**
1026 * Copy out the pollfd struct because the host may have updated fields
1027 * in the structure.
1028 */
1029 fdsBuf.copyOut(tc->getMemProxy());
1030
1031 return status;
1032}
1033
1034/// Target fchmod() handler.
1035template <class OS>
1036SyscallReturn
1037fchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1038{
1039 int index = 0;
1040 int tgt_fd = p->getSyscallArg(tc, index);
1041 uint32_t mode = p->getSyscallArg(tc, index);
1042
1043 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1044 if (!ffdp)
1045 return -EBADF;
1046 int sim_fd = ffdp->getSimFD();
1047
1048 mode_t hostMode = mode;
1049
1050 int result = fchmod(sim_fd, hostMode);
1051
1052 return (result < 0) ? -errno : 0;
1053}
1054
1055/// Target mremap() handler.
1056template <class OS>
1057SyscallReturn
1058mremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
1059{
1060 int index = 0;
1061 Addr start = process->getSyscallArg(tc, index);
1062 uint64_t old_length = process->getSyscallArg(tc, index);
1063 uint64_t new_length = process->getSyscallArg(tc, index);
1064 uint64_t flags = process->getSyscallArg(tc, index);
1065 uint64_t provided_address = 0;
1066 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
1067
1068 if (use_provided_address)
1069 provided_address = process->getSyscallArg(tc, index);
1070
1071 if ((start % TheISA::PageBytes != 0) ||
1072 (provided_address % TheISA::PageBytes != 0)) {
1073 warn("mremap failing: arguments not page aligned");
1074 return -EINVAL;
1075 }
1076
1077 new_length = roundUp(new_length, TheISA::PageBytes);
1078
1079 if (new_length > old_length) {
1080 std::shared_ptr<MemState> mem_state = process->memState;
1081 Addr mmap_end = mem_state->getMmapEnd();
1082
1083 if ((start + old_length) == mmap_end &&
1084 (!use_provided_address || provided_address == start)) {
1085 // This case cannot occur when growing downward, as
1086 // start is greater than or equal to mmap_end.
1087 uint64_t diff = new_length - old_length;
1088 process->allocateMem(mmap_end, diff);
1089 mem_state->setMmapEnd(mmap_end + diff);
1090 return start;
1091 } else {
1092 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
1093 warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
1094 return -ENOMEM;
1095 } else {
1096 uint64_t new_start = provided_address;
1097 if (!use_provided_address) {
1098 new_start = process->mmapGrowsDown() ?
1099 mmap_end - new_length : mmap_end;
1100 mmap_end = process->mmapGrowsDown() ?
1101 new_start : mmap_end + new_length;
1102 mem_state->setMmapEnd(mmap_end);
1103 }
1104
1105 process->pTable->remap(start, old_length, new_start);
1106 warn("mremapping to new vaddr %08p-%08p, adding %d\n",
1107 new_start, new_start + new_length,
1108 new_length - old_length);
1109 // add on the remaining unallocated pages
1110 process->allocateMem(new_start + old_length,
1111 new_length - old_length,
1112 use_provided_address /* clobber */);
1113 if (use_provided_address &&
1114 ((new_start + new_length > mem_state->getMmapEnd() &&
1115 !process->mmapGrowsDown()) ||
1116 (new_start < mem_state->getMmapEnd() &&
1117 process->mmapGrowsDown()))) {
1118 // something fishy going on here, at least notify the user
1119 // @todo: increase mmap_end?
1120 warn("mmap region limit exceeded with MREMAP_FIXED\n");
1121 }
1122 warn("returning %08p as start\n", new_start);
1123 return new_start;
1124 }
1125 }
1126 } else {
1127 if (use_provided_address && provided_address != start)
1128 process->pTable->remap(start, new_length, provided_address);
1129 process->pTable->unmap(start + new_length, old_length - new_length);
1130 return use_provided_address ? provided_address : start;
1131 }
1132}
1133
1134/// Target stat() handler.
1135template <class OS>
1136SyscallReturn
1137statFunc(SyscallDesc *desc, int callnum, Process *process,
1138 ThreadContext *tc)
1139{
1140 std::string path;
1141
1142 int index = 0;
1143 if (!tc->getMemProxy().tryReadString(path,
1144 process->getSyscallArg(tc, index))) {
1145 return -EFAULT;
1146 }
1147 Addr bufPtr = process->getSyscallArg(tc, index);
1148
1149 // Adjust path for current working directory
1150 path = process->fullPath(path);
1151
1152 struct stat hostBuf;
1153 int result = stat(path.c_str(), &hostBuf);
1154
1155 if (result < 0)
1156 return -errno;
1157
1158 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1159
1160 return 0;
1161}
1162
1163
1164/// Target stat64() handler.
1165template <class OS>
1166SyscallReturn
1167stat64Func(SyscallDesc *desc, int callnum, Process *process,
1168 ThreadContext *tc)
1169{
1170 std::string path;
1171
1172 int index = 0;
1173 if (!tc->getMemProxy().tryReadString(path,
1174 process->getSyscallArg(tc, index)))
1175 return -EFAULT;
1176 Addr bufPtr = process->getSyscallArg(tc, index);
1177
1178 // Adjust path for current working directory
1179 path = process->fullPath(path);
1180
1181#if NO_STAT64
1182 struct stat hostBuf;
1183 int result = stat(path.c_str(), &hostBuf);
1184#else
1185 struct stat64 hostBuf;
1186 int result = stat64(path.c_str(), &hostBuf);
1187#endif
1188
1189 if (result < 0)
1190 return -errno;
1191
1192 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1193
1194 return 0;
1195}
1196
1197
1198/// Target fstatat64() handler.
1199template <class OS>
1200SyscallReturn
1201fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
1202 ThreadContext *tc)
1203{
1204 int index = 0;
1205 int dirfd = process->getSyscallArg(tc, index);
1206 if (dirfd != OS::TGT_AT_FDCWD)
1207 warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1208
1209 std::string path;
1210 if (!tc->getMemProxy().tryReadString(path,
1211 process->getSyscallArg(tc, index)))
1212 return -EFAULT;
1213 Addr bufPtr = process->getSyscallArg(tc, index);
1214
1215 // Adjust path for current working directory
1216 path = process->fullPath(path);
1217
1218#if NO_STAT64
1219 struct stat hostBuf;
1220 int result = stat(path.c_str(), &hostBuf);
1221#else
1222 struct stat64 hostBuf;
1223 int result = stat64(path.c_str(), &hostBuf);
1224#endif
1225
1226 if (result < 0)
1227 return -errno;
1228
1229 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1230
1231 return 0;
1232}
1233
1234
1235/// Target fstat64() handler.
1236template <class OS>
1237SyscallReturn
1238fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1239{
1240 int index = 0;
1241 int tgt_fd = p->getSyscallArg(tc, index);
1242 Addr bufPtr = p->getSyscallArg(tc, index);
1243
1244 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1245 if (!ffdp)
1246 return -EBADF;
1247 int sim_fd = ffdp->getSimFD();
1248
1249#if NO_STAT64
1250 struct stat hostBuf;
1251 int result = fstat(sim_fd, &hostBuf);
1252#else
1253 struct stat64 hostBuf;
1254 int result = fstat64(sim_fd, &hostBuf);
1255#endif
1256
1257 if (result < 0)
1258 return -errno;
1259
1260 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1261
1262 return 0;
1263}
1264
1265
1266/// Target lstat() handler.
1267template <class OS>
1268SyscallReturn
1269lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1270 ThreadContext *tc)
1271{
1272 std::string path;
1273
1274 int index = 0;
1275 if (!tc->getMemProxy().tryReadString(path,
1276 process->getSyscallArg(tc, index))) {
1277 return -EFAULT;
1278 }
1279 Addr bufPtr = process->getSyscallArg(tc, index);
1280
1281 // Adjust path for current working directory
1282 path = process->fullPath(path);
1283
1284 struct stat hostBuf;
1285 int result = lstat(path.c_str(), &hostBuf);
1286
1287 if (result < 0)
1288 return -errno;
1289
1290 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1291
1292 return 0;
1293}
1294
1295/// Target lstat64() handler.
1296template <class OS>
1297SyscallReturn
1298lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1299 ThreadContext *tc)
1300{
1301 std::string path;
1302
1303 int index = 0;
1304 if (!tc->getMemProxy().tryReadString(path,
1305 process->getSyscallArg(tc, index))) {
1306 return -EFAULT;
1307 }
1308 Addr bufPtr = process->getSyscallArg(tc, index);
1309
1310 // Adjust path for current working directory
1311 path = process->fullPath(path);
1312
1313#if NO_STAT64
1314 struct stat hostBuf;
1315 int result = lstat(path.c_str(), &hostBuf);
1316#else
1317 struct stat64 hostBuf;
1318 int result = lstat64(path.c_str(), &hostBuf);
1319#endif
1320
1321 if (result < 0)
1322 return -errno;
1323
1324 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1325
1326 return 0;
1327}
1328
1329/// Target fstat() handler.
1330template <class OS>
1331SyscallReturn
1332fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1333{
1334 int index = 0;
1335 int tgt_fd = p->getSyscallArg(tc, index);
1336 Addr bufPtr = p->getSyscallArg(tc, index);
1337
1338 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1339
1340 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1341 if (!ffdp)
1342 return -EBADF;
1343 int sim_fd = ffdp->getSimFD();
1344
1345 struct stat hostBuf;
1346 int result = fstat(sim_fd, &hostBuf);
1347
1348 if (result < 0)
1349 return -errno;
1350
1351 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1352
1353 return 0;
1354}
1355
1356/// Target statfs() handler.
1357template <class OS>
1358SyscallReturn
1359statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1360 ThreadContext *tc)
1361{
1362#if NO_STATFS
1363 warn("Host OS cannot support calls to statfs. Ignoring syscall");
1364#else
1365 std::string path;
1366
1367 int index = 0;
1368 if (!tc->getMemProxy().tryReadString(path,
1369 process->getSyscallArg(tc, index))) {
1370 return -EFAULT;
1371 }
1372 Addr bufPtr = process->getSyscallArg(tc, index);
1373
1374 // Adjust path for current working directory
1375 path = process->fullPath(path);
1376
1377 struct statfs hostBuf;
1378 int result = statfs(path.c_str(), &hostBuf);
1379
1380 if (result < 0)
1381 return -errno;
1382
1383 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1384#endif
1385 return 0;
1386}
1387
1388template <class OS>
1389SyscallReturn
1390cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1391{
1392 int index = 0;
1393
1394 RegVal flags = p->getSyscallArg(tc, index);
1395 RegVal newStack = p->getSyscallArg(tc, index);
1396 Addr ptidPtr = p->getSyscallArg(tc, index);
1397
1398#if THE_ISA == RISCV_ISA or THE_ISA == ARM_ISA
1399 /**
1400 * Linux sets CLONE_BACKWARDS flag for RISC-V and Arm.
1401 * The flag defines the list of clone() arguments in the following
1402 * order: flags -> newStack -> ptidPtr -> tlsPtr -> ctidPtr
1403 */
1404 Addr tlsPtr = p->getSyscallArg(tc, index);
1405 Addr ctidPtr = p->getSyscallArg(tc, index);
1406#else
1407 Addr ctidPtr = p->getSyscallArg(tc, index);
1408 Addr tlsPtr = p->getSyscallArg(tc, index);
1409#endif
1410
1411 if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1412 ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1413 ((flags & OS::TGT_CLONE_FS) && (flags & OS::TGT_CLONE_NEWNS)) ||
1414 ((flags & OS::TGT_CLONE_NEWIPC) && (flags & OS::TGT_CLONE_SYSVSEM)) ||
1415 ((flags & OS::TGT_CLONE_NEWPID) && (flags & OS::TGT_CLONE_THREAD)) ||
1416 ((flags & OS::TGT_CLONE_VM) && !(newStack)))
1417 return -EINVAL;
1418
1419 ThreadContext *ctc;
1420 if (!(ctc = p->findFreeContext()))
1421 fatal("clone: no spare thread context in system");
1422
1423 /**
1424 * Note that ProcessParams is generated by swig and there are no other
1425 * examples of how to create anything but this default constructor. The
1426 * fields are manually initialized instead of passing parameters to the
1427 * constructor.
1428 */
1429 ProcessParams *pp = new ProcessParams();
1430 pp->executable.assign(*(new std::string(p->progName())));
1431 pp->cmd.push_back(*(new std::string(p->progName())));
1432 pp->system = p->system;
1433 pp->cwd.assign(p->getcwd());
1434 pp->input.assign("stdin");
1435 pp->output.assign("stdout");
1436 pp->errout.assign("stderr");
1437 pp->uid = p->uid();
1438 pp->euid = p->euid();
1439 pp->gid = p->gid();
1440 pp->egid = p->egid();
1441
1442 /* Find the first free PID that's less than the maximum */
1443 std::set<int> const& pids = p->system->PIDs;
1444 int temp_pid = *pids.begin();
1445 do {
1446 temp_pid++;
1447 } while (pids.find(temp_pid) != pids.end());
1448 if (temp_pid >= System::maxPID)
1449 fatal("temp_pid is too large: %d", temp_pid);
1450
1451 pp->pid = temp_pid;
1452 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1453 Process *cp = pp->create();
1454 delete pp;
1455
1456 Process *owner = ctc->getProcessPtr();
1457 ctc->setProcessPtr(cp);
1458 cp->assignThreadContext(ctc->contextId());
1459 owner->revokeThreadContext(ctc->contextId());
1460
1461 if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1462 BufferArg ptidBuf(ptidPtr, sizeof(long));
1463 long *ptid = (long *)ptidBuf.bufferPtr();
1464 *ptid = cp->pid();
1465 ptidBuf.copyOut(tc->getMemProxy());
1466 }
1467
1468 cp->initState();
1469 p->clone(tc, ctc, cp, flags);
1470
1471 if (flags & OS::TGT_CLONE_THREAD) {
1472 delete cp->sigchld;
1473 cp->sigchld = p->sigchld;
1474 } else if (flags & OS::TGT_SIGCHLD) {
1475 *cp->sigchld = true;
1476 }
1477
1478 if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1479 BufferArg ctidBuf(ctidPtr, sizeof(long));
1480 long *ctid = (long *)ctidBuf.bufferPtr();
1481 *ctid = cp->pid();
1482 ctidBuf.copyOut(ctc->getMemProxy());
1483 }
1484
1485 if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1486 cp->childClearTID = (uint64_t)ctidPtr;
1487
1488 ctc->clearArchRegs();
1489
1490 OS::archClone(flags, p, cp, tc, ctc, newStack, tlsPtr);
1491
1492 cp->setSyscallReturn(ctc, 0);
1493
1494#if THE_ISA == ALPHA_ISA
1495 ctc->setIntReg(TheISA::SyscallSuccessReg, 0);
1496#elif THE_ISA == SPARC_ISA
1497 tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1498 ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1499#endif
1500
1501 TheISA::PCState cpc = tc->pcState();
1502 cpc.advance();
1503 ctc->pcState(cpc);
1504 ctc->activate();
1505
1506 return cp->pid();
1507}
1508
1509/// Target fstatfs() handler.
1510template <class OS>
1511SyscallReturn
1512fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1513{
1514 int index = 0;
1515 int tgt_fd = p->getSyscallArg(tc, index);
1516 Addr bufPtr = p->getSyscallArg(tc, index);
1517
1518 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1519 if (!ffdp)
1520 return -EBADF;
1521 int sim_fd = ffdp->getSimFD();
1522
1523 struct statfs hostBuf;
1524 int result = fstatfs(sim_fd, &hostBuf);
1525
1526 if (result < 0)
1527 return -errno;
1528
1529 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1530
1531 return 0;
1532}
1533
1534/// Target readv() handler.
1535template <class OS>
1536SyscallReturn
1537readvFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1538{
1539 int index = 0;
1540 int tgt_fd = p->getSyscallArg(tc, index);
1534
1541
1542 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1543 if (!ffdp)
1544 return -EBADF;
1545 int sim_fd = ffdp->getSimFD();
1546
1547 SETranslatingPortProxy &prox = tc->getMemProxy();
1548 uint64_t tiov_base = p->getSyscallArg(tc, index);
1549 size_t count = p->getSyscallArg(tc, index);
1550 typename OS::tgt_iovec tiov[count];
1551 struct iovec hiov[count];
1552 for (size_t i = 0; i < count; ++i) {
1553 prox.readBlob(tiov_base + (i * sizeof(typename OS::tgt_iovec)),
1554 (uint8_t*)&tiov[i], sizeof(typename OS::tgt_iovec));
1555 hiov[i].iov_len = TheISA::gtoh(tiov[i].iov_len);
1556 hiov[i].iov_base = new char [hiov[i].iov_len];
1557 }
1558
1559 int result = readv(sim_fd, hiov, count);
1560 int local_errno = errno;
1561
1562 for (size_t i = 0; i < count; ++i) {
1563 if (result != -1) {
1564 prox.writeBlob(TheISA::htog(tiov[i].iov_base),
1565 (uint8_t*)hiov[i].iov_base, hiov[i].iov_len);
1566 }
1567 delete [] (char *)hiov[i].iov_base;
1568 }
1569
1570 return (result == -1) ? -local_errno : result;
1571}
1572
1535/// Target writev() handler.
1536template <class OS>
1537SyscallReturn
1538writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1539{
1540 int index = 0;
1541 int tgt_fd = p->getSyscallArg(tc, index);
1542
1543 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1544 if (!hbfdp)
1545 return -EBADF;
1546 int sim_fd = hbfdp->getSimFD();
1547
1548 SETranslatingPortProxy &prox = tc->getMemProxy();
1549 uint64_t tiov_base = p->getSyscallArg(tc, index);
1550 size_t count = p->getSyscallArg(tc, index);
1551 struct iovec hiov[count];
1552 for (size_t i = 0; i < count; ++i) {
1553 typename OS::tgt_iovec tiov;
1554
1555 prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1556 (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1557 hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1558 hiov[i].iov_base = new char [hiov[i].iov_len];
1559 prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1560 hiov[i].iov_len);
1561 }
1562
1563 int result = writev(sim_fd, hiov, count);
1564
1565 for (size_t i = 0; i < count; ++i)
1566 delete [] (char *)hiov[i].iov_base;
1567
1573/// Target writev() handler.
1574template <class OS>
1575SyscallReturn
1576writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1577{
1578 int index = 0;
1579 int tgt_fd = p->getSyscallArg(tc, index);
1580
1581 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1582 if (!hbfdp)
1583 return -EBADF;
1584 int sim_fd = hbfdp->getSimFD();
1585
1586 SETranslatingPortProxy &prox = tc->getMemProxy();
1587 uint64_t tiov_base = p->getSyscallArg(tc, index);
1588 size_t count = p->getSyscallArg(tc, index);
1589 struct iovec hiov[count];
1590 for (size_t i = 0; i < count; ++i) {
1591 typename OS::tgt_iovec tiov;
1592
1593 prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1594 (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1595 hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1596 hiov[i].iov_base = new char [hiov[i].iov_len];
1597 prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1598 hiov[i].iov_len);
1599 }
1600
1601 int result = writev(sim_fd, hiov, count);
1602
1603 for (size_t i = 0; i < count; ++i)
1604 delete [] (char *)hiov[i].iov_base;
1605
1568 if (result < 0)
1569 return -errno;
1570
1571 return result;
1606 return (result == -1) ? -errno : result;
1572}
1573
1574/// Real mmap handler.
1575template <class OS>
1576SyscallReturn
1577mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1578 bool is_mmap2)
1579{
1580 int index = 0;
1581 Addr start = p->getSyscallArg(tc, index);
1582 uint64_t length = p->getSyscallArg(tc, index);
1583 int prot = p->getSyscallArg(tc, index);
1584 int tgt_flags = p->getSyscallArg(tc, index);
1585 int tgt_fd = p->getSyscallArg(tc, index);
1586 int offset = p->getSyscallArg(tc, index);
1587
1588 if (is_mmap2)
1589 offset *= TheISA::PageBytes;
1590
1591 if (start & (TheISA::PageBytes - 1) ||
1592 offset & (TheISA::PageBytes - 1) ||
1593 (tgt_flags & OS::TGT_MAP_PRIVATE &&
1594 tgt_flags & OS::TGT_MAP_SHARED) ||
1595 (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1596 !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1597 !length) {
1598 return -EINVAL;
1599 }
1600
1601 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1602 // With shared mmaps, there are two cases to consider:
1603 // 1) anonymous: writes should modify the mapping and this should be
1604 // visible to observers who share the mapping. Currently, it's
1605 // difficult to update the shared mapping because there's no
1606 // structure which maintains information about the which virtual
1607 // memory areas are shared. If that structure existed, it would be
1608 // possible to make the translations point to the same frames.
1609 // 2) file-backed: writes should modify the mapping and the file
1610 // which is backed by the mapping. The shared mapping problem is the
1611 // same as what was mentioned about the anonymous mappings. For
1612 // file-backed mappings, the writes to the file are difficult
1613 // because it requires syncing what the mapping holds with the file
1614 // that resides on the host system. So, any write on a real system
1615 // would cause the change to be propagated to the file mapping at
1616 // some point in the future (the inode is tracked along with the
1617 // mapping). This isn't guaranteed to always happen, but it usually
1618 // works well enough. The guarantee is provided by the msync system
1619 // call. We could force the change through with shared mappings with
1620 // a call to msync, but that again would require more information
1621 // than we currently maintain.
1622 warn("mmap: writing to shared mmap region is currently "
1623 "unsupported. The write succeeds on the target, but it "
1624 "will not be propagated to the host or shared mappings");
1625 }
1626
1627 length = roundUp(length, TheISA::PageBytes);
1628
1629 int sim_fd = -1;
1630 uint8_t *pmap = nullptr;
1631 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1632 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1633
1634 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1635 if (dfdp) {
1636 EmulatedDriver *emul_driver = dfdp->getDriver();
1637 return emul_driver->mmap(p, tc, start, length, prot,
1638 tgt_flags, tgt_fd, offset);
1639 }
1640
1641 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1642 if (!ffdp)
1643 return -EBADF;
1644 sim_fd = ffdp->getSimFD();
1645
1646 pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1647 sim_fd, offset);
1648
1649 if (pmap == (decltype(pmap))-1) {
1650 warn("mmap: failed to map file into host address space");
1651 return -errno;
1652 }
1653 }
1654
1655 // Extend global mmap region if necessary. Note that we ignore the
1656 // start address unless MAP_FIXED is specified.
1657 if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1658 std::shared_ptr<MemState> mem_state = p->memState;
1659 Addr mmap_end = mem_state->getMmapEnd();
1660
1661 start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1662 mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1663
1664 mem_state->setMmapEnd(mmap_end);
1665 }
1666
1667 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1668 start, start + length - 1);
1669
1670 // We only allow mappings to overwrite existing mappings if
1671 // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1672 // because we ignore the start hint if TGT_MAP_FIXED is not set.
1673 int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1674 if (clobber) {
1675 for (auto tc : p->system->threadContexts) {
1676 // If we might be overwriting old mappings, we need to
1677 // invalidate potentially stale mappings out of the TLBs.
1678 tc->getDTBPtr()->flushAll();
1679 tc->getITBPtr()->flushAll();
1680 }
1681 }
1682
1683 // Allocate physical memory and map it in. If the page table is already
1684 // mapped and clobber is not set, the simulator will issue throw a
1685 // fatal and bail out of the simulation.
1686 p->allocateMem(start, length, clobber);
1687
1688 // Transfer content into target address space.
1689 SETranslatingPortProxy &tp = tc->getMemProxy();
1690 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1691 // In general, we should zero the mapped area for anonymous mappings,
1692 // with something like:
1693 // tp.memsetBlob(start, 0, length);
1694 // However, given that we don't support sparse mappings, and
1695 // some applications can map a couple of gigabytes of space
1696 // (intending sparse usage), that can get painfully expensive.
1697 // Fortunately, since we don't properly implement munmap either,
1698 // there's no danger of remapping used memory, so for now all
1699 // newly mapped memory should already be zeroed so we can skip it.
1700 } else {
1701 // It is possible to mmap an area larger than a file, however
1702 // accessing unmapped portions the system triggers a "Bus error"
1703 // on the host. We must know when to stop copying the file from
1704 // the host into the target address space.
1705 struct stat file_stat;
1706 if (fstat(sim_fd, &file_stat) > 0)
1707 fatal("mmap: cannot stat file");
1708
1709 // Copy the portion of the file that is resident. This requires
1710 // checking both the mmap size and the filesize that we are
1711 // trying to mmap into this space; the mmap size also depends
1712 // on the specified offset into the file.
1713 uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1714 length);
1715 tp.writeBlob(start, pmap, size);
1716
1717 // Cleanup the mmap region before exiting this function.
1718 munmap(pmap, length);
1719
1720 // Maintain the symbol table for dynamic executables.
1721 // The loader will call mmap to map the images into its address
1722 // space and we intercept that here. We can verify that we are
1723 // executing inside the loader by checking the program counter value.
1724 // XXX: with multiprogrammed workloads or multi-node configurations,
1725 // this will not work since there is a single global symbol table.
1726 ObjectFile *interpreter = p->getInterpreter();
1727 if (interpreter) {
1728 Addr text_start = interpreter->textBase();
1729 Addr text_end = text_start + interpreter->textSize();
1730
1731 Addr pc = tc->pcState().pc();
1732
1733 if (pc >= text_start && pc < text_end) {
1734 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1735 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1736 ObjectFile *lib = createObjectFile(ffdp->getFileName());
1737
1738 if (lib) {
1739 lib->loadAllSymbols(debugSymbolTable,
1740 lib->textBase(), start);
1741 }
1742 }
1743 }
1744
1745 // Note that we do not zero out the remainder of the mapping. This
1746 // is done by a real system, but it probably will not affect
1747 // execution (hopefully).
1748 }
1749
1750 return start;
1751}
1752
1753template <class OS>
1754SyscallReturn
1755pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1756{
1757 int index = 0;
1758 int tgt_fd = p->getSyscallArg(tc, index);
1759 Addr bufPtr = p->getSyscallArg(tc, index);
1760 int nbytes = p->getSyscallArg(tc, index);
1761 int offset = p->getSyscallArg(tc, index);
1762
1763 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1764 if (!ffdp)
1765 return -EBADF;
1766 int sim_fd = ffdp->getSimFD();
1767
1768 BufferArg bufArg(bufPtr, nbytes);
1769 bufArg.copyIn(tc->getMemProxy());
1770
1771 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1772
1773 return (bytes_written == -1) ? -errno : bytes_written;
1774}
1775
1776/// Target mmap() handler.
1777template <class OS>
1778SyscallReturn
1779mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1780{
1781 return mmapImpl<OS>(desc, num, p, tc, false);
1782}
1783
1784/// Target mmap2() handler.
1785template <class OS>
1786SyscallReturn
1787mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1788{
1789 return mmapImpl<OS>(desc, num, p, tc, true);
1790}
1791
1792/// Target getrlimit() handler.
1793template <class OS>
1794SyscallReturn
1795getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1796 ThreadContext *tc)
1797{
1798 int index = 0;
1799 unsigned resource = process->getSyscallArg(tc, index);
1800 TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1801
1802 switch (resource) {
1803 case OS::TGT_RLIMIT_STACK:
1804 // max stack size in bytes: make up a number (8MB for now)
1805 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1806 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1807 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1808 break;
1809
1810 case OS::TGT_RLIMIT_DATA:
1811 // max data segment size in bytes: make up a number
1812 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1813 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1814 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1815 break;
1816
1817 default:
1818 warn("getrlimit: unimplemented resource %d", resource);
1819 return -EINVAL;
1820 break;
1821 }
1822
1823 rlp.copyOut(tc->getMemProxy());
1824 return 0;
1825}
1826
1827template <class OS>
1828SyscallReturn
1829prlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1830 ThreadContext *tc)
1831{
1832 int index = 0;
1833 if (process->getSyscallArg(tc, index) != 0)
1834 {
1835 warn("prlimit: ignoring rlimits for nonzero pid");
1836 return -EPERM;
1837 }
1838 int resource = process->getSyscallArg(tc, index);
1839 Addr n = process->getSyscallArg(tc, index);
1840 if (n != 0)
1841 warn("prlimit: ignoring new rlimit");
1842 Addr o = process->getSyscallArg(tc, index);
1843 if (o != 0)
1844 {
1845 TypedBufferArg<typename OS::rlimit> rlp(o);
1846 switch (resource) {
1847 case OS::TGT_RLIMIT_STACK:
1848 // max stack size in bytes: make up a number (8MB for now)
1849 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1850 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1851 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1852 break;
1853 case OS::TGT_RLIMIT_DATA:
1854 // max data segment size in bytes: make up a number
1855 rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
1856 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1857 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1858 break;
1859 default:
1860 warn("prlimit: unimplemented resource %d", resource);
1861 return -EINVAL;
1862 break;
1863 }
1864 rlp.copyOut(tc->getMemProxy());
1865 }
1866 return 0;
1867}
1868
1869/// Target clock_gettime() function.
1870template <class OS>
1871SyscallReturn
1872clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1873{
1874 int index = 1;
1875 //int clk_id = p->getSyscallArg(tc, index);
1876 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1877
1878 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1879 tp->tv_sec += seconds_since_epoch;
1880 tp->tv_sec = TheISA::htog(tp->tv_sec);
1881 tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1882
1883 tp.copyOut(tc->getMemProxy());
1884
1885 return 0;
1886}
1887
1888/// Target clock_getres() function.
1889template <class OS>
1890SyscallReturn
1891clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1892{
1893 int index = 1;
1894 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1895
1896 // Set resolution at ns, which is what clock_gettime() returns
1897 tp->tv_sec = 0;
1898 tp->tv_nsec = 1;
1899
1900 tp.copyOut(tc->getMemProxy());
1901
1902 return 0;
1903}
1904
1905/// Target gettimeofday() handler.
1906template <class OS>
1907SyscallReturn
1908gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1909 ThreadContext *tc)
1910{
1911 int index = 0;
1912 TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1913
1914 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1915 tp->tv_sec += seconds_since_epoch;
1916 tp->tv_sec = TheISA::htog(tp->tv_sec);
1917 tp->tv_usec = TheISA::htog(tp->tv_usec);
1918
1919 tp.copyOut(tc->getMemProxy());
1920
1921 return 0;
1922}
1923
1924
1925/// Target utimes() handler.
1926template <class OS>
1927SyscallReturn
1928utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1929 ThreadContext *tc)
1930{
1931 std::string path;
1932
1933 int index = 0;
1934 if (!tc->getMemProxy().tryReadString(path,
1935 process->getSyscallArg(tc, index))) {
1936 return -EFAULT;
1937 }
1938
1939 TypedBufferArg<typename OS::timeval [2]>
1940 tp(process->getSyscallArg(tc, index));
1941 tp.copyIn(tc->getMemProxy());
1942
1943 struct timeval hostTimeval[2];
1944 for (int i = 0; i < 2; ++i) {
1945 hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1946 hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1947 }
1948
1949 // Adjust path for current working directory
1950 path = process->fullPath(path);
1951
1952 int result = utimes(path.c_str(), hostTimeval);
1953
1954 if (result < 0)
1955 return -errno;
1956
1957 return 0;
1958}
1959
1960template <class OS>
1961SyscallReturn
1962execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1963{
1964 desc->setFlags(0);
1965
1966 int index = 0;
1967 std::string path;
1968 SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
1969 if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
1970 return -EFAULT;
1971
1972 if (access(path.c_str(), F_OK) == -1)
1973 return -EACCES;
1974
1975 auto read_in = [](std::vector<std::string> & vect,
1976 SETranslatingPortProxy & mem_proxy,
1977 Addr mem_loc)
1978 {
1979 for (int inc = 0; ; inc++) {
1980 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
1981 b.copyIn(mem_proxy);
1982
1983 if (!*(Addr*)b.bufferPtr())
1984 break;
1985
1986 vect.push_back(std::string());
1987 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
1988 }
1989 };
1990
1991 /**
1992 * Note that ProcessParams is generated by swig and there are no other
1993 * examples of how to create anything but this default constructor. The
1994 * fields are manually initialized instead of passing parameters to the
1995 * constructor.
1996 */
1997 ProcessParams *pp = new ProcessParams();
1998 pp->executable = path;
1999 Addr argv_mem_loc = p->getSyscallArg(tc, index);
2000 read_in(pp->cmd, mem_proxy, argv_mem_loc);
2001 Addr envp_mem_loc = p->getSyscallArg(tc, index);
2002 read_in(pp->env, mem_proxy, envp_mem_loc);
2003 pp->uid = p->uid();
2004 pp->egid = p->egid();
2005 pp->euid = p->euid();
2006 pp->gid = p->gid();
2007 pp->ppid = p->ppid();
2008 pp->pid = p->pid();
2009 pp->input.assign("cin");
2010 pp->output.assign("cout");
2011 pp->errout.assign("cerr");
2012 pp->cwd.assign(p->getcwd());
2013 pp->system = p->system;
2014 /**
2015 * Prevent process object creation with identical PIDs (which will trip
2016 * a fatal check in Process constructor). The execve call is supposed to
2017 * take over the currently executing process' identity but replace
2018 * whatever it is doing with a new process image. Instead of hijacking
2019 * the process object in the simulator, we create a new process object
2020 * and bind to the previous process' thread below (hijacking the thread).
2021 */
2022 p->system->PIDs.erase(p->pid());
2023 Process *new_p = pp->create();
2024 delete pp;
2025
2026 /**
2027 * Work through the file descriptor array and close any files marked
2028 * close-on-exec.
2029 */
2030 new_p->fds = p->fds;
2031 for (int i = 0; i < new_p->fds->getSize(); i++) {
2032 std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
2033 if (fdep && fdep->getCOE())
2034 new_p->fds->closeFDEntry(i);
2035 }
2036
2037 *new_p->sigchld = true;
2038
2039 delete p;
2040 tc->clearArchRegs();
2041 tc->setProcessPtr(new_p);
2042 new_p->assignThreadContext(tc->contextId());
2043 new_p->initState();
2044 tc->activate();
2045 TheISA::PCState pcState = tc->pcState();
2046 tc->setNPC(pcState.instAddr());
2047
2048 desc->setFlags(SyscallDesc::SuppressReturnValue);
2049 return 0;
2050}
2051
2052/// Target getrusage() function.
2053template <class OS>
2054SyscallReturn
2055getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
2056 ThreadContext *tc)
2057{
2058 int index = 0;
2059 int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
2060 TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
2061
2062 rup->ru_utime.tv_sec = 0;
2063 rup->ru_utime.tv_usec = 0;
2064 rup->ru_stime.tv_sec = 0;
2065 rup->ru_stime.tv_usec = 0;
2066 rup->ru_maxrss = 0;
2067 rup->ru_ixrss = 0;
2068 rup->ru_idrss = 0;
2069 rup->ru_isrss = 0;
2070 rup->ru_minflt = 0;
2071 rup->ru_majflt = 0;
2072 rup->ru_nswap = 0;
2073 rup->ru_inblock = 0;
2074 rup->ru_oublock = 0;
2075 rup->ru_msgsnd = 0;
2076 rup->ru_msgrcv = 0;
2077 rup->ru_nsignals = 0;
2078 rup->ru_nvcsw = 0;
2079 rup->ru_nivcsw = 0;
2080
2081 switch (who) {
2082 case OS::TGT_RUSAGE_SELF:
2083 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
2084 rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
2085 rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
2086 break;
2087
2088 case OS::TGT_RUSAGE_CHILDREN:
2089 // do nothing. We have no child processes, so they take no time.
2090 break;
2091
2092 default:
2093 // don't really handle THREAD or CHILDREN, but just warn and
2094 // plow ahead
2095 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
2096 who);
2097 }
2098
2099 rup.copyOut(tc->getMemProxy());
2100
2101 return 0;
2102}
2103
2104/// Target times() function.
2105template <class OS>
2106SyscallReturn
2107timesFunc(SyscallDesc *desc, int callnum, Process *process,
2108 ThreadContext *tc)
2109{
2110 int index = 0;
2111 TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
2112
2113 // Fill in the time structure (in clocks)
2114 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
2115 bufp->tms_utime = clocks;
2116 bufp->tms_stime = 0;
2117 bufp->tms_cutime = 0;
2118 bufp->tms_cstime = 0;
2119
2120 // Convert to host endianness
2121 bufp->tms_utime = TheISA::htog(bufp->tms_utime);
2122
2123 // Write back
2124 bufp.copyOut(tc->getMemProxy());
2125
2126 // Return clock ticks since system boot
2127 return clocks;
2128}
2129
2130/// Target time() function.
2131template <class OS>
2132SyscallReturn
2133timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
2134{
2135 typename OS::time_t sec, usec;
2136 getElapsedTimeMicro(sec, usec);
2137 sec += seconds_since_epoch;
2138
2139 int index = 0;
2140 Addr taddr = (Addr)process->getSyscallArg(tc, index);
2141 if (taddr != 0) {
2142 typename OS::time_t t = sec;
2143 t = TheISA::htog(t);
2144 SETranslatingPortProxy &p = tc->getMemProxy();
2145 p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
2146 }
2147 return sec;
2148}
2149
2150template <class OS>
2151SyscallReturn
2152tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
2153{
2154 int index = 0;
2155 int tgid = process->getSyscallArg(tc, index);
2156 int tid = process->getSyscallArg(tc, index);
2157 int sig = process->getSyscallArg(tc, index);
2158
2159 /**
2160 * This system call is intended to allow killing a specific thread
2161 * within an arbitrary thread group if sanctioned with permission checks.
2162 * It's usually true that threads share the termination signal as pointed
2163 * out by the pthread_kill man page and this seems to be the intended
2164 * usage. Due to this being an emulated environment, assume the following:
2165 * Threads are allowed to call tgkill because the EUID for all threads
2166 * should be the same. There is no signal handling mechanism for kernel
2167 * registration of signal handlers since signals are poorly supported in
2168 * emulation mode. Since signal handlers cannot be registered, all
2169 * threads within in a thread group must share the termination signal.
2170 * We never exhaust PIDs so there's no chance of finding the wrong one
2171 * due to PID rollover.
2172 */
2173
2174 System *sys = tc->getSystemPtr();
2175 Process *tgt_proc = nullptr;
2176 for (int i = 0; i < sys->numContexts(); i++) {
2177 Process *temp = sys->threadContexts[i]->getProcessPtr();
2178 if (temp->pid() == tid) {
2179 tgt_proc = temp;
2180 break;
2181 }
2182 }
2183
2184 if (sig != 0 || sig != OS::TGT_SIGABRT)
2185 return -EINVAL;
2186
2187 if (tgt_proc == nullptr)
2188 return -ESRCH;
2189
2190 if (tgid != -1 && tgt_proc->tgid() != tgid)
2191 return -ESRCH;
2192
2193 if (sig == OS::TGT_SIGABRT)
2194 exitGroupFunc(desc, 252, process, tc);
2195
2196 return 0;
2197}
2198
2199template <class OS>
2200SyscallReturn
2201socketFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2202{
2203 int index = 0;
2204 int domain = p->getSyscallArg(tc, index);
2205 int type = p->getSyscallArg(tc, index);
2206 int prot = p->getSyscallArg(tc, index);
2207
2208 int sim_fd = socket(domain, type, prot);
2209 if (sim_fd == -1)
2210 return -errno;
2211
2212 auto sfdp = std::make_shared<SocketFDEntry>(sim_fd, domain, type, prot);
2213 int tgt_fd = p->fds->allocFD(sfdp);
2214
2215 return tgt_fd;
2216}
2217
2218template <class OS>
2219SyscallReturn
2220socketpairFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2221{
2222 int index = 0;
2223 int domain = p->getSyscallArg(tc, index);
2224 int type = p->getSyscallArg(tc, index);
2225 int prot = p->getSyscallArg(tc, index);
2226 Addr svPtr = p->getSyscallArg(tc, index);
2227
2228 BufferArg svBuf((Addr)svPtr, 2 * sizeof(int));
2229 int status = socketpair(domain, type, prot, (int *)svBuf.bufferPtr());
2230 if (status == -1)
2231 return -errno;
2232
2233 int *fds = (int *)svBuf.bufferPtr();
2234
2235 auto sfdp1 = std::make_shared<SocketFDEntry>(fds[0], domain, type, prot);
2236 fds[0] = p->fds->allocFD(sfdp1);
2237 auto sfdp2 = std::make_shared<SocketFDEntry>(fds[1], domain, type, prot);
2238 fds[1] = p->fds->allocFD(sfdp2);
2239 svBuf.copyOut(tc->getMemProxy());
2240
2241 return status;
2242}
2243
2244template <class OS>
2245SyscallReturn
2246selectFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
2247{
2248 int retval;
2249
2250 int index = 0;
2251 int nfds_t = p->getSyscallArg(tc, index);
2252 Addr fds_read_ptr = p->getSyscallArg(tc, index);
2253 Addr fds_writ_ptr = p->getSyscallArg(tc, index);
2254 Addr fds_excp_ptr = p->getSyscallArg(tc, index);
2255 Addr time_val_ptr = p->getSyscallArg(tc, index);
2256
2257 TypedBufferArg<typename OS::fd_set> rd_t(fds_read_ptr);
2258 TypedBufferArg<typename OS::fd_set> wr_t(fds_writ_ptr);
2259 TypedBufferArg<typename OS::fd_set> ex_t(fds_excp_ptr);
2260 TypedBufferArg<typename OS::timeval> tp(time_val_ptr);
2261
2262 /**
2263 * Host fields. Notice that these use the definitions from the system
2264 * headers instead of the gem5 headers and libraries. If the host and
2265 * target have different header file definitions, this will not work.
2266 */
2267 fd_set rd_h;
2268 FD_ZERO(&rd_h);
2269 fd_set wr_h;
2270 FD_ZERO(&wr_h);
2271 fd_set ex_h;
2272 FD_ZERO(&ex_h);
2273
2274 /**
2275 * Copy in the fd_set from the target.
2276 */
2277 if (fds_read_ptr)
2278 rd_t.copyIn(tc->getMemProxy());
2279 if (fds_writ_ptr)
2280 wr_t.copyIn(tc->getMemProxy());
2281 if (fds_excp_ptr)
2282 ex_t.copyIn(tc->getMemProxy());
2283
2284 /**
2285 * We need to translate the target file descriptor set into a host file
2286 * descriptor set. This involves both our internal process fd array
2287 * and the fd_set defined in Linux header files. The nfds field also
2288 * needs to be updated as it will be only target specific after
2289 * retrieving it from the target; the nfds value is expected to be the
2290 * highest file descriptor that needs to be checked, so we need to extend
2291 * it out for nfds_h when we do the update.
2292 */
2293 int nfds_h = 0;
2294 std::map<int, int> trans_map;
2295 auto try_add_host_set = [&](fd_set *tgt_set_entry,
2296 fd_set *hst_set_entry,
2297 int iter) -> bool
2298 {
2299 /**
2300 * By this point, we know that we are looking at a valid file
2301 * descriptor set on the target. We need to check if the target file
2302 * descriptor value passed in as iter is part of the set.
2303 */
2304 if (FD_ISSET(iter, tgt_set_entry)) {
2305 /**
2306 * We know that the target file descriptor belongs to the set,
2307 * but we do not yet know if the file descriptor is valid or
2308 * that we have a host mapping. Check that now.
2309 */
2310 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[iter]);
2311 if (!hbfdp)
2312 return true;
2313 auto sim_fd = hbfdp->getSimFD();
2314
2315 /**
2316 * Add the sim_fd to tgt_fd translation into trans_map for use
2317 * later when we need to zero the target fd_set structures and
2318 * then update them with hits returned from the host select call.
2319 */
2320 trans_map[sim_fd] = iter;
2321
2322 /**
2323 * We know that the host file descriptor exists so now we check
2324 * if we need to update the max count for nfds_h before passing
2325 * the duplicated structure into the host.
2326 */
2327 nfds_h = std::max(nfds_h - 1, sim_fd + 1);
2328
2329 /**
2330 * Add the host file descriptor to the set that we are going to
2331 * pass into the host.
2332 */
2333 FD_SET(sim_fd, hst_set_entry);
2334 }
2335 return false;
2336 };
2337
2338 for (int i = 0; i < nfds_t; i++) {
2339 if (fds_read_ptr) {
2340 bool ebadf = try_add_host_set((fd_set*)&*rd_t, &rd_h, i);
2341 if (ebadf) return -EBADF;
2342 }
2343 if (fds_writ_ptr) {
2344 bool ebadf = try_add_host_set((fd_set*)&*wr_t, &wr_h, i);
2345 if (ebadf) return -EBADF;
2346 }
2347 if (fds_excp_ptr) {
2348 bool ebadf = try_add_host_set((fd_set*)&*ex_t, &ex_h, i);
2349 if (ebadf) return -EBADF;
2350 }
2351 }
2352
2353 if (time_val_ptr) {
2354 /**
2355 * It might be possible to decrement the timeval based on some
2356 * derivation of wall clock determined from elapsed simulator ticks
2357 * but that seems like overkill. Rather, we just set the timeval with
2358 * zero timeout. (There is no reason to block during the simulation
2359 * as it only decreases simulator performance.)
2360 */
2361 tp->tv_sec = 0;
2362 tp->tv_usec = 0;
2363
2364 retval = select(nfds_h,
2365 fds_read_ptr ? &rd_h : nullptr,
2366 fds_writ_ptr ? &wr_h : nullptr,
2367 fds_excp_ptr ? &ex_h : nullptr,
2368 (timeval*)&*tp);
2369 } else {
2370 /**
2371 * If the timeval pointer is null, setup a new timeval structure to
2372 * pass into the host select call. Unfortunately, we will need to
2373 * manually check the return value and throw a retry fault if the
2374 * return value is zero. Allowing the system call to block will
2375 * likely deadlock the event queue.
2376 */
2377 struct timeval tv = { 0, 0 };
2378
2379 retval = select(nfds_h,
2380 fds_read_ptr ? &rd_h : nullptr,
2381 fds_writ_ptr ? &wr_h : nullptr,
2382 fds_excp_ptr ? &ex_h : nullptr,
2383 &tv);
2384
2385 if (retval == 0) {
2386 /**
2387 * If blocking indefinitely, check the signal list to see if a
2388 * signal would break the poll out of the retry cycle and try to
2389 * return the signal interrupt instead.
2390 */
2391 for (auto sig : tc->getSystemPtr()->signalList)
2392 if (sig.receiver == p)
2393 return -EINTR;
2394 return SyscallReturn::retry();
2395 }
2396 }
2397
2398 if (retval == -1)
2399 return -errno;
2400
2401 FD_ZERO((fd_set*)&*rd_t);
2402 FD_ZERO((fd_set*)&*wr_t);
2403 FD_ZERO((fd_set*)&*ex_t);
2404
2405 /**
2406 * We need to translate the host file descriptor set into a target file
2407 * descriptor set. This involves both our internal process fd array
2408 * and the fd_set defined in header files.
2409 */
2410 for (int i = 0; i < nfds_h; i++) {
2411 if (fds_read_ptr) {
2412 if (FD_ISSET(i, &rd_h))
2413 FD_SET(trans_map[i], (fd_set*)&*rd_t);
2414 }
2415
2416 if (fds_writ_ptr) {
2417 if (FD_ISSET(i, &wr_h))
2418 FD_SET(trans_map[i], (fd_set*)&*wr_t);
2419 }
2420
2421 if (fds_excp_ptr) {
2422 if (FD_ISSET(i, &ex_h))
2423 FD_SET(trans_map[i], (fd_set*)&*ex_t);
2424 }
2425 }
2426
2427 if (fds_read_ptr)
2428 rd_t.copyOut(tc->getMemProxy());
2429 if (fds_writ_ptr)
2430 wr_t.copyOut(tc->getMemProxy());
2431 if (fds_excp_ptr)
2432 ex_t.copyOut(tc->getMemProxy());
2433 if (time_val_ptr)
2434 tp.copyOut(tc->getMemProxy());
2435
2436 return retval;
2437}
2438
2439template <class OS>
2440SyscallReturn
2441readFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2442{
2443 int index = 0;
2444 int tgt_fd = p->getSyscallArg(tc, index);
2445 Addr buf_ptr = p->getSyscallArg(tc, index);
2446 int nbytes = p->getSyscallArg(tc, index);
2447
2448 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2449 if (!hbfdp)
2450 return -EBADF;
2451 int sim_fd = hbfdp->getSimFD();
2452
2453 struct pollfd pfd;
2454 pfd.fd = sim_fd;
2455 pfd.events = POLLIN | POLLPRI;
2456 if ((poll(&pfd, 1, 0) == 0)
2457 && !(hbfdp->getFlags() & OS::TGT_O_NONBLOCK))
2458 return SyscallReturn::retry();
2459
2460 BufferArg buf_arg(buf_ptr, nbytes);
2461 int bytes_read = read(sim_fd, buf_arg.bufferPtr(), nbytes);
2462
2463 if (bytes_read > 0)
2464 buf_arg.copyOut(tc->getMemProxy());
2465
2466 return (bytes_read == -1) ? -errno : bytes_read;
2467}
2468
2469template <class OS>
2470SyscallReturn
2471writeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2472{
2473 int index = 0;
2474 int tgt_fd = p->getSyscallArg(tc, index);
2475 Addr buf_ptr = p->getSyscallArg(tc, index);
2476 int nbytes = p->getSyscallArg(tc, index);
2477
2478 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2479 if (!hbfdp)
2480 return -EBADF;
2481 int sim_fd = hbfdp->getSimFD();
2482
2483 BufferArg buf_arg(buf_ptr, nbytes);
2484 buf_arg.copyIn(tc->getMemProxy());
2485
2486 struct pollfd pfd;
2487 pfd.fd = sim_fd;
2488 pfd.events = POLLOUT;
2489
2490 /**
2491 * We don't want to poll on /dev/random. The kernel will not enable the
2492 * file descriptor for writing unless the entropy in the system falls
2493 * below write_wakeup_threshold. This is not guaranteed to happen
2494 * depending on host settings.
2495 */
2496 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(hbfdp);
2497 if (ffdp && (ffdp->getFileName() != "/dev/random")) {
2498 if (!poll(&pfd, 1, 0) && !(ffdp->getFlags() & OS::TGT_O_NONBLOCK))
2499 return SyscallReturn::retry();
2500 }
2501
2502 int bytes_written = write(sim_fd, buf_arg.bufferPtr(), nbytes);
2503
2504 if (bytes_written != -1)
2505 fsync(sim_fd);
2506
2507 return (bytes_written == -1) ? -errno : bytes_written;
2508}
2509
2510template <class OS>
2511SyscallReturn
2512wait4Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2513{
2514 int index = 0;
2515 pid_t pid = p->getSyscallArg(tc, index);
2516 Addr statPtr = p->getSyscallArg(tc, index);
2517 int options = p->getSyscallArg(tc, index);
2518 Addr rusagePtr = p->getSyscallArg(tc, index);
2519
2520 if (rusagePtr)
2521 DPRINTFR(SyscallVerbose,
2522 "%d: %s: syscall wait4: rusage pointer provided however "
2523 "functionality not supported. Ignoring rusage pointer.\n",
2524 curTick(), tc->getCpuPtr()->name());
2525
2526 /**
2527 * Currently, wait4 is only implemented so that it will wait for children
2528 * exit conditions which are denoted by a SIGCHLD signals posted into the
2529 * system signal list. We return no additional information via any of the
2530 * parameters supplied to wait4. If nothing is found in the system signal
2531 * list, we will wait indefinitely for SIGCHLD to post by retrying the
2532 * call.
2533 */
2534 System *sysh = tc->getSystemPtr();
2535 std::list<BasicSignal>::iterator iter;
2536 for (iter=sysh->signalList.begin(); iter!=sysh->signalList.end(); iter++) {
2537 if (iter->receiver == p) {
2538 if (pid < -1) {
2539 if ((iter->sender->pgid() == -pid)
2540 && (iter->signalValue == OS::TGT_SIGCHLD))
2541 goto success;
2542 } else if (pid == -1) {
2543 if (iter->signalValue == OS::TGT_SIGCHLD)
2544 goto success;
2545 } else if (pid == 0) {
2546 if ((iter->sender->pgid() == p->pgid())
2547 && (iter->signalValue == OS::TGT_SIGCHLD))
2548 goto success;
2549 } else {
2550 if ((iter->sender->pid() == pid)
2551 && (iter->signalValue == OS::TGT_SIGCHLD))
2552 goto success;
2553 }
2554 }
2555 }
2556
2557 return (options & OS::TGT_WNOHANG) ? 0 : SyscallReturn::retry();
2558
2559success:
2560 // Set status to EXITED for WIFEXITED evaluations.
2561 const int EXITED = 0;
2562 BufferArg statusBuf(statPtr, sizeof(int));
2563 *(int *)statusBuf.bufferPtr() = EXITED;
2564 statusBuf.copyOut(tc->getMemProxy());
2565
2566 // Return the child PID.
2567 pid_t retval = iter->sender->pid();
2568 sysh->signalList.erase(iter);
2569 return retval;
2570}
2571
2572template <class OS>
2573SyscallReturn
2574acceptFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2575{
2576 struct sockaddr sa;
2577 socklen_t addrLen;
2578 int host_fd;
2579 int index = 0;
2580 int tgt_fd = p->getSyscallArg(tc, index);
2581 Addr addrPtr = p->getSyscallArg(tc, index);
2582 Addr lenPtr = p->getSyscallArg(tc, index);
2583
2584 BufferArg *lenBufPtr = nullptr;
2585 BufferArg *addrBufPtr = nullptr;
2586
2587 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
2588 if (!sfdp)
2589 return -EBADF;
2590 int sim_fd = sfdp->getSimFD();
2591
2592 /**
2593 * We poll the socket file descriptor first to guarantee that we do not
2594 * block on our accept call. The socket can be opened without the
2595 * non-blocking flag (it blocks). This will cause deadlocks between
2596 * communicating processes.
2597 */
2598 struct pollfd pfd;
2599 pfd.fd = sim_fd;
2600 pfd.events = POLLIN | POLLPRI;
2601 if ((poll(&pfd, 1, 0) == 0)
2602 && !(sfdp->getFlags() & OS::TGT_O_NONBLOCK))
2603 return SyscallReturn::retry();
2604
2605 if (lenPtr) {
2606 lenBufPtr = new BufferArg(lenPtr, sizeof(socklen_t));
2607 lenBufPtr->copyIn(tc->getMemProxy());
2608 memcpy(&addrLen, (socklen_t *)lenBufPtr->bufferPtr(),
2609 sizeof(socklen_t));
2610 }
2611
2612 if (addrPtr) {
2613 addrBufPtr = new BufferArg(addrPtr, sizeof(struct sockaddr));
2614 addrBufPtr->copyIn(tc->getMemProxy());
2615 memcpy(&sa, (struct sockaddr *)addrBufPtr->bufferPtr(),
2616 sizeof(struct sockaddr));
2617 }
2618
2619 host_fd = accept(sim_fd, &sa, &addrLen);
2620
2621 if (host_fd == -1)
2622 return -errno;
2623
2624 if (addrPtr) {
2625 memcpy(addrBufPtr->bufferPtr(), &sa, sizeof(sa));
2626 addrBufPtr->copyOut(tc->getMemProxy());
2627 delete(addrBufPtr);
2628 }
2629
2630 if (lenPtr) {
2631 *(socklen_t *)lenBufPtr->bufferPtr() = addrLen;
2632 lenBufPtr->copyOut(tc->getMemProxy());
2633 delete(lenBufPtr);
2634 }
2635
2636 auto afdp = std::make_shared<SocketFDEntry>(host_fd, sfdp->_domain,
2637 sfdp->_type, sfdp->_protocol);
2638 return p->fds->allocFD(afdp);
2639}
2640
2641#endif // __SIM_SYSCALL_EMUL_HH__
1607}
1608
1609/// Real mmap handler.
1610template <class OS>
1611SyscallReturn
1612mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1613 bool is_mmap2)
1614{
1615 int index = 0;
1616 Addr start = p->getSyscallArg(tc, index);
1617 uint64_t length = p->getSyscallArg(tc, index);
1618 int prot = p->getSyscallArg(tc, index);
1619 int tgt_flags = p->getSyscallArg(tc, index);
1620 int tgt_fd = p->getSyscallArg(tc, index);
1621 int offset = p->getSyscallArg(tc, index);
1622
1623 if (is_mmap2)
1624 offset *= TheISA::PageBytes;
1625
1626 if (start & (TheISA::PageBytes - 1) ||
1627 offset & (TheISA::PageBytes - 1) ||
1628 (tgt_flags & OS::TGT_MAP_PRIVATE &&
1629 tgt_flags & OS::TGT_MAP_SHARED) ||
1630 (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1631 !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1632 !length) {
1633 return -EINVAL;
1634 }
1635
1636 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1637 // With shared mmaps, there are two cases to consider:
1638 // 1) anonymous: writes should modify the mapping and this should be
1639 // visible to observers who share the mapping. Currently, it's
1640 // difficult to update the shared mapping because there's no
1641 // structure which maintains information about the which virtual
1642 // memory areas are shared. If that structure existed, it would be
1643 // possible to make the translations point to the same frames.
1644 // 2) file-backed: writes should modify the mapping and the file
1645 // which is backed by the mapping. The shared mapping problem is the
1646 // same as what was mentioned about the anonymous mappings. For
1647 // file-backed mappings, the writes to the file are difficult
1648 // because it requires syncing what the mapping holds with the file
1649 // that resides on the host system. So, any write on a real system
1650 // would cause the change to be propagated to the file mapping at
1651 // some point in the future (the inode is tracked along with the
1652 // mapping). This isn't guaranteed to always happen, but it usually
1653 // works well enough. The guarantee is provided by the msync system
1654 // call. We could force the change through with shared mappings with
1655 // a call to msync, but that again would require more information
1656 // than we currently maintain.
1657 warn("mmap: writing to shared mmap region is currently "
1658 "unsupported. The write succeeds on the target, but it "
1659 "will not be propagated to the host or shared mappings");
1660 }
1661
1662 length = roundUp(length, TheISA::PageBytes);
1663
1664 int sim_fd = -1;
1665 uint8_t *pmap = nullptr;
1666 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1667 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1668
1669 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1670 if (dfdp) {
1671 EmulatedDriver *emul_driver = dfdp->getDriver();
1672 return emul_driver->mmap(p, tc, start, length, prot,
1673 tgt_flags, tgt_fd, offset);
1674 }
1675
1676 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1677 if (!ffdp)
1678 return -EBADF;
1679 sim_fd = ffdp->getSimFD();
1680
1681 pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1682 sim_fd, offset);
1683
1684 if (pmap == (decltype(pmap))-1) {
1685 warn("mmap: failed to map file into host address space");
1686 return -errno;
1687 }
1688 }
1689
1690 // Extend global mmap region if necessary. Note that we ignore the
1691 // start address unless MAP_FIXED is specified.
1692 if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1693 std::shared_ptr<MemState> mem_state = p->memState;
1694 Addr mmap_end = mem_state->getMmapEnd();
1695
1696 start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1697 mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1698
1699 mem_state->setMmapEnd(mmap_end);
1700 }
1701
1702 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1703 start, start + length - 1);
1704
1705 // We only allow mappings to overwrite existing mappings if
1706 // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1707 // because we ignore the start hint if TGT_MAP_FIXED is not set.
1708 int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1709 if (clobber) {
1710 for (auto tc : p->system->threadContexts) {
1711 // If we might be overwriting old mappings, we need to
1712 // invalidate potentially stale mappings out of the TLBs.
1713 tc->getDTBPtr()->flushAll();
1714 tc->getITBPtr()->flushAll();
1715 }
1716 }
1717
1718 // Allocate physical memory and map it in. If the page table is already
1719 // mapped and clobber is not set, the simulator will issue throw a
1720 // fatal and bail out of the simulation.
1721 p->allocateMem(start, length, clobber);
1722
1723 // Transfer content into target address space.
1724 SETranslatingPortProxy &tp = tc->getMemProxy();
1725 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1726 // In general, we should zero the mapped area for anonymous mappings,
1727 // with something like:
1728 // tp.memsetBlob(start, 0, length);
1729 // However, given that we don't support sparse mappings, and
1730 // some applications can map a couple of gigabytes of space
1731 // (intending sparse usage), that can get painfully expensive.
1732 // Fortunately, since we don't properly implement munmap either,
1733 // there's no danger of remapping used memory, so for now all
1734 // newly mapped memory should already be zeroed so we can skip it.
1735 } else {
1736 // It is possible to mmap an area larger than a file, however
1737 // accessing unmapped portions the system triggers a "Bus error"
1738 // on the host. We must know when to stop copying the file from
1739 // the host into the target address space.
1740 struct stat file_stat;
1741 if (fstat(sim_fd, &file_stat) > 0)
1742 fatal("mmap: cannot stat file");
1743
1744 // Copy the portion of the file that is resident. This requires
1745 // checking both the mmap size and the filesize that we are
1746 // trying to mmap into this space; the mmap size also depends
1747 // on the specified offset into the file.
1748 uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1749 length);
1750 tp.writeBlob(start, pmap, size);
1751
1752 // Cleanup the mmap region before exiting this function.
1753 munmap(pmap, length);
1754
1755 // Maintain the symbol table for dynamic executables.
1756 // The loader will call mmap to map the images into its address
1757 // space and we intercept that here. We can verify that we are
1758 // executing inside the loader by checking the program counter value.
1759 // XXX: with multiprogrammed workloads or multi-node configurations,
1760 // this will not work since there is a single global symbol table.
1761 ObjectFile *interpreter = p->getInterpreter();
1762 if (interpreter) {
1763 Addr text_start = interpreter->textBase();
1764 Addr text_end = text_start + interpreter->textSize();
1765
1766 Addr pc = tc->pcState().pc();
1767
1768 if (pc >= text_start && pc < text_end) {
1769 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1770 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1771 ObjectFile *lib = createObjectFile(ffdp->getFileName());
1772
1773 if (lib) {
1774 lib->loadAllSymbols(debugSymbolTable,
1775 lib->textBase(), start);
1776 }
1777 }
1778 }
1779
1780 // Note that we do not zero out the remainder of the mapping. This
1781 // is done by a real system, but it probably will not affect
1782 // execution (hopefully).
1783 }
1784
1785 return start;
1786}
1787
1788template <class OS>
1789SyscallReturn
1790pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1791{
1792 int index = 0;
1793 int tgt_fd = p->getSyscallArg(tc, index);
1794 Addr bufPtr = p->getSyscallArg(tc, index);
1795 int nbytes = p->getSyscallArg(tc, index);
1796 int offset = p->getSyscallArg(tc, index);
1797
1798 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1799 if (!ffdp)
1800 return -EBADF;
1801 int sim_fd = ffdp->getSimFD();
1802
1803 BufferArg bufArg(bufPtr, nbytes);
1804 bufArg.copyIn(tc->getMemProxy());
1805
1806 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1807
1808 return (bytes_written == -1) ? -errno : bytes_written;
1809}
1810
1811/// Target mmap() handler.
1812template <class OS>
1813SyscallReturn
1814mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1815{
1816 return mmapImpl<OS>(desc, num, p, tc, false);
1817}
1818
1819/// Target mmap2() handler.
1820template <class OS>
1821SyscallReturn
1822mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1823{
1824 return mmapImpl<OS>(desc, num, p, tc, true);
1825}
1826
1827/// Target getrlimit() handler.
1828template <class OS>
1829SyscallReturn
1830getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1831 ThreadContext *tc)
1832{
1833 int index = 0;
1834 unsigned resource = process->getSyscallArg(tc, index);
1835 TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1836
1837 switch (resource) {
1838 case OS::TGT_RLIMIT_STACK:
1839 // max stack size in bytes: make up a number (8MB for now)
1840 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1841 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1842 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1843 break;
1844
1845 case OS::TGT_RLIMIT_DATA:
1846 // max data segment size in bytes: make up a number
1847 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1848 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1849 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1850 break;
1851
1852 default:
1853 warn("getrlimit: unimplemented resource %d", resource);
1854 return -EINVAL;
1855 break;
1856 }
1857
1858 rlp.copyOut(tc->getMemProxy());
1859 return 0;
1860}
1861
1862template <class OS>
1863SyscallReturn
1864prlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1865 ThreadContext *tc)
1866{
1867 int index = 0;
1868 if (process->getSyscallArg(tc, index) != 0)
1869 {
1870 warn("prlimit: ignoring rlimits for nonzero pid");
1871 return -EPERM;
1872 }
1873 int resource = process->getSyscallArg(tc, index);
1874 Addr n = process->getSyscallArg(tc, index);
1875 if (n != 0)
1876 warn("prlimit: ignoring new rlimit");
1877 Addr o = process->getSyscallArg(tc, index);
1878 if (o != 0)
1879 {
1880 TypedBufferArg<typename OS::rlimit> rlp(o);
1881 switch (resource) {
1882 case OS::TGT_RLIMIT_STACK:
1883 // max stack size in bytes: make up a number (8MB for now)
1884 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1885 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1886 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1887 break;
1888 case OS::TGT_RLIMIT_DATA:
1889 // max data segment size in bytes: make up a number
1890 rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
1891 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1892 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1893 break;
1894 default:
1895 warn("prlimit: unimplemented resource %d", resource);
1896 return -EINVAL;
1897 break;
1898 }
1899 rlp.copyOut(tc->getMemProxy());
1900 }
1901 return 0;
1902}
1903
1904/// Target clock_gettime() function.
1905template <class OS>
1906SyscallReturn
1907clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1908{
1909 int index = 1;
1910 //int clk_id = p->getSyscallArg(tc, index);
1911 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1912
1913 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1914 tp->tv_sec += seconds_since_epoch;
1915 tp->tv_sec = TheISA::htog(tp->tv_sec);
1916 tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1917
1918 tp.copyOut(tc->getMemProxy());
1919
1920 return 0;
1921}
1922
1923/// Target clock_getres() function.
1924template <class OS>
1925SyscallReturn
1926clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1927{
1928 int index = 1;
1929 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1930
1931 // Set resolution at ns, which is what clock_gettime() returns
1932 tp->tv_sec = 0;
1933 tp->tv_nsec = 1;
1934
1935 tp.copyOut(tc->getMemProxy());
1936
1937 return 0;
1938}
1939
1940/// Target gettimeofday() handler.
1941template <class OS>
1942SyscallReturn
1943gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1944 ThreadContext *tc)
1945{
1946 int index = 0;
1947 TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1948
1949 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1950 tp->tv_sec += seconds_since_epoch;
1951 tp->tv_sec = TheISA::htog(tp->tv_sec);
1952 tp->tv_usec = TheISA::htog(tp->tv_usec);
1953
1954 tp.copyOut(tc->getMemProxy());
1955
1956 return 0;
1957}
1958
1959
1960/// Target utimes() handler.
1961template <class OS>
1962SyscallReturn
1963utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1964 ThreadContext *tc)
1965{
1966 std::string path;
1967
1968 int index = 0;
1969 if (!tc->getMemProxy().tryReadString(path,
1970 process->getSyscallArg(tc, index))) {
1971 return -EFAULT;
1972 }
1973
1974 TypedBufferArg<typename OS::timeval [2]>
1975 tp(process->getSyscallArg(tc, index));
1976 tp.copyIn(tc->getMemProxy());
1977
1978 struct timeval hostTimeval[2];
1979 for (int i = 0; i < 2; ++i) {
1980 hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1981 hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1982 }
1983
1984 // Adjust path for current working directory
1985 path = process->fullPath(path);
1986
1987 int result = utimes(path.c_str(), hostTimeval);
1988
1989 if (result < 0)
1990 return -errno;
1991
1992 return 0;
1993}
1994
1995template <class OS>
1996SyscallReturn
1997execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1998{
1999 desc->setFlags(0);
2000
2001 int index = 0;
2002 std::string path;
2003 SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
2004 if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
2005 return -EFAULT;
2006
2007 if (access(path.c_str(), F_OK) == -1)
2008 return -EACCES;
2009
2010 auto read_in = [](std::vector<std::string> & vect,
2011 SETranslatingPortProxy & mem_proxy,
2012 Addr mem_loc)
2013 {
2014 for (int inc = 0; ; inc++) {
2015 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
2016 b.copyIn(mem_proxy);
2017
2018 if (!*(Addr*)b.bufferPtr())
2019 break;
2020
2021 vect.push_back(std::string());
2022 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
2023 }
2024 };
2025
2026 /**
2027 * Note that ProcessParams is generated by swig and there are no other
2028 * examples of how to create anything but this default constructor. The
2029 * fields are manually initialized instead of passing parameters to the
2030 * constructor.
2031 */
2032 ProcessParams *pp = new ProcessParams();
2033 pp->executable = path;
2034 Addr argv_mem_loc = p->getSyscallArg(tc, index);
2035 read_in(pp->cmd, mem_proxy, argv_mem_loc);
2036 Addr envp_mem_loc = p->getSyscallArg(tc, index);
2037 read_in(pp->env, mem_proxy, envp_mem_loc);
2038 pp->uid = p->uid();
2039 pp->egid = p->egid();
2040 pp->euid = p->euid();
2041 pp->gid = p->gid();
2042 pp->ppid = p->ppid();
2043 pp->pid = p->pid();
2044 pp->input.assign("cin");
2045 pp->output.assign("cout");
2046 pp->errout.assign("cerr");
2047 pp->cwd.assign(p->getcwd());
2048 pp->system = p->system;
2049 /**
2050 * Prevent process object creation with identical PIDs (which will trip
2051 * a fatal check in Process constructor). The execve call is supposed to
2052 * take over the currently executing process' identity but replace
2053 * whatever it is doing with a new process image. Instead of hijacking
2054 * the process object in the simulator, we create a new process object
2055 * and bind to the previous process' thread below (hijacking the thread).
2056 */
2057 p->system->PIDs.erase(p->pid());
2058 Process *new_p = pp->create();
2059 delete pp;
2060
2061 /**
2062 * Work through the file descriptor array and close any files marked
2063 * close-on-exec.
2064 */
2065 new_p->fds = p->fds;
2066 for (int i = 0; i < new_p->fds->getSize(); i++) {
2067 std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
2068 if (fdep && fdep->getCOE())
2069 new_p->fds->closeFDEntry(i);
2070 }
2071
2072 *new_p->sigchld = true;
2073
2074 delete p;
2075 tc->clearArchRegs();
2076 tc->setProcessPtr(new_p);
2077 new_p->assignThreadContext(tc->contextId());
2078 new_p->initState();
2079 tc->activate();
2080 TheISA::PCState pcState = tc->pcState();
2081 tc->setNPC(pcState.instAddr());
2082
2083 desc->setFlags(SyscallDesc::SuppressReturnValue);
2084 return 0;
2085}
2086
2087/// Target getrusage() function.
2088template <class OS>
2089SyscallReturn
2090getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
2091 ThreadContext *tc)
2092{
2093 int index = 0;
2094 int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
2095 TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
2096
2097 rup->ru_utime.tv_sec = 0;
2098 rup->ru_utime.tv_usec = 0;
2099 rup->ru_stime.tv_sec = 0;
2100 rup->ru_stime.tv_usec = 0;
2101 rup->ru_maxrss = 0;
2102 rup->ru_ixrss = 0;
2103 rup->ru_idrss = 0;
2104 rup->ru_isrss = 0;
2105 rup->ru_minflt = 0;
2106 rup->ru_majflt = 0;
2107 rup->ru_nswap = 0;
2108 rup->ru_inblock = 0;
2109 rup->ru_oublock = 0;
2110 rup->ru_msgsnd = 0;
2111 rup->ru_msgrcv = 0;
2112 rup->ru_nsignals = 0;
2113 rup->ru_nvcsw = 0;
2114 rup->ru_nivcsw = 0;
2115
2116 switch (who) {
2117 case OS::TGT_RUSAGE_SELF:
2118 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
2119 rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
2120 rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
2121 break;
2122
2123 case OS::TGT_RUSAGE_CHILDREN:
2124 // do nothing. We have no child processes, so they take no time.
2125 break;
2126
2127 default:
2128 // don't really handle THREAD or CHILDREN, but just warn and
2129 // plow ahead
2130 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
2131 who);
2132 }
2133
2134 rup.copyOut(tc->getMemProxy());
2135
2136 return 0;
2137}
2138
2139/// Target times() function.
2140template <class OS>
2141SyscallReturn
2142timesFunc(SyscallDesc *desc, int callnum, Process *process,
2143 ThreadContext *tc)
2144{
2145 int index = 0;
2146 TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
2147
2148 // Fill in the time structure (in clocks)
2149 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
2150 bufp->tms_utime = clocks;
2151 bufp->tms_stime = 0;
2152 bufp->tms_cutime = 0;
2153 bufp->tms_cstime = 0;
2154
2155 // Convert to host endianness
2156 bufp->tms_utime = TheISA::htog(bufp->tms_utime);
2157
2158 // Write back
2159 bufp.copyOut(tc->getMemProxy());
2160
2161 // Return clock ticks since system boot
2162 return clocks;
2163}
2164
2165/// Target time() function.
2166template <class OS>
2167SyscallReturn
2168timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
2169{
2170 typename OS::time_t sec, usec;
2171 getElapsedTimeMicro(sec, usec);
2172 sec += seconds_since_epoch;
2173
2174 int index = 0;
2175 Addr taddr = (Addr)process->getSyscallArg(tc, index);
2176 if (taddr != 0) {
2177 typename OS::time_t t = sec;
2178 t = TheISA::htog(t);
2179 SETranslatingPortProxy &p = tc->getMemProxy();
2180 p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
2181 }
2182 return sec;
2183}
2184
2185template <class OS>
2186SyscallReturn
2187tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
2188{
2189 int index = 0;
2190 int tgid = process->getSyscallArg(tc, index);
2191 int tid = process->getSyscallArg(tc, index);
2192 int sig = process->getSyscallArg(tc, index);
2193
2194 /**
2195 * This system call is intended to allow killing a specific thread
2196 * within an arbitrary thread group if sanctioned with permission checks.
2197 * It's usually true that threads share the termination signal as pointed
2198 * out by the pthread_kill man page and this seems to be the intended
2199 * usage. Due to this being an emulated environment, assume the following:
2200 * Threads are allowed to call tgkill because the EUID for all threads
2201 * should be the same. There is no signal handling mechanism for kernel
2202 * registration of signal handlers since signals are poorly supported in
2203 * emulation mode. Since signal handlers cannot be registered, all
2204 * threads within in a thread group must share the termination signal.
2205 * We never exhaust PIDs so there's no chance of finding the wrong one
2206 * due to PID rollover.
2207 */
2208
2209 System *sys = tc->getSystemPtr();
2210 Process *tgt_proc = nullptr;
2211 for (int i = 0; i < sys->numContexts(); i++) {
2212 Process *temp = sys->threadContexts[i]->getProcessPtr();
2213 if (temp->pid() == tid) {
2214 tgt_proc = temp;
2215 break;
2216 }
2217 }
2218
2219 if (sig != 0 || sig != OS::TGT_SIGABRT)
2220 return -EINVAL;
2221
2222 if (tgt_proc == nullptr)
2223 return -ESRCH;
2224
2225 if (tgid != -1 && tgt_proc->tgid() != tgid)
2226 return -ESRCH;
2227
2228 if (sig == OS::TGT_SIGABRT)
2229 exitGroupFunc(desc, 252, process, tc);
2230
2231 return 0;
2232}
2233
2234template <class OS>
2235SyscallReturn
2236socketFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2237{
2238 int index = 0;
2239 int domain = p->getSyscallArg(tc, index);
2240 int type = p->getSyscallArg(tc, index);
2241 int prot = p->getSyscallArg(tc, index);
2242
2243 int sim_fd = socket(domain, type, prot);
2244 if (sim_fd == -1)
2245 return -errno;
2246
2247 auto sfdp = std::make_shared<SocketFDEntry>(sim_fd, domain, type, prot);
2248 int tgt_fd = p->fds->allocFD(sfdp);
2249
2250 return tgt_fd;
2251}
2252
2253template <class OS>
2254SyscallReturn
2255socketpairFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2256{
2257 int index = 0;
2258 int domain = p->getSyscallArg(tc, index);
2259 int type = p->getSyscallArg(tc, index);
2260 int prot = p->getSyscallArg(tc, index);
2261 Addr svPtr = p->getSyscallArg(tc, index);
2262
2263 BufferArg svBuf((Addr)svPtr, 2 * sizeof(int));
2264 int status = socketpair(domain, type, prot, (int *)svBuf.bufferPtr());
2265 if (status == -1)
2266 return -errno;
2267
2268 int *fds = (int *)svBuf.bufferPtr();
2269
2270 auto sfdp1 = std::make_shared<SocketFDEntry>(fds[0], domain, type, prot);
2271 fds[0] = p->fds->allocFD(sfdp1);
2272 auto sfdp2 = std::make_shared<SocketFDEntry>(fds[1], domain, type, prot);
2273 fds[1] = p->fds->allocFD(sfdp2);
2274 svBuf.copyOut(tc->getMemProxy());
2275
2276 return status;
2277}
2278
2279template <class OS>
2280SyscallReturn
2281selectFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
2282{
2283 int retval;
2284
2285 int index = 0;
2286 int nfds_t = p->getSyscallArg(tc, index);
2287 Addr fds_read_ptr = p->getSyscallArg(tc, index);
2288 Addr fds_writ_ptr = p->getSyscallArg(tc, index);
2289 Addr fds_excp_ptr = p->getSyscallArg(tc, index);
2290 Addr time_val_ptr = p->getSyscallArg(tc, index);
2291
2292 TypedBufferArg<typename OS::fd_set> rd_t(fds_read_ptr);
2293 TypedBufferArg<typename OS::fd_set> wr_t(fds_writ_ptr);
2294 TypedBufferArg<typename OS::fd_set> ex_t(fds_excp_ptr);
2295 TypedBufferArg<typename OS::timeval> tp(time_val_ptr);
2296
2297 /**
2298 * Host fields. Notice that these use the definitions from the system
2299 * headers instead of the gem5 headers and libraries. If the host and
2300 * target have different header file definitions, this will not work.
2301 */
2302 fd_set rd_h;
2303 FD_ZERO(&rd_h);
2304 fd_set wr_h;
2305 FD_ZERO(&wr_h);
2306 fd_set ex_h;
2307 FD_ZERO(&ex_h);
2308
2309 /**
2310 * Copy in the fd_set from the target.
2311 */
2312 if (fds_read_ptr)
2313 rd_t.copyIn(tc->getMemProxy());
2314 if (fds_writ_ptr)
2315 wr_t.copyIn(tc->getMemProxy());
2316 if (fds_excp_ptr)
2317 ex_t.copyIn(tc->getMemProxy());
2318
2319 /**
2320 * We need to translate the target file descriptor set into a host file
2321 * descriptor set. This involves both our internal process fd array
2322 * and the fd_set defined in Linux header files. The nfds field also
2323 * needs to be updated as it will be only target specific after
2324 * retrieving it from the target; the nfds value is expected to be the
2325 * highest file descriptor that needs to be checked, so we need to extend
2326 * it out for nfds_h when we do the update.
2327 */
2328 int nfds_h = 0;
2329 std::map<int, int> trans_map;
2330 auto try_add_host_set = [&](fd_set *tgt_set_entry,
2331 fd_set *hst_set_entry,
2332 int iter) -> bool
2333 {
2334 /**
2335 * By this point, we know that we are looking at a valid file
2336 * descriptor set on the target. We need to check if the target file
2337 * descriptor value passed in as iter is part of the set.
2338 */
2339 if (FD_ISSET(iter, tgt_set_entry)) {
2340 /**
2341 * We know that the target file descriptor belongs to the set,
2342 * but we do not yet know if the file descriptor is valid or
2343 * that we have a host mapping. Check that now.
2344 */
2345 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[iter]);
2346 if (!hbfdp)
2347 return true;
2348 auto sim_fd = hbfdp->getSimFD();
2349
2350 /**
2351 * Add the sim_fd to tgt_fd translation into trans_map for use
2352 * later when we need to zero the target fd_set structures and
2353 * then update them with hits returned from the host select call.
2354 */
2355 trans_map[sim_fd] = iter;
2356
2357 /**
2358 * We know that the host file descriptor exists so now we check
2359 * if we need to update the max count for nfds_h before passing
2360 * the duplicated structure into the host.
2361 */
2362 nfds_h = std::max(nfds_h - 1, sim_fd + 1);
2363
2364 /**
2365 * Add the host file descriptor to the set that we are going to
2366 * pass into the host.
2367 */
2368 FD_SET(sim_fd, hst_set_entry);
2369 }
2370 return false;
2371 };
2372
2373 for (int i = 0; i < nfds_t; i++) {
2374 if (fds_read_ptr) {
2375 bool ebadf = try_add_host_set((fd_set*)&*rd_t, &rd_h, i);
2376 if (ebadf) return -EBADF;
2377 }
2378 if (fds_writ_ptr) {
2379 bool ebadf = try_add_host_set((fd_set*)&*wr_t, &wr_h, i);
2380 if (ebadf) return -EBADF;
2381 }
2382 if (fds_excp_ptr) {
2383 bool ebadf = try_add_host_set((fd_set*)&*ex_t, &ex_h, i);
2384 if (ebadf) return -EBADF;
2385 }
2386 }
2387
2388 if (time_val_ptr) {
2389 /**
2390 * It might be possible to decrement the timeval based on some
2391 * derivation of wall clock determined from elapsed simulator ticks
2392 * but that seems like overkill. Rather, we just set the timeval with
2393 * zero timeout. (There is no reason to block during the simulation
2394 * as it only decreases simulator performance.)
2395 */
2396 tp->tv_sec = 0;
2397 tp->tv_usec = 0;
2398
2399 retval = select(nfds_h,
2400 fds_read_ptr ? &rd_h : nullptr,
2401 fds_writ_ptr ? &wr_h : nullptr,
2402 fds_excp_ptr ? &ex_h : nullptr,
2403 (timeval*)&*tp);
2404 } else {
2405 /**
2406 * If the timeval pointer is null, setup a new timeval structure to
2407 * pass into the host select call. Unfortunately, we will need to
2408 * manually check the return value and throw a retry fault if the
2409 * return value is zero. Allowing the system call to block will
2410 * likely deadlock the event queue.
2411 */
2412 struct timeval tv = { 0, 0 };
2413
2414 retval = select(nfds_h,
2415 fds_read_ptr ? &rd_h : nullptr,
2416 fds_writ_ptr ? &wr_h : nullptr,
2417 fds_excp_ptr ? &ex_h : nullptr,
2418 &tv);
2419
2420 if (retval == 0) {
2421 /**
2422 * If blocking indefinitely, check the signal list to see if a
2423 * signal would break the poll out of the retry cycle and try to
2424 * return the signal interrupt instead.
2425 */
2426 for (auto sig : tc->getSystemPtr()->signalList)
2427 if (sig.receiver == p)
2428 return -EINTR;
2429 return SyscallReturn::retry();
2430 }
2431 }
2432
2433 if (retval == -1)
2434 return -errno;
2435
2436 FD_ZERO((fd_set*)&*rd_t);
2437 FD_ZERO((fd_set*)&*wr_t);
2438 FD_ZERO((fd_set*)&*ex_t);
2439
2440 /**
2441 * We need to translate the host file descriptor set into a target file
2442 * descriptor set. This involves both our internal process fd array
2443 * and the fd_set defined in header files.
2444 */
2445 for (int i = 0; i < nfds_h; i++) {
2446 if (fds_read_ptr) {
2447 if (FD_ISSET(i, &rd_h))
2448 FD_SET(trans_map[i], (fd_set*)&*rd_t);
2449 }
2450
2451 if (fds_writ_ptr) {
2452 if (FD_ISSET(i, &wr_h))
2453 FD_SET(trans_map[i], (fd_set*)&*wr_t);
2454 }
2455
2456 if (fds_excp_ptr) {
2457 if (FD_ISSET(i, &ex_h))
2458 FD_SET(trans_map[i], (fd_set*)&*ex_t);
2459 }
2460 }
2461
2462 if (fds_read_ptr)
2463 rd_t.copyOut(tc->getMemProxy());
2464 if (fds_writ_ptr)
2465 wr_t.copyOut(tc->getMemProxy());
2466 if (fds_excp_ptr)
2467 ex_t.copyOut(tc->getMemProxy());
2468 if (time_val_ptr)
2469 tp.copyOut(tc->getMemProxy());
2470
2471 return retval;
2472}
2473
2474template <class OS>
2475SyscallReturn
2476readFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2477{
2478 int index = 0;
2479 int tgt_fd = p->getSyscallArg(tc, index);
2480 Addr buf_ptr = p->getSyscallArg(tc, index);
2481 int nbytes = p->getSyscallArg(tc, index);
2482
2483 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2484 if (!hbfdp)
2485 return -EBADF;
2486 int sim_fd = hbfdp->getSimFD();
2487
2488 struct pollfd pfd;
2489 pfd.fd = sim_fd;
2490 pfd.events = POLLIN | POLLPRI;
2491 if ((poll(&pfd, 1, 0) == 0)
2492 && !(hbfdp->getFlags() & OS::TGT_O_NONBLOCK))
2493 return SyscallReturn::retry();
2494
2495 BufferArg buf_arg(buf_ptr, nbytes);
2496 int bytes_read = read(sim_fd, buf_arg.bufferPtr(), nbytes);
2497
2498 if (bytes_read > 0)
2499 buf_arg.copyOut(tc->getMemProxy());
2500
2501 return (bytes_read == -1) ? -errno : bytes_read;
2502}
2503
2504template <class OS>
2505SyscallReturn
2506writeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2507{
2508 int index = 0;
2509 int tgt_fd = p->getSyscallArg(tc, index);
2510 Addr buf_ptr = p->getSyscallArg(tc, index);
2511 int nbytes = p->getSyscallArg(tc, index);
2512
2513 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
2514 if (!hbfdp)
2515 return -EBADF;
2516 int sim_fd = hbfdp->getSimFD();
2517
2518 BufferArg buf_arg(buf_ptr, nbytes);
2519 buf_arg.copyIn(tc->getMemProxy());
2520
2521 struct pollfd pfd;
2522 pfd.fd = sim_fd;
2523 pfd.events = POLLOUT;
2524
2525 /**
2526 * We don't want to poll on /dev/random. The kernel will not enable the
2527 * file descriptor for writing unless the entropy in the system falls
2528 * below write_wakeup_threshold. This is not guaranteed to happen
2529 * depending on host settings.
2530 */
2531 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(hbfdp);
2532 if (ffdp && (ffdp->getFileName() != "/dev/random")) {
2533 if (!poll(&pfd, 1, 0) && !(ffdp->getFlags() & OS::TGT_O_NONBLOCK))
2534 return SyscallReturn::retry();
2535 }
2536
2537 int bytes_written = write(sim_fd, buf_arg.bufferPtr(), nbytes);
2538
2539 if (bytes_written != -1)
2540 fsync(sim_fd);
2541
2542 return (bytes_written == -1) ? -errno : bytes_written;
2543}
2544
2545template <class OS>
2546SyscallReturn
2547wait4Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2548{
2549 int index = 0;
2550 pid_t pid = p->getSyscallArg(tc, index);
2551 Addr statPtr = p->getSyscallArg(tc, index);
2552 int options = p->getSyscallArg(tc, index);
2553 Addr rusagePtr = p->getSyscallArg(tc, index);
2554
2555 if (rusagePtr)
2556 DPRINTFR(SyscallVerbose,
2557 "%d: %s: syscall wait4: rusage pointer provided however "
2558 "functionality not supported. Ignoring rusage pointer.\n",
2559 curTick(), tc->getCpuPtr()->name());
2560
2561 /**
2562 * Currently, wait4 is only implemented so that it will wait for children
2563 * exit conditions which are denoted by a SIGCHLD signals posted into the
2564 * system signal list. We return no additional information via any of the
2565 * parameters supplied to wait4. If nothing is found in the system signal
2566 * list, we will wait indefinitely for SIGCHLD to post by retrying the
2567 * call.
2568 */
2569 System *sysh = tc->getSystemPtr();
2570 std::list<BasicSignal>::iterator iter;
2571 for (iter=sysh->signalList.begin(); iter!=sysh->signalList.end(); iter++) {
2572 if (iter->receiver == p) {
2573 if (pid < -1) {
2574 if ((iter->sender->pgid() == -pid)
2575 && (iter->signalValue == OS::TGT_SIGCHLD))
2576 goto success;
2577 } else if (pid == -1) {
2578 if (iter->signalValue == OS::TGT_SIGCHLD)
2579 goto success;
2580 } else if (pid == 0) {
2581 if ((iter->sender->pgid() == p->pgid())
2582 && (iter->signalValue == OS::TGT_SIGCHLD))
2583 goto success;
2584 } else {
2585 if ((iter->sender->pid() == pid)
2586 && (iter->signalValue == OS::TGT_SIGCHLD))
2587 goto success;
2588 }
2589 }
2590 }
2591
2592 return (options & OS::TGT_WNOHANG) ? 0 : SyscallReturn::retry();
2593
2594success:
2595 // Set status to EXITED for WIFEXITED evaluations.
2596 const int EXITED = 0;
2597 BufferArg statusBuf(statPtr, sizeof(int));
2598 *(int *)statusBuf.bufferPtr() = EXITED;
2599 statusBuf.copyOut(tc->getMemProxy());
2600
2601 // Return the child PID.
2602 pid_t retval = iter->sender->pid();
2603 sysh->signalList.erase(iter);
2604 return retval;
2605}
2606
2607template <class OS>
2608SyscallReturn
2609acceptFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
2610{
2611 struct sockaddr sa;
2612 socklen_t addrLen;
2613 int host_fd;
2614 int index = 0;
2615 int tgt_fd = p->getSyscallArg(tc, index);
2616 Addr addrPtr = p->getSyscallArg(tc, index);
2617 Addr lenPtr = p->getSyscallArg(tc, index);
2618
2619 BufferArg *lenBufPtr = nullptr;
2620 BufferArg *addrBufPtr = nullptr;
2621
2622 auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
2623 if (!sfdp)
2624 return -EBADF;
2625 int sim_fd = sfdp->getSimFD();
2626
2627 /**
2628 * We poll the socket file descriptor first to guarantee that we do not
2629 * block on our accept call. The socket can be opened without the
2630 * non-blocking flag (it blocks). This will cause deadlocks between
2631 * communicating processes.
2632 */
2633 struct pollfd pfd;
2634 pfd.fd = sim_fd;
2635 pfd.events = POLLIN | POLLPRI;
2636 if ((poll(&pfd, 1, 0) == 0)
2637 && !(sfdp->getFlags() & OS::TGT_O_NONBLOCK))
2638 return SyscallReturn::retry();
2639
2640 if (lenPtr) {
2641 lenBufPtr = new BufferArg(lenPtr, sizeof(socklen_t));
2642 lenBufPtr->copyIn(tc->getMemProxy());
2643 memcpy(&addrLen, (socklen_t *)lenBufPtr->bufferPtr(),
2644 sizeof(socklen_t));
2645 }
2646
2647 if (addrPtr) {
2648 addrBufPtr = new BufferArg(addrPtr, sizeof(struct sockaddr));
2649 addrBufPtr->copyIn(tc->getMemProxy());
2650 memcpy(&sa, (struct sockaddr *)addrBufPtr->bufferPtr(),
2651 sizeof(struct sockaddr));
2652 }
2653
2654 host_fd = accept(sim_fd, &sa, &addrLen);
2655
2656 if (host_fd == -1)
2657 return -errno;
2658
2659 if (addrPtr) {
2660 memcpy(addrBufPtr->bufferPtr(), &sa, sizeof(sa));
2661 addrBufPtr->copyOut(tc->getMemProxy());
2662 delete(addrBufPtr);
2663 }
2664
2665 if (lenPtr) {
2666 *(socklen_t *)lenBufPtr->bufferPtr() = addrLen;
2667 lenBufPtr->copyOut(tc->getMemProxy());
2668 delete(lenBufPtr);
2669 }
2670
2671 auto afdp = std::make_shared<SocketFDEntry>(host_fd, sfdp->_domain,
2672 sfdp->_type, sfdp->_protocol);
2673 return p->fds->allocFD(afdp);
2674}
2675
2676#endif // __SIM_SYSCALL_EMUL_HH__