/
syscall_emul.hh
2724 lines (2301 loc) · 89.4 KB
/
syscall_emul.hh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2012-2013, 2015, 2019 ARM Limited
* Copyright (c) 2015 Advanced Micro Devices, Inc.
* All rights reserved
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2003-2005 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Authors: Steve Reinhardt
* Kevin Lim
*/
#ifndef __SIM_SYSCALL_EMUL_HH__
#define __SIM_SYSCALL_EMUL_HH__
#if (defined(__APPLE__) || defined(__OpenBSD__) || \
defined(__FreeBSD__) || defined(__CYGWIN__) || \
defined(__NetBSD__))
#define NO_STAT64 1
#else
#define NO_STAT64 0
#endif
///
/// @file syscall_emul.hh
///
/// This file defines objects used to emulate syscalls from the target
/// application on the host machine.
#if defined(__linux__)
#include <sys/eventfd.h>
#include <sys/statfs.h>
#else
#include <sys/mount.h>
#endif
#ifdef __CYGWIN32__
#include <sys/fcntl.h>
#endif
#include <fcntl.h>
#include <net/if.h>
#include <poll.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <unistd.h>
#include <cerrno>
#include <memory>
#include <string>
#include "arch/generic/tlb.hh"
#include "arch/utility.hh"
#include "base/intmath.hh"
#include "base/loader/object_file.hh"
#include "base/logging.hh"
#include "base/trace.hh"
#include "base/types.hh"
#include "config/the_isa.hh"
#include "cpu/base.hh"
#include "cpu/thread_context.hh"
#include "mem/page_table.hh"
#include "params/Process.hh"
#include "sim/emul_driver.hh"
#include "sim/futex_map.hh"
#include "sim/process.hh"
#include "sim/syscall_debug_macros.hh"
#include "sim/syscall_desc.hh"
#include "sim/syscall_emul_buf.hh"
#include "sim/syscall_return.hh"
#if defined(__APPLE__) && defined(__MACH__) && !defined(CMSG_ALIGN)
#define CMSG_ALIGN(len) (((len) + sizeof(size_t) - 1) & ~(sizeof(size_t) - 1))
#endif
//////////////////////////////////////////////////////////////////////
//
// The following emulation functions are generic enough that they
// don't need to be recompiled for different emulated OS's. They are
// defined in sim/syscall_emul.cc.
//
//////////////////////////////////////////////////////////////////////
void warnUnsupportedOS(std::string syscall_name);
/// Handler for unimplemented syscalls that we haven't thought about.
SyscallReturn unimplementedFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Handler for unimplemented syscalls that we never intend to
/// implement (signal handling, etc.) and should not affect the correct
/// behavior of the program. Prints a warning. Return success to the target
/// program.
SyscallReturn ignoreFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Like above, but only prints a warning once per syscall desc it's used with.
SyscallReturn
ignoreWarnOnceFunc(SyscallDesc *desc, int num, ThreadContext *tc);
// Target fallocateFunc() handler.
SyscallReturn fallocateFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, int mode, off_t offset, off_t len);
/// Target exit() handler: terminate current context.
SyscallReturn exitFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int status);
/// Target exit_group() handler: terminate simulation. (exit all threads)
SyscallReturn exitGroupFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int status);
/// Target set_tid_address() handler.
SyscallReturn setTidAddressFunc(SyscallDesc *desc, int num, ThreadContext *tc,
uint64_t tidPtr);
/// Target getpagesize() handler.
SyscallReturn getpagesizeFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target brk() handler: set brk address.
SyscallReturn brkFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr new_brk);
/// Target close() handler.
SyscallReturn closeFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd);
/// Target lseek() handler.
SyscallReturn lseekFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, uint64_t offs, int whence);
/// Target _llseek() handler.
SyscallReturn _llseekFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, uint64_t offset_high,
uint32_t offset_low, Addr result_ptr, int whence);
/// Target munmap() handler.
SyscallReturn munmapFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target shutdown() handler.
SyscallReturn shutdownFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, int how);
/// Target gethostname() handler.
SyscallReturn gethostnameFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr buf_ptr, int name_len);
/// Target getcwd() handler.
SyscallReturn getcwdFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr buf_ptr, unsigned long size);
/// Target readlink() handler.
SyscallReturn readlinkFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, Addr buf, size_t bufsiz);
/// Target unlink() handler.
SyscallReturn unlinkFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname);
/// Target link() handler
SyscallReturn linkFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, Addr new_pathname);
/// Target symlink() handler.
SyscallReturn symlinkFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, Addr new_pathname);
/// Target mkdir() handler.
SyscallReturn mkdirFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, mode_t mode);
/// Target mknod() handler.
SyscallReturn mknodFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, mode_t mode, dev_t dev);
/// Target chdir() handler.
SyscallReturn chdirFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname);
// Target rmdir() handler.
SyscallReturn rmdirFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname);
/// Target rename() handler.
SyscallReturn renameFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr oldpath, Addr newpath);
/// Target truncate() handler.
SyscallReturn truncateFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, off_t length);
/// Target ftruncate() handler.
SyscallReturn ftruncateFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, off_t length);
/// Target truncate64() handler.
SyscallReturn truncate64Func(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, int64_t length);
/// Target ftruncate64() handler.
SyscallReturn ftruncate64Func(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target umask() handler.
SyscallReturn umaskFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target gettid() handler.
SyscallReturn gettidFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target chown() handler.
SyscallReturn chownFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, uint32_t owner, uint32_t group);
/// Target getpgrpFunc() handler.
SyscallReturn getpgrpFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target setpgid() handler.
SyscallReturn setpgidFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int pid, int pgid);
/// Target fchown() handler.
SyscallReturn fchownFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, uint32_t owner, uint32_t group);
/// Target dup() handler.
SyscallReturn dupFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd);
/// Target dup2() handler.
SyscallReturn dup2Func(SyscallDesc *desc, int num, ThreadContext *tc,
int old_tgt_fd, int new_tgt_fd);
/// Target fcntl() handler.
SyscallReturn fcntlFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target fcntl64() handler.
SyscallReturn fcntl64Func(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target pipe() handler.
SyscallReturn pipeFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Internal pipe() handler.
SyscallReturn pipeImpl(SyscallDesc *desc, int num, ThreadContext *tc,
bool pseudo_pipe, bool is_pipe2=false);
/// Target pipe() handler.
SyscallReturn pipe2Func(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target getpid() handler.
SyscallReturn getpidFunc(SyscallDesc *desc, int num, ThreadContext *tc);
// Target getpeername() handler.
SyscallReturn getpeernameFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr sockAddrPtr, Addr addrlenPtr);
// Target bind() handler.
SyscallReturn bindFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr buf_ptr, int addrlen);
// Target listen() handler.
SyscallReturn listenFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, int backlog);
// Target connect() handler.
SyscallReturn connectFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr buf_ptr, int addrlen);
#if defined(SYS_getdents)
// Target getdents() handler.
SyscallReturn getdentsFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr buf_ptr, unsigned count);
#endif
#if defined(SYS_getdents64)
// Target getdents() handler.
SyscallReturn getdents64Func(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr buf_ptr, unsigned count);
#endif
// Target sendto() handler.
SyscallReturn sendtoFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr bufrPtr, size_t bufrLen, int flags,
Addr addrPtr, socklen_t addrLen);
// Target recvfrom() handler.
SyscallReturn recvfromFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr bufrPtr, size_t bufrLen,
int flags, Addr addrPtr, Addr addrlenPtr);
// Target recvmsg() handler.
SyscallReturn recvmsgFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr msgPtr, int flags);
// Target sendmsg() handler.
SyscallReturn sendmsgFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr msgPtr, int flags);
// Target getuid() handler.
SyscallReturn getuidFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target getgid() handler.
SyscallReturn getgidFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target getppid() handler.
SyscallReturn getppidFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target geteuid() handler.
SyscallReturn geteuidFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target getegid() handler.
SyscallReturn getegidFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target access() handler
SyscallReturn accessFunc(SyscallDesc *desc, int num, ThreadContext *tc,
Addr pathname, mode_t mode);
// Target getsockopt() handler.
SyscallReturn getsockoptFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, int level, int optname,
Addr valPtr, Addr lenPtr);
// Target setsockopt() handler.
SyscallReturn setsockoptFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, int level, int optname,
Addr valPtr, socklen_t len);
// Target getsockname() handler.
SyscallReturn getsocknameFunc(SyscallDesc *desc, int num, ThreadContext *tc,
int tgt_fd, Addr addrPtr, Addr lenPtr);
/// Futex system call
/// Implemented by Daniel Sanchez
/// Used by printf's in multi-threaded apps
template <class OS>
SyscallReturn
futexFunc(SyscallDesc *desc, int callnum, ThreadContext *tc,
Addr uaddr, int op, int val, int timeout, Addr uaddr2, int val3)
{
using namespace std;
auto process = tc->getProcessPtr();
/*
* Unsupported option that does not affect the correctness of the
* application. This is a performance optimization utilized by Linux.
*/
op &= ~OS::TGT_FUTEX_PRIVATE_FLAG;
op &= ~OS::TGT_FUTEX_CLOCK_REALTIME_FLAG;
FutexMap &futex_map = tc->getSystemPtr()->futexMap;
if (OS::TGT_FUTEX_WAIT == op || OS::TGT_FUTEX_WAIT_BITSET == op) {
// Ensure futex system call accessed atomically.
BufferArg buf(uaddr, sizeof(int));
buf.copyIn(tc->getVirtProxy());
int mem_val = *(int*)buf.bufferPtr();
/*
* The value in memory at uaddr is not equal with the expected val
* (a different thread must have changed it before the system call was
* invoked). In this case, we need to throw an error.
*/
if (val != mem_val)
return -OS::TGT_EWOULDBLOCK;
if (OS::TGT_FUTEX_WAIT == op) {
futex_map.suspend(uaddr, process->tgid(), tc);
} else {
futex_map.suspend_bitset(uaddr, process->tgid(), tc, val3);
}
return 0;
} else if (OS::TGT_FUTEX_WAKE == op) {
return futex_map.wakeup(uaddr, process->tgid(), val);
} else if (OS::TGT_FUTEX_WAKE_BITSET == op) {
return futex_map.wakeup_bitset(uaddr, process->tgid(), val3);
} else if (OS::TGT_FUTEX_REQUEUE == op ||
OS::TGT_FUTEX_CMP_REQUEUE == op) {
// Ensure futex system call accessed atomically.
BufferArg buf(uaddr, sizeof(int));
buf.copyIn(tc->getVirtProxy());
int mem_val = *(int*)buf.bufferPtr();
/*
* For CMP_REQUEUE, the whole operation is only started only if
* val3 is still the value of the futex pointed to by uaddr.
*/
if (OS::TGT_FUTEX_CMP_REQUEUE && val3 != mem_val)
return -OS::TGT_EWOULDBLOCK;
return futex_map.requeue(uaddr, process->tgid(), val, timeout, uaddr2);
} else if (OS::TGT_FUTEX_WAKE_OP == op) {
/*
* The FUTEX_WAKE_OP operation is equivalent to executing the
* following code atomically and totally ordered with respect to
* other futex operations on any of the two supplied futex words:
*
* int oldval = *(int *) addr2;
* *(int *) addr2 = oldval op oparg;
* futex(addr1, FUTEX_WAKE, val, 0, 0, 0);
* if (oldval cmp cmparg)
* futex(addr2, FUTEX_WAKE, val2, 0, 0, 0);
*
* (op, oparg, cmp, cmparg are encoded in val3)
*
* +---+---+-----------+-----------+
* |op |cmp| oparg | cmparg |
* +---+---+-----------+-----------+
* 4 4 12 12 <== # of bits
*
* reference: http://man7.org/linux/man-pages/man2/futex.2.html
*
*/
// get value from simulated-space
BufferArg buf(uaddr2, sizeof(int));
buf.copyIn(tc->getVirtProxy());
int oldval = *(int*)buf.bufferPtr();
int newval = oldval;
// extract op, oparg, cmp, cmparg from val3
int wake_cmparg = val3 & 0xfff;
int wake_oparg = (val3 & 0xfff000) >> 12;
int wake_cmp = (val3 & 0xf000000) >> 24;
int wake_op = (val3 & 0xf0000000) >> 28;
if ((wake_op & OS::TGT_FUTEX_OP_ARG_SHIFT) >> 3 == 1)
wake_oparg = (1 << wake_oparg);
wake_op &= ~OS::TGT_FUTEX_OP_ARG_SHIFT;
// perform operation on the value of the second futex
if (wake_op == OS::TGT_FUTEX_OP_SET)
newval = wake_oparg;
else if (wake_op == OS::TGT_FUTEX_OP_ADD)
newval += wake_oparg;
else if (wake_op == OS::TGT_FUTEX_OP_OR)
newval |= wake_oparg;
else if (wake_op == OS::TGT_FUTEX_OP_ANDN)
newval &= ~wake_oparg;
else if (wake_op == OS::TGT_FUTEX_OP_XOR)
newval ^= wake_oparg;
// copy updated value back to simulated-space
*(int*)buf.bufferPtr() = newval;
buf.copyOut(tc->getVirtProxy());
// perform the first wake-up
int woken1 = futex_map.wakeup(uaddr, process->tgid(), val);
int woken2 = 0;
// calculate the condition of the second wake-up
bool is_wake2 = false;
if (wake_cmp == OS::TGT_FUTEX_OP_CMP_EQ)
is_wake2 = oldval == wake_cmparg;
else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_NE)
is_wake2 = oldval != wake_cmparg;
else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LT)
is_wake2 = oldval < wake_cmparg;
else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_LE)
is_wake2 = oldval <= wake_cmparg;
else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GT)
is_wake2 = oldval > wake_cmparg;
else if (wake_cmp == OS::TGT_FUTEX_OP_CMP_GE)
is_wake2 = oldval >= wake_cmparg;
// perform the second wake-up
if (is_wake2)
woken2 = futex_map.wakeup(uaddr2, process->tgid(), timeout);
return woken1 + woken2;
}
warn("futex: op %d not implemented; ignoring.", op);
return -ENOSYS;
}
/// Pseudo Funcs - These functions use a different return convension,
/// returning a second value in a register other than the normal return register
SyscallReturn pipePseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target getpidPseudo() handler.
SyscallReturn getpidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target getuidPseudo() handler.
SyscallReturn getuidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// Target getgidPseudo() handler.
SyscallReturn getgidPseudoFunc(SyscallDesc *desc, int num, ThreadContext *tc);
/// A readable name for 1,000,000, for converting microseconds to seconds.
const int one_million = 1000000;
/// A readable name for 1,000,000,000, for converting nanoseconds to seconds.
const int one_billion = 1000000000;
/// Approximate seconds since the epoch (1/1/1970). About a billion,
/// by my reckoning. We want to keep this a constant (not use the
/// real-world time) to keep simulations repeatable.
const unsigned seconds_since_epoch = 1000000000;
/// Helper function to convert current elapsed time to seconds and
/// microseconds.
template <class T1, class T2>
void
getElapsedTimeMicro(T1 &sec, T2 &usec)
{
uint64_t elapsed_usecs = curTick() / SimClock::Int::us;
sec = elapsed_usecs / one_million;
usec = elapsed_usecs % one_million;
}
/// Helper function to convert current elapsed time to seconds and
/// nanoseconds.
template <class T1, class T2>
void
getElapsedTimeNano(T1 &sec, T2 &nsec)
{
uint64_t elapsed_nsecs = curTick() / SimClock::Int::ns;
sec = elapsed_nsecs / one_billion;
nsec = elapsed_nsecs % one_billion;
}
//////////////////////////////////////////////////////////////////////
//
// The following emulation functions are generic, but need to be
// templated to account for differences in types, constants, etc.
//
//////////////////////////////////////////////////////////////////////
typedef struct statfs hst_statfs;
#if NO_STAT64
typedef struct stat hst_stat;
typedef struct stat hst_stat64;
#else
typedef struct stat hst_stat;
typedef struct stat64 hst_stat64;
#endif
//// Helper function to convert a host stat buffer to a target stat
//// buffer. Also copies the target buffer out to the simulated
//// memory space. Used by stat(), fstat(), and lstat().
template <typename target_stat, typename host_stat>
void
convertStatBuf(target_stat &tgt, host_stat *host,
ByteOrder bo, bool fakeTTY=false)
{
if (fakeTTY)
tgt->st_dev = 0xA;
else
tgt->st_dev = host->st_dev;
tgt->st_dev = htog(tgt->st_dev, bo);
tgt->st_ino = host->st_ino;
tgt->st_ino = htog(tgt->st_ino, bo);
tgt->st_mode = host->st_mode;
if (fakeTTY) {
// Claim to be a character device
tgt->st_mode &= ~S_IFMT; // Clear S_IFMT
tgt->st_mode |= S_IFCHR; // Set S_IFCHR
}
tgt->st_mode = htog(tgt->st_mode, bo);
tgt->st_nlink = host->st_nlink;
tgt->st_nlink = htog(tgt->st_nlink, bo);
tgt->st_uid = host->st_uid;
tgt->st_uid = htog(tgt->st_uid, bo);
tgt->st_gid = host->st_gid;
tgt->st_gid = htog(tgt->st_gid, bo);
if (fakeTTY)
tgt->st_rdev = 0x880d;
else
tgt->st_rdev = host->st_rdev;
tgt->st_rdev = htog(tgt->st_rdev, bo);
tgt->st_size = host->st_size;
tgt->st_size = htog(tgt->st_size, bo);
tgt->st_atimeX = host->st_atime;
tgt->st_atimeX = htog(tgt->st_atimeX, bo);
tgt->st_mtimeX = host->st_mtime;
tgt->st_mtimeX = htog(tgt->st_mtimeX, bo);
tgt->st_ctimeX = host->st_ctime;
tgt->st_ctimeX = htog(tgt->st_ctimeX, bo);
// Force the block size to be 8KB. This helps to ensure buffered io works
// consistently across different hosts.
tgt->st_blksize = 0x2000;
tgt->st_blksize = htog(tgt->st_blksize, bo);
tgt->st_blocks = host->st_blocks;
tgt->st_blocks = htog(tgt->st_blocks, bo);
}
// Same for stat64
template <typename target_stat, typename host_stat64>
void
convertStat64Buf(target_stat &tgt, host_stat64 *host,
ByteOrder bo, bool fakeTTY=false)
{
convertStatBuf<target_stat, host_stat64>(tgt, host, bo, fakeTTY);
#if defined(STAT_HAVE_NSEC)
tgt->st_atime_nsec = host->st_atime_nsec;
tgt->st_atime_nsec = htog(tgt->st_atime_nsec, bo);
tgt->st_mtime_nsec = host->st_mtime_nsec;
tgt->st_mtime_nsec = htog(tgt->st_mtime_nsec, bo);
tgt->st_ctime_nsec = host->st_ctime_nsec;
tgt->st_ctime_nsec = htog(tgt->st_ctime_nsec, bo);
#else
tgt->st_atime_nsec = 0;
tgt->st_mtime_nsec = 0;
tgt->st_ctime_nsec = 0;
#endif
}
// Here are a couple of convenience functions
template<class OS>
void
copyOutStatBuf(PortProxy &mem, Addr addr,
hst_stat *host, bool fakeTTY = false)
{
typedef TypedBufferArg<typename OS::tgt_stat> tgt_stat_buf;
tgt_stat_buf tgt(addr);
convertStatBuf<tgt_stat_buf, hst_stat>(tgt, host, OS::byteOrder, fakeTTY);
tgt.copyOut(mem);
}
template<class OS>
void
copyOutStat64Buf(PortProxy &mem, Addr addr,
hst_stat64 *host, bool fakeTTY = false)
{
typedef TypedBufferArg<typename OS::tgt_stat64> tgt_stat_buf;
tgt_stat_buf tgt(addr);
convertStat64Buf<tgt_stat_buf, hst_stat64>(
tgt, host, OS::byteOrder, fakeTTY);
tgt.copyOut(mem);
}
template <class OS>
void
copyOutStatfsBuf(PortProxy &mem, Addr addr,
hst_statfs *host)
{
TypedBufferArg<typename OS::tgt_statfs> tgt(addr);
const ByteOrder bo = OS::byteOrder;
tgt->f_type = htog(host->f_type, bo);
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
tgt->f_bsize = htog(host->f_iosize, bo);
#else
tgt->f_bsize = htog(host->f_bsize, bo);
#endif
tgt->f_blocks = htog(host->f_blocks, bo);
tgt->f_bfree = htog(host->f_bfree, bo);
tgt->f_bavail = htog(host->f_bavail, bo);
tgt->f_files = htog(host->f_files, bo);
tgt->f_ffree = htog(host->f_ffree, bo);
memcpy(&tgt->f_fsid, &host->f_fsid, sizeof(host->f_fsid));
#if defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
tgt->f_namelen = htog(host->f_namemax, bo);
tgt->f_frsize = htog(host->f_bsize, bo);
#elif defined(__APPLE__)
tgt->f_namelen = 0;
tgt->f_frsize = 0;
#else
tgt->f_namelen = htog(host->f_namelen, bo);
tgt->f_frsize = htog(host->f_frsize, bo);
#endif
#if defined(__linux__)
memcpy(&tgt->f_spare, &host->f_spare, sizeof(host->f_spare));
#else
/*
* The fields are different sizes per OS. Don't bother with
* f_spare or f_reserved on non-Linux for now.
*/
memset(&tgt->f_spare, 0, sizeof(tgt->f_spare));
#endif
tgt.copyOut(mem);
}
/// Target ioctl() handler. For the most part, programs call ioctl()
/// only to find out if their stdout is a tty, to determine whether to
/// do line or block buffering. We always claim that output fds are
/// not TTYs to provide repeatable results.
template <class OS>
SyscallReturn
ioctlFunc(SyscallDesc *desc, int callnum, ThreadContext *tc)
{
int index = 0;
auto p = tc->getProcessPtr();
int tgt_fd = p->getSyscallArg(tc, index);
unsigned req = p->getSyscallArg(tc, index);
DPRINTF_SYSCALL(Verbose, "ioctl(%d, 0x%x, ...)\n", tgt_fd, req);
if (OS::isTtyReq(req))
return -ENOTTY;
auto dfdp = std::dynamic_pointer_cast<DeviceFDEntry>((*p->fds)[tgt_fd]);
if (dfdp) {
EmulatedDriver *emul_driver = dfdp->getDriver();
if (emul_driver)
return emul_driver->ioctl(tc, req);
}
auto sfdp = std::dynamic_pointer_cast<SocketFDEntry>((*p->fds)[tgt_fd]);
if (sfdp) {
int status;
switch (req) {
case SIOCGIFCONF: {
Addr conf_addr = p->getSyscallArg(tc, index);
BufferArg conf_arg(conf_addr, sizeof(ifconf));
conf_arg.copyIn(tc->getVirtProxy());
ifconf *conf = (ifconf*)conf_arg.bufferPtr();
Addr ifc_buf_addr = (Addr)conf->ifc_buf;
BufferArg ifc_buf_arg(ifc_buf_addr, conf->ifc_len);
ifc_buf_arg.copyIn(tc->getVirtProxy());
conf->ifc_buf = (char*)ifc_buf_arg.bufferPtr();
status = ioctl(sfdp->getSimFD(), req, conf_arg.bufferPtr());
if (status != -1) {
conf->ifc_buf = (char*)ifc_buf_addr;
ifc_buf_arg.copyOut(tc->getVirtProxy());
conf_arg.copyOut(tc->getVirtProxy());
}
return status;
}
case SIOCGIFFLAGS:
#if defined(__linux__)
case SIOCGIFINDEX:
#endif
case SIOCGIFNETMASK:
case SIOCGIFADDR:
#if defined(__linux__)
case SIOCGIFHWADDR:
#endif
case SIOCGIFMTU: {
Addr req_addr = p->getSyscallArg(tc, index);
BufferArg req_arg(req_addr, sizeof(ifreq));
req_arg.copyIn(tc->getVirtProxy());
status = ioctl(sfdp->getSimFD(), req, req_arg.bufferPtr());
if (status != -1)
req_arg.copyOut(tc->getVirtProxy());
return status;
}
}
}
/**
* For lack of a better return code, return ENOTTY. Ideally, we should
* return something better here, but at least we issue the warning.
*/
warn("Unsupported ioctl call (return ENOTTY): ioctl(%d, 0x%x, ...) @ \n",
tgt_fd, req, tc->pcState());
return -ENOTTY;
}
/// Target open() handler.
template <class OS>
SyscallReturn
openatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc,
int tgt_dirfd, Addr pathname, int tgt_flags, int mode)
{
auto p = tc->getProcessPtr();
/**
* Retrieve the simulated process' memory proxy and then read in the path
* string from that memory space into the host's working memory space.
*/
std::string path;
if (!tc->getVirtProxy().tryReadString(path, pathname))
return -EFAULT;
#ifdef __CYGWIN32__
int host_flags = O_BINARY;
#else
int host_flags = 0;
#endif
/**
* Translate target flags into host flags. Flags exist which are not
* ported between architectures which can cause check failures.
*/
for (int i = 0; i < OS::NUM_OPEN_FLAGS; i++) {
if (tgt_flags & OS::openFlagTable[i].tgtFlag) {
tgt_flags &= ~OS::openFlagTable[i].tgtFlag;
host_flags |= OS::openFlagTable[i].hostFlag;
}
}
if (tgt_flags)
warn("%s: cannot decode flags %#x", desc->name(), tgt_flags);
#ifdef __CYGWIN32__
host_flags |= O_BINARY;
#endif
/**
* If the simulated process called open or openat with AT_FDCWD specified,
* take the current working directory value which was passed into the
* process class as a Python parameter and append the current path to
* create a full path.
* Otherwise, openat with a valid target directory file descriptor has
* been called. If the path option, which was passed in as a parameter,
* is not absolute, retrieve the directory file descriptor's path and
* prepend it to the path passed in as a parameter.
* In every case, we should have a full path (which is relevant to the
* host) to work with after this block has been passed.
*/
std::string redir_path = path;
std::string abs_path = path;
if (tgt_dirfd == OS::TGT_AT_FDCWD) {
abs_path = p->absolutePath(path, true);
redir_path = p->checkPathRedirect(path);
} else if (!startswith(path, "/")) {
std::shared_ptr<FDEntry> fdep = ((*p->fds)[tgt_dirfd]);
auto ffdp = std::dynamic_pointer_cast<FileFDEntry>(fdep);
if (!ffdp)
return -EBADF;
abs_path = ffdp->getFileName() + path;
redir_path = p->checkPathRedirect(abs_path);
}
/**
* Since this is an emulated environment, we create pseudo file
* descriptors for device requests that have been registered with
* the process class through Python; this allows us to create a file
* descriptor for subsequent ioctl or mmap calls.
*/
if (startswith(abs_path, "/dev/")) {
std::string filename = abs_path.substr(strlen("/dev/"));
EmulatedDriver *drv = p->findDriver(filename);
if (drv) {
DPRINTF_SYSCALL(Verbose, "%s: passing call to "
"driver open with path[%s]\n",
desc->name(), abs_path.c_str());
return drv->open(tc, mode, host_flags);
}
/**
* Fall through here for pass through to host devices, such
* as /dev/zero
*/
}
/**
* We make several attempts resolve a call to open.
*
* 1) Resolve any path redirection before hand. This will set the path
* up with variable 'redir_path' which may contain a modified path or
* the original path value. This should already be done in prior code.
* 2) Try to handle the access using 'special_paths'. Some special_paths
* and files cannot be called on the host and need to be handled as
* special cases inside the simulator. These special_paths are handled by
* C++ routines to provide output back to userspace.
* 3) If the full path that was created above does not match any of the
* special cases, pass it through to the open call on the __HOST__ to let
* the host open the file on our behalf. Again, the openImpl tries to
* USE_THE_HOST_FILESYSTEM_OPEN (with a possible redirection to the
* faux-filesystem files). The faux-filesystem is dynamically created
* during simulator configuration using Python functions.
* 4) If the host cannot open the file, the open attempt failed in "3)".
* Return the host's error code back through the system call to the
* simulated process. If running a debug trace, also notify the user that
* the open call failed.
*
* Any success will set sim_fd to something other than -1 and skip the
* next conditions effectively bypassing them.
*/
int sim_fd = -1;
std::string used_path;
std::vector<std::string> special_paths =
{ "/proc/meminfo/", "/system/", "/platform/", "/etc/passwd" };
for (auto entry : special_paths) {
if (startswith(path, entry)) {
sim_fd = OS::openSpecialFile(abs_path, p, tc);
used_path = abs_path;
}
}
if (sim_fd == -1) {
sim_fd = open(redir_path.c_str(), host_flags, mode);
used_path = redir_path;
}
if (sim_fd == -1) {
int local = -errno;
DPRINTF_SYSCALL(Verbose, "%s: failed -> path:%s "
"(inferred from:%s)\n", desc->name(),
used_path.c_str(), path.c_str());
return local;
}
/**
* The file was opened successfully and needs to be recorded in the
* process' file descriptor array so that it can be retrieved later.
* The target file descriptor that is chosen will be the lowest unused
* file descriptor.
* Return the indirect target file descriptor back to the simulated
* process to act as a handle for the opened file.
*/
auto ffdp = std::make_shared<FileFDEntry>(sim_fd, host_flags, path, 0);
int tgt_fd = p->fds->allocFD(ffdp);
DPRINTF_SYSCALL(Verbose, "%s: sim_fd[%d], target_fd[%d] -> path:%s\n"
"(inferred from:%s)\n", desc->name(),
sim_fd, tgt_fd, used_path.c_str(), path.c_str());
return tgt_fd;
}
/// Target open() handler.
template <class OS>
SyscallReturn
openFunc(SyscallDesc *desc, int callnum, ThreadContext *tc,
Addr pathname, int tgt_flags, int mode)
{
return openatFunc<OS>(desc, callnum, tc, OS::TGT_AT_FDCWD,
pathname, tgt_flags, mode);
}
/// Target unlinkat() handler.
template <class OS>
SyscallReturn
unlinkatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc,
int dirfd, Addr pathname)
{
if (dirfd != OS::TGT_AT_FDCWD)
warn("unlinkat: first argument not AT_FDCWD; unlikely to work");
return unlinkFunc(desc, callnum, tc, pathname);
}
/// Target facessat() handler
template <class OS>
SyscallReturn
faccessatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc,
int dirfd, Addr pathname, int mode)
{
if (dirfd != OS::TGT_AT_FDCWD)
warn("faccessat: first argument not AT_FDCWD; unlikely to work");
return accessFunc(desc, callnum, tc, pathname, mode);
}
/// Target readlinkat() handler
template <class OS>
SyscallReturn
readlinkatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc,
int dirfd, Addr pathname, Addr buf, size_t bufsiz)
{
if (dirfd != OS::TGT_AT_FDCWD)
warn("openat: first argument not AT_FDCWD; unlikely to work");
return readlinkFunc(desc, callnum, tc, pathname, buf, bufsiz);
}
/// Target renameat() handler.
template <class OS>
SyscallReturn
renameatFunc(SyscallDesc *desc, int callnum, ThreadContext *tc,
int olddirfd, Addr oldpath, int newdirfd, Addr newpath)
{
if (olddirfd != OS::TGT_AT_FDCWD)
warn("renameat: first argument not AT_FDCWD; unlikely to work");
if (newdirfd != OS::TGT_AT_FDCWD)
warn("renameat: third argument not AT_FDCWD; unlikely to work");
return renameFunc(desc, callnum, tc, oldpath, newpath);
}
/// Target sysinfo() handler.
template <class OS>
SyscallReturn