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