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