syscall_emul.hh (12426:bd598b155482) syscall_emul.hh (12461:a4cb506cda74)
1/*
2 * Copyright (c) 2012-2013, 2015 ARM Limited
3 * Copyright (c) 2015 Advanced Micro Devices, Inc.
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder. You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2003-2005 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Steve Reinhardt
42 * Kevin Lim
43 */
44
45#ifndef __SIM_SYSCALL_EMUL_HH__
46#define __SIM_SYSCALL_EMUL_HH__
47
48#if (defined(__APPLE__) || defined(__OpenBSD__) || \
49 defined(__FreeBSD__) || defined(__CYGWIN__) || \
50 defined(__NetBSD__))
51#define NO_STAT64 1
52#else
53#define NO_STAT64 0
54#endif
55
56#if (defined(__APPLE__) || defined(__OpenBSD__) || \
57 defined(__FreeBSD__) || defined(__NetBSD__))
58#define NO_STATFS 1
59#else
60#define NO_STATFS 0
61#endif
62
63#if (defined(__APPLE__) || defined(__OpenBSD__) || \
64 defined(__FreeBSD__) || defined(__NetBSD__))
65#define NO_FALLOCATE 1
66#else
67#define NO_FALLOCATE 0
68#endif
69
70///
71/// @file syscall_emul.hh
72///
73/// This file defines objects used to emulate syscalls from the target
74/// application on the host machine.
75
76#ifdef __CYGWIN32__
77#include <sys/fcntl.h>
78
79#endif
80#include <fcntl.h>
81#include <sys/mman.h>
82#include <sys/stat.h>
83#if (NO_STATFS == 0)
84#include <sys/statfs.h>
85#else
86#include <sys/mount.h>
87#endif
88#include <sys/time.h>
89#include <sys/uio.h>
90#include <unistd.h>
91
92#include <cerrno>
93#include <memory>
94#include <string>
95
1/*
2 * Copyright (c) 2012-2013, 2015 ARM Limited
3 * Copyright (c) 2015 Advanced Micro Devices, Inc.
4 * All rights reserved
5 *
6 * The license below extends only to copyright in the software and shall
7 * not be construed as granting a license to any other intellectual
8 * property including but not limited to intellectual property relating
9 * to a hardware implementation of the functionality of the software
10 * licensed hereunder. You may use the software subject to the license
11 * terms below provided that you ensure that this notice is replicated
12 * unmodified and in its entirety in all distributions of the software,
13 * modified or unmodified, in source code or in binary form.
14 *
15 * Copyright (c) 2003-2005 The Regents of The University of Michigan
16 * All rights reserved.
17 *
18 * Redistribution and use in source and binary forms, with or without
19 * modification, are permitted provided that the following conditions are
20 * met: redistributions of source code must retain the above copyright
21 * notice, this list of conditions and the following disclaimer;
22 * redistributions in binary form must reproduce the above copyright
23 * notice, this list of conditions and the following disclaimer in the
24 * documentation and/or other materials provided with the distribution;
25 * neither the name of the copyright holders nor the names of its
26 * contributors may be used to endorse or promote products derived from
27 * this software without specific prior written permission.
28 *
29 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 *
41 * Authors: Steve Reinhardt
42 * Kevin Lim
43 */
44
45#ifndef __SIM_SYSCALL_EMUL_HH__
46#define __SIM_SYSCALL_EMUL_HH__
47
48#if (defined(__APPLE__) || defined(__OpenBSD__) || \
49 defined(__FreeBSD__) || defined(__CYGWIN__) || \
50 defined(__NetBSD__))
51#define NO_STAT64 1
52#else
53#define NO_STAT64 0
54#endif
55
56#if (defined(__APPLE__) || defined(__OpenBSD__) || \
57 defined(__FreeBSD__) || defined(__NetBSD__))
58#define NO_STATFS 1
59#else
60#define NO_STATFS 0
61#endif
62
63#if (defined(__APPLE__) || defined(__OpenBSD__) || \
64 defined(__FreeBSD__) || defined(__NetBSD__))
65#define NO_FALLOCATE 1
66#else
67#define NO_FALLOCATE 0
68#endif
69
70///
71/// @file syscall_emul.hh
72///
73/// This file defines objects used to emulate syscalls from the target
74/// application on the host machine.
75
76#ifdef __CYGWIN32__
77#include <sys/fcntl.h>
78
79#endif
80#include <fcntl.h>
81#include <sys/mman.h>
82#include <sys/stat.h>
83#if (NO_STATFS == 0)
84#include <sys/statfs.h>
85#else
86#include <sys/mount.h>
87#endif
88#include <sys/time.h>
89#include <sys/uio.h>
90#include <unistd.h>
91
92#include <cerrno>
93#include <memory>
94#include <string>
95
96#include "arch/generic/tlb.hh"
96#include "arch/utility.hh"
97#include "base/intmath.hh"
98#include "base/loader/object_file.hh"
99#include "base/logging.hh"
100#include "base/trace.hh"
101#include "base/types.hh"
102#include "config/the_isa.hh"
103#include "cpu/base.hh"
104#include "cpu/thread_context.hh"
105#include "mem/page_table.hh"
106#include "params/Process.hh"
107#include "sim/emul_driver.hh"
108#include "sim/futex_map.hh"
109#include "sim/process.hh"
110#include "sim/syscall_debug_macros.hh"
111#include "sim/syscall_desc.hh"
112#include "sim/syscall_emul_buf.hh"
113#include "sim/syscall_return.hh"
114
115//////////////////////////////////////////////////////////////////////
116//
117// The following emulation functions are generic enough that they
118// don't need to be recompiled for different emulated OS's. They are
119// defined in sim/syscall_emul.cc.
120//
121//////////////////////////////////////////////////////////////////////
122
123
124/// Handler for unimplemented syscalls that we haven't thought about.
125SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
126 Process *p, ThreadContext *tc);
127
128/// Handler for unimplemented syscalls that we never intend to
129/// implement (signal handling, etc.) and should not affect the correct
130/// behavior of the program. Print a warning only if the appropriate
131/// trace flag is enabled. Return success to the target program.
132SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
133 Process *p, ThreadContext *tc);
134
135// Target fallocateFunc() handler.
136SyscallReturn fallocateFunc(SyscallDesc *desc, int num,
137 Process *p, ThreadContext *tc);
138
139/// Target exit() handler: terminate current context.
140SyscallReturn exitFunc(SyscallDesc *desc, int num,
141 Process *p, ThreadContext *tc);
142
143/// Target exit_group() handler: terminate simulation. (exit all threads)
144SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
145 Process *p, ThreadContext *tc);
146
147/// Target set_tid_address() handler.
148SyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
149 Process *p, ThreadContext *tc);
150
151/// Target getpagesize() handler.
152SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
153 Process *p, ThreadContext *tc);
154
155/// Target brk() handler: set brk address.
156SyscallReturn brkFunc(SyscallDesc *desc, int num,
157 Process *p, ThreadContext *tc);
158
159/// Target close() handler.
160SyscallReturn closeFunc(SyscallDesc *desc, int num,
161 Process *p, ThreadContext *tc);
162
163// Target read() handler.
164SyscallReturn readFunc(SyscallDesc *desc, int num,
165 Process *p, ThreadContext *tc);
166
167/// Target write() handler.
168SyscallReturn writeFunc(SyscallDesc *desc, int num,
169 Process *p, ThreadContext *tc);
170
171/// Target lseek() handler.
172SyscallReturn lseekFunc(SyscallDesc *desc, int num,
173 Process *p, ThreadContext *tc);
174
175/// Target _llseek() handler.
176SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
177 Process *p, ThreadContext *tc);
178
179/// Target munmap() handler.
180SyscallReturn munmapFunc(SyscallDesc *desc, int num,
181 Process *p, ThreadContext *tc);
182
183/// Target gethostname() handler.
184SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
185 Process *p, ThreadContext *tc);
186
187/// Target getcwd() handler.
188SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
189 Process *p, ThreadContext *tc);
190
191/// Target readlink() handler.
192SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
193 Process *p, ThreadContext *tc,
194 int index = 0);
195SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
196 Process *p, ThreadContext *tc);
197
198/// Target unlink() handler.
199SyscallReturn unlinkHelper(SyscallDesc *desc, int num,
200 Process *p, ThreadContext *tc,
201 int index);
202SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
203 Process *p, ThreadContext *tc);
204
205/// Target mkdir() handler.
206SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
207 Process *p, ThreadContext *tc);
208
209/// Target rename() handler.
210SyscallReturn renameFunc(SyscallDesc *desc, int num,
211 Process *p, ThreadContext *tc);
212
213
214/// Target truncate() handler.
215SyscallReturn truncateFunc(SyscallDesc *desc, int num,
216 Process *p, ThreadContext *tc);
217
218
219/// Target ftruncate() handler.
220SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
221 Process *p, ThreadContext *tc);
222
223
224/// Target truncate64() handler.
225SyscallReturn truncate64Func(SyscallDesc *desc, int num,
226 Process *p, ThreadContext *tc);
227
228/// Target ftruncate64() handler.
229SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
230 Process *p, ThreadContext *tc);
231
232
233/// Target umask() handler.
234SyscallReturn umaskFunc(SyscallDesc *desc, int num,
235 Process *p, ThreadContext *tc);
236
237/// Target gettid() handler.
238SyscallReturn gettidFunc(SyscallDesc *desc, int num,
239 Process *p, ThreadContext *tc);
240
241/// Target chown() handler.
242SyscallReturn chownFunc(SyscallDesc *desc, int num,
243 Process *p, ThreadContext *tc);
244
245/// Target setpgid() handler.
246SyscallReturn setpgidFunc(SyscallDesc *desc, int num,
247 Process *p, ThreadContext *tc);
248
249/// Target fchown() handler.
250SyscallReturn fchownFunc(SyscallDesc *desc, int num,
251 Process *p, ThreadContext *tc);
252
253/// Target dup() handler.
254SyscallReturn dupFunc(SyscallDesc *desc, int num,
255 Process *process, ThreadContext *tc);
256
257/// Target dup2() handler.
258SyscallReturn dup2Func(SyscallDesc *desc, int num,
259 Process *process, ThreadContext *tc);
260
261/// Target fcntl() handler.
262SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
263 Process *process, ThreadContext *tc);
264
265/// Target fcntl64() handler.
266SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
267 Process *process, ThreadContext *tc);
268
269/// Target setuid() handler.
270SyscallReturn setuidFunc(SyscallDesc *desc, int num,
271 Process *p, ThreadContext *tc);
272
273/// Target pipe() handler.
274SyscallReturn pipeFunc(SyscallDesc *desc, int num,
275 Process *p, ThreadContext *tc);
276
277/// Internal pipe() handler.
278SyscallReturn pipeImpl(SyscallDesc *desc, int num, Process *p,
279 ThreadContext *tc, bool pseudoPipe);
280
281/// Target getpid() handler.
282SyscallReturn getpidFunc(SyscallDesc *desc, int num,
283 Process *p, ThreadContext *tc);
284
285/// Target getuid() handler.
286SyscallReturn getuidFunc(SyscallDesc *desc, int num,
287 Process *p, ThreadContext *tc);
288
289/// Target getgid() handler.
290SyscallReturn getgidFunc(SyscallDesc *desc, int num,
291 Process *p, ThreadContext *tc);
292
293/// Target getppid() handler.
294SyscallReturn getppidFunc(SyscallDesc *desc, int num,
295 Process *p, ThreadContext *tc);
296
297/// Target geteuid() handler.
298SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
299 Process *p, ThreadContext *tc);
300
301/// Target getegid() handler.
302SyscallReturn getegidFunc(SyscallDesc *desc, int num,
303 Process *p, ThreadContext *tc);
304
305/// Target access() handler
306SyscallReturn accessFunc(SyscallDesc *desc, int num,
307 Process *p, ThreadContext *tc);
308SyscallReturn accessFunc(SyscallDesc *desc, int num,
309 Process *p, ThreadContext *tc,
310 int index);
311
312/// Futex system call
313/// Implemented by Daniel Sanchez
314/// Used by printf's in multi-threaded apps
315template <class OS>
316SyscallReturn
317futexFunc(SyscallDesc *desc, int callnum, Process *process,
318 ThreadContext *tc)
319{
320 using namespace std;
321
322 int index = 0;
323 Addr uaddr = process->getSyscallArg(tc, index);
324 int op = process->getSyscallArg(tc, index);
325 int val = process->getSyscallArg(tc, index);
326
327 /*
328 * Unsupported option that does not affect the correctness of the
329 * application. This is a performance optimization utilized by Linux.
330 */
331 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
332
333 FutexMap &futex_map = tc->getSystemPtr()->futexMap;
334
335 if (OS::TGT_FUTEX_WAIT == op) {
336 // Ensure futex system call accessed atomically.
337 BufferArg buf(uaddr, sizeof(int));
338 buf.copyIn(tc->getMemProxy());
339 int mem_val = *(int*)buf.bufferPtr();
340
341 /*
342 * The value in memory at uaddr is not equal with the expected val
343 * (a different thread must have changed it before the system call was
344 * invoked). In this case, we need to throw an error.
345 */
346 if (val != mem_val)
347 return -OS::TGT_EWOULDBLOCK;
348
349 futex_map.suspend(uaddr, process->tgid(), tc);
350
351 return 0;
352 } else if (OS::TGT_FUTEX_WAKE == op) {
353 return futex_map.wakeup(uaddr, process->tgid(), val);
354 }
355
356 warn("futex: op %d not implemented; ignoring.", op);
357 return -ENOSYS;
358}
359
360
361/// Pseudo Funcs - These functions use a different return convension,
362/// returning a second value in a register other than the normal return register
363SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
364 Process *process, ThreadContext *tc);
365
366/// Target getpidPseudo() handler.
367SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
368 Process *p, ThreadContext *tc);
369
370/// Target getuidPseudo() handler.
371SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
372 Process *p, ThreadContext *tc);
373
374/// Target getgidPseudo() handler.
375SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
376 Process *p, ThreadContext *tc);
377
378
379/// A readable name for 1,000,000, for converting microseconds to seconds.
380const int one_million = 1000000;
381/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
382const int one_billion = 1000000000;
383
384/// Approximate seconds since the epoch (1/1/1970). About a billion,
385/// by my reckoning. We want to keep this a constant (not use the
386/// real-world time) to keep simulations repeatable.
387const unsigned seconds_since_epoch = 1000000000;
388
389/// Helper function to convert current elapsed time to seconds and
390/// microseconds.
391template <class T1, class T2>
392void
393getElapsedTimeMicro(T1 &sec, T2 &usec)
394{
395 uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
396 sec = elapsed_usecs / one_million;
397 usec = elapsed_usecs % one_million;
398}
399
400/// Helper function to convert current elapsed time to seconds and
401/// nanoseconds.
402template <class T1, class T2>
403void
404getElapsedTimeNano(T1 &sec, T2 &nsec)
405{
406 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
407 sec = elapsed_nsecs / one_billion;
408 nsec = elapsed_nsecs % one_billion;
409}
410
411//////////////////////////////////////////////////////////////////////
412//
413// The following emulation functions are generic, but need to be
414// templated to account for differences in types, constants, etc.
415//
416//////////////////////////////////////////////////////////////////////
417
418 typedef struct statfs hst_statfs;
419#if NO_STAT64
420 typedef struct stat hst_stat;
421 typedef struct stat hst_stat64;
422#else
423 typedef struct stat hst_stat;
424 typedef struct stat64 hst_stat64;
425#endif
426
427//// Helper function to convert a host stat buffer to a target stat
428//// buffer. Also copies the target buffer out to the simulated
429//// memory space. Used by stat(), fstat(), and lstat().
430
431template <typename target_stat, typename host_stat>
432void
433convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
434{
435 using namespace TheISA;
436
437 if (fakeTTY)
438 tgt->st_dev = 0xA;
439 else
440 tgt->st_dev = host->st_dev;
441 tgt->st_dev = TheISA::htog(tgt->st_dev);
442 tgt->st_ino = host->st_ino;
443 tgt->st_ino = TheISA::htog(tgt->st_ino);
444 tgt->st_mode = host->st_mode;
445 if (fakeTTY) {
446 // Claim to be a character device
447 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT
448 tgt->st_mode |= S_IFCHR; // Set S_IFCHR
449 }
450 tgt->st_mode = TheISA::htog(tgt->st_mode);
451 tgt->st_nlink = host->st_nlink;
452 tgt->st_nlink = TheISA::htog(tgt->st_nlink);
453 tgt->st_uid = host->st_uid;
454 tgt->st_uid = TheISA::htog(tgt->st_uid);
455 tgt->st_gid = host->st_gid;
456 tgt->st_gid = TheISA::htog(tgt->st_gid);
457 if (fakeTTY)
458 tgt->st_rdev = 0x880d;
459 else
460 tgt->st_rdev = host->st_rdev;
461 tgt->st_rdev = TheISA::htog(tgt->st_rdev);
462 tgt->st_size = host->st_size;
463 tgt->st_size = TheISA::htog(tgt->st_size);
464 tgt->st_atimeX = host->st_atime;
465 tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
466 tgt->st_mtimeX = host->st_mtime;
467 tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
468 tgt->st_ctimeX = host->st_ctime;
469 tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
470 // Force the block size to be 8KB. This helps to ensure buffered io works
471 // consistently across different hosts.
472 tgt->st_blksize = 0x2000;
473 tgt->st_blksize = TheISA::htog(tgt->st_blksize);
474 tgt->st_blocks = host->st_blocks;
475 tgt->st_blocks = TheISA::htog(tgt->st_blocks);
476}
477
478// Same for stat64
479
480template <typename target_stat, typename host_stat64>
481void
482convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
483{
484 using namespace TheISA;
485
486 convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
487#if defined(STAT_HAVE_NSEC)
488 tgt->st_atime_nsec = host->st_atime_nsec;
489 tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
490 tgt->st_mtime_nsec = host->st_mtime_nsec;
491 tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
492 tgt->st_ctime_nsec = host->st_ctime_nsec;
493 tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
494#else
495 tgt->st_atime_nsec = 0;
496 tgt->st_mtime_nsec = 0;
497 tgt->st_ctime_nsec = 0;
498#endif
499}
500
501// Here are a couple of convenience functions
502template<class OS>
503void
504copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
505 hst_stat *host, bool fakeTTY = false)
506{
507 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
508 tgt_stat_buf tgt(addr);
509 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
510 tgt.copyOut(mem);
511}
512
513template<class OS>
514void
515copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
516 hst_stat64 *host, bool fakeTTY = false)
517{
518 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
519 tgt_stat_buf tgt(addr);
520 convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
521 tgt.copyOut(mem);
522}
523
524template <class OS>
525void
526copyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
527 hst_statfs *host)
528{
529 TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
530
531 tgt->f_type = TheISA::htog(host->f_type);
532#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
533 tgt->f_bsize = TheISA::htog(host->f_iosize);
534#else
535 tgt->f_bsize = TheISA::htog(host->f_bsize);
536#endif
537 tgt->f_blocks = TheISA::htog(host->f_blocks);
538 tgt->f_bfree = TheISA::htog(host->f_bfree);
539 tgt->f_bavail = TheISA::htog(host->f_bavail);
540 tgt->f_files = TheISA::htog(host->f_files);
541 tgt->f_ffree = TheISA::htog(host->f_ffree);
542 memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
543#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
544 tgt->f_namelen = TheISA::htog(host->f_namemax);
545 tgt->f_frsize = TheISA::htog(host->f_bsize);
546#elif defined(__APPLE__)
547 tgt->f_namelen = 0;
548 tgt->f_frsize = 0;
549#else
550 tgt->f_namelen = TheISA::htog(host->f_namelen);
551 tgt->f_frsize = TheISA::htog(host->f_frsize);
552#endif
553#if defined(__linux__)
554 memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
555#else
556 /*
557 * The fields are different sizes per OS. Don't bother with
558 * f_spare or f_reserved on non-Linux for now.
559 */
560 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
561#endif
562
563 tgt.copyOut(mem);
564}
565
566/// Target ioctl() handler. For the most part, programs call ioctl()
567/// only to find out if their stdout is a tty, to determine whether to
568/// do line or block buffering. We always claim that output fds are
569/// not TTYs to provide repeatable results.
570template <class OS>
571SyscallReturn
572ioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
573{
574 int index = 0;
575 int tgt_fd = p->getSyscallArg(tc, index);
576 unsigned req = p->getSyscallArg(tc, index);
577
578 DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
579
580 if (OS::isTtyReq(req))
581 return -ENOTTY;
582
583 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
584 if (!dfdp)
585 return -EBADF;
586
587 /**
588 * If the driver is valid, issue the ioctl through it. Otherwise,
589 * there's an implicit assumption that the device is a TTY type and we
590 * return that we do not have a valid TTY.
591 */
592 EmulatedDriver *emul_driver = dfdp->getDriver();
593 if (emul_driver)
594 return emul_driver->ioctl(p, tc, req);
595
596 /**
597 * For lack of a better return code, return ENOTTY. Ideally, we should
598 * return something better here, but at least we issue the warning.
599 */
600 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
601 tgt_fd, req, tc->pcState());
602 return -ENOTTY;
603}
604
605template <class OS>
606SyscallReturn
607openImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
608 bool isopenat)
609{
610 int index = 0;
611 int tgt_dirfd = -1;
612
613 /**
614 * If using the openat variant, read in the target directory file
615 * descriptor from the simulated process.
616 */
617 if (isopenat)
618 tgt_dirfd = p->getSyscallArg(tc, index);
619
620 /**
621 * Retrieve the simulated process' memory proxy and then read in the path
622 * string from that memory space into the host's working memory space.
623 */
624 std::string path;
625 if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
626 return -EFAULT;
627
628#ifdef __CYGWIN32__
629 int host_flags = O_BINARY;
630#else
631 int host_flags = 0;
632#endif
633 /**
634 * Translate target flags into host flags. Flags exist which are not
635 * ported between architectures which can cause check failures.
636 */
637 int tgt_flags = p->getSyscallArg(tc, index);
638 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
639 if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
640 tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
641 host_flags |= OS::openFlagTable[i].hostFlag;
642 }
643 }
644 if (tgt_flags) {
645 warn("open%s: cannot decode flags 0x%x",
646 isopenat ? "at" : "", tgt_flags);
647 }
648#ifdef __CYGWIN32__
649 host_flags |= O_BINARY;
650#endif
651
652 int mode = p->getSyscallArg(tc, index);
653
654 /**
655 * If the simulated process called open or openat with AT_FDCWD specified,
656 * take the current working directory value which was passed into the
657 * process class as a Python parameter and append the current path to
658 * create a full path.
659 * Otherwise, openat with a valid target directory file descriptor has
660 * been called. If the path option, which was passed in as a parameter,
661 * is not absolute, retrieve the directory file descriptor's path and
662 * prepend it to the path passed in as a parameter.
663 * In every case, we should have a full path (which is relevant to the
664 * host) to work with after this block has been passed.
665 */
666 if (!isopenat || (isopenat && tgt_dirfd == OS::TGT_AT_FDCWD)) {
667 path = p->fullPath(path);
668 } else if (!startswith(path, "/")) {
669 std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
670 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
671 if (!ffdp)
672 return -EBADF;
673 path.insert(0, ffdp->getFileName());
674 }
675
676 /**
677 * Since this is an emulated environment, we create pseudo file
678 * descriptors for device requests that have been registered with
679 * the process class through Python; this allows us to create a file
680 * descriptor for subsequent ioctl or mmap calls.
681 */
682 if (startswith(path, "/dev/")) {
683 std::string filename = path.substr(strlen("/dev/"));
684 EmulatedDriver *drv = p->findDriver(filename);
685 if (drv) {
686 DPRINTF_SYSCALL(Verbose, "open%s: passing call to "
687 "driver open with path[%s]\n",
688 isopenat ? "at" : "", path.c_str());
689 return drv->open(p, tc, mode, host_flags);
690 }
691 /**
692 * Fall through here for pass through to host devices, such
693 * as /dev/zero
694 */
695 }
696
697 /**
698 * Some special paths and files cannot be called on the host and need
699 * to be handled as special cases inside the simulator.
700 * If the full path that was created above does not match any of the
701 * special cases, pass it through to the open call on the host to let
702 * the host open the file on our behalf.
703 * If the host cannot open the file, return the host's error code back
704 * through the system call to the simulated process.
705 */
706 int sim_fd = -1;
707 std::vector<std::string> special_paths =
708 { "/proc/", "/system/", "/sys/", "/platform/", "/etc/passwd" };
709 for (auto entry : special_paths) {
710 if (startswith(path, entry))
711 sim_fd = OS::openSpecialFile(path, p, tc);
712 }
713 if (sim_fd == -1) {
714 sim_fd = open(path.c_str(), host_flags, mode);
715 }
716 if (sim_fd == -1) {
717 int local = -errno;
718 DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s\n",
719 isopenat ? "at" : "", path.c_str());
720 return local;
721 }
722
723 /**
724 * The file was opened successfully and needs to be recorded in the
725 * process' file descriptor array so that it can be retrieved later.
726 * The target file descriptor that is chosen will be the lowest unused
727 * file descriptor.
728 * Return the indirect target file descriptor back to the simulated
729 * process to act as a handle for the opened file.
730 */
731 auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
732 int tgt_fd = p->fds->allocFD(ffdp);
733 DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n",
734 isopenat ? "at" : "", sim_fd, tgt_fd, path.c_str());
735 return tgt_fd;
736}
737
738/// Target open() handler.
739template <class OS>
740SyscallReturn
741openFunc(SyscallDesc *desc, int callnum, Process *process,
742 ThreadContext *tc)
743{
744 return openImpl<OS>(desc, callnum, process, tc, false);
745}
746
747/// Target openat() handler.
748template <class OS>
749SyscallReturn
750openatFunc(SyscallDesc *desc, int callnum, Process *process,
751 ThreadContext *tc)
752{
753 return openImpl<OS>(desc, callnum, process, tc, true);
754}
755
756/// Target unlinkat() handler.
757template <class OS>
758SyscallReturn
759unlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
760 ThreadContext *tc)
761{
762 int index = 0;
763 int dirfd = process->getSyscallArg(tc, index);
764 if (dirfd != OS::TGT_AT_FDCWD)
765 warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
766
767 return unlinkHelper(desc, callnum, process, tc, 1);
768}
769
770/// Target facessat() handler
771template <class OS>
772SyscallReturn
773faccessatFunc(SyscallDesc *desc, int callnum, Process *process,
774 ThreadContext *tc)
775{
776 int index = 0;
777 int dirfd = process->getSyscallArg(tc, index);
778 if (dirfd != OS::TGT_AT_FDCWD)
779 warn("faccessat: first argument not AT_FDCWD; unlikely to work");
780 return accessFunc(desc, callnum, process, tc, 1);
781}
782
783/// Target readlinkat() handler
784template <class OS>
785SyscallReturn
786readlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
787 ThreadContext *tc)
788{
789 int index = 0;
790 int dirfd = process->getSyscallArg(tc, index);
791 if (dirfd != OS::TGT_AT_FDCWD)
792 warn("openat: first argument not AT_FDCWD; unlikely to work");
793 return readlinkFunc(desc, callnum, process, tc, 1);
794}
795
796/// Target renameat() handler.
797template <class OS>
798SyscallReturn
799renameatFunc(SyscallDesc *desc, int callnum, Process *process,
800 ThreadContext *tc)
801{
802 int index = 0;
803
804 int olddirfd = process->getSyscallArg(tc, index);
805 if (olddirfd != OS::TGT_AT_FDCWD)
806 warn("renameat: first argument not AT_FDCWD; unlikely to work");
807
808 std::string old_name;
809
810 if (!tc->getMemProxy().tryReadString(old_name,
811 process->getSyscallArg(tc, index)))
812 return -EFAULT;
813
814 int newdirfd = process->getSyscallArg(tc, index);
815 if (newdirfd != OS::TGT_AT_FDCWD)
816 warn("renameat: third argument not AT_FDCWD; unlikely to work");
817
818 std::string new_name;
819
820 if (!tc->getMemProxy().tryReadString(new_name,
821 process->getSyscallArg(tc, index)))
822 return -EFAULT;
823
824 // Adjust path for current working directory
825 old_name = process->fullPath(old_name);
826 new_name = process->fullPath(new_name);
827
828 int result = rename(old_name.c_str(), new_name.c_str());
829 return (result == -1) ? -errno : result;
830}
831
832/// Target sysinfo() handler.
833template <class OS>
834SyscallReturn
835sysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
836 ThreadContext *tc)
837{
838
839 int index = 0;
840 TypedBufferArg<typename OS::tgt_sysinfo>
841 sysinfo(process->getSyscallArg(tc, index));
842
843 sysinfo->uptime = seconds_since_epoch;
844 sysinfo->totalram = process->system->memSize();
845 sysinfo->mem_unit = 1;
846
847 sysinfo.copyOut(tc->getMemProxy());
848
849 return 0;
850}
851
852/// Target chmod() handler.
853template <class OS>
854SyscallReturn
855chmodFunc(SyscallDesc *desc, int callnum, Process *process,
856 ThreadContext *tc)
857{
858 std::string path;
859
860 int index = 0;
861 if (!tc->getMemProxy().tryReadString(path,
862 process->getSyscallArg(tc, index))) {
863 return -EFAULT;
864 }
865
866 uint32_t mode = process->getSyscallArg(tc, index);
867 mode_t hostMode = 0;
868
869 // XXX translate mode flags via OS::something???
870 hostMode = mode;
871
872 // Adjust path for current working directory
873 path = process->fullPath(path);
874
875 // do the chmod
876 int result = chmod(path.c_str(), hostMode);
877 if (result < 0)
878 return -errno;
879
880 return 0;
881}
882
883
884/// Target fchmod() handler.
885template <class OS>
886SyscallReturn
887fchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
888{
889 int index = 0;
890 int tgt_fd = p->getSyscallArg(tc, index);
891 uint32_t mode = p->getSyscallArg(tc, index);
892
893 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
894 if (!ffdp)
895 return -EBADF;
896 int sim_fd = ffdp->getSimFD();
897
898 mode_t hostMode = mode;
899
900 int result = fchmod(sim_fd, hostMode);
901
902 return (result < 0) ? -errno : 0;
903}
904
905/// Target mremap() handler.
906template <class OS>
907SyscallReturn
908mremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
909{
910 int index = 0;
911 Addr start = process->getSyscallArg(tc, index);
912 uint64_t old_length = process->getSyscallArg(tc, index);
913 uint64_t new_length = process->getSyscallArg(tc, index);
914 uint64_t flags = process->getSyscallArg(tc, index);
915 uint64_t provided_address = 0;
916 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
917
918 if (use_provided_address)
919 provided_address = process->getSyscallArg(tc, index);
920
921 if ((start % TheISA::PageBytes != 0) ||
922 (provided_address % TheISA::PageBytes != 0)) {
923 warn("mremap failing: arguments not page aligned");
924 return -EINVAL;
925 }
926
927 new_length = roundUp(new_length, TheISA::PageBytes);
928
929 if (new_length > old_length) {
930 std::shared_ptr<MemState> mem_state = process->memState;
931 Addr mmap_end = mem_state->getMmapEnd();
932
933 if ((start + old_length) == mmap_end &&
934 (!use_provided_address || provided_address == start)) {
935 // This case cannot occur when growing downward, as
936 // start is greater than or equal to mmap_end.
937 uint64_t diff = new_length - old_length;
938 process->allocateMem(mmap_end, diff);
939 mem_state->setMmapEnd(mmap_end + diff);
940 return start;
941 } else {
942 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
943 warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
944 return -ENOMEM;
945 } else {
946 uint64_t new_start = provided_address;
947 if (!use_provided_address) {
948 new_start = process->mmapGrowsDown() ?
949 mmap_end - new_length : mmap_end;
950 mmap_end = process->mmapGrowsDown() ?
951 new_start : mmap_end + new_length;
952 mem_state->setMmapEnd(mmap_end);
953 }
954
955 process->pTable->remap(start, old_length, new_start);
956 warn("mremapping to new vaddr %08p-%08p, adding %d\n",
957 new_start, new_start + new_length,
958 new_length - old_length);
959 // add on the remaining unallocated pages
960 process->allocateMem(new_start + old_length,
961 new_length - old_length,
962 use_provided_address /* clobber */);
963 if (use_provided_address &&
964 ((new_start + new_length > mem_state->getMmapEnd() &&
965 !process->mmapGrowsDown()) ||
966 (new_start < mem_state->getMmapEnd() &&
967 process->mmapGrowsDown()))) {
968 // something fishy going on here, at least notify the user
969 // @todo: increase mmap_end?
970 warn("mmap region limit exceeded with MREMAP_FIXED\n");
971 }
972 warn("returning %08p as start\n", new_start);
973 return new_start;
974 }
975 }
976 } else {
977 if (use_provided_address && provided_address != start)
978 process->pTable->remap(start, new_length, provided_address);
979 process->pTable->unmap(start + new_length, old_length - new_length);
980 return use_provided_address ? provided_address : start;
981 }
982}
983
984/// Target stat() handler.
985template <class OS>
986SyscallReturn
987statFunc(SyscallDesc *desc, int callnum, Process *process,
988 ThreadContext *tc)
989{
990 std::string path;
991
992 int index = 0;
993 if (!tc->getMemProxy().tryReadString(path,
994 process->getSyscallArg(tc, index))) {
995 return -EFAULT;
996 }
997 Addr bufPtr = process->getSyscallArg(tc, index);
998
999 // Adjust path for current working directory
1000 path = process->fullPath(path);
1001
1002 struct stat hostBuf;
1003 int result = stat(path.c_str(), &hostBuf);
1004
1005 if (result < 0)
1006 return -errno;
1007
1008 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1009
1010 return 0;
1011}
1012
1013
1014/// Target stat64() handler.
1015template <class OS>
1016SyscallReturn
1017stat64Func(SyscallDesc *desc, int callnum, Process *process,
1018 ThreadContext *tc)
1019{
1020 std::string path;
1021
1022 int index = 0;
1023 if (!tc->getMemProxy().tryReadString(path,
1024 process->getSyscallArg(tc, index)))
1025 return -EFAULT;
1026 Addr bufPtr = process->getSyscallArg(tc, index);
1027
1028 // Adjust path for current working directory
1029 path = process->fullPath(path);
1030
1031#if NO_STAT64
1032 struct stat hostBuf;
1033 int result = stat(path.c_str(), &hostBuf);
1034#else
1035 struct stat64 hostBuf;
1036 int result = stat64(path.c_str(), &hostBuf);
1037#endif
1038
1039 if (result < 0)
1040 return -errno;
1041
1042 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1043
1044 return 0;
1045}
1046
1047
1048/// Target fstatat64() handler.
1049template <class OS>
1050SyscallReturn
1051fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
1052 ThreadContext *tc)
1053{
1054 int index = 0;
1055 int dirfd = process->getSyscallArg(tc, index);
1056 if (dirfd != OS::TGT_AT_FDCWD)
1057 warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1058
1059 std::string path;
1060 if (!tc->getMemProxy().tryReadString(path,
1061 process->getSyscallArg(tc, index)))
1062 return -EFAULT;
1063 Addr bufPtr = process->getSyscallArg(tc, index);
1064
1065 // Adjust path for current working directory
1066 path = process->fullPath(path);
1067
1068#if NO_STAT64
1069 struct stat hostBuf;
1070 int result = stat(path.c_str(), &hostBuf);
1071#else
1072 struct stat64 hostBuf;
1073 int result = stat64(path.c_str(), &hostBuf);
1074#endif
1075
1076 if (result < 0)
1077 return -errno;
1078
1079 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1080
1081 return 0;
1082}
1083
1084
1085/// Target fstat64() handler.
1086template <class OS>
1087SyscallReturn
1088fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1089{
1090 int index = 0;
1091 int tgt_fd = p->getSyscallArg(tc, index);
1092 Addr bufPtr = p->getSyscallArg(tc, index);
1093
1094 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1095 if (!ffdp)
1096 return -EBADF;
1097 int sim_fd = ffdp->getSimFD();
1098
1099#if NO_STAT64
1100 struct stat hostBuf;
1101 int result = fstat(sim_fd, &hostBuf);
1102#else
1103 struct stat64 hostBuf;
1104 int result = fstat64(sim_fd, &hostBuf);
1105#endif
1106
1107 if (result < 0)
1108 return -errno;
1109
1110 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1111
1112 return 0;
1113}
1114
1115
1116/// Target lstat() handler.
1117template <class OS>
1118SyscallReturn
1119lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1120 ThreadContext *tc)
1121{
1122 std::string path;
1123
1124 int index = 0;
1125 if (!tc->getMemProxy().tryReadString(path,
1126 process->getSyscallArg(tc, index))) {
1127 return -EFAULT;
1128 }
1129 Addr bufPtr = process->getSyscallArg(tc, index);
1130
1131 // Adjust path for current working directory
1132 path = process->fullPath(path);
1133
1134 struct stat hostBuf;
1135 int result = lstat(path.c_str(), &hostBuf);
1136
1137 if (result < 0)
1138 return -errno;
1139
1140 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1141
1142 return 0;
1143}
1144
1145/// Target lstat64() handler.
1146template <class OS>
1147SyscallReturn
1148lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1149 ThreadContext *tc)
1150{
1151 std::string path;
1152
1153 int index = 0;
1154 if (!tc->getMemProxy().tryReadString(path,
1155 process->getSyscallArg(tc, index))) {
1156 return -EFAULT;
1157 }
1158 Addr bufPtr = process->getSyscallArg(tc, index);
1159
1160 // Adjust path for current working directory
1161 path = process->fullPath(path);
1162
1163#if NO_STAT64
1164 struct stat hostBuf;
1165 int result = lstat(path.c_str(), &hostBuf);
1166#else
1167 struct stat64 hostBuf;
1168 int result = lstat64(path.c_str(), &hostBuf);
1169#endif
1170
1171 if (result < 0)
1172 return -errno;
1173
1174 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1175
1176 return 0;
1177}
1178
1179/// Target fstat() handler.
1180template <class OS>
1181SyscallReturn
1182fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1183{
1184 int index = 0;
1185 int tgt_fd = p->getSyscallArg(tc, index);
1186 Addr bufPtr = p->getSyscallArg(tc, index);
1187
1188 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1189
1190 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1191 if (!ffdp)
1192 return -EBADF;
1193 int sim_fd = ffdp->getSimFD();
1194
1195 struct stat hostBuf;
1196 int result = fstat(sim_fd, &hostBuf);
1197
1198 if (result < 0)
1199 return -errno;
1200
1201 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1202
1203 return 0;
1204}
1205
1206
1207/// Target statfs() handler.
1208template <class OS>
1209SyscallReturn
1210statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1211 ThreadContext *tc)
1212{
1213#if NO_STATFS
1214 warn("Host OS cannot support calls to statfs. Ignoring syscall");
1215#else
1216 std::string path;
1217
1218 int index = 0;
1219 if (!tc->getMemProxy().tryReadString(path,
1220 process->getSyscallArg(tc, index))) {
1221 return -EFAULT;
1222 }
1223 Addr bufPtr = process->getSyscallArg(tc, index);
1224
1225 // Adjust path for current working directory
1226 path = process->fullPath(path);
1227
1228 struct statfs hostBuf;
1229 int result = statfs(path.c_str(), &hostBuf);
1230
1231 if (result < 0)
1232 return -errno;
1233
1234 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1235#endif
1236 return 0;
1237}
1238
1239template <class OS>
1240SyscallReturn
1241cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1242{
1243 int index = 0;
1244
1245 TheISA::IntReg flags = p->getSyscallArg(tc, index);
1246 TheISA::IntReg newStack = p->getSyscallArg(tc, index);
1247 Addr ptidPtr = p->getSyscallArg(tc, index);
1248
1249#if THE_ISA == RISCV_ISA
1250 /**
1251 * Linux kernel 4.15 sets CLONE_BACKWARDS flag for RISC-V.
1252 * The flag defines the list of clone() arguments in the following
1253 * order: flags -> newStack -> ptidPtr -> tlsPtr -> ctidPtr
1254 */
1255 Addr tlsPtr M5_VAR_USED = p->getSyscallArg(tc, index);
1256 Addr ctidPtr = p->getSyscallArg(tc, index);
1257#else
1258 Addr ctidPtr = p->getSyscallArg(tc, index);
1259 Addr tlsPtr M5_VAR_USED = p->getSyscallArg(tc, index);
1260#endif
1261
1262 if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1263 ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1264 ((flags & OS::TGT_CLONE_FS) && (flags & OS::TGT_CLONE_NEWNS)) ||
1265 ((flags & OS::TGT_CLONE_NEWIPC) && (flags & OS::TGT_CLONE_SYSVSEM)) ||
1266 ((flags & OS::TGT_CLONE_NEWPID) && (flags & OS::TGT_CLONE_THREAD)) ||
1267 ((flags & OS::TGT_CLONE_VM) && !(newStack)))
1268 return -EINVAL;
1269
1270 ThreadContext *ctc;
1271 if (!(ctc = p->findFreeContext()))
1272 fatal("clone: no spare thread context in system");
1273
1274 /**
1275 * Note that ProcessParams is generated by swig and there are no other
1276 * examples of how to create anything but this default constructor. The
1277 * fields are manually initialized instead of passing parameters to the
1278 * constructor.
1279 */
1280 ProcessParams *pp = new ProcessParams();
1281 pp->executable.assign(*(new std::string(p->progName())));
1282 pp->cmd.push_back(*(new std::string(p->progName())));
1283 pp->system = p->system;
1284 pp->cwd.assign(p->getcwd());
1285 pp->input.assign("stdin");
1286 pp->output.assign("stdout");
1287 pp->errout.assign("stderr");
1288 pp->uid = p->uid();
1289 pp->euid = p->euid();
1290 pp->gid = p->gid();
1291 pp->egid = p->egid();
1292
1293 /* Find the first free PID that's less than the maximum */
1294 std::set<int> const& pids = p->system->PIDs;
1295 int temp_pid = *pids.begin();
1296 do {
1297 temp_pid++;
1298 } while (pids.find(temp_pid) != pids.end());
1299 if (temp_pid >= System::maxPID)
1300 fatal("temp_pid is too large: %d", temp_pid);
1301
1302 pp->pid = temp_pid;
1303 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1304 Process *cp = pp->create();
1305 delete pp;
1306
1307 Process *owner = ctc->getProcessPtr();
1308 ctc->setProcessPtr(cp);
1309 cp->assignThreadContext(ctc->contextId());
1310 owner->revokeThreadContext(ctc->contextId());
1311
1312 if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1313 BufferArg ptidBuf(ptidPtr, sizeof(long));
1314 long *ptid = (long *)ptidBuf.bufferPtr();
1315 *ptid = cp->pid();
1316 ptidBuf.copyOut(tc->getMemProxy());
1317 }
1318
1319 cp->initState();
1320 p->clone(tc, ctc, cp, flags);
1321
1322 if (flags & OS::TGT_CLONE_THREAD) {
1323 delete cp->sigchld;
1324 cp->sigchld = p->sigchld;
1325 } else if (flags & OS::TGT_SIGCHLD) {
1326 *cp->sigchld = true;
1327 }
1328
1329 if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1330 BufferArg ctidBuf(ctidPtr, sizeof(long));
1331 long *ctid = (long *)ctidBuf.bufferPtr();
1332 *ctid = cp->pid();
1333 ctidBuf.copyOut(ctc->getMemProxy());
1334 }
1335
1336 if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1337 cp->childClearTID = (uint64_t)ctidPtr;
1338
1339 ctc->clearArchRegs();
1340
1341#if THE_ISA == ALPHA_ISA
1342 TheISA::copyMiscRegs(tc, ctc);
1343#elif THE_ISA == SPARC_ISA
1344 TheISA::copyRegs(tc, ctc);
1345 ctc->setIntReg(TheISA::NumIntArchRegs + 6, 0);
1346 ctc->setIntReg(TheISA::NumIntArchRegs + 4, 0);
1347 ctc->setIntReg(TheISA::NumIntArchRegs + 3, TheISA::NWindows - 2);
1348 ctc->setIntReg(TheISA::NumIntArchRegs + 5, TheISA::NWindows);
1349 ctc->setMiscReg(TheISA::MISCREG_CWP, 0);
1350 ctc->setIntReg(TheISA::NumIntArchRegs + 7, 0);
1351 ctc->setMiscRegNoEffect(TheISA::MISCREG_TL, 0);
1352 ctc->setMiscReg(TheISA::MISCREG_ASI, TheISA::ASI_PRIMARY);
1353 for (int y = 8; y < 32; y++)
1354 ctc->setIntReg(y, tc->readIntReg(y));
1355#elif THE_ISA == ARM_ISA or THE_ISA == X86_ISA or THE_ISA == RISCV_ISA
1356 TheISA::copyRegs(tc, ctc);
1357#endif
1358
1359#if THE_ISA == X86_ISA
1360 if (flags & OS::TGT_CLONE_SETTLS) {
1361 ctc->setMiscRegNoEffect(TheISA::MISCREG_FS_BASE, tlsPtr);
1362 ctc->setMiscRegNoEffect(TheISA::MISCREG_FS_EFF_BASE, tlsPtr);
1363 }
1364#endif
1365
1366 if (newStack)
1367 ctc->setIntReg(TheISA::StackPointerReg, newStack);
1368
1369 cp->setSyscallReturn(ctc, 0);
1370
1371#if THE_ISA == ALPHA_ISA
1372 ctc->setIntReg(TheISA::SyscallSuccessReg, 0);
1373#elif THE_ISA == SPARC_ISA
1374 tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1375 ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1376#endif
1377
1378 ctc->pcState(tc->nextInstAddr());
1379 ctc->activate();
1380
1381 return cp->pid();
1382}
1383
1384/// Target fstatfs() handler.
1385template <class OS>
1386SyscallReturn
1387fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1388{
1389 int index = 0;
1390 int tgt_fd = p->getSyscallArg(tc, index);
1391 Addr bufPtr = p->getSyscallArg(tc, index);
1392
1393 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1394 if (!ffdp)
1395 return -EBADF;
1396 int sim_fd = ffdp->getSimFD();
1397
1398 struct statfs hostBuf;
1399 int result = fstatfs(sim_fd, &hostBuf);
1400
1401 if (result < 0)
1402 return -errno;
1403
1404 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1405
1406 return 0;
1407}
1408
1409
1410/// Target writev() handler.
1411template <class OS>
1412SyscallReturn
1413writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1414{
1415 int index = 0;
1416 int tgt_fd = p->getSyscallArg(tc, index);
1417
1418 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1419 if (!hbfdp)
1420 return -EBADF;
1421 int sim_fd = hbfdp->getSimFD();
1422
1423 SETranslatingPortProxy &prox = tc->getMemProxy();
1424 uint64_t tiov_base = p->getSyscallArg(tc, index);
1425 size_t count = p->getSyscallArg(tc, index);
1426 struct iovec hiov[count];
1427 for (size_t i = 0; i < count; ++i) {
1428 typename OS::tgt_iovec tiov;
1429
1430 prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1431 (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1432 hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1433 hiov[i].iov_base = new char [hiov[i].iov_len];
1434 prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1435 hiov[i].iov_len);
1436 }
1437
1438 int result = writev(sim_fd, hiov, count);
1439
1440 for (size_t i = 0; i < count; ++i)
1441 delete [] (char *)hiov[i].iov_base;
1442
1443 if (result < 0)
1444 return -errno;
1445
1446 return result;
1447}
1448
1449/// Real mmap handler.
1450template <class OS>
1451SyscallReturn
1452mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1453 bool is_mmap2)
1454{
1455 int index = 0;
1456 Addr start = p->getSyscallArg(tc, index);
1457 uint64_t length = p->getSyscallArg(tc, index);
1458 int prot = p->getSyscallArg(tc, index);
1459 int tgt_flags = p->getSyscallArg(tc, index);
1460 int tgt_fd = p->getSyscallArg(tc, index);
1461 int offset = p->getSyscallArg(tc, index);
1462
1463 if (is_mmap2)
1464 offset *= TheISA::PageBytes;
1465
1466 if (start & (TheISA::PageBytes - 1) ||
1467 offset & (TheISA::PageBytes - 1) ||
1468 (tgt_flags & OS::TGT_MAP_PRIVATE &&
1469 tgt_flags & OS::TGT_MAP_SHARED) ||
1470 (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1471 !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1472 !length) {
1473 return -EINVAL;
1474 }
1475
1476 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1477 // With shared mmaps, there are two cases to consider:
1478 // 1) anonymous: writes should modify the mapping and this should be
1479 // visible to observers who share the mapping. Currently, it's
1480 // difficult to update the shared mapping because there's no
1481 // structure which maintains information about the which virtual
1482 // memory areas are shared. If that structure existed, it would be
1483 // possible to make the translations point to the same frames.
1484 // 2) file-backed: writes should modify the mapping and the file
1485 // which is backed by the mapping. The shared mapping problem is the
1486 // same as what was mentioned about the anonymous mappings. For
1487 // file-backed mappings, the writes to the file are difficult
1488 // because it requires syncing what the mapping holds with the file
1489 // that resides on the host system. So, any write on a real system
1490 // would cause the change to be propagated to the file mapping at
1491 // some point in the future (the inode is tracked along with the
1492 // mapping). This isn't guaranteed to always happen, but it usually
1493 // works well enough. The guarantee is provided by the msync system
1494 // call. We could force the change through with shared mappings with
1495 // a call to msync, but that again would require more information
1496 // than we currently maintain.
1497 warn("mmap: writing to shared mmap region is currently "
1498 "unsupported. The write succeeds on the target, but it "
1499 "will not be propagated to the host or shared mappings");
1500 }
1501
1502 length = roundUp(length, TheISA::PageBytes);
1503
1504 int sim_fd = -1;
1505 uint8_t *pmap = nullptr;
1506 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1507 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1508
1509 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1510 if (dfdp) {
1511 EmulatedDriver *emul_driver = dfdp->getDriver();
1512 return emul_driver->mmap(p, tc, start, length, prot,
1513 tgt_flags, tgt_fd, offset);
1514 }
1515
1516 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1517 if (!ffdp)
1518 return -EBADF;
1519 sim_fd = ffdp->getSimFD();
1520
1521 pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1522 sim_fd, offset);
1523
1524 if (pmap == (decltype(pmap))-1) {
1525 warn("mmap: failed to map file into host address space");
1526 return -errno;
1527 }
1528 }
1529
1530 // Extend global mmap region if necessary. Note that we ignore the
1531 // start address unless MAP_FIXED is specified.
1532 if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1533 std::shared_ptr<MemState> mem_state = p->memState;
1534 Addr mmap_end = mem_state->getMmapEnd();
1535
1536 start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1537 mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1538
1539 mem_state->setMmapEnd(mmap_end);
1540 }
1541
1542 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1543 start, start + length - 1);
1544
1545 // We only allow mappings to overwrite existing mappings if
1546 // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1547 // because we ignore the start hint if TGT_MAP_FIXED is not set.
1548 int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1549 if (clobber) {
1550 for (auto tc : p->system->threadContexts) {
1551 // If we might be overwriting old mappings, we need to
1552 // invalidate potentially stale mappings out of the TLBs.
1553 tc->getDTBPtr()->flushAll();
1554 tc->getITBPtr()->flushAll();
1555 }
1556 }
1557
1558 // Allocate physical memory and map it in. If the page table is already
1559 // mapped and clobber is not set, the simulator will issue throw a
1560 // fatal and bail out of the simulation.
1561 p->allocateMem(start, length, clobber);
1562
1563 // Transfer content into target address space.
1564 SETranslatingPortProxy &tp = tc->getMemProxy();
1565 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1566 // In general, we should zero the mapped area for anonymous mappings,
1567 // with something like:
1568 // tp.memsetBlob(start, 0, length);
1569 // However, given that we don't support sparse mappings, and
1570 // some applications can map a couple of gigabytes of space
1571 // (intending sparse usage), that can get painfully expensive.
1572 // Fortunately, since we don't properly implement munmap either,
1573 // there's no danger of remapping used memory, so for now all
1574 // newly mapped memory should already be zeroed so we can skip it.
1575 } else {
1576 // It is possible to mmap an area larger than a file, however
1577 // accessing unmapped portions the system triggers a "Bus error"
1578 // on the host. We must know when to stop copying the file from
1579 // the host into the target address space.
1580 struct stat file_stat;
1581 if (fstat(sim_fd, &file_stat) > 0)
1582 fatal("mmap: cannot stat file");
1583
1584 // Copy the portion of the file that is resident. This requires
1585 // checking both the mmap size and the filesize that we are
1586 // trying to mmap into this space; the mmap size also depends
1587 // on the specified offset into the file.
1588 uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1589 length);
1590 tp.writeBlob(start, pmap, size);
1591
1592 // Cleanup the mmap region before exiting this function.
1593 munmap(pmap, length);
1594
1595 // Maintain the symbol table for dynamic executables.
1596 // The loader will call mmap to map the images into its address
1597 // space and we intercept that here. We can verify that we are
1598 // executing inside the loader by checking the program counter value.
1599 // XXX: with multiprogrammed workloads or multi-node configurations,
1600 // this will not work since there is a single global symbol table.
1601 ObjectFile *interpreter = p->getInterpreter();
1602 if (interpreter) {
1603 Addr text_start = interpreter->textBase();
1604 Addr text_end = text_start + interpreter->textSize();
1605
1606 Addr pc = tc->pcState().pc();
1607
1608 if (pc >= text_start && pc < text_end) {
1609 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1610 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1611 ObjectFile *lib = createObjectFile(ffdp->getFileName());
1612
1613 if (lib) {
1614 lib->loadAllSymbols(debugSymbolTable,
1615 lib->textBase(), start);
1616 }
1617 }
1618 }
1619
1620 // Note that we do not zero out the remainder of the mapping. This
1621 // is done by a real system, but it probably will not affect
1622 // execution (hopefully).
1623 }
1624
1625 return start;
1626}
1627
1628template <class OS>
1629SyscallReturn
1630pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1631{
1632 int index = 0;
1633 int tgt_fd = p->getSyscallArg(tc, index);
1634 Addr bufPtr = p->getSyscallArg(tc, index);
1635 int nbytes = p->getSyscallArg(tc, index);
1636 int offset = p->getSyscallArg(tc, index);
1637
1638 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1639 if (!ffdp)
1640 return -EBADF;
1641 int sim_fd = ffdp->getSimFD();
1642
1643 BufferArg bufArg(bufPtr, nbytes);
1644 bufArg.copyIn(tc->getMemProxy());
1645
1646 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1647
1648 return (bytes_written == -1) ? -errno : bytes_written;
1649}
1650
1651/// Target mmap() handler.
1652template <class OS>
1653SyscallReturn
1654mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1655{
1656 return mmapImpl<OS>(desc, num, p, tc, false);
1657}
1658
1659/// Target mmap2() handler.
1660template <class OS>
1661SyscallReturn
1662mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1663{
1664 return mmapImpl<OS>(desc, num, p, tc, true);
1665}
1666
1667/// Target getrlimit() handler.
1668template <class OS>
1669SyscallReturn
1670getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1671 ThreadContext *tc)
1672{
1673 int index = 0;
1674 unsigned resource = process->getSyscallArg(tc, index);
1675 TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1676
1677 switch (resource) {
1678 case OS::TGT_RLIMIT_STACK:
1679 // max stack size in bytes: make up a number (8MB for now)
1680 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1681 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1682 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1683 break;
1684
1685 case OS::TGT_RLIMIT_DATA:
1686 // max data segment size in bytes: make up a number
1687 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1688 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1689 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1690 break;
1691
1692 default:
1693 warn("getrlimit: unimplemented resource %d", resource);
1694 return -EINVAL;
1695 break;
1696 }
1697
1698 rlp.copyOut(tc->getMemProxy());
1699 return 0;
1700}
1701
1702template <class OS>
1703SyscallReturn
1704prlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1705 ThreadContext *tc)
1706{
1707 int index = 0;
1708 if (process->getSyscallArg(tc, index) != 0)
1709 {
1710 warn("prlimit: ignoring rlimits for nonzero pid");
1711 return -EPERM;
1712 }
1713 int resource = process->getSyscallArg(tc, index);
1714 Addr n = process->getSyscallArg(tc, index);
1715 if (n != 0)
1716 warn("prlimit: ignoring new rlimit");
1717 Addr o = process->getSyscallArg(tc, index);
1718 if (o != 0)
1719 {
1720 TypedBufferArg<typename OS::rlimit> rlp(o);
1721 switch (resource) {
1722 case OS::TGT_RLIMIT_STACK:
1723 // max stack size in bytes: make up a number (8MB for now)
1724 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1725 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1726 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1727 break;
1728 case OS::TGT_RLIMIT_DATA:
1729 // max data segment size in bytes: make up a number
1730 rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
1731 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1732 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1733 default:
1734 warn("prlimit: unimplemented resource %d", resource);
1735 return -EINVAL;
1736 break;
1737 }
1738 rlp.copyOut(tc->getMemProxy());
1739 }
1740 return 0;
1741}
1742
1743/// Target clock_gettime() function.
1744template <class OS>
1745SyscallReturn
1746clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1747{
1748 int index = 1;
1749 //int clk_id = p->getSyscallArg(tc, index);
1750 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1751
1752 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1753 tp->tv_sec += seconds_since_epoch;
1754 tp->tv_sec = TheISA::htog(tp->tv_sec);
1755 tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1756
1757 tp.copyOut(tc->getMemProxy());
1758
1759 return 0;
1760}
1761
1762/// Target clock_getres() function.
1763template <class OS>
1764SyscallReturn
1765clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1766{
1767 int index = 1;
1768 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1769
1770 // Set resolution at ns, which is what clock_gettime() returns
1771 tp->tv_sec = 0;
1772 tp->tv_nsec = 1;
1773
1774 tp.copyOut(tc->getMemProxy());
1775
1776 return 0;
1777}
1778
1779/// Target gettimeofday() handler.
1780template <class OS>
1781SyscallReturn
1782gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1783 ThreadContext *tc)
1784{
1785 int index = 0;
1786 TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1787
1788 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1789 tp->tv_sec += seconds_since_epoch;
1790 tp->tv_sec = TheISA::htog(tp->tv_sec);
1791 tp->tv_usec = TheISA::htog(tp->tv_usec);
1792
1793 tp.copyOut(tc->getMemProxy());
1794
1795 return 0;
1796}
1797
1798
1799/// Target utimes() handler.
1800template <class OS>
1801SyscallReturn
1802utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1803 ThreadContext *tc)
1804{
1805 std::string path;
1806
1807 int index = 0;
1808 if (!tc->getMemProxy().tryReadString(path,
1809 process->getSyscallArg(tc, index))) {
1810 return -EFAULT;
1811 }
1812
1813 TypedBufferArg<typename OS::timeval [2]>
1814 tp(process->getSyscallArg(tc, index));
1815 tp.copyIn(tc->getMemProxy());
1816
1817 struct timeval hostTimeval[2];
1818 for (int i = 0; i < 2; ++i) {
1819 hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1820 hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1821 }
1822
1823 // Adjust path for current working directory
1824 path = process->fullPath(path);
1825
1826 int result = utimes(path.c_str(), hostTimeval);
1827
1828 if (result < 0)
1829 return -errno;
1830
1831 return 0;
1832}
1833
1834template <class OS>
1835SyscallReturn
1836execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1837{
1838 desc->setFlags(0);
1839
1840 int index = 0;
1841 std::string path;
1842 SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
1843 if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
1844 return -EFAULT;
1845
1846 if (access(path.c_str(), F_OK) == -1)
1847 return -EACCES;
1848
1849 auto read_in = [](std::vector<std::string> & vect,
1850 SETranslatingPortProxy & mem_proxy,
1851 Addr mem_loc)
1852 {
1853 for (int inc = 0; ; inc++) {
1854 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
1855 b.copyIn(mem_proxy);
1856
1857 if (!*(Addr*)b.bufferPtr())
1858 break;
1859
1860 vect.push_back(std::string());
1861 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
1862 }
1863 };
1864
1865 /**
1866 * Note that ProcessParams is generated by swig and there are no other
1867 * examples of how to create anything but this default constructor. The
1868 * fields are manually initialized instead of passing parameters to the
1869 * constructor.
1870 */
1871 ProcessParams *pp = new ProcessParams();
1872 pp->executable = path;
1873 Addr argv_mem_loc = p->getSyscallArg(tc, index);
1874 read_in(pp->cmd, mem_proxy, argv_mem_loc);
1875 Addr envp_mem_loc = p->getSyscallArg(tc, index);
1876 read_in(pp->env, mem_proxy, envp_mem_loc);
1877 pp->uid = p->uid();
1878 pp->egid = p->egid();
1879 pp->euid = p->euid();
1880 pp->gid = p->gid();
1881 pp->ppid = p->ppid();
1882 pp->pid = p->pid();
1883 pp->input.assign("cin");
1884 pp->output.assign("cout");
1885 pp->errout.assign("cerr");
1886 pp->cwd.assign(p->getcwd());
1887 pp->system = p->system;
1888 /**
1889 * Prevent process object creation with identical PIDs (which will trip
1890 * a fatal check in Process constructor). The execve call is supposed to
1891 * take over the currently executing process' identity but replace
1892 * whatever it is doing with a new process image. Instead of hijacking
1893 * the process object in the simulator, we create a new process object
1894 * and bind to the previous process' thread below (hijacking the thread).
1895 */
1896 p->system->PIDs.erase(p->pid());
1897 Process *new_p = pp->create();
1898 delete pp;
1899
1900 /**
1901 * Work through the file descriptor array and close any files marked
1902 * close-on-exec.
1903 */
1904 new_p->fds = p->fds;
1905 for (int i = 0; i < new_p->fds->getSize(); i++) {
1906 std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
1907 if (fdep && fdep->getCOE())
1908 new_p->fds->closeFDEntry(i);
1909 }
1910
1911 *new_p->sigchld = true;
1912
1913 delete p;
1914 tc->clearArchRegs();
1915 tc->setProcessPtr(new_p);
1916 new_p->assignThreadContext(tc->contextId());
1917 new_p->initState();
1918 tc->activate();
1919 TheISA::PCState pcState = tc->pcState();
1920 tc->setNPC(pcState.instAddr());
1921
1922 desc->setFlags(SyscallDesc::SuppressReturnValue);
1923 return 0;
1924}
1925
1926/// Target getrusage() function.
1927template <class OS>
1928SyscallReturn
1929getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
1930 ThreadContext *tc)
1931{
1932 int index = 0;
1933 int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
1934 TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
1935
1936 rup->ru_utime.tv_sec = 0;
1937 rup->ru_utime.tv_usec = 0;
1938 rup->ru_stime.tv_sec = 0;
1939 rup->ru_stime.tv_usec = 0;
1940 rup->ru_maxrss = 0;
1941 rup->ru_ixrss = 0;
1942 rup->ru_idrss = 0;
1943 rup->ru_isrss = 0;
1944 rup->ru_minflt = 0;
1945 rup->ru_majflt = 0;
1946 rup->ru_nswap = 0;
1947 rup->ru_inblock = 0;
1948 rup->ru_oublock = 0;
1949 rup->ru_msgsnd = 0;
1950 rup->ru_msgrcv = 0;
1951 rup->ru_nsignals = 0;
1952 rup->ru_nvcsw = 0;
1953 rup->ru_nivcsw = 0;
1954
1955 switch (who) {
1956 case OS::TGT_RUSAGE_SELF:
1957 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
1958 rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
1959 rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
1960 break;
1961
1962 case OS::TGT_RUSAGE_CHILDREN:
1963 // do nothing. We have no child processes, so they take no time.
1964 break;
1965
1966 default:
1967 // don't really handle THREAD or CHILDREN, but just warn and
1968 // plow ahead
1969 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
1970 who);
1971 }
1972
1973 rup.copyOut(tc->getMemProxy());
1974
1975 return 0;
1976}
1977
1978/// Target times() function.
1979template <class OS>
1980SyscallReturn
1981timesFunc(SyscallDesc *desc, int callnum, Process *process,
1982 ThreadContext *tc)
1983{
1984 int index = 0;
1985 TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
1986
1987 // Fill in the time structure (in clocks)
1988 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
1989 bufp->tms_utime = clocks;
1990 bufp->tms_stime = 0;
1991 bufp->tms_cutime = 0;
1992 bufp->tms_cstime = 0;
1993
1994 // Convert to host endianness
1995 bufp->tms_utime = TheISA::htog(bufp->tms_utime);
1996
1997 // Write back
1998 bufp.copyOut(tc->getMemProxy());
1999
2000 // Return clock ticks since system boot
2001 return clocks;
2002}
2003
2004/// Target time() function.
2005template <class OS>
2006SyscallReturn
2007timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
2008{
2009 typename OS::time_t sec, usec;
2010 getElapsedTimeMicro(sec, usec);
2011 sec += seconds_since_epoch;
2012
2013 int index = 0;
2014 Addr taddr = (Addr)process->getSyscallArg(tc, index);
2015 if (taddr != 0) {
2016 typename OS::time_t t = sec;
2017 t = TheISA::htog(t);
2018 SETranslatingPortProxy &p = tc->getMemProxy();
2019 p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
2020 }
2021 return sec;
2022}
2023
2024template <class OS>
2025SyscallReturn
2026tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
2027{
2028 int index = 0;
2029 int tgid = process->getSyscallArg(tc, index);
2030 int tid = process->getSyscallArg(tc, index);
2031 int sig = process->getSyscallArg(tc, index);
2032
2033 /**
2034 * This system call is intended to allow killing a specific thread
2035 * within an arbitrary thread group if sanctioned with permission checks.
2036 * It's usually true that threads share the termination signal as pointed
2037 * out by the pthread_kill man page and this seems to be the intended
2038 * usage. Due to this being an emulated environment, assume the following:
2039 * Threads are allowed to call tgkill because the EUID for all threads
2040 * should be the same. There is no signal handling mechanism for kernel
2041 * registration of signal handlers since signals are poorly supported in
2042 * emulation mode. Since signal handlers cannot be registered, all
2043 * threads within in a thread group must share the termination signal.
2044 * We never exhaust PIDs so there's no chance of finding the wrong one
2045 * due to PID rollover.
2046 */
2047
2048 System *sys = tc->getSystemPtr();
2049 Process *tgt_proc = nullptr;
2050 for (int i = 0; i < sys->numContexts(); i++) {
2051 Process *temp = sys->threadContexts[i]->getProcessPtr();
2052 if (temp->pid() == tid) {
2053 tgt_proc = temp;
2054 break;
2055 }
2056 }
2057
2058 if (sig != 0 || sig != OS::TGT_SIGABRT)
2059 return -EINVAL;
2060
2061 if (tgt_proc == nullptr)
2062 return -ESRCH;
2063
2064 if (tgid != -1 && tgt_proc->tgid() != tgid)
2065 return -ESRCH;
2066
2067 if (sig == OS::TGT_SIGABRT)
2068 exitGroupFunc(desc, 252, process, tc);
2069
2070 return 0;
2071}
2072
2073
2074#endif // __SIM_SYSCALL_EMUL_HH__
97#include "arch/utility.hh"
98#include "base/intmath.hh"
99#include "base/loader/object_file.hh"
100#include "base/logging.hh"
101#include "base/trace.hh"
102#include "base/types.hh"
103#include "config/the_isa.hh"
104#include "cpu/base.hh"
105#include "cpu/thread_context.hh"
106#include "mem/page_table.hh"
107#include "params/Process.hh"
108#include "sim/emul_driver.hh"
109#include "sim/futex_map.hh"
110#include "sim/process.hh"
111#include "sim/syscall_debug_macros.hh"
112#include "sim/syscall_desc.hh"
113#include "sim/syscall_emul_buf.hh"
114#include "sim/syscall_return.hh"
115
116//////////////////////////////////////////////////////////////////////
117//
118// The following emulation functions are generic enough that they
119// don't need to be recompiled for different emulated OS's. They are
120// defined in sim/syscall_emul.cc.
121//
122//////////////////////////////////////////////////////////////////////
123
124
125/// Handler for unimplemented syscalls that we haven't thought about.
126SyscallReturn unimplementedFunc(SyscallDesc *desc, int num,
127 Process *p, ThreadContext *tc);
128
129/// Handler for unimplemented syscalls that we never intend to
130/// implement (signal handling, etc.) and should not affect the correct
131/// behavior of the program. Print a warning only if the appropriate
132/// trace flag is enabled. Return success to the target program.
133SyscallReturn ignoreFunc(SyscallDesc *desc, int num,
134 Process *p, ThreadContext *tc);
135
136// Target fallocateFunc() handler.
137SyscallReturn fallocateFunc(SyscallDesc *desc, int num,
138 Process *p, ThreadContext *tc);
139
140/// Target exit() handler: terminate current context.
141SyscallReturn exitFunc(SyscallDesc *desc, int num,
142 Process *p, ThreadContext *tc);
143
144/// Target exit_group() handler: terminate simulation. (exit all threads)
145SyscallReturn exitGroupFunc(SyscallDesc *desc, int num,
146 Process *p, ThreadContext *tc);
147
148/// Target set_tid_address() handler.
149SyscallReturn setTidAddressFunc(SyscallDesc *desc, int num,
150 Process *p, ThreadContext *tc);
151
152/// Target getpagesize() handler.
153SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num,
154 Process *p, ThreadContext *tc);
155
156/// Target brk() handler: set brk address.
157SyscallReturn brkFunc(SyscallDesc *desc, int num,
158 Process *p, ThreadContext *tc);
159
160/// Target close() handler.
161SyscallReturn closeFunc(SyscallDesc *desc, int num,
162 Process *p, ThreadContext *tc);
163
164// Target read() handler.
165SyscallReturn readFunc(SyscallDesc *desc, int num,
166 Process *p, ThreadContext *tc);
167
168/// Target write() handler.
169SyscallReturn writeFunc(SyscallDesc *desc, int num,
170 Process *p, ThreadContext *tc);
171
172/// Target lseek() handler.
173SyscallReturn lseekFunc(SyscallDesc *desc, int num,
174 Process *p, ThreadContext *tc);
175
176/// Target _llseek() handler.
177SyscallReturn _llseekFunc(SyscallDesc *desc, int num,
178 Process *p, ThreadContext *tc);
179
180/// Target munmap() handler.
181SyscallReturn munmapFunc(SyscallDesc *desc, int num,
182 Process *p, ThreadContext *tc);
183
184/// Target gethostname() handler.
185SyscallReturn gethostnameFunc(SyscallDesc *desc, int num,
186 Process *p, ThreadContext *tc);
187
188/// Target getcwd() handler.
189SyscallReturn getcwdFunc(SyscallDesc *desc, int num,
190 Process *p, ThreadContext *tc);
191
192/// Target readlink() handler.
193SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
194 Process *p, ThreadContext *tc,
195 int index = 0);
196SyscallReturn readlinkFunc(SyscallDesc *desc, int num,
197 Process *p, ThreadContext *tc);
198
199/// Target unlink() handler.
200SyscallReturn unlinkHelper(SyscallDesc *desc, int num,
201 Process *p, ThreadContext *tc,
202 int index);
203SyscallReturn unlinkFunc(SyscallDesc *desc, int num,
204 Process *p, ThreadContext *tc);
205
206/// Target mkdir() handler.
207SyscallReturn mkdirFunc(SyscallDesc *desc, int num,
208 Process *p, ThreadContext *tc);
209
210/// Target rename() handler.
211SyscallReturn renameFunc(SyscallDesc *desc, int num,
212 Process *p, ThreadContext *tc);
213
214
215/// Target truncate() handler.
216SyscallReturn truncateFunc(SyscallDesc *desc, int num,
217 Process *p, ThreadContext *tc);
218
219
220/// Target ftruncate() handler.
221SyscallReturn ftruncateFunc(SyscallDesc *desc, int num,
222 Process *p, ThreadContext *tc);
223
224
225/// Target truncate64() handler.
226SyscallReturn truncate64Func(SyscallDesc *desc, int num,
227 Process *p, ThreadContext *tc);
228
229/// Target ftruncate64() handler.
230SyscallReturn ftruncate64Func(SyscallDesc *desc, int num,
231 Process *p, ThreadContext *tc);
232
233
234/// Target umask() handler.
235SyscallReturn umaskFunc(SyscallDesc *desc, int num,
236 Process *p, ThreadContext *tc);
237
238/// Target gettid() handler.
239SyscallReturn gettidFunc(SyscallDesc *desc, int num,
240 Process *p, ThreadContext *tc);
241
242/// Target chown() handler.
243SyscallReturn chownFunc(SyscallDesc *desc, int num,
244 Process *p, ThreadContext *tc);
245
246/// Target setpgid() handler.
247SyscallReturn setpgidFunc(SyscallDesc *desc, int num,
248 Process *p, ThreadContext *tc);
249
250/// Target fchown() handler.
251SyscallReturn fchownFunc(SyscallDesc *desc, int num,
252 Process *p, ThreadContext *tc);
253
254/// Target dup() handler.
255SyscallReturn dupFunc(SyscallDesc *desc, int num,
256 Process *process, ThreadContext *tc);
257
258/// Target dup2() handler.
259SyscallReturn dup2Func(SyscallDesc *desc, int num,
260 Process *process, ThreadContext *tc);
261
262/// Target fcntl() handler.
263SyscallReturn fcntlFunc(SyscallDesc *desc, int num,
264 Process *process, ThreadContext *tc);
265
266/// Target fcntl64() handler.
267SyscallReturn fcntl64Func(SyscallDesc *desc, int num,
268 Process *process, ThreadContext *tc);
269
270/// Target setuid() handler.
271SyscallReturn setuidFunc(SyscallDesc *desc, int num,
272 Process *p, ThreadContext *tc);
273
274/// Target pipe() handler.
275SyscallReturn pipeFunc(SyscallDesc *desc, int num,
276 Process *p, ThreadContext *tc);
277
278/// Internal pipe() handler.
279SyscallReturn pipeImpl(SyscallDesc *desc, int num, Process *p,
280 ThreadContext *tc, bool pseudoPipe);
281
282/// Target getpid() handler.
283SyscallReturn getpidFunc(SyscallDesc *desc, int num,
284 Process *p, ThreadContext *tc);
285
286/// Target getuid() handler.
287SyscallReturn getuidFunc(SyscallDesc *desc, int num,
288 Process *p, ThreadContext *tc);
289
290/// Target getgid() handler.
291SyscallReturn getgidFunc(SyscallDesc *desc, int num,
292 Process *p, ThreadContext *tc);
293
294/// Target getppid() handler.
295SyscallReturn getppidFunc(SyscallDesc *desc, int num,
296 Process *p, ThreadContext *tc);
297
298/// Target geteuid() handler.
299SyscallReturn geteuidFunc(SyscallDesc *desc, int num,
300 Process *p, ThreadContext *tc);
301
302/// Target getegid() handler.
303SyscallReturn getegidFunc(SyscallDesc *desc, int num,
304 Process *p, ThreadContext *tc);
305
306/// Target access() handler
307SyscallReturn accessFunc(SyscallDesc *desc, int num,
308 Process *p, ThreadContext *tc);
309SyscallReturn accessFunc(SyscallDesc *desc, int num,
310 Process *p, ThreadContext *tc,
311 int index);
312
313/// Futex system call
314/// Implemented by Daniel Sanchez
315/// Used by printf's in multi-threaded apps
316template <class OS>
317SyscallReturn
318futexFunc(SyscallDesc *desc, int callnum, Process *process,
319 ThreadContext *tc)
320{
321 using namespace std;
322
323 int index = 0;
324 Addr uaddr = process->getSyscallArg(tc, index);
325 int op = process->getSyscallArg(tc, index);
326 int val = process->getSyscallArg(tc, index);
327
328 /*
329 * Unsupported option that does not affect the correctness of the
330 * application. This is a performance optimization utilized by Linux.
331 */
332 op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
333
334 FutexMap &futex_map = tc->getSystemPtr()->futexMap;
335
336 if (OS::TGT_FUTEX_WAIT == op) {
337 // Ensure futex system call accessed atomically.
338 BufferArg buf(uaddr, sizeof(int));
339 buf.copyIn(tc->getMemProxy());
340 int mem_val = *(int*)buf.bufferPtr();
341
342 /*
343 * The value in memory at uaddr is not equal with the expected val
344 * (a different thread must have changed it before the system call was
345 * invoked). In this case, we need to throw an error.
346 */
347 if (val != mem_val)
348 return -OS::TGT_EWOULDBLOCK;
349
350 futex_map.suspend(uaddr, process->tgid(), tc);
351
352 return 0;
353 } else if (OS::TGT_FUTEX_WAKE == op) {
354 return futex_map.wakeup(uaddr, process->tgid(), val);
355 }
356
357 warn("futex: op %d not implemented; ignoring.", op);
358 return -ENOSYS;
359}
360
361
362/// Pseudo Funcs - These functions use a different return convension,
363/// returning a second value in a register other than the normal return register
364SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num,
365 Process *process, ThreadContext *tc);
366
367/// Target getpidPseudo() handler.
368SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num,
369 Process *p, ThreadContext *tc);
370
371/// Target getuidPseudo() handler.
372SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num,
373 Process *p, ThreadContext *tc);
374
375/// Target getgidPseudo() handler.
376SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num,
377 Process *p, ThreadContext *tc);
378
379
380/// A readable name for 1,000,000, for converting microseconds to seconds.
381const int one_million = 1000000;
382/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
383const int one_billion = 1000000000;
384
385/// Approximate seconds since the epoch (1/1/1970). About a billion,
386/// by my reckoning. We want to keep this a constant (not use the
387/// real-world time) to keep simulations repeatable.
388const unsigned seconds_since_epoch = 1000000000;
389
390/// Helper function to convert current elapsed time to seconds and
391/// microseconds.
392template <class T1, class T2>
393void
394getElapsedTimeMicro(T1 &sec, T2 &usec)
395{
396 uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
397 sec = elapsed_usecs / one_million;
398 usec = elapsed_usecs % one_million;
399}
400
401/// Helper function to convert current elapsed time to seconds and
402/// nanoseconds.
403template <class T1, class T2>
404void
405getElapsedTimeNano(T1 &sec, T2 &nsec)
406{
407 uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
408 sec = elapsed_nsecs / one_billion;
409 nsec = elapsed_nsecs % one_billion;
410}
411
412//////////////////////////////////////////////////////////////////////
413//
414// The following emulation functions are generic, but need to be
415// templated to account for differences in types, constants, etc.
416//
417//////////////////////////////////////////////////////////////////////
418
419 typedef struct statfs hst_statfs;
420#if NO_STAT64
421 typedef struct stat hst_stat;
422 typedef struct stat hst_stat64;
423#else
424 typedef struct stat hst_stat;
425 typedef struct stat64 hst_stat64;
426#endif
427
428//// Helper function to convert a host stat buffer to a target stat
429//// buffer. Also copies the target buffer out to the simulated
430//// memory space. Used by stat(), fstat(), and lstat().
431
432template <typename target_stat, typename host_stat>
433void
434convertStatBuf(target_stat &tgt, host_stat *host, bool fakeTTY = false)
435{
436 using namespace TheISA;
437
438 if (fakeTTY)
439 tgt->st_dev = 0xA;
440 else
441 tgt->st_dev = host->st_dev;
442 tgt->st_dev = TheISA::htog(tgt->st_dev);
443 tgt->st_ino = host->st_ino;
444 tgt->st_ino = TheISA::htog(tgt->st_ino);
445 tgt->st_mode = host->st_mode;
446 if (fakeTTY) {
447 // Claim to be a character device
448 tgt->st_mode &= ~S_IFMT; // Clear S_IFMT
449 tgt->st_mode |= S_IFCHR; // Set S_IFCHR
450 }
451 tgt->st_mode = TheISA::htog(tgt->st_mode);
452 tgt->st_nlink = host->st_nlink;
453 tgt->st_nlink = TheISA::htog(tgt->st_nlink);
454 tgt->st_uid = host->st_uid;
455 tgt->st_uid = TheISA::htog(tgt->st_uid);
456 tgt->st_gid = host->st_gid;
457 tgt->st_gid = TheISA::htog(tgt->st_gid);
458 if (fakeTTY)
459 tgt->st_rdev = 0x880d;
460 else
461 tgt->st_rdev = host->st_rdev;
462 tgt->st_rdev = TheISA::htog(tgt->st_rdev);
463 tgt->st_size = host->st_size;
464 tgt->st_size = TheISA::htog(tgt->st_size);
465 tgt->st_atimeX = host->st_atime;
466 tgt->st_atimeX = TheISA::htog(tgt->st_atimeX);
467 tgt->st_mtimeX = host->st_mtime;
468 tgt->st_mtimeX = TheISA::htog(tgt->st_mtimeX);
469 tgt->st_ctimeX = host->st_ctime;
470 tgt->st_ctimeX = TheISA::htog(tgt->st_ctimeX);
471 // Force the block size to be 8KB. This helps to ensure buffered io works
472 // consistently across different hosts.
473 tgt->st_blksize = 0x2000;
474 tgt->st_blksize = TheISA::htog(tgt->st_blksize);
475 tgt->st_blocks = host->st_blocks;
476 tgt->st_blocks = TheISA::htog(tgt->st_blocks);
477}
478
479// Same for stat64
480
481template <typename target_stat, typename host_stat64>
482void
483convertStat64Buf(target_stat &tgt, host_stat64 *host, bool fakeTTY = false)
484{
485 using namespace TheISA;
486
487 convertStatBuf<target_stat, host_stat64>(tgt, host, fakeTTY);
488#if defined(STAT_HAVE_NSEC)
489 tgt->st_atime_nsec = host->st_atime_nsec;
490 tgt->st_atime_nsec = TheISA::htog(tgt->st_atime_nsec);
491 tgt->st_mtime_nsec = host->st_mtime_nsec;
492 tgt->st_mtime_nsec = TheISA::htog(tgt->st_mtime_nsec);
493 tgt->st_ctime_nsec = host->st_ctime_nsec;
494 tgt->st_ctime_nsec = TheISA::htog(tgt->st_ctime_nsec);
495#else
496 tgt->st_atime_nsec = 0;
497 tgt->st_mtime_nsec = 0;
498 tgt->st_ctime_nsec = 0;
499#endif
500}
501
502// Here are a couple of convenience functions
503template<class OS>
504void
505copyOutStatBuf(SETranslatingPortProxy &mem, Addr addr,
506 hst_stat *host, bool fakeTTY = false)
507{
508 typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
509 tgt_stat_buf tgt(addr);
510 convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, fakeTTY);
511 tgt.copyOut(mem);
512}
513
514template<class OS>
515void
516copyOutStat64Buf(SETranslatingPortProxy &mem, Addr addr,
517 hst_stat64 *host, bool fakeTTY = false)
518{
519 typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
520 tgt_stat_buf tgt(addr);
521 convertStat64Buf<tgt_stat_buf, hst_stat64>(tgt, host, fakeTTY);
522 tgt.copyOut(mem);
523}
524
525template <class OS>
526void
527copyOutStatfsBuf(SETranslatingPortProxy &mem, Addr addr,
528 hst_statfs *host)
529{
530 TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
531
532 tgt->f_type = TheISA::htog(host->f_type);
533#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
534 tgt->f_bsize = TheISA::htog(host->f_iosize);
535#else
536 tgt->f_bsize = TheISA::htog(host->f_bsize);
537#endif
538 tgt->f_blocks = TheISA::htog(host->f_blocks);
539 tgt->f_bfree = TheISA::htog(host->f_bfree);
540 tgt->f_bavail = TheISA::htog(host->f_bavail);
541 tgt->f_files = TheISA::htog(host->f_files);
542 tgt->f_ffree = TheISA::htog(host->f_ffree);
543 memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
544#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
545 tgt->f_namelen = TheISA::htog(host->f_namemax);
546 tgt->f_frsize = TheISA::htog(host->f_bsize);
547#elif defined(__APPLE__)
548 tgt->f_namelen = 0;
549 tgt->f_frsize = 0;
550#else
551 tgt->f_namelen = TheISA::htog(host->f_namelen);
552 tgt->f_frsize = TheISA::htog(host->f_frsize);
553#endif
554#if defined(__linux__)
555 memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
556#else
557 /*
558 * The fields are different sizes per OS. Don't bother with
559 * f_spare or f_reserved on non-Linux for now.
560 */
561 memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
562#endif
563
564 tgt.copyOut(mem);
565}
566
567/// Target ioctl() handler. For the most part, programs call ioctl()
568/// only to find out if their stdout is a tty, to determine whether to
569/// do line or block buffering. We always claim that output fds are
570/// not TTYs to provide repeatable results.
571template <class OS>
572SyscallReturn
573ioctlFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
574{
575 int index = 0;
576 int tgt_fd = p->getSyscallArg(tc, index);
577 unsigned req = p->getSyscallArg(tc, index);
578
579 DPRINTF(SyscallVerbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
580
581 if (OS::isTtyReq(req))
582 return -ENOTTY;
583
584 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
585 if (!dfdp)
586 return -EBADF;
587
588 /**
589 * If the driver is valid, issue the ioctl through it. Otherwise,
590 * there's an implicit assumption that the device is a TTY type and we
591 * return that we do not have a valid TTY.
592 */
593 EmulatedDriver *emul_driver = dfdp->getDriver();
594 if (emul_driver)
595 return emul_driver->ioctl(p, tc, req);
596
597 /**
598 * For lack of a better return code, return ENOTTY. Ideally, we should
599 * return something better here, but at least we issue the warning.
600 */
601 warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
602 tgt_fd, req, tc->pcState());
603 return -ENOTTY;
604}
605
606template <class OS>
607SyscallReturn
608openImpl(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc,
609 bool isopenat)
610{
611 int index = 0;
612 int tgt_dirfd = -1;
613
614 /**
615 * If using the openat variant, read in the target directory file
616 * descriptor from the simulated process.
617 */
618 if (isopenat)
619 tgt_dirfd = p->getSyscallArg(tc, index);
620
621 /**
622 * Retrieve the simulated process' memory proxy and then read in the path
623 * string from that memory space into the host's working memory space.
624 */
625 std::string path;
626 if (!tc->getMemProxy().tryReadString(path, p->getSyscallArg(tc, index)))
627 return -EFAULT;
628
629#ifdef __CYGWIN32__
630 int host_flags = O_BINARY;
631#else
632 int host_flags = 0;
633#endif
634 /**
635 * Translate target flags into host flags. Flags exist which are not
636 * ported between architectures which can cause check failures.
637 */
638 int tgt_flags = p->getSyscallArg(tc, index);
639 for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
640 if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
641 tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
642 host_flags |= OS::openFlagTable[i].hostFlag;
643 }
644 }
645 if (tgt_flags) {
646 warn("open%s: cannot decode flags 0x%x",
647 isopenat ? "at" : "", tgt_flags);
648 }
649#ifdef __CYGWIN32__
650 host_flags |= O_BINARY;
651#endif
652
653 int mode = p->getSyscallArg(tc, index);
654
655 /**
656 * If the simulated process called open or openat with AT_FDCWD specified,
657 * take the current working directory value which was passed into the
658 * process class as a Python parameter and append the current path to
659 * create a full path.
660 * Otherwise, openat with a valid target directory file descriptor has
661 * been called. If the path option, which was passed in as a parameter,
662 * is not absolute, retrieve the directory file descriptor's path and
663 * prepend it to the path passed in as a parameter.
664 * In every case, we should have a full path (which is relevant to the
665 * host) to work with after this block has been passed.
666 */
667 if (!isopenat || (isopenat && tgt_dirfd == OS::TGT_AT_FDCWD)) {
668 path = p->fullPath(path);
669 } else if (!startswith(path, "/")) {
670 std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
671 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
672 if (!ffdp)
673 return -EBADF;
674 path.insert(0, ffdp->getFileName());
675 }
676
677 /**
678 * Since this is an emulated environment, we create pseudo file
679 * descriptors for device requests that have been registered with
680 * the process class through Python; this allows us to create a file
681 * descriptor for subsequent ioctl or mmap calls.
682 */
683 if (startswith(path, "/dev/")) {
684 std::string filename = path.substr(strlen("/dev/"));
685 EmulatedDriver *drv = p->findDriver(filename);
686 if (drv) {
687 DPRINTF_SYSCALL(Verbose, "open%s: passing call to "
688 "driver open with path[%s]\n",
689 isopenat ? "at" : "", path.c_str());
690 return drv->open(p, tc, mode, host_flags);
691 }
692 /**
693 * Fall through here for pass through to host devices, such
694 * as /dev/zero
695 */
696 }
697
698 /**
699 * Some special paths and files cannot be called on the host and need
700 * to be handled as special cases inside the simulator.
701 * If the full path that was created above does not match any of the
702 * special cases, pass it through to the open call on the host to let
703 * the host open the file on our behalf.
704 * If the host cannot open the file, return the host's error code back
705 * through the system call to the simulated process.
706 */
707 int sim_fd = -1;
708 std::vector<std::string> special_paths =
709 { "/proc/", "/system/", "/sys/", "/platform/", "/etc/passwd" };
710 for (auto entry : special_paths) {
711 if (startswith(path, entry))
712 sim_fd = OS::openSpecialFile(path, p, tc);
713 }
714 if (sim_fd == -1) {
715 sim_fd = open(path.c_str(), host_flags, mode);
716 }
717 if (sim_fd == -1) {
718 int local = -errno;
719 DPRINTF_SYSCALL(Verbose, "open%s: failed -> path:%s\n",
720 isopenat ? "at" : "", path.c_str());
721 return local;
722 }
723
724 /**
725 * The file was opened successfully and needs to be recorded in the
726 * process' file descriptor array so that it can be retrieved later.
727 * The target file descriptor that is chosen will be the lowest unused
728 * file descriptor.
729 * Return the indirect target file descriptor back to the simulated
730 * process to act as a handle for the opened file.
731 */
732 auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
733 int tgt_fd = p->fds->allocFD(ffdp);
734 DPRINTF_SYSCALL(Verbose, "open%s: sim_fd[%d], target_fd[%d] -> path:%s\n",
735 isopenat ? "at" : "", sim_fd, tgt_fd, path.c_str());
736 return tgt_fd;
737}
738
739/// Target open() handler.
740template <class OS>
741SyscallReturn
742openFunc(SyscallDesc *desc, int callnum, Process *process,
743 ThreadContext *tc)
744{
745 return openImpl<OS>(desc, callnum, process, tc, false);
746}
747
748/// Target openat() handler.
749template <class OS>
750SyscallReturn
751openatFunc(SyscallDesc *desc, int callnum, Process *process,
752 ThreadContext *tc)
753{
754 return openImpl<OS>(desc, callnum, process, tc, true);
755}
756
757/// Target unlinkat() handler.
758template <class OS>
759SyscallReturn
760unlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
761 ThreadContext *tc)
762{
763 int index = 0;
764 int dirfd = process->getSyscallArg(tc, index);
765 if (dirfd != OS::TGT_AT_FDCWD)
766 warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
767
768 return unlinkHelper(desc, callnum, process, tc, 1);
769}
770
771/// Target facessat() handler
772template <class OS>
773SyscallReturn
774faccessatFunc(SyscallDesc *desc, int callnum, Process *process,
775 ThreadContext *tc)
776{
777 int index = 0;
778 int dirfd = process->getSyscallArg(tc, index);
779 if (dirfd != OS::TGT_AT_FDCWD)
780 warn("faccessat: first argument not AT_FDCWD; unlikely to work");
781 return accessFunc(desc, callnum, process, tc, 1);
782}
783
784/// Target readlinkat() handler
785template <class OS>
786SyscallReturn
787readlinkatFunc(SyscallDesc *desc, int callnum, Process *process,
788 ThreadContext *tc)
789{
790 int index = 0;
791 int dirfd = process->getSyscallArg(tc, index);
792 if (dirfd != OS::TGT_AT_FDCWD)
793 warn("openat: first argument not AT_FDCWD; unlikely to work");
794 return readlinkFunc(desc, callnum, process, tc, 1);
795}
796
797/// Target renameat() handler.
798template <class OS>
799SyscallReturn
800renameatFunc(SyscallDesc *desc, int callnum, Process *process,
801 ThreadContext *tc)
802{
803 int index = 0;
804
805 int olddirfd = process->getSyscallArg(tc, index);
806 if (olddirfd != OS::TGT_AT_FDCWD)
807 warn("renameat: first argument not AT_FDCWD; unlikely to work");
808
809 std::string old_name;
810
811 if (!tc->getMemProxy().tryReadString(old_name,
812 process->getSyscallArg(tc, index)))
813 return -EFAULT;
814
815 int newdirfd = process->getSyscallArg(tc, index);
816 if (newdirfd != OS::TGT_AT_FDCWD)
817 warn("renameat: third argument not AT_FDCWD; unlikely to work");
818
819 std::string new_name;
820
821 if (!tc->getMemProxy().tryReadString(new_name,
822 process->getSyscallArg(tc, index)))
823 return -EFAULT;
824
825 // Adjust path for current working directory
826 old_name = process->fullPath(old_name);
827 new_name = process->fullPath(new_name);
828
829 int result = rename(old_name.c_str(), new_name.c_str());
830 return (result == -1) ? -errno : result;
831}
832
833/// Target sysinfo() handler.
834template <class OS>
835SyscallReturn
836sysinfoFunc(SyscallDesc *desc, int callnum, Process *process,
837 ThreadContext *tc)
838{
839
840 int index = 0;
841 TypedBufferArg<typename OS::tgt_sysinfo>
842 sysinfo(process->getSyscallArg(tc, index));
843
844 sysinfo->uptime = seconds_since_epoch;
845 sysinfo->totalram = process->system->memSize();
846 sysinfo->mem_unit = 1;
847
848 sysinfo.copyOut(tc->getMemProxy());
849
850 return 0;
851}
852
853/// Target chmod() handler.
854template <class OS>
855SyscallReturn
856chmodFunc(SyscallDesc *desc, int callnum, Process *process,
857 ThreadContext *tc)
858{
859 std::string path;
860
861 int index = 0;
862 if (!tc->getMemProxy().tryReadString(path,
863 process->getSyscallArg(tc, index))) {
864 return -EFAULT;
865 }
866
867 uint32_t mode = process->getSyscallArg(tc, index);
868 mode_t hostMode = 0;
869
870 // XXX translate mode flags via OS::something???
871 hostMode = mode;
872
873 // Adjust path for current working directory
874 path = process->fullPath(path);
875
876 // do the chmod
877 int result = chmod(path.c_str(), hostMode);
878 if (result < 0)
879 return -errno;
880
881 return 0;
882}
883
884
885/// Target fchmod() handler.
886template <class OS>
887SyscallReturn
888fchmodFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
889{
890 int index = 0;
891 int tgt_fd = p->getSyscallArg(tc, index);
892 uint32_t mode = p->getSyscallArg(tc, index);
893
894 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
895 if (!ffdp)
896 return -EBADF;
897 int sim_fd = ffdp->getSimFD();
898
899 mode_t hostMode = mode;
900
901 int result = fchmod(sim_fd, hostMode);
902
903 return (result < 0) ? -errno : 0;
904}
905
906/// Target mremap() handler.
907template <class OS>
908SyscallReturn
909mremapFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
910{
911 int index = 0;
912 Addr start = process->getSyscallArg(tc, index);
913 uint64_t old_length = process->getSyscallArg(tc, index);
914 uint64_t new_length = process->getSyscallArg(tc, index);
915 uint64_t flags = process->getSyscallArg(tc, index);
916 uint64_t provided_address = 0;
917 bool use_provided_address = flags & OS::TGT_MREMAP_FIXED;
918
919 if (use_provided_address)
920 provided_address = process->getSyscallArg(tc, index);
921
922 if ((start % TheISA::PageBytes != 0) ||
923 (provided_address % TheISA::PageBytes != 0)) {
924 warn("mremap failing: arguments not page aligned");
925 return -EINVAL;
926 }
927
928 new_length = roundUp(new_length, TheISA::PageBytes);
929
930 if (new_length > old_length) {
931 std::shared_ptr<MemState> mem_state = process->memState;
932 Addr mmap_end = mem_state->getMmapEnd();
933
934 if ((start + old_length) == mmap_end &&
935 (!use_provided_address || provided_address == start)) {
936 // This case cannot occur when growing downward, as
937 // start is greater than or equal to mmap_end.
938 uint64_t diff = new_length - old_length;
939 process->allocateMem(mmap_end, diff);
940 mem_state->setMmapEnd(mmap_end + diff);
941 return start;
942 } else {
943 if (!use_provided_address && !(flags & OS::TGT_MREMAP_MAYMOVE)) {
944 warn("can't remap here and MREMAP_MAYMOVE flag not set\n");
945 return -ENOMEM;
946 } else {
947 uint64_t new_start = provided_address;
948 if (!use_provided_address) {
949 new_start = process->mmapGrowsDown() ?
950 mmap_end - new_length : mmap_end;
951 mmap_end = process->mmapGrowsDown() ?
952 new_start : mmap_end + new_length;
953 mem_state->setMmapEnd(mmap_end);
954 }
955
956 process->pTable->remap(start, old_length, new_start);
957 warn("mremapping to new vaddr %08p-%08p, adding %d\n",
958 new_start, new_start + new_length,
959 new_length - old_length);
960 // add on the remaining unallocated pages
961 process->allocateMem(new_start + old_length,
962 new_length - old_length,
963 use_provided_address /* clobber */);
964 if (use_provided_address &&
965 ((new_start + new_length > mem_state->getMmapEnd() &&
966 !process->mmapGrowsDown()) ||
967 (new_start < mem_state->getMmapEnd() &&
968 process->mmapGrowsDown()))) {
969 // something fishy going on here, at least notify the user
970 // @todo: increase mmap_end?
971 warn("mmap region limit exceeded with MREMAP_FIXED\n");
972 }
973 warn("returning %08p as start\n", new_start);
974 return new_start;
975 }
976 }
977 } else {
978 if (use_provided_address && provided_address != start)
979 process->pTable->remap(start, new_length, provided_address);
980 process->pTable->unmap(start + new_length, old_length - new_length);
981 return use_provided_address ? provided_address : start;
982 }
983}
984
985/// Target stat() handler.
986template <class OS>
987SyscallReturn
988statFunc(SyscallDesc *desc, int callnum, Process *process,
989 ThreadContext *tc)
990{
991 std::string path;
992
993 int index = 0;
994 if (!tc->getMemProxy().tryReadString(path,
995 process->getSyscallArg(tc, index))) {
996 return -EFAULT;
997 }
998 Addr bufPtr = process->getSyscallArg(tc, index);
999
1000 // Adjust path for current working directory
1001 path = process->fullPath(path);
1002
1003 struct stat hostBuf;
1004 int result = stat(path.c_str(), &hostBuf);
1005
1006 if (result < 0)
1007 return -errno;
1008
1009 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1010
1011 return 0;
1012}
1013
1014
1015/// Target stat64() handler.
1016template <class OS>
1017SyscallReturn
1018stat64Func(SyscallDesc *desc, int callnum, Process *process,
1019 ThreadContext *tc)
1020{
1021 std::string path;
1022
1023 int index = 0;
1024 if (!tc->getMemProxy().tryReadString(path,
1025 process->getSyscallArg(tc, index)))
1026 return -EFAULT;
1027 Addr bufPtr = process->getSyscallArg(tc, index);
1028
1029 // Adjust path for current working directory
1030 path = process->fullPath(path);
1031
1032#if NO_STAT64
1033 struct stat hostBuf;
1034 int result = stat(path.c_str(), &hostBuf);
1035#else
1036 struct stat64 hostBuf;
1037 int result = stat64(path.c_str(), &hostBuf);
1038#endif
1039
1040 if (result < 0)
1041 return -errno;
1042
1043 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1044
1045 return 0;
1046}
1047
1048
1049/// Target fstatat64() handler.
1050template <class OS>
1051SyscallReturn
1052fstatat64Func(SyscallDesc *desc, int callnum, Process *process,
1053 ThreadContext *tc)
1054{
1055 int index = 0;
1056 int dirfd = process->getSyscallArg(tc, index);
1057 if (dirfd != OS::TGT_AT_FDCWD)
1058 warn("fstatat64: first argument not AT_FDCWD; unlikely to work");
1059
1060 std::string path;
1061 if (!tc->getMemProxy().tryReadString(path,
1062 process->getSyscallArg(tc, index)))
1063 return -EFAULT;
1064 Addr bufPtr = process->getSyscallArg(tc, index);
1065
1066 // Adjust path for current working directory
1067 path = process->fullPath(path);
1068
1069#if NO_STAT64
1070 struct stat hostBuf;
1071 int result = stat(path.c_str(), &hostBuf);
1072#else
1073 struct stat64 hostBuf;
1074 int result = stat64(path.c_str(), &hostBuf);
1075#endif
1076
1077 if (result < 0)
1078 return -errno;
1079
1080 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1081
1082 return 0;
1083}
1084
1085
1086/// Target fstat64() handler.
1087template <class OS>
1088SyscallReturn
1089fstat64Func(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1090{
1091 int index = 0;
1092 int tgt_fd = p->getSyscallArg(tc, index);
1093 Addr bufPtr = p->getSyscallArg(tc, index);
1094
1095 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1096 if (!ffdp)
1097 return -EBADF;
1098 int sim_fd = ffdp->getSimFD();
1099
1100#if NO_STAT64
1101 struct stat hostBuf;
1102 int result = fstat(sim_fd, &hostBuf);
1103#else
1104 struct stat64 hostBuf;
1105 int result = fstat64(sim_fd, &hostBuf);
1106#endif
1107
1108 if (result < 0)
1109 return -errno;
1110
1111 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1112
1113 return 0;
1114}
1115
1116
1117/// Target lstat() handler.
1118template <class OS>
1119SyscallReturn
1120lstatFunc(SyscallDesc *desc, int callnum, Process *process,
1121 ThreadContext *tc)
1122{
1123 std::string path;
1124
1125 int index = 0;
1126 if (!tc->getMemProxy().tryReadString(path,
1127 process->getSyscallArg(tc, index))) {
1128 return -EFAULT;
1129 }
1130 Addr bufPtr = process->getSyscallArg(tc, index);
1131
1132 // Adjust path for current working directory
1133 path = process->fullPath(path);
1134
1135 struct stat hostBuf;
1136 int result = lstat(path.c_str(), &hostBuf);
1137
1138 if (result < 0)
1139 return -errno;
1140
1141 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1142
1143 return 0;
1144}
1145
1146/// Target lstat64() handler.
1147template <class OS>
1148SyscallReturn
1149lstat64Func(SyscallDesc *desc, int callnum, Process *process,
1150 ThreadContext *tc)
1151{
1152 std::string path;
1153
1154 int index = 0;
1155 if (!tc->getMemProxy().tryReadString(path,
1156 process->getSyscallArg(tc, index))) {
1157 return -EFAULT;
1158 }
1159 Addr bufPtr = process->getSyscallArg(tc, index);
1160
1161 // Adjust path for current working directory
1162 path = process->fullPath(path);
1163
1164#if NO_STAT64
1165 struct stat hostBuf;
1166 int result = lstat(path.c_str(), &hostBuf);
1167#else
1168 struct stat64 hostBuf;
1169 int result = lstat64(path.c_str(), &hostBuf);
1170#endif
1171
1172 if (result < 0)
1173 return -errno;
1174
1175 copyOutStat64Buf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1176
1177 return 0;
1178}
1179
1180/// Target fstat() handler.
1181template <class OS>
1182SyscallReturn
1183fstatFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1184{
1185 int index = 0;
1186 int tgt_fd = p->getSyscallArg(tc, index);
1187 Addr bufPtr = p->getSyscallArg(tc, index);
1188
1189 DPRINTF_SYSCALL(Verbose, "fstat(%d, ...)\n", tgt_fd);
1190
1191 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1192 if (!ffdp)
1193 return -EBADF;
1194 int sim_fd = ffdp->getSimFD();
1195
1196 struct stat hostBuf;
1197 int result = fstat(sim_fd, &hostBuf);
1198
1199 if (result < 0)
1200 return -errno;
1201
1202 copyOutStatBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf, (sim_fd == 1));
1203
1204 return 0;
1205}
1206
1207
1208/// Target statfs() handler.
1209template <class OS>
1210SyscallReturn
1211statfsFunc(SyscallDesc *desc, int callnum, Process *process,
1212 ThreadContext *tc)
1213{
1214#if NO_STATFS
1215 warn("Host OS cannot support calls to statfs. Ignoring syscall");
1216#else
1217 std::string path;
1218
1219 int index = 0;
1220 if (!tc->getMemProxy().tryReadString(path,
1221 process->getSyscallArg(tc, index))) {
1222 return -EFAULT;
1223 }
1224 Addr bufPtr = process->getSyscallArg(tc, index);
1225
1226 // Adjust path for current working directory
1227 path = process->fullPath(path);
1228
1229 struct statfs hostBuf;
1230 int result = statfs(path.c_str(), &hostBuf);
1231
1232 if (result < 0)
1233 return -errno;
1234
1235 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1236#endif
1237 return 0;
1238}
1239
1240template <class OS>
1241SyscallReturn
1242cloneFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1243{
1244 int index = 0;
1245
1246 TheISA::IntReg flags = p->getSyscallArg(tc, index);
1247 TheISA::IntReg newStack = p->getSyscallArg(tc, index);
1248 Addr ptidPtr = p->getSyscallArg(tc, index);
1249
1250#if THE_ISA == RISCV_ISA
1251 /**
1252 * Linux kernel 4.15 sets CLONE_BACKWARDS flag for RISC-V.
1253 * The flag defines the list of clone() arguments in the following
1254 * order: flags -> newStack -> ptidPtr -> tlsPtr -> ctidPtr
1255 */
1256 Addr tlsPtr M5_VAR_USED = p->getSyscallArg(tc, index);
1257 Addr ctidPtr = p->getSyscallArg(tc, index);
1258#else
1259 Addr ctidPtr = p->getSyscallArg(tc, index);
1260 Addr tlsPtr M5_VAR_USED = p->getSyscallArg(tc, index);
1261#endif
1262
1263 if (((flags & OS::TGT_CLONE_SIGHAND)&& !(flags & OS::TGT_CLONE_VM)) ||
1264 ((flags & OS::TGT_CLONE_THREAD) && !(flags & OS::TGT_CLONE_SIGHAND)) ||
1265 ((flags & OS::TGT_CLONE_FS) && (flags & OS::TGT_CLONE_NEWNS)) ||
1266 ((flags & OS::TGT_CLONE_NEWIPC) && (flags & OS::TGT_CLONE_SYSVSEM)) ||
1267 ((flags & OS::TGT_CLONE_NEWPID) && (flags & OS::TGT_CLONE_THREAD)) ||
1268 ((flags & OS::TGT_CLONE_VM) && !(newStack)))
1269 return -EINVAL;
1270
1271 ThreadContext *ctc;
1272 if (!(ctc = p->findFreeContext()))
1273 fatal("clone: no spare thread context in system");
1274
1275 /**
1276 * Note that ProcessParams is generated by swig and there are no other
1277 * examples of how to create anything but this default constructor. The
1278 * fields are manually initialized instead of passing parameters to the
1279 * constructor.
1280 */
1281 ProcessParams *pp = new ProcessParams();
1282 pp->executable.assign(*(new std::string(p->progName())));
1283 pp->cmd.push_back(*(new std::string(p->progName())));
1284 pp->system = p->system;
1285 pp->cwd.assign(p->getcwd());
1286 pp->input.assign("stdin");
1287 pp->output.assign("stdout");
1288 pp->errout.assign("stderr");
1289 pp->uid = p->uid();
1290 pp->euid = p->euid();
1291 pp->gid = p->gid();
1292 pp->egid = p->egid();
1293
1294 /* Find the first free PID that's less than the maximum */
1295 std::set<int> const& pids = p->system->PIDs;
1296 int temp_pid = *pids.begin();
1297 do {
1298 temp_pid++;
1299 } while (pids.find(temp_pid) != pids.end());
1300 if (temp_pid >= System::maxPID)
1301 fatal("temp_pid is too large: %d", temp_pid);
1302
1303 pp->pid = temp_pid;
1304 pp->ppid = (flags & OS::TGT_CLONE_THREAD) ? p->ppid() : p->pid();
1305 Process *cp = pp->create();
1306 delete pp;
1307
1308 Process *owner = ctc->getProcessPtr();
1309 ctc->setProcessPtr(cp);
1310 cp->assignThreadContext(ctc->contextId());
1311 owner->revokeThreadContext(ctc->contextId());
1312
1313 if (flags & OS::TGT_CLONE_PARENT_SETTID) {
1314 BufferArg ptidBuf(ptidPtr, sizeof(long));
1315 long *ptid = (long *)ptidBuf.bufferPtr();
1316 *ptid = cp->pid();
1317 ptidBuf.copyOut(tc->getMemProxy());
1318 }
1319
1320 cp->initState();
1321 p->clone(tc, ctc, cp, flags);
1322
1323 if (flags & OS::TGT_CLONE_THREAD) {
1324 delete cp->sigchld;
1325 cp->sigchld = p->sigchld;
1326 } else if (flags & OS::TGT_SIGCHLD) {
1327 *cp->sigchld = true;
1328 }
1329
1330 if (flags & OS::TGT_CLONE_CHILD_SETTID) {
1331 BufferArg ctidBuf(ctidPtr, sizeof(long));
1332 long *ctid = (long *)ctidBuf.bufferPtr();
1333 *ctid = cp->pid();
1334 ctidBuf.copyOut(ctc->getMemProxy());
1335 }
1336
1337 if (flags & OS::TGT_CLONE_CHILD_CLEARTID)
1338 cp->childClearTID = (uint64_t)ctidPtr;
1339
1340 ctc->clearArchRegs();
1341
1342#if THE_ISA == ALPHA_ISA
1343 TheISA::copyMiscRegs(tc, ctc);
1344#elif THE_ISA == SPARC_ISA
1345 TheISA::copyRegs(tc, ctc);
1346 ctc->setIntReg(TheISA::NumIntArchRegs + 6, 0);
1347 ctc->setIntReg(TheISA::NumIntArchRegs + 4, 0);
1348 ctc->setIntReg(TheISA::NumIntArchRegs + 3, TheISA::NWindows - 2);
1349 ctc->setIntReg(TheISA::NumIntArchRegs + 5, TheISA::NWindows);
1350 ctc->setMiscReg(TheISA::MISCREG_CWP, 0);
1351 ctc->setIntReg(TheISA::NumIntArchRegs + 7, 0);
1352 ctc->setMiscRegNoEffect(TheISA::MISCREG_TL, 0);
1353 ctc->setMiscReg(TheISA::MISCREG_ASI, TheISA::ASI_PRIMARY);
1354 for (int y = 8; y < 32; y++)
1355 ctc->setIntReg(y, tc->readIntReg(y));
1356#elif THE_ISA == ARM_ISA or THE_ISA == X86_ISA or THE_ISA == RISCV_ISA
1357 TheISA::copyRegs(tc, ctc);
1358#endif
1359
1360#if THE_ISA == X86_ISA
1361 if (flags & OS::TGT_CLONE_SETTLS) {
1362 ctc->setMiscRegNoEffect(TheISA::MISCREG_FS_BASE, tlsPtr);
1363 ctc->setMiscRegNoEffect(TheISA::MISCREG_FS_EFF_BASE, tlsPtr);
1364 }
1365#endif
1366
1367 if (newStack)
1368 ctc->setIntReg(TheISA::StackPointerReg, newStack);
1369
1370 cp->setSyscallReturn(ctc, 0);
1371
1372#if THE_ISA == ALPHA_ISA
1373 ctc->setIntReg(TheISA::SyscallSuccessReg, 0);
1374#elif THE_ISA == SPARC_ISA
1375 tc->setIntReg(TheISA::SyscallPseudoReturnReg, 0);
1376 ctc->setIntReg(TheISA::SyscallPseudoReturnReg, 1);
1377#endif
1378
1379 ctc->pcState(tc->nextInstAddr());
1380 ctc->activate();
1381
1382 return cp->pid();
1383}
1384
1385/// Target fstatfs() handler.
1386template <class OS>
1387SyscallReturn
1388fstatfsFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1389{
1390 int index = 0;
1391 int tgt_fd = p->getSyscallArg(tc, index);
1392 Addr bufPtr = p->getSyscallArg(tc, index);
1393
1394 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1395 if (!ffdp)
1396 return -EBADF;
1397 int sim_fd = ffdp->getSimFD();
1398
1399 struct statfs hostBuf;
1400 int result = fstatfs(sim_fd, &hostBuf);
1401
1402 if (result < 0)
1403 return -errno;
1404
1405 copyOutStatfsBuf<OS>(tc->getMemProxy(), bufPtr, &hostBuf);
1406
1407 return 0;
1408}
1409
1410
1411/// Target writev() handler.
1412template <class OS>
1413SyscallReturn
1414writevFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1415{
1416 int index = 0;
1417 int tgt_fd = p->getSyscallArg(tc, index);
1418
1419 auto hbfdp = std::dynamic_pointer_cast<HBFDEntry>((*p->fds)[tgt_fd]);
1420 if (!hbfdp)
1421 return -EBADF;
1422 int sim_fd = hbfdp->getSimFD();
1423
1424 SETranslatingPortProxy &prox = tc->getMemProxy();
1425 uint64_t tiov_base = p->getSyscallArg(tc, index);
1426 size_t count = p->getSyscallArg(tc, index);
1427 struct iovec hiov[count];
1428 for (size_t i = 0; i < count; ++i) {
1429 typename OS::tgt_iovec tiov;
1430
1431 prox.readBlob(tiov_base + i*sizeof(typename OS::tgt_iovec),
1432 (uint8_t*)&tiov, sizeof(typename OS::tgt_iovec));
1433 hiov[i].iov_len = TheISA::gtoh(tiov.iov_len);
1434 hiov[i].iov_base = new char [hiov[i].iov_len];
1435 prox.readBlob(TheISA::gtoh(tiov.iov_base), (uint8_t *)hiov[i].iov_base,
1436 hiov[i].iov_len);
1437 }
1438
1439 int result = writev(sim_fd, hiov, count);
1440
1441 for (size_t i = 0; i < count; ++i)
1442 delete [] (char *)hiov[i].iov_base;
1443
1444 if (result < 0)
1445 return -errno;
1446
1447 return result;
1448}
1449
1450/// Real mmap handler.
1451template <class OS>
1452SyscallReturn
1453mmapImpl(SyscallDesc *desc, int num, Process *p, ThreadContext *tc,
1454 bool is_mmap2)
1455{
1456 int index = 0;
1457 Addr start = p->getSyscallArg(tc, index);
1458 uint64_t length = p->getSyscallArg(tc, index);
1459 int prot = p->getSyscallArg(tc, index);
1460 int tgt_flags = p->getSyscallArg(tc, index);
1461 int tgt_fd = p->getSyscallArg(tc, index);
1462 int offset = p->getSyscallArg(tc, index);
1463
1464 if (is_mmap2)
1465 offset *= TheISA::PageBytes;
1466
1467 if (start & (TheISA::PageBytes - 1) ||
1468 offset & (TheISA::PageBytes - 1) ||
1469 (tgt_flags & OS::TGT_MAP_PRIVATE &&
1470 tgt_flags & OS::TGT_MAP_SHARED) ||
1471 (!(tgt_flags & OS::TGT_MAP_PRIVATE) &&
1472 !(tgt_flags & OS::TGT_MAP_SHARED)) ||
1473 !length) {
1474 return -EINVAL;
1475 }
1476
1477 if ((prot & PROT_WRITE) && (tgt_flags & OS::TGT_MAP_SHARED)) {
1478 // With shared mmaps, there are two cases to consider:
1479 // 1) anonymous: writes should modify the mapping and this should be
1480 // visible to observers who share the mapping. Currently, it's
1481 // difficult to update the shared mapping because there's no
1482 // structure which maintains information about the which virtual
1483 // memory areas are shared. If that structure existed, it would be
1484 // possible to make the translations point to the same frames.
1485 // 2) file-backed: writes should modify the mapping and the file
1486 // which is backed by the mapping. The shared mapping problem is the
1487 // same as what was mentioned about the anonymous mappings. For
1488 // file-backed mappings, the writes to the file are difficult
1489 // because it requires syncing what the mapping holds with the file
1490 // that resides on the host system. So, any write on a real system
1491 // would cause the change to be propagated to the file mapping at
1492 // some point in the future (the inode is tracked along with the
1493 // mapping). This isn't guaranteed to always happen, but it usually
1494 // works well enough. The guarantee is provided by the msync system
1495 // call. We could force the change through with shared mappings with
1496 // a call to msync, but that again would require more information
1497 // than we currently maintain.
1498 warn("mmap: writing to shared mmap region is currently "
1499 "unsupported. The write succeeds on the target, but it "
1500 "will not be propagated to the host or shared mappings");
1501 }
1502
1503 length = roundUp(length, TheISA::PageBytes);
1504
1505 int sim_fd = -1;
1506 uint8_t *pmap = nullptr;
1507 if (!(tgt_flags & OS::TGT_MAP_ANONYMOUS)) {
1508 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1509
1510 auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>(fdep);
1511 if (dfdp) {
1512 EmulatedDriver *emul_driver = dfdp->getDriver();
1513 return emul_driver->mmap(p, tc, start, length, prot,
1514 tgt_flags, tgt_fd, offset);
1515 }
1516
1517 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1518 if (!ffdp)
1519 return -EBADF;
1520 sim_fd = ffdp->getSimFD();
1521
1522 pmap = (decltype(pmap))mmap(nullptr, length, PROT_READ, MAP_PRIVATE,
1523 sim_fd, offset);
1524
1525 if (pmap == (decltype(pmap))-1) {
1526 warn("mmap: failed to map file into host address space");
1527 return -errno;
1528 }
1529 }
1530
1531 // Extend global mmap region if necessary. Note that we ignore the
1532 // start address unless MAP_FIXED is specified.
1533 if (!(tgt_flags & OS::TGT_MAP_FIXED)) {
1534 std::shared_ptr<MemState> mem_state = p->memState;
1535 Addr mmap_end = mem_state->getMmapEnd();
1536
1537 start = p->mmapGrowsDown() ? mmap_end - length : mmap_end;
1538 mmap_end = p->mmapGrowsDown() ? start : mmap_end + length;
1539
1540 mem_state->setMmapEnd(mmap_end);
1541 }
1542
1543 DPRINTF_SYSCALL(Verbose, " mmap range is 0x%x - 0x%x\n",
1544 start, start + length - 1);
1545
1546 // We only allow mappings to overwrite existing mappings if
1547 // TGT_MAP_FIXED is set. Otherwise it shouldn't be a problem
1548 // because we ignore the start hint if TGT_MAP_FIXED is not set.
1549 int clobber = tgt_flags & OS::TGT_MAP_FIXED;
1550 if (clobber) {
1551 for (auto tc : p->system->threadContexts) {
1552 // If we might be overwriting old mappings, we need to
1553 // invalidate potentially stale mappings out of the TLBs.
1554 tc->getDTBPtr()->flushAll();
1555 tc->getITBPtr()->flushAll();
1556 }
1557 }
1558
1559 // Allocate physical memory and map it in. If the page table is already
1560 // mapped and clobber is not set, the simulator will issue throw a
1561 // fatal and bail out of the simulation.
1562 p->allocateMem(start, length, clobber);
1563
1564 // Transfer content into target address space.
1565 SETranslatingPortProxy &tp = tc->getMemProxy();
1566 if (tgt_flags & OS::TGT_MAP_ANONYMOUS) {
1567 // In general, we should zero the mapped area for anonymous mappings,
1568 // with something like:
1569 // tp.memsetBlob(start, 0, length);
1570 // However, given that we don't support sparse mappings, and
1571 // some applications can map a couple of gigabytes of space
1572 // (intending sparse usage), that can get painfully expensive.
1573 // Fortunately, since we don't properly implement munmap either,
1574 // there's no danger of remapping used memory, so for now all
1575 // newly mapped memory should already be zeroed so we can skip it.
1576 } else {
1577 // It is possible to mmap an area larger than a file, however
1578 // accessing unmapped portions the system triggers a "Bus error"
1579 // on the host. We must know when to stop copying the file from
1580 // the host into the target address space.
1581 struct stat file_stat;
1582 if (fstat(sim_fd, &file_stat) > 0)
1583 fatal("mmap: cannot stat file");
1584
1585 // Copy the portion of the file that is resident. This requires
1586 // checking both the mmap size and the filesize that we are
1587 // trying to mmap into this space; the mmap size also depends
1588 // on the specified offset into the file.
1589 uint64_t size = std::min((uint64_t)file_stat.st_size - offset,
1590 length);
1591 tp.writeBlob(start, pmap, size);
1592
1593 // Cleanup the mmap region before exiting this function.
1594 munmap(pmap, length);
1595
1596 // Maintain the symbol table for dynamic executables.
1597 // The loader will call mmap to map the images into its address
1598 // space and we intercept that here. We can verify that we are
1599 // executing inside the loader by checking the program counter value.
1600 // XXX: with multiprogrammed workloads or multi-node configurations,
1601 // this will not work since there is a single global symbol table.
1602 ObjectFile *interpreter = p->getInterpreter();
1603 if (interpreter) {
1604 Addr text_start = interpreter->textBase();
1605 Addr text_end = text_start + interpreter->textSize();
1606
1607 Addr pc = tc->pcState().pc();
1608
1609 if (pc >= text_start && pc < text_end) {
1610 std::shared_ptr<FDEntry> fdep = (*p->fds)[tgt_fd];
1611 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
1612 ObjectFile *lib = createObjectFile(ffdp->getFileName());
1613
1614 if (lib) {
1615 lib->loadAllSymbols(debugSymbolTable,
1616 lib->textBase(), start);
1617 }
1618 }
1619 }
1620
1621 // Note that we do not zero out the remainder of the mapping. This
1622 // is done by a real system, but it probably will not affect
1623 // execution (hopefully).
1624 }
1625
1626 return start;
1627}
1628
1629template <class OS>
1630SyscallReturn
1631pwrite64Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1632{
1633 int index = 0;
1634 int tgt_fd = p->getSyscallArg(tc, index);
1635 Addr bufPtr = p->getSyscallArg(tc, index);
1636 int nbytes = p->getSyscallArg(tc, index);
1637 int offset = p->getSyscallArg(tc, index);
1638
1639 auto ffdp = std::dynamic_pointer_cast<FileFDEntry>((*p->fds)[tgt_fd]);
1640 if (!ffdp)
1641 return -EBADF;
1642 int sim_fd = ffdp->getSimFD();
1643
1644 BufferArg bufArg(bufPtr, nbytes);
1645 bufArg.copyIn(tc->getMemProxy());
1646
1647 int bytes_written = pwrite(sim_fd, bufArg.bufferPtr(), nbytes, offset);
1648
1649 return (bytes_written == -1) ? -errno : bytes_written;
1650}
1651
1652/// Target mmap() handler.
1653template <class OS>
1654SyscallReturn
1655mmapFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1656{
1657 return mmapImpl<OS>(desc, num, p, tc, false);
1658}
1659
1660/// Target mmap2() handler.
1661template <class OS>
1662SyscallReturn
1663mmap2Func(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1664{
1665 return mmapImpl<OS>(desc, num, p, tc, true);
1666}
1667
1668/// Target getrlimit() handler.
1669template <class OS>
1670SyscallReturn
1671getrlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1672 ThreadContext *tc)
1673{
1674 int index = 0;
1675 unsigned resource = process->getSyscallArg(tc, index);
1676 TypedBufferArg<typename OS::rlimit> rlp(process->getSyscallArg(tc, index));
1677
1678 switch (resource) {
1679 case OS::TGT_RLIMIT_STACK:
1680 // max stack size in bytes: make up a number (8MB for now)
1681 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1682 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1683 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1684 break;
1685
1686 case OS::TGT_RLIMIT_DATA:
1687 // max data segment size in bytes: make up a number
1688 rlp->rlim_cur = rlp->rlim_max = 256 * 1024 * 1024;
1689 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1690 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1691 break;
1692
1693 default:
1694 warn("getrlimit: unimplemented resource %d", resource);
1695 return -EINVAL;
1696 break;
1697 }
1698
1699 rlp.copyOut(tc->getMemProxy());
1700 return 0;
1701}
1702
1703template <class OS>
1704SyscallReturn
1705prlimitFunc(SyscallDesc *desc, int callnum, Process *process,
1706 ThreadContext *tc)
1707{
1708 int index = 0;
1709 if (process->getSyscallArg(tc, index) != 0)
1710 {
1711 warn("prlimit: ignoring rlimits for nonzero pid");
1712 return -EPERM;
1713 }
1714 int resource = process->getSyscallArg(tc, index);
1715 Addr n = process->getSyscallArg(tc, index);
1716 if (n != 0)
1717 warn("prlimit: ignoring new rlimit");
1718 Addr o = process->getSyscallArg(tc, index);
1719 if (o != 0)
1720 {
1721 TypedBufferArg<typename OS::rlimit> rlp(o);
1722 switch (resource) {
1723 case OS::TGT_RLIMIT_STACK:
1724 // max stack size in bytes: make up a number (8MB for now)
1725 rlp->rlim_cur = rlp->rlim_max = 8 * 1024 * 1024;
1726 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1727 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1728 break;
1729 case OS::TGT_RLIMIT_DATA:
1730 // max data segment size in bytes: make up a number
1731 rlp->rlim_cur = rlp->rlim_max = 256*1024*1024;
1732 rlp->rlim_cur = TheISA::htog(rlp->rlim_cur);
1733 rlp->rlim_max = TheISA::htog(rlp->rlim_max);
1734 default:
1735 warn("prlimit: unimplemented resource %d", resource);
1736 return -EINVAL;
1737 break;
1738 }
1739 rlp.copyOut(tc->getMemProxy());
1740 }
1741 return 0;
1742}
1743
1744/// Target clock_gettime() function.
1745template <class OS>
1746SyscallReturn
1747clock_gettimeFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1748{
1749 int index = 1;
1750 //int clk_id = p->getSyscallArg(tc, index);
1751 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1752
1753 getElapsedTimeNano(tp->tv_sec, tp->tv_nsec);
1754 tp->tv_sec += seconds_since_epoch;
1755 tp->tv_sec = TheISA::htog(tp->tv_sec);
1756 tp->tv_nsec = TheISA::htog(tp->tv_nsec);
1757
1758 tp.copyOut(tc->getMemProxy());
1759
1760 return 0;
1761}
1762
1763/// Target clock_getres() function.
1764template <class OS>
1765SyscallReturn
1766clock_getresFunc(SyscallDesc *desc, int num, Process *p, ThreadContext *tc)
1767{
1768 int index = 1;
1769 TypedBufferArg<typename OS::timespec> tp(p->getSyscallArg(tc, index));
1770
1771 // Set resolution at ns, which is what clock_gettime() returns
1772 tp->tv_sec = 0;
1773 tp->tv_nsec = 1;
1774
1775 tp.copyOut(tc->getMemProxy());
1776
1777 return 0;
1778}
1779
1780/// Target gettimeofday() handler.
1781template <class OS>
1782SyscallReturn
1783gettimeofdayFunc(SyscallDesc *desc, int callnum, Process *process,
1784 ThreadContext *tc)
1785{
1786 int index = 0;
1787 TypedBufferArg<typename OS::timeval> tp(process->getSyscallArg(tc, index));
1788
1789 getElapsedTimeMicro(tp->tv_sec, tp->tv_usec);
1790 tp->tv_sec += seconds_since_epoch;
1791 tp->tv_sec = TheISA::htog(tp->tv_sec);
1792 tp->tv_usec = TheISA::htog(tp->tv_usec);
1793
1794 tp.copyOut(tc->getMemProxy());
1795
1796 return 0;
1797}
1798
1799
1800/// Target utimes() handler.
1801template <class OS>
1802SyscallReturn
1803utimesFunc(SyscallDesc *desc, int callnum, Process *process,
1804 ThreadContext *tc)
1805{
1806 std::string path;
1807
1808 int index = 0;
1809 if (!tc->getMemProxy().tryReadString(path,
1810 process->getSyscallArg(tc, index))) {
1811 return -EFAULT;
1812 }
1813
1814 TypedBufferArg<typename OS::timeval [2]>
1815 tp(process->getSyscallArg(tc, index));
1816 tp.copyIn(tc->getMemProxy());
1817
1818 struct timeval hostTimeval[2];
1819 for (int i = 0; i < 2; ++i) {
1820 hostTimeval[i].tv_sec = TheISA::gtoh((*tp)[i].tv_sec);
1821 hostTimeval[i].tv_usec = TheISA::gtoh((*tp)[i].tv_usec);
1822 }
1823
1824 // Adjust path for current working directory
1825 path = process->fullPath(path);
1826
1827 int result = utimes(path.c_str(), hostTimeval);
1828
1829 if (result < 0)
1830 return -errno;
1831
1832 return 0;
1833}
1834
1835template <class OS>
1836SyscallReturn
1837execveFunc(SyscallDesc *desc, int callnum, Process *p, ThreadContext *tc)
1838{
1839 desc->setFlags(0);
1840
1841 int index = 0;
1842 std::string path;
1843 SETranslatingPortProxy & mem_proxy = tc->getMemProxy();
1844 if (!mem_proxy.tryReadString(path, p->getSyscallArg(tc, index)))
1845 return -EFAULT;
1846
1847 if (access(path.c_str(), F_OK) == -1)
1848 return -EACCES;
1849
1850 auto read_in = [](std::vector<std::string> & vect,
1851 SETranslatingPortProxy & mem_proxy,
1852 Addr mem_loc)
1853 {
1854 for (int inc = 0; ; inc++) {
1855 BufferArg b((mem_loc + sizeof(Addr) * inc), sizeof(Addr));
1856 b.copyIn(mem_proxy);
1857
1858 if (!*(Addr*)b.bufferPtr())
1859 break;
1860
1861 vect.push_back(std::string());
1862 mem_proxy.tryReadString(vect[inc], *(Addr*)b.bufferPtr());
1863 }
1864 };
1865
1866 /**
1867 * Note that ProcessParams is generated by swig and there are no other
1868 * examples of how to create anything but this default constructor. The
1869 * fields are manually initialized instead of passing parameters to the
1870 * constructor.
1871 */
1872 ProcessParams *pp = new ProcessParams();
1873 pp->executable = path;
1874 Addr argv_mem_loc = p->getSyscallArg(tc, index);
1875 read_in(pp->cmd, mem_proxy, argv_mem_loc);
1876 Addr envp_mem_loc = p->getSyscallArg(tc, index);
1877 read_in(pp->env, mem_proxy, envp_mem_loc);
1878 pp->uid = p->uid();
1879 pp->egid = p->egid();
1880 pp->euid = p->euid();
1881 pp->gid = p->gid();
1882 pp->ppid = p->ppid();
1883 pp->pid = p->pid();
1884 pp->input.assign("cin");
1885 pp->output.assign("cout");
1886 pp->errout.assign("cerr");
1887 pp->cwd.assign(p->getcwd());
1888 pp->system = p->system;
1889 /**
1890 * Prevent process object creation with identical PIDs (which will trip
1891 * a fatal check in Process constructor). The execve call is supposed to
1892 * take over the currently executing process' identity but replace
1893 * whatever it is doing with a new process image. Instead of hijacking
1894 * the process object in the simulator, we create a new process object
1895 * and bind to the previous process' thread below (hijacking the thread).
1896 */
1897 p->system->PIDs.erase(p->pid());
1898 Process *new_p = pp->create();
1899 delete pp;
1900
1901 /**
1902 * Work through the file descriptor array and close any files marked
1903 * close-on-exec.
1904 */
1905 new_p->fds = p->fds;
1906 for (int i = 0; i < new_p->fds->getSize(); i++) {
1907 std::shared_ptr<FDEntry> fdep = (*new_p->fds)[i];
1908 if (fdep && fdep->getCOE())
1909 new_p->fds->closeFDEntry(i);
1910 }
1911
1912 *new_p->sigchld = true;
1913
1914 delete p;
1915 tc->clearArchRegs();
1916 tc->setProcessPtr(new_p);
1917 new_p->assignThreadContext(tc->contextId());
1918 new_p->initState();
1919 tc->activate();
1920 TheISA::PCState pcState = tc->pcState();
1921 tc->setNPC(pcState.instAddr());
1922
1923 desc->setFlags(SyscallDesc::SuppressReturnValue);
1924 return 0;
1925}
1926
1927/// Target getrusage() function.
1928template <class OS>
1929SyscallReturn
1930getrusageFunc(SyscallDesc *desc, int callnum, Process *process,
1931 ThreadContext *tc)
1932{
1933 int index = 0;
1934 int who = process->getSyscallArg(tc, index); // THREAD, SELF, or CHILDREN
1935 TypedBufferArg<typename OS::rusage> rup(process->getSyscallArg(tc, index));
1936
1937 rup->ru_utime.tv_sec = 0;
1938 rup->ru_utime.tv_usec = 0;
1939 rup->ru_stime.tv_sec = 0;
1940 rup->ru_stime.tv_usec = 0;
1941 rup->ru_maxrss = 0;
1942 rup->ru_ixrss = 0;
1943 rup->ru_idrss = 0;
1944 rup->ru_isrss = 0;
1945 rup->ru_minflt = 0;
1946 rup->ru_majflt = 0;
1947 rup->ru_nswap = 0;
1948 rup->ru_inblock = 0;
1949 rup->ru_oublock = 0;
1950 rup->ru_msgsnd = 0;
1951 rup->ru_msgrcv = 0;
1952 rup->ru_nsignals = 0;
1953 rup->ru_nvcsw = 0;
1954 rup->ru_nivcsw = 0;
1955
1956 switch (who) {
1957 case OS::TGT_RUSAGE_SELF:
1958 getElapsedTimeMicro(rup->ru_utime.tv_sec, rup->ru_utime.tv_usec);
1959 rup->ru_utime.tv_sec = TheISA::htog(rup->ru_utime.tv_sec);
1960 rup->ru_utime.tv_usec = TheISA::htog(rup->ru_utime.tv_usec);
1961 break;
1962
1963 case OS::TGT_RUSAGE_CHILDREN:
1964 // do nothing. We have no child processes, so they take no time.
1965 break;
1966
1967 default:
1968 // don't really handle THREAD or CHILDREN, but just warn and
1969 // plow ahead
1970 warn("getrusage() only supports RUSAGE_SELF. Parameter %d ignored.",
1971 who);
1972 }
1973
1974 rup.copyOut(tc->getMemProxy());
1975
1976 return 0;
1977}
1978
1979/// Target times() function.
1980template <class OS>
1981SyscallReturn
1982timesFunc(SyscallDesc *desc, int callnum, Process *process,
1983 ThreadContext *tc)
1984{
1985 int index = 0;
1986 TypedBufferArg<typename OS::tms> bufp(process->getSyscallArg(tc, index));
1987
1988 // Fill in the time structure (in clocks)
1989 int64_t clocks = curTick() * OS::M5_SC_CLK_TCK / SimClock::Int::s;
1990 bufp->tms_utime = clocks;
1991 bufp->tms_stime = 0;
1992 bufp->tms_cutime = 0;
1993 bufp->tms_cstime = 0;
1994
1995 // Convert to host endianness
1996 bufp->tms_utime = TheISA::htog(bufp->tms_utime);
1997
1998 // Write back
1999 bufp.copyOut(tc->getMemProxy());
2000
2001 // Return clock ticks since system boot
2002 return clocks;
2003}
2004
2005/// Target time() function.
2006template <class OS>
2007SyscallReturn
2008timeFunc(SyscallDesc *desc, int callnum, Process *process, ThreadContext *tc)
2009{
2010 typename OS::time_t sec, usec;
2011 getElapsedTimeMicro(sec, usec);
2012 sec += seconds_since_epoch;
2013
2014 int index = 0;
2015 Addr taddr = (Addr)process->getSyscallArg(tc, index);
2016 if (taddr != 0) {
2017 typename OS::time_t t = sec;
2018 t = TheISA::htog(t);
2019 SETranslatingPortProxy &p = tc->getMemProxy();
2020 p.writeBlob(taddr, (uint8_t*)&t, (int)sizeof(typename OS::time_t));
2021 }
2022 return sec;
2023}
2024
2025template <class OS>
2026SyscallReturn
2027tgkillFunc(SyscallDesc *desc, int num, Process *process, ThreadContext *tc)
2028{
2029 int index = 0;
2030 int tgid = process->getSyscallArg(tc, index);
2031 int tid = process->getSyscallArg(tc, index);
2032 int sig = process->getSyscallArg(tc, index);
2033
2034 /**
2035 * This system call is intended to allow killing a specific thread
2036 * within an arbitrary thread group if sanctioned with permission checks.
2037 * It's usually true that threads share the termination signal as pointed
2038 * out by the pthread_kill man page and this seems to be the intended
2039 * usage. Due to this being an emulated environment, assume the following:
2040 * Threads are allowed to call tgkill because the EUID for all threads
2041 * should be the same. There is no signal handling mechanism for kernel
2042 * registration of signal handlers since signals are poorly supported in
2043 * emulation mode. Since signal handlers cannot be registered, all
2044 * threads within in a thread group must share the termination signal.
2045 * We never exhaust PIDs so there's no chance of finding the wrong one
2046 * due to PID rollover.
2047 */
2048
2049 System *sys = tc->getSystemPtr();
2050 Process *tgt_proc = nullptr;
2051 for (int i = 0; i < sys->numContexts(); i++) {
2052 Process *temp = sys->threadContexts[i]->getProcessPtr();
2053 if (temp->pid() == tid) {
2054 tgt_proc = temp;
2055 break;
2056 }
2057 }
2058
2059 if (sig != 0 || sig != OS::TGT_SIGABRT)
2060 return -EINVAL;
2061
2062 if (tgt_proc == nullptr)
2063 return -ESRCH;
2064
2065 if (tgid != -1 && tgt_proc->tgid() != tgid)
2066 return -ESRCH;
2067
2068 if (sig == OS::TGT_SIGABRT)
2069 exitGroupFunc(desc, 252, process, tc);
2070
2071 return 0;
2072}
2073
2074
2075#endif // __SIM_SYSCALL_EMUL_HH__