-
Notifications
You must be signed in to change notification settings - Fork 656
Expand file tree
/
Copy pathrecord_syscall.cc
More file actions
7482 lines (6909 loc) · 257 KB
/
record_syscall.cc
File metadata and controls
7482 lines (6909 loc) · 257 KB
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
/* -*- Mode: C++; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */
#include <arpa/inet.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <linux/auxvec.h>
#include <linux/blkzoned.h>
#include <linux/capability.h>
#include <linux/cdrom.h>
#include <linux/dma-buf.h>
#include <linux/elf.h>
#include <linux/ethtool.h>
#include <linux/fb.h>
#include <linux/fiemap.h>
#include <linux/fs.h>
#include <linux/futex.h>
#include <linux/hidraw.h>
#include <linux/if.h>
#include <linux/if_bridge.h>
#include <linux/if_packet.h>
#include <linux/if_tun.h>
#include <linux/input.h>
#include <linux/ipc.h>
#include <linux/joystick.h>
#include <linux/kd.h>
#include <linux/msdos_fs.h>
#include <linux/msg.h>
#include <linux/net.h>
#include <linux/netlink.h>
#include <linux/perf_event.h>
#include <linux/personality.h>
#include <linux/prctl.h>
#include <linux/random.h>
#include <linux/seccomp.h>
#include <linux/sem.h>
#include <linux/shm.h>
#include <linux/sockios.h>
#include <linux/videodev2.h>
#include <linux/vt.h>
#include <linux/wireless.h>
#include <mtd/mtd-user.h>
#include <poll.h>
#include <sched.h>
#include <scsi/sg.h>
#include <sound/asound.h>
#include <sys/epoll.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/quota.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/sysinfo.h>
#include <sys/time.h>
#include <sys/times.h>
#include <sys/un.h>
#include <sys/utsname.h>
#include <sys/vfs.h>
#include <sys/wait.h>
#include <sys/xattr.h>
#include <termios.h>
#include <limits>
#include <sstream>
#include <utility>
#include <unordered_set>
#include <rr/rr.h>
#include "record_syscall.h"
#include "preload/preload_interface.h"
#include "AutoRemoteSyscalls.h"
#include "BpfMapMonitor.h"
#include "CPUs.h"
#include "DiversionSession.h"
#include "ElfReader.h"
#include "FileMonitor.h"
#include "Flags.h"
#include "MmappedFileMonitor.h"
#include "NonvirtualPerfCounterMonitor.h"
#include "ODirectFileMonitor.h"
#include "ProcFdDirMonitor.h"
#include "ProcMemMonitor.h"
#include "ProcStatMonitor.h"
#include "RRPageMonitor.h"
#include "RecordSession.h"
#include "RecordTask.h"
#include "Scheduler.h"
#include "StdioMonitor.h"
#include "SysCpuMonitor.h"
#include "TraceStream.h"
#include "VirtualPerfCounterMonitor.h"
#include "cpp_supplement.h"
#include "ftrace.h"
#include "kernel_abi.h"
#include "kernel_metadata.h"
#include "kernel_supplement.h"
#include "log.h"
#include "util.h"
using namespace std;
#if defined (TCGETS2) && ! defined (HAVE_TERMIOS2)
// The kernel header that defines this conflicts badly with glibc headers
// (but not bionic, which does define this) so we define it ourselves.
// NB: We need this struct defined so that the preprocessor macro for
// TCGETS2 will evaluate. But we use IOCTL_MASK_SIZE on it and we use
// the size from the tracee to determine how many bytes to record, so
// we don't actually depend on this being *accurate*.
struct termios2 {
tcflag_t c_iflag;
tcflag_t c_oflag;
tcflag_t c_cflag;
tcflag_t c_lflag;
cc_t c_line;
cc_t c_cc[19];
speed_t c_ispeed;
speed_t c_ospeed;
};
#endif
namespace rr {
union _semun {
int val;
struct semid64_ds* buf;
unsigned short int* array;
struct seminfo* __buf;
};
/* We can't include <sys/shm.h> to get shmctl because it clashes with
* linux/shm.h.
*/
static int _shmctl(int shmid, int cmd, shmid64_ds* buf) {
#ifdef SYS_shmctl
int ret = syscall(SYS_shmctl, shmid, cmd, buf);
if (ret >= 0 || errno != ENOSYS) {
return ret;
}
#endif
#ifdef SYS_ipc
if (sizeof(void*) == 4) {
cmd |= IPC_64;
}
return syscall(SYS_ipc, SHMCTL, shmid, cmd, 0, buf);
#else
return ret;
#endif
}
static int _semctl(int semid, int semnum, int cmd, _semun un_arg) {
#ifdef SYS_semctl
int ret = syscall(SYS_semctl, semid, semnum, cmd, un_arg);
if (ret >= 0 || errno != ENOSYS) {
return ret;
}
#endif
#ifdef SYS_ipc
if (sizeof(void*) == 4) {
cmd |= IPC_64;
}
return syscall(SYS_ipc, SEMCTL, semid, semnum, cmd, &un_arg);
#else
return ret;
#endif
}
/**
* Modes used to register syscall memory parameter with TaskSyscallState.
*/
enum ArgMode {
// Syscall memory parameter is an in-parameter only.
// This is only important when we want to move the buffer to scratch memory
// so we can modify it without making the modifications potentially visible
// to user code. Otherwise, such parameters can be ignored.
IN,
// Syscall memory parameter is out-parameter only.
OUT,
// Syscall memory parameter is an in-out parameter.
IN_OUT,
// Syscall memory parameter is an in-out parameter but we must not use
// scratch (e.g. for futexes, we must use the actual memory word).
IN_OUT_NO_SCRATCH
};
/**
* Specifies how to determine the size of a syscall memory
* parameter. There is usually an incoming size determined before the syscall
* executes (which we need in order to allocate scratch memory), combined
* with an optional final size taken from the syscall result or a specific
* memory location after the syscall has executed. The minimum of the incoming
* and final sizes is used, if both are present.
*/
struct ParamSize {
ParamSize() : incoming_size(size_t(-1)), from_syscall_multiplier(0) {}
// Clamp incoming_size to INTPTR_MAX. No system call can read more data
// than that in practice (to a single output parameter).
ParamSize(size_t incoming_size)
: incoming_size(min<size_t>(INTPTR_MAX, incoming_size)),
from_syscall_multiplier(0) {}
/**
* p points to a tracee location that is already initialized with a
* "maximum buffer size" passed in by the tracee, and which will be filled
* in with the size of the data by the kernel when the syscall exits.
*/
template <typename T>
static ParamSize from_initialized_mem(RecordTask* t, remote_ptr<T> p) {
ParamSize r(p.is_null() ? size_t(0) : size_t(t->read_mem(p)));
r.mem_ptr = p;
r.read_size = sizeof(T);
return r;
}
/**
* p points to a tracee location which will be filled in with the size of
* the data by the kernel when the syscall exits, but the location
* is uninitialized before the syscall.
*/
template <typename T> static ParamSize from_mem(remote_ptr<T> p) {
ParamSize r;
r.mem_ptr = p;
r.read_size = sizeof(T);
return r;
}
/**
* When the syscall exits, the syscall result will be of type T and contain
* the size of the data. 'incoming_size', if present, is a bound on the size
* of the data.
*/
template <typename T> static ParamSize from_syscall_result() {
ParamSize r;
r.from_syscall_multiplier = 1;
r.read_size = sizeof(T);
return r;
}
template <typename T>
static ParamSize from_syscall_result(size_t incoming_size, uint32_t multiplier = 1) {
ParamSize r(incoming_size);
r.from_syscall_multiplier = multiplier;
r.read_size = sizeof(T);
return r;
}
/**
* Indicate that the size will be at most 'max'.
*/
ParamSize limit_size(size_t max) const {
ParamSize r(*this);
r.incoming_size = min(r.incoming_size, max);
return r;
}
/**
* Return true if 'other' takes its dynamic size from the same source as
* this.
* When multiple syscall memory parameters take their dynamic size from the
* same source, the source size is distributed among them, with the first
* registered parameter taking up to its max_size bytes, followed by the next,
* etc. This lets us efficiently record iovec buffers.
*/
bool is_same_source(const ParamSize& other) const {
return ((!mem_ptr.is_null() && other.mem_ptr == mem_ptr) ||
(from_syscall_multiplier && other.from_syscall_multiplier)) &&
(read_size == other.read_size);
}
/**
* Compute the actual size after the syscall has executed.
* 'already_consumed' bytes are subtracted from the syscall-result/
* memory-location part of the size.
*/
size_t eval(RecordTask* t, size_t already_consumed) const;
size_t incoming_size;
/** If non-null, the size is limited by the value at this location after
* the syscall. */
remote_ptr<void> mem_ptr;
/** Size of the value at mem_ptr or in the syscall result register. */
size_t read_size;
/** If from_syscall_multiplier > 0, the size is limited by the value of
* the syscall result * from_syscall_multiplier. */
uint32_t from_syscall_multiplier;
};
size_t ParamSize::eval(RecordTask* t, size_t already_consumed) const {
size_t s = incoming_size;
if (!mem_ptr.is_null()) {
size_t mem_size;
switch (read_size) {
case 4:
mem_size = t->read_mem(mem_ptr.cast<uint32_t>());
break;
case 8:
mem_size = t->read_mem(mem_ptr.cast<uint64_t>());
break;
default:
ASSERT(t, false) << "Unknown read_size";
return 0;
}
ASSERT(t, already_consumed <= mem_size);
s = min(s, mem_size - already_consumed);
}
if (from_syscall_multiplier) {
size_t syscall_size = max<ssize_t>(0, t->regs().syscall_result_signed())
* from_syscall_multiplier;
switch (read_size) {
case 4:
syscall_size = uint32_t(syscall_size);
break;
case 8:
syscall_size = uint64_t(syscall_size);
break;
default:
ASSERT(t, false) << "Unknown read_size";
return 0;
}
ASSERT(t, already_consumed <= syscall_size);
s = min(s, syscall_size - already_consumed);
}
ASSERT(t, s < size_t(-1));
return s;
}
typedef bool (*ArgMutator)(RecordTask*, remote_ptr<void>, void*);
/**
* When tasks enter syscalls that may block and so must be
* prepared for a context-switch, and the syscall params
* include (in)outparams that point to buffers, we need to
* redirect those arguments to scratch memory. This allows rr
* to serialize execution of what may be multiple blocked
* syscalls completing "simultaneously" (from rr's
* perspective). After the syscall exits, we restore the data
* saved in scratch memory to the original buffers.
*
* Then during replay, we simply restore the saved data to the
* tracee's passed-in buffer args and continue on.
*
* This is implemented by having rec_prepare_syscall_arch set up
* a record in param_list for syscall in-memory parameter (whether
* "in" or "out"). Then done_preparing is called, which does the actual
* scratch setup. process_syscall_results is called when the syscall is
* done, to write back scratch results to the real parameters and
* clean everything up.
*
* ... a fly in this ointment is may-block buffered syscalls.
* If a task blocks in one of those, it will look like it just
* entered a syscall that needs a scratch buffer. However,
* it's too late at that point to fudge the syscall args,
* because processing of the syscall has already begun in the
* kernel. But that's OK: the syscallbuf code has already
* swapped out the original buffer-pointers for pointers into
* the syscallbuf (which acts as its own scratch memory). We
* just have to worry about setting things up properly for
* replay.
*
* The descheduled syscall will "abort" its commit into the
* syscallbuf, so the outparam data won't actually be saved
* there (and thus, won't be restored during replay). During
* replay, we have to restore them like we restore the
* non-buffered-syscall scratch data. This is done by recording
* the relevant syscallbuf record data in rec_process_syscall_arch.
*/
struct TaskSyscallState : TaskSyscallStateBase {
static TaskSyscallState& get(RecordTask* t) {
auto base = t->syscall_state.get();
ASSERT(t, base) << "Expected syscall-state but didn't find one";
return *static_cast<TaskSyscallState*>(base);
}
static TaskSyscallState* maybe_get(RecordTask* t) {
auto base = t->syscall_state.get();
return static_cast<TaskSyscallState*>(base);
}
void init(RecordTask* t) {
if (preparation_done) {
return;
}
this->t = t;
scratch = t->scratch_ptr;
}
/**
* Identify a syscall memory parameter whose address is in register 'arg'
* with type T.
* Returns a remote_ptr to the data in the child (before scratch relocation)
* or null if parameters have already been prepared (the syscall is
* resuming).
*/
template <typename T>
remote_ptr<T> reg_parameter(int arg, ArgMode mode = OUT,
ArgMutator mutator = nullptr) {
return reg_parameter(arg, sizeof(T), mode, mutator).cast<T>();
}
/**
* Identify a syscall memory parameter whose address is in register 'arg'
* with size 'size'.
* Returns a remote_ptr to the data in the child (before scratch relocation)
* or null if parameters have already been prepared (the syscall is
* resuming).
*/
remote_ptr<void> reg_parameter(int arg, const ParamSize& size,
ArgMode mode = OUT,
ArgMutator mutator = nullptr);
/**
* Identify a syscall memory parameter whose address is in memory at
* location 'addr_of_buf_ptr' with type T.
* Returns a remote_ptr to the data in the child (before scratch relocation)
* or null if parameters have already been prepared (the syscall is
* resuming).
* addr_of_buf_ptr must be in a buffer identified by some init_..._parameter
* call.
*/
template <typename T>
remote_ptr<T> mem_ptr_parameter(remote_ptr<void> addr_of_buf_ptr,
ArgMode mode = OUT,
ArgMutator mutator = nullptr) {
return mem_ptr_parameter(addr_of_buf_ptr, sizeof(T), mode, mutator)
.cast<T>();
}
/**
* Identify a syscall memory parameter whose address is in memory at
* location 'addr_of_buf_ptr' with type T.
* Returns a remote_ptr to the data in the child (before scratch relocation)
* or null if parameters have already been prepared (the syscall is
* resuming).
* addr_of_buf_ptr must be in a buffer identified by some init_..._parameter
* call.
*/
template <typename Ptr>
remote_ptr<typename Ptr::Referent> mem_ptr_parameter_inferred(
remote_ptr<Ptr> addr_of_buf_ptr, ArgMode mode = OUT,
ArgMutator mutator = nullptr) {
remote_ptr<void> p =
mem_ptr_parameter(addr_of_buf_ptr, Ptr::referent_size(), mode, mutator);
return p.cast<typename Ptr::Referent>();
}
/**
* Identify a syscall memory parameter whose address is in memory at
* location 'addr_of_buf_ptr' with size 'size'.
* Returns a remote_ptr to the data in the child (before scratch relocation)
* or null if parameters have already been prepared (the syscall is
* resuming).
* addr_of_buf_ptr must be in a buffer identified by some init_..._parameter
* call.
*/
remote_ptr<void> mem_ptr_parameter(remote_ptr<void> addr_of_buf_ptr,
const ParamSize& size, ArgMode mode = OUT,
ArgMutator mutator = nullptr);
typedef void (*AfterSyscallAction)(RecordTask* t);
// Register a callback to run when the syscall has completed.
// This runs after parameters have been restored.
void after_syscall_action(AfterSyscallAction action) {
after_syscall_actions.push_back(action);
}
void emulate_result(uint64_t result) {
ASSERT(t, !preparation_done);
ASSERT(t, !should_emulate_result);
should_emulate_result = true;
emulated_result = result;
}
/**
* Internal method that takes 'ptr', an address within some memory parameter,
* and relocates it to the parameter's location in scratch memory.
*/
remote_ptr<void> relocate_pointer_to_scratch(remote_ptr<void> ptr);
/**
* Internal method that takes the index of a MemoryParam and a vector
* containing the actual sizes assigned to each param < param_index, and
* computes the actual size to use for parameter param_index.
*/
size_t eval_param_size(size_t param_index, vector<size_t>& actual_sizes);
/**
* Called when all memory parameters have been identified. If 'sw' is
* ALLOW_SWITCH, sets up scratch memory and updates registers etc as
* necessary.
* If scratch can't be used for some reason, returns PREVENT_SWITCH,
* otherwise returns 'sw'.
*/
Switchable done_preparing(Switchable sw);
Switchable done_preparing_internal(Switchable sw);
enum WriteBack { WRITE_BACK, NO_WRITE_BACK };
/**
* Called when a syscall exits to copy results from scratch memory to their
* original destinations, update registers, etc.
*/
void process_syscall_results();
/**
* Called when a syscall has been completely aborted to undo any changes we
* made.
*/
void abort_syscall_results();
/**
* Upon successful syscall completion, each RestoreAndRecordScratch record
* in param_list consumes num_bytes from the t->scratch_ptr
* buffer, copying the data to remote_dest and recording the data at
* remote_dest. If ptr_in_reg is greater than zero, updates the task's
* ptr_in_reg register with 'remote_dest'. If ptr_in_memory is non-null,
* updates the ptr_in_memory location with the value 'remote_dest'.
*/
struct MemoryParam {
MemoryParam() : ptr_in_reg(0) {}
remote_ptr<void> dest;
remote_ptr<void> scratch;
ParamSize num_bytes;
remote_ptr<void> ptr_in_memory;
int ptr_in_reg;
ArgMode mode;
ArgMutator mutator;
};
RecordTask* t;
vector<MemoryParam> param_list;
/** Tracks the position in t's scratch_ptr buffer where we should allocate
* the next scratch area.
*/
remote_ptr<void> scratch;
vector<AfterSyscallAction> after_syscall_actions;
std::unique_ptr<TraceTaskEvent> exec_saved_event;
RecordTask* emulate_wait_for_child;
/** Saved syscall-entry registers, used by code paths that modify the
* registers temporarily.
*/
Registers syscall_entry_registers;
/** When nonzero, syscall is expected to return the given errno and we should
* die if it does not. This is set when we detect an error condition during
* syscall-enter preparation.
*/
int expect_errno;
/** When should_emulate_result is true, syscall result should be adjusted to
* be emulated_result. */
bool should_emulate_result;
uint64_t emulated_result;
/** Records whether the syscall is switchable. Only valid when
* preparation_done is true. */
Switchable switchable;
/** Whether we should write back the syscall results from scratch. Only
* valid when preparation_done is true. */
WriteBack write_back;
/** When true, this syscall has already been prepared and should not
* be set up again.
*/
bool preparation_done;
/** When true, the scratch area is enabled, otherwise we're letting
* syscall outputs be written directly to their destinations.
* Only valid when preparation_done is true.
*/
bool scratch_enabled;
/** Miscellaneous saved data that can be used by particular syscalls */
vector<uint8_t> saved_data;
TaskSyscallState()
: t(nullptr),
emulate_wait_for_child(nullptr),
expect_errno(0),
should_emulate_result(false),
preparation_done(false),
scratch_enabled(false) {}
};
template <typename Arch>
static void set_remote_ptr_arch(RecordTask* t, remote_ptr<void> addr,
remote_ptr<void> value) {
auto typed_addr = addr.cast<typename Arch::unsigned_word>();
t->write_mem(typed_addr, (typename Arch::unsigned_word)value.as_int());
}
static void set_remote_ptr(RecordTask* t, remote_ptr<void> addr,
remote_ptr<void> value) {
RR_ARCH_FUNCTION(set_remote_ptr_arch, t->arch(), t, addr, value);
}
template <typename Arch>
static remote_ptr<void> get_remote_ptr_arch(RecordTask* t,
remote_ptr<void> addr) {
auto typed_addr = addr.cast<typename Arch::unsigned_word>();
auto old = t->read_mem(typed_addr);
return remote_ptr<void>(old);
}
static remote_ptr<void> get_remote_ptr(RecordTask* t, remote_ptr<void> addr) {
RR_ARCH_FUNCTION(get_remote_ptr_arch, t->arch(), t, addr);
}
static void align_scratch(remote_ptr<void>* scratch, uintptr_t amount = 8) {
*scratch = (scratch->as_int() + amount - 1) & ~(amount - 1);
}
remote_ptr<void> TaskSyscallState::reg_parameter(int arg, const ParamSize& size,
ArgMode mode,
ArgMutator mutator) {
if (preparation_done) {
return remote_ptr<void>();
}
MemoryParam param;
param.dest = syscall_entry_registers.arg(arg);
if (param.dest.is_null()) {
return remote_ptr<void>();
}
param.num_bytes = size;
param.mode = mode;
param.mutator = mutator;
ASSERT(t, !mutator || mode == IN);
if (mode != IN_OUT_NO_SCRATCH) {
param.scratch = scratch;
scratch += param.num_bytes.incoming_size;
align_scratch(&scratch);
param.ptr_in_reg = arg;
}
param_list.push_back(param);
return param.dest;
}
remote_ptr<void> TaskSyscallState::mem_ptr_parameter(
remote_ptr<void> addr_of_buf_ptr, const ParamSize& size, ArgMode mode,
ArgMutator mutator) {
if (preparation_done || addr_of_buf_ptr.is_null()) {
return remote_ptr<void>();
}
MemoryParam param;
param.dest = get_remote_ptr(t, addr_of_buf_ptr);
if (param.dest.is_null()) {
return remote_ptr<void>();
}
param.num_bytes = size;
param.mode = mode;
param.mutator = mutator;
ASSERT(t, !mutator || mode == IN);
if (mode != IN_OUT_NO_SCRATCH) {
param.scratch = scratch;
scratch += param.num_bytes.incoming_size;
align_scratch(&scratch);
param.ptr_in_memory = addr_of_buf_ptr;
}
param_list.push_back(param);
return param.dest;
}
remote_ptr<void> TaskSyscallState::relocate_pointer_to_scratch(
remote_ptr<void> ptr) {
int num_relocations = 0;
remote_ptr<void> result;
for (auto& param : param_list) {
if (param.dest <= ptr && ptr < param.dest + param.num_bytes.incoming_size) {
result = param.scratch + (ptr - param.dest);
++num_relocations;
}
}
DEBUG_ASSERT(
num_relocations > 0 &&
"Pointer in non-scratch memory being updated to point to scratch?");
DEBUG_ASSERT(num_relocations <= 1 &&
"Overlapping buffers containing relocated pointer?");
return result;
}
Switchable TaskSyscallState::done_preparing_internal(Switchable sw) {
ASSERT(t, !preparation_done);
preparation_done = true;
write_back = WRITE_BACK;
switchable = sw;
if (!t->scratch_ptr) {
return switchable;
}
ASSERT(t, scratch >= t->scratch_ptr);
if (sw == ALLOW_SWITCH &&
scratch > t->scratch_ptr + t->usable_scratch_size()) {
LOG(warn)
<< "`" << t->ev().Syscall().syscall_name()
<< "' needed a scratch buffer of size " << scratch - t->scratch_ptr
<< ", but only " << t->usable_scratch_size()
<< " was available. Allowing the syscall to proceed without scratch, which may race.";
return switchable;
}
if (switchable == PREVENT_SWITCH || param_list.empty()) {
return switchable;
}
scratch_enabled = true;
// Step 1: Copy all IN/IN_OUT parameters to their scratch areas
for (auto& param : param_list) {
ASSERT(t, param.num_bytes.incoming_size < size_t(-1));
if (param.mode == IN_OUT || param.mode == IN) {
// Initialize scratch buffer with input data
std::unique_ptr<uint8_t[]> buf(
new uint8_t[param.num_bytes.incoming_size]);
t->read_bytes_helper(param.dest, param.num_bytes.incoming_size,
buf.get());
t->write_bytes_helper(param.scratch, param.num_bytes.incoming_size,
buf.get());
}
}
// Step 2: Update pointers in registers/memory to point to scratch areas
{
Registers r = t->regs();
for (auto& param : param_list) {
if (param.ptr_in_reg) {
r.set_arg(param.ptr_in_reg, param.scratch.as_int());
}
if (!param.ptr_in_memory.is_null()) {
// Pointers being relocated must themselves be in scratch memory.
// We don't want to modify non-scratch memory. Find the pointer's
// location
// in scratch memory.
auto p = relocate_pointer_to_scratch(param.ptr_in_memory);
// Update pointer to point to scratch.
// Note that this can only happen after step 1 is complete and all
// parameter data has been copied to scratch memory.
set_remote_ptr(t, p, param.scratch);
}
// If the number of bytes to record is coming from a memory location,
// update that location to scratch.
if (!param.num_bytes.mem_ptr.is_null()) {
param.num_bytes.mem_ptr =
relocate_pointer_to_scratch(param.num_bytes.mem_ptr);
}
}
t->set_regs(r);
}
return switchable;
}
Switchable TaskSyscallState::done_preparing(Switchable sw) {
if (preparation_done) {
return switchable;
}
sw = done_preparing_internal(sw);
ASSERT(t, sw == switchable);
// Step 3: Execute mutators. This must run even if the scratch steps do not.
for (auto& param : param_list) {
if (param.mutator) {
// Mutated parameters must be IN. If we have scratch space, we don't need
// to save anything.
void* saved_data_loc = nullptr;
if (!scratch_enabled) {
auto prev_size = saved_data.size();
saved_data.resize(prev_size + param.num_bytes.incoming_size);
saved_data_loc = saved_data.data() + prev_size;
}
if (!(*param.mutator)(t, scratch_enabled ? param.scratch : param.dest,
saved_data_loc)) {
// Nothing was modified, no need to clean up when we unwind.
param.mutator = nullptr;
if (!scratch_enabled) {
saved_data.resize(saved_data.size() - param.num_bytes.incoming_size);
}
}
}
}
return switchable;
}
size_t TaskSyscallState::eval_param_size(size_t i,
vector<size_t>& actual_sizes) {
DEBUG_ASSERT(actual_sizes.size() == i);
size_t already_consumed = 0;
for (size_t j = 0; j < i; ++j) {
if (param_list[j].num_bytes.is_same_source(param_list[i].num_bytes)) {
already_consumed += actual_sizes[j];
}
}
size_t size = param_list[i].num_bytes.eval(t, already_consumed);
actual_sizes.push_back(size);
return size;
}
void TaskSyscallState::process_syscall_results() {
ASSERT(t, preparation_done);
// XXX what's the best way to handle failed syscalls? Currently we just
// record everything as if it succeeded. That handles failed syscalls that
// wrote partial results, but doesn't handle syscalls that failed with
// EFAULT.
vector<size_t> actual_sizes;
if (scratch_enabled) {
size_t scratch_num_bytes = scratch - t->scratch_ptr;
auto data = t->read_mem(t->scratch_ptr.cast<uint8_t>(), scratch_num_bytes);
Registers r = t->regs();
// Step 1: compute actual sizes of all buffers and copy outputs
// from scratch back to their origin
for (size_t i = 0; i < param_list.size(); ++i) {
auto& param = param_list[i];
size_t size = eval_param_size(i, actual_sizes);
if (write_back == WRITE_BACK &&
(param.mode == IN_OUT || param.mode == OUT)) {
const uint8_t* d = data.data() + (param.scratch - t->scratch_ptr);
t->write_bytes_helper(param.dest, size, d);
}
}
bool memory_cleaned_up = false;
// Step 2: restore modified in-memory pointers and registers
for (size_t i = 0; i < param_list.size(); ++i) {
auto& param = param_list[i];
if (param.ptr_in_reg) {
r.set_orig_arg(param.ptr_in_reg, param.dest.as_int());
}
if (!param.ptr_in_memory.is_null()) {
memory_cleaned_up = true;
set_remote_ptr(t, param.ptr_in_memory, param.dest);
}
}
if (write_back == WRITE_BACK) {
// Step 3: record all output memory areas
for (size_t i = 0; i < param_list.size(); ++i) {
auto& param = param_list[i];
size_t size = actual_sizes[i];
if (param.mode == IN_OUT_NO_SCRATCH) {
t->record_remote(param.dest, size);
} else if (param.mode == IN_OUT || param.mode == OUT) {
// If pointers in memory were fixed up in step 2, then record
// from tracee memory to ensure we record such fixes. Otherwise we
// can record from our local data.
// XXX This optimization can be improved if necessary...
if (memory_cleaned_up) {
t->record_remote(param.dest, size);
} else {
const uint8_t* d = data.data() + (param.scratch - t->scratch_ptr);
t->record_local(param.dest, size, d);
}
}
}
}
t->set_regs(r);
} else {
// Step 1: Determine the size of all output memory areas
for (size_t i = 0; i < param_list.size(); ++i) {
eval_param_size(i, actual_sizes);
}
// Step 2: restore all mutated memory
for (auto& param : param_list) {
if (param.mutator) {
size_t size = param.num_bytes.incoming_size;
ASSERT(t, saved_data.size() >= size);
// If this intersects an output region, we need to be careful not to
// clobber what the kernel gave us.
for (size_t i = 0; i < param_list.size(); ++i) {
auto& param2 = param_list[i];
size_t param2_size = actual_sizes[i];
if (param2.mode == IN) {
continue;
}
MemoryRange intersection = MemoryRange(param2.dest, param2_size).
intersect(MemoryRange(param.dest, size));
if (intersection.size() != 0) {
// Just update the saved data we already have. We could try
// splitting the range and only writing what needs to still change,
// but we'd probably just end up doing the exact same number of
// syscalls and this is simpler.
t->read_bytes_helper(intersection.start(), intersection.size(),
saved_data.data() + (intersection.start() - param.dest));
}
}
t->write_bytes_helper(param.dest, size, saved_data.data());
saved_data.erase(saved_data.begin(), saved_data.begin() + size);
}
}
ASSERT(t, saved_data.empty());
// Step 3: record all output memory areas
for (size_t i = 0; i < param_list.size(); ++i) {
auto& param = param_list[i];
size_t size = actual_sizes[i];
if (param.mode != IN) {
t->record_remote(param.dest, size);
}
}
}
if (should_emulate_result) {
Registers r = t->regs();
r.set_syscall_result(emulated_result);
t->set_regs(r);
}
for (auto& action : after_syscall_actions) {
action(t);
}
}
void TaskSyscallState::abort_syscall_results() {
ASSERT(t, preparation_done);
if (scratch_enabled) {
Registers r = t->regs();
// restore modified in-memory pointers and registers
for (size_t i = 0; i < param_list.size(); ++i) {
auto& param = param_list[i];
if (param.ptr_in_reg) {
r.set_arg(param.ptr_in_reg, param.dest.as_int());
}
if (!param.ptr_in_memory.is_null()) {
set_remote_ptr(t, param.ptr_in_memory, param.dest);
}
}
t->set_regs(r);
} else {
for (auto& param : param_list) {
if (param.mutator) {
size_t size = param.num_bytes.incoming_size;
ASSERT(t, saved_data.size() >= size);
t->write_bytes_helper(param.dest, size, saved_data.data());
saved_data.erase(saved_data.begin(), saved_data.begin() + size);
}
}
}
}
template <typename Arch>
static void prepare_recvmsg(RecordTask* t, TaskSyscallState& syscall_state,
remote_ptr<typename Arch::msghdr> msgp,
const ParamSize& io_size) {
auto namelen_ptr = REMOTE_PTR_FIELD(msgp, msg_namelen);
syscall_state.mem_ptr_parameter(
REMOTE_PTR_FIELD(msgp, msg_name),
ParamSize::from_initialized_mem(t, namelen_ptr));
auto msg = t->read_mem(msgp);
remote_ptr<void> iovecsp_void = syscall_state.mem_ptr_parameter(
REMOTE_PTR_FIELD(msgp, msg_iov),
sizeof(typename Arch::iovec) * msg.msg_iovlen, IN);
auto iovecsp = iovecsp_void.cast<typename Arch::iovec>();
auto iovecs = t->read_mem(iovecsp, msg.msg_iovlen);
for (size_t i = 0; i < msg.msg_iovlen; ++i) {
syscall_state.mem_ptr_parameter(REMOTE_PTR_FIELD(iovecsp + i, iov_base),
io_size.limit_size(iovecs[i].iov_len));
}
auto controllen_ptr = REMOTE_PTR_FIELD(msgp, msg_controllen);
syscall_state.mem_ptr_parameter(
REMOTE_PTR_FIELD(msgp, msg_control),
ParamSize::from_initialized_mem(t, controllen_ptr));
}
template <typename Arch>
static void prepare_recvmmsg(RecordTask* t, TaskSyscallState& syscall_state,
remote_ptr<typename Arch::mmsghdr> mmsgp,
unsigned int vlen) {
for (unsigned int i = 0; i < vlen; ++i) {
auto msgp = mmsgp + i;
prepare_recvmsg<Arch>(t, syscall_state, REMOTE_PTR_FIELD(msgp, msg_hdr),
ParamSize::from_mem(REMOTE_PTR_FIELD(msgp, msg_len)));
}
}
static bool block_sock_opt(int level, int optname,
TaskSyscallState& syscall_state) {
switch (level) {
case SOL_PACKET:
switch (optname) {
case PACKET_RX_RING:
case PACKET_TX_RING:
syscall_state.emulate_result(-ENOPROTOOPT);
return true;
}
break;
case SOL_NETLINK:
switch (optname) {
case NETLINK_RX_RING:
case NETLINK_TX_RING:
syscall_state.emulate_result(-ENOPROTOOPT);
return true;
}
break;
}
return false;
}
template <typename Arch>
static Switchable prepare_setsockopt(RecordTask* t,
TaskSyscallState& syscall_state,
typename Arch::setsockopt_args& args) {
if (block_sock_opt(args.level, args.optname, syscall_state)) {
Registers r = t->regs();
r.set_arg1(-1);
t->set_regs(r);