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