-
Notifications
You must be signed in to change notification settings - Fork 563
/
syscallbuf.c
2751 lines (2416 loc) · 89.3 KB
/
syscallbuf.c
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; -*- */
#define RR_IMPLEMENT_PRELOAD
#ifndef _GNU_SOURCE
#define _GNU_SOURCE 1
#endif
#include "syscallbuf.h"
/**
* Buffer syscalls, so that rr can process the entire buffer with one
* trap instead of a trap per call.
*
* This file is compiled into a dso that's PRELOADed in recorded
* applications. The dso replaces libc syscall wrappers with our own
* implementation that saves nondetermistic outparams in a fixed-size
* buffer. When the buffer is full or the recorded application
* invokes an un-buffered syscall or receives a signal, we trap to rr
* and it records the state of the buffer.
*
* During replay, rr simply refills the buffer with the recorded data
* when it reaches the "flush-buffer" events that were recorded. Then
* rr emulates each buffered syscall, and the code here restores the
* client data from the refilled buffer.
*
* The crux of the implementation here is to selectively ptrace-trap
* syscalls. The normal (un-buffered) syscalls generate a ptrace
* trap, and the buffered syscalls trap directly to the kernel. This
* is implemented with a seccomp-bpf which examines the syscall and
* decides how to handle it (see seccomp-bpf.h and Task::spawn).
*
* Because this code runs in the tracee's address space and overrides
* system calls, the code is rather delicate. The following rules
* must be followed
*
* o No rr headers (other than seccomp-bpf.h and rr.h) may be included
* o All syscalls invoked by this code must be called directly, not
* through libc wrappers (which this file may itself indirectly override)
*
* The wrapper functions are named sys_xxxx. Each wrapper normally makes one
* untraced syscall or one traced syscall of the same type, but there are
* exceptions. For example sys_read can make a number of untraced syscalls
* instead of a single untraced syscall. A critical rule is that any traced
* or MAY_BLOCK untraced syscall *must* be the last syscall performed by the
* wrapper.
*/
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <link.h>
#include <linux/futex.h>
#include <linux/net.h>
#include <linux/perf_event.h>
#include <poll.h>
#include <pthread.h>
#include <signal.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/epoll.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/resource.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/un.h>
#include <syscall.h>
#include <sysexits.h>
#include <time.h>
#include <unistd.h>
#include "preload_interface.h"
#include "rr/rr.h"
#ifndef BTRFS_IOCTL_MAGIC
#define BTRFS_IOCTL_MAGIC 0x94
#endif
#ifndef BTRFS_IOC_CLONE_RANGE
struct btrfs_ioctl_clone_range_args {
int64_t src_fd;
uint64_t src_offset;
uint64_t src_length;
uint64_t dest_offset;
};
#define BTRFS_IOC_CLONE_RANGE \
_IOW(BTRFS_IOCTL_MAGIC, 13, struct btrfs_ioctl_clone_range_args)
#endif
#ifndef MADV_FREE
#define MADV_FREE 8
#endif
/* NB: don't include any other local headers here. */
#ifdef memcpy
#undef memcpy
#endif
#define memcpy you_must_use_local_memcpy
#ifdef syscall
#undef syscall
#endif
#define syscall you_must_use_traced_syscall
/* Nonzero when syscall buffering is enabled. */
static int buffer_enabled;
/* Nonzero after process-global state has been initialized. */
static int process_inited;
RR_HIDDEN struct preload_globals globals;
RR_HIDDEN char impose_syscall_delay;
RR_HIDDEN char impose_spurious_desched;
static struct preload_thread_locals* const thread_locals =
(struct preload_thread_locals*)PRELOAD_THREAD_LOCALS_ADDR;
/**
* Return a pointer to the buffer header, which happens to occupy the
* initial bytes in the mapped region.
*/
static struct syscallbuf_hdr* buffer_hdr(void) {
return (struct syscallbuf_hdr*)thread_locals->buffer;
}
/**
* This is for testing purposes only.
*/
void* syscallbuf_ptr(void) {
return thread_locals->buffer;
}
/**
* Return a pointer to the byte just after the last valid syscall record in
* the buffer.
*/
static uint8_t* buffer_last(void) {
return (uint8_t*)next_record(buffer_hdr());
}
/**
* Return a pointer to the byte just after the very end of the mapped
* region.
*/
static uint8_t* buffer_end(void) {
return thread_locals->buffer + thread_locals->buffer_size;
}
/**
* Same as libc memcpy(), but usable within syscallbuf transaction
* critical sections.
*/
static void local_memcpy(void* dest, const void* source, int n) {
#if defined(__i386__) || defined(__x86_64__)
/* On modern x86-ish CPUs rep movsb is fast, usually able to move
* 64 bytes at a time.
*/
__asm__ __volatile__("rep movsb\n\t"
: "+S"(source), "+D"(dest), "+c"(n)
:
: "cc", "memory");
#else
#error Unknown architecture
#endif
}
/**
* Xorshift* RNG
*/
static int64_t local_random(void) {
uint64_t x = globals.random_seed;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
globals.random_seed = x;
return x * 0x2545F4914F6CDD1D;
}
/* The following are wrappers for the syscalls invoked by this library
* itself. These syscalls will generate ptrace traps.
* stack_param_1 and stack_param_2 are pushed onto the stack just before
* the syscall, for SYS_rrcall_notify_syscall_hook_exit which takes stack
* parameters as well as register parameters.
* syscall_instruction is the actual syscall invocation instruction
* (a function which we call with the registers set up appropriately).
*/
extern RR_HIDDEN long _raw_syscall(int syscallno, long a0, long a1, long a2,
long a3, long a4, long a5,
void* syscall_instruction,
long stack_param_1, long stack_param_2);
static int privileged_traced_syscall(int syscallno, long a0, long a1, long a2,
long a3, long a4, long a5) {
return _raw_syscall(syscallno, a0, a1, a2, a3, a4, a5,
RR_PAGE_SYSCALL_PRIVILEGED_TRACED, 0, 0);
}
#define privileged_traced_syscall6(no, a0, a1, a2, a3, a4, a5) \
privileged_traced_syscall(no, (uintptr_t)a0, (uintptr_t)a1, (uintptr_t)a2, \
(uintptr_t)a3, (uintptr_t)a4, (uintptr_t)a5)
#define privileged_traced_syscall5(no, a0, a1, a2, a3, a4) \
privileged_traced_syscall6(no, a0, a1, a2, a3, a4, 0)
#define privileged_traced_syscall4(no, a0, a1, a2, a3) \
privileged_traced_syscall5(no, a0, a1, a2, a3, 0)
#define privileged_traced_syscall3(no, a0, a1, a2) \
privileged_traced_syscall4(no, a0, a1, a2, 0)
#define privileged_traced_syscall2(no, a0, a1) \
privileged_traced_syscall3(no, a0, a1, 0)
#define privileged_traced_syscall1(no, a0) privileged_traced_syscall2(no, a0, 0)
#define privileged_traced_syscall0(no) privileged_traced_syscall1(no, 0)
/**
* Make a raw traced syscall using the params in |call|.
*/
static long traced_raw_syscall(const struct syscall_info* call) {
/* FIXME: pass |call| to avoid pushing these on the stack
* again. */
return _raw_syscall(call->no, call->args[0], call->args[1], call->args[2],
call->args[3], call->args[4], call->args[5],
RR_PAGE_SYSCALL_TRACED, 0, 0);
}
#if defined(SYS_fcntl64)
#define RR_FCNTL_SYSCALL SYS_fcntl64
#else
#define RR_FCNTL_SYSCALL SYS_fcntl
#endif
static int privileged_traced_fcntl(int fd, int cmd, ...) {
va_list ap;
void* arg;
va_start(ap, cmd);
arg = va_arg(ap, void*);
va_end(ap);
return privileged_traced_syscall3(RR_FCNTL_SYSCALL, fd, cmd, arg);
}
static pid_t privileged_traced_getpid(void) {
return privileged_traced_syscall0(SYS_getpid);
}
static pid_t privileged_traced_gettid(void) {
return privileged_traced_syscall0(SYS_gettid);
}
static int privileged_traced_perf_event_open(struct perf_event_attr* attr,
pid_t pid, int cpu, int group_fd,
unsigned long flags) {
return privileged_traced_syscall5(SYS_perf_event_open, attr, pid, cpu,
group_fd, flags);
}
static int privileged_traced_raise(int sig) {
return privileged_traced_syscall2(SYS_kill, privileged_traced_getpid(), sig);
}
static ssize_t privileged_traced_write(int fd, const void* buf, size_t count) {
return privileged_traced_syscall3(SYS_write, fd, buf, count);
}
static void logmsg(const char* msg) {
privileged_traced_write(STDERR_FILENO, msg, rrstrlen(msg));
}
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
#ifndef NDEBUG
#define assert(cond) \
do { \
if (!(cond)) { \
logmsg(__FILE__ ":" STR(__LINE__) ": Assertion `" #cond "' failed.\n"); \
privileged_traced_raise(SIGABRT); \
} \
} while (0)
#else
#define assert(cond) \
do { \
__attribute__((unused)) size_t s = sizeof(cond); \
} while (0)
#endif
#define fatal(msg) \
do { \
logmsg(__FILE__ ":" STR(__LINE__) ": Fatal error: " #msg "\n"); \
privileged_traced_raise(SIGABRT); \
} while (0)
/**
* Unlike |traced_syscall()|, this helper is implicitly "raw" (returns
* the direct kernel return value), because the syscall hooks have to
* save that raw return value.
* This is only called from syscall wrappers that are doing a proper
* buffered syscall.
*/
static long untraced_syscall_base(int syscallno, long a0, long a1, long a2,
long a3, long a4, long a5,
void* syscall_instruction) {
struct syscallbuf_record* rec = (struct syscallbuf_record*)buffer_last();
/* Ensure tools analyzing the replay can find the pending syscall result */
thread_locals->pending_untraced_syscall_result = &rec->ret;
long ret = _raw_syscall(syscallno, a0, a1, a2, a3, a4, a5,
syscall_instruction, 0, 0);
unsigned char tmp_in_replay = globals.in_replay;
/* During replay, return the result that's already in the buffer, instead
of what our "syscall" returned. */
#if defined(__i386__) || defined(__x86_64__)
/* On entry, during recording %eax/%rax are whatever the kernel returned
* but during replay they may be invalid (e.g. 0). During replay, reload
* %eax/%rax from |rec->ret|. At the end of this sequence all registers
* will match between recording and replay. We clobber the temporary
* in_replay register, and the condition codes, to ensure this.
* This all assumes the compiler doesn't create unnecessary temporaries
* holding values like |ret|. Inspection of generated code shows it doesn't.
*/
__asm__("test %1,%1\n\t"
"cmovne %2,%0\n\t"
"xor %1,%1\n\t"
: "+a"(ret), "+c"(tmp_in_replay)
: "m"(rec->ret)
: "cc");
#else
#error Unknown architecture
#endif
return ret;
}
#define untraced_syscall6(no, a0, a1, a2, a3, a4, a5) \
untraced_syscall_base(no, (uintptr_t)a0, (uintptr_t)a1, (uintptr_t)a2, \
(uintptr_t)a3, (uintptr_t)a4, (uintptr_t)a5, \
RR_PAGE_SYSCALL_UNTRACED_RECORDING_ONLY)
#define untraced_syscall5(no, a0, a1, a2, a3, a4) \
untraced_syscall6(no, a0, a1, a2, a3, a4, 0)
#define untraced_syscall4(no, a0, a1, a2, a3) \
untraced_syscall5(no, a0, a1, a2, a3, 0)
#define untraced_syscall3(no, a0, a1, a2) untraced_syscall4(no, a0, a1, a2, 0)
#define untraced_syscall2(no, a0, a1) untraced_syscall3(no, a0, a1, 0)
#define untraced_syscall1(no, a0) untraced_syscall2(no, a0, 0)
#define untraced_syscall0(no) untraced_syscall1(no, 0)
#define untraced_replayed_syscall6(no, a0, a1, a2, a3, a4, a5) \
untraced_syscall_base(no, (uintptr_t)a0, (uintptr_t)a1, (uintptr_t)a2, \
(uintptr_t)a3, (uintptr_t)a4, (uintptr_t)a5, \
RR_PAGE_SYSCALL_UNTRACED)
#define untraced_replayed_syscall5(no, a0, a1, a2, a3, a4) \
untraced_replayed_syscall6(no, a0, a1, a2, a3, a4, 0)
#define untraced_replayed_syscall4(no, a0, a1, a2, a3) \
untraced_replayed_syscall5(no, a0, a1, a2, a3, 0)
#define untraced_replayed_syscall3(no, a0, a1, a2) \
untraced_replayed_syscall4(no, a0, a1, a2, 0)
#define untraced_replayed_syscall2(no, a0, a1) \
untraced_replayed_syscall3(no, a0, a1, 0)
#define untraced_replayed_syscall1(no, a0) untraced_replayed_syscall2(no, a0, 0)
#define untraced_replayed_syscall0(no) untraced_replayed_syscall1(no, 0)
#define privileged_untraced_syscall6(no, a0, a1, a2, a3, a4, a5) \
_raw_syscall(no, (uintptr_t)a0, (uintptr_t)a1, (uintptr_t)a2, (uintptr_t)a3, \
(uintptr_t)a4, (uintptr_t)a5, \
RR_PAGE_SYSCALL_PRIVILEGED_UNTRACED_RECORDING_ONLY, 0, 0)
#define privileged_untraced_syscall5(no, a0, a1, a2, a3, a4) \
privileged_untraced_syscall6(no, a0, a1, a2, a3, a4, 0)
#define privileged_untraced_syscall4(no, a0, a1, a2, a3) \
privileged_untraced_syscall5(no, a0, a1, a2, a3, 0)
#define privileged_untraced_syscall3(no, a0, a1, a2) \
privileged_untraced_syscall4(no, a0, a1, a2, 0)
#define privileged_untraced_syscall2(no, a0, a1) \
privileged_untraced_syscall3(no, a0, a1, 0)
#define privileged_untraced_syscall1(no, a0) \
privileged_untraced_syscall2(no, a0, 0)
#define privileged_untraced_syscall0(no) privileged_untraced_syscall1(no, 0)
#define replay_only_syscall6(no, a0, a1, a2, a3, a4, a5) \
_raw_syscall(no, (uintptr_t)a0, (uintptr_t)a1, (uintptr_t)a2, (uintptr_t)a3, \
(uintptr_t)a4, (uintptr_t)a5, \
RR_PAGE_SYSCALL_PRIVILEGED_UNTRACED_REPLAY_ONLY, 0, 0)
#define replay_only_syscall5(no, a0, a1, a2, a3, a4) \
replay_only_syscall6(no, a0, a1, a2, a3, a4, 0)
#define replay_only_syscall4(no, a0, a1, a2, a3) \
replay_only_syscall5(no, a0, a1, a2, a3, 0)
#define replay_only_syscall3(no, a0, a1, a2) \
replay_only_syscall4(no, a0, a1, a2, 0)
#define replay_only_syscall2(no, a0, a1) replay_only_syscall3(no, a0, a1, 0)
#define replay_only_syscall1(no, a0) replay_only_syscall2(no, a0, 0)
#define replay_only_syscall0(no) replay_only_syscall1(no, 0)
static int privileged_untraced_close(int fd) {
return privileged_untraced_syscall1(SYS_close, fd);
}
static int privileged_untraced_fcntl(int fd, int cmd, ...) {
va_list ap;
void* arg;
va_start(ap, cmd);
arg = va_arg(ap, void*);
va_end(ap);
return privileged_untraced_syscall3(RR_FCNTL_SYSCALL, fd, cmd, arg);
}
/**
* Do what's necessary to set up buffers for the caller.
* |untraced_syscall_ip| lets rr know where our untraced syscalls will
* originate from. |addr| is the address of the control socket the
* child expects to connect to. |msg| is a pre-prepared IPC that can
* be used to share fds; |fdptr| is a pointer to the control-message
* data buffer where the fd number being shared will be stored.
* |args_vec| provides the tracer with preallocated space to make
* socketcall syscalls.
*
* Return a pointer to the syscallbuf (with an initialized header
* including the available size), if syscallbuf is enabled.
*
* This is a "magic" syscall implemented by rr.
*/
static void rrcall_init_buffers(struct rrcall_init_buffers_params* args) {
privileged_traced_syscall1(SYS_rrcall_init_buffers, args);
}
/**
* Return a counter that generates a signal targeted at this task
* every time the task is descheduled |nr_descheds| times.
*/
static int open_desched_event_counter(size_t nr_descheds, pid_t tid) {
struct perf_event_attr attr;
int tmp_fd, fd;
struct f_owner_ex own;
memset(&attr, 0, sizeof(attr));
attr.size = sizeof(attr);
attr.type = PERF_TYPE_SOFTWARE;
attr.config = PERF_COUNT_SW_CONTEXT_SWITCHES;
attr.disabled = 1;
attr.sample_period = nr_descheds;
tmp_fd = privileged_traced_perf_event_open(&attr, 0 /*self*/, -1 /*any cpu*/,
-1, 0);
if (0 > tmp_fd) {
fatal("Failed to perf_event_open");
}
fd = privileged_traced_fcntl(tmp_fd, F_DUPFD_CLOEXEC,
RR_DESCHED_EVENT_FLOOR_FD);
if (0 > fd) {
fatal("Failed to dup desched fd");
}
if (privileged_untraced_close(tmp_fd)) {
fatal("Failed to close tmp_fd");
}
if (privileged_untraced_fcntl(fd, F_SETFL, O_ASYNC)) {
fatal("Failed to fcntl(O_ASYNC) the desched counter");
}
own.type = F_OWNER_TID;
own.pid = tid;
if (privileged_untraced_fcntl(fd, F_SETOWN_EX, &own)) {
fatal("Failed to fcntl(SETOWN_EX) the desched counter to this");
}
if (privileged_untraced_fcntl(fd, F_SETSIG, SYSCALLBUF_DESCHED_SIGNAL)) {
fatal("Failed to fcntl(SETSIG) the desched counter");
}
return fd;
}
/**
* Initialize thread-local buffering state, if enabled and not already
* initialized.
*/
static void init_thread(void) {
struct rrcall_init_buffers_params args;
assert(process_inited);
if (thread_locals->thread_inited) {
return;
}
thread_locals->thread_inited = 1;
/* Do not do any syscall buffering in a DiversionSession! */
if (!buffer_enabled || globals.in_diversion) {
return;
}
/* NB: we want this setup emulated during replay. */
thread_locals->desched_counter_fd =
open_desched_event_counter(1, privileged_traced_gettid());
args.desched_counter_fd = thread_locals->desched_counter_fd;
/* Trap to rr: let the magic begin!
*
* If the desched signal is currently blocked, then the tracer
* will clear our TCB guard and we won't be able to buffer
* syscalls. But the tracee will set the guard when (or if)
* the signal is unblocked. */
rrcall_init_buffers(&args);
thread_locals->cloned_file_data_fd = args.cloned_file_data_fd;
/* rr initializes the buffer header. */
thread_locals->buffer = args.syscallbuf_ptr;
thread_locals->buffer_size = args.syscallbuf_size;
thread_locals->scratch_buf = args.scratch_buf;
thread_locals->usable_scratch_size = args.usable_scratch_size;
}
extern char _breakpoint_table_entry_start;
extern char _breakpoint_table_entry_end;
/**
* Initialize process-global buffering state, if enabled.
* NOTE: constructors go into a special section by default so this won't
* be counted as syscall-buffering code!
*/
static void __attribute__((constructor)) init_process(void) {
struct rrcall_init_preload_params params;
extern char _syscallbuf_final_exit_instruction;
extern char _syscallbuf_code_start;
extern char _syscallbuf_code_end;
#if defined(__i386__)
extern RR_HIDDEN void __morestack(void);
extern RR_HIDDEN void _syscall_hook_trampoline_3d_01_f0_ff_ff(void);
extern RR_HIDDEN void _syscall_hook_trampoline_90_90_90(void);
struct syscall_patch_hook syscall_patch_hooks[] = {
/* pthread_cond_broadcast has 'int 80' followed by
* cmp $-4095,%eax (in glibc-2.18-16.fc20.i686) */
{ 0,
5,
{ 0x3d, 0x01, 0xf0, 0xff, 0xff },
(uintptr_t)_syscall_hook_trampoline_3d_01_f0_ff_ff },
/* Our vdso syscall patch has 'int 80' followed by onp; nop; nop */
{ 0, 3, { 0x90, 0x90, 0x90 }, (uintptr_t)_syscall_hook_trampoline_90_90_90 }
};
extern char _get_pc_thunks_start;
extern char _get_pc_thunks_end;
#elif defined(__x86_64__)
extern RR_HIDDEN void _syscall_hook_trampoline_48_3d_01_f0_ff_ff(void);
extern RR_HIDDEN void _syscall_hook_trampoline_48_3d_00_f0_ff_ff(void);
extern RR_HIDDEN void _syscall_hook_trampoline_48_8b_3c_24(void);
extern RR_HIDDEN void _syscall_hook_trampoline_5a_5e_c3(void);
extern RR_HIDDEN void _syscall_hook_trampoline_89_c2_f7_da(void);
extern RR_HIDDEN void _syscall_hook_trampoline_90_90_90(void);
extern RR_HIDDEN void _syscall_hook_trampoline_ba_01_00_00_00(void);
extern RR_HIDDEN void _syscall_hook_trampoline_89_c1_31_d2(void);
extern RR_HIDDEN void _syscall_hook_trampoline_c3_0f_1f_84_00_00_00_00_00(
void);
struct syscall_patch_hook syscall_patch_hooks[] = {
/* Many glibc syscall wrappers (e.g. read) have 'syscall' followed
* by
* cmp $-4095,%rax (in glibc-2.18-16.fc20.x86_64) */
{ 0,
6,
{ 0x48, 0x3d, 0x01, 0xf0, 0xff, 0xff },
(uintptr_t)_syscall_hook_trampoline_48_3d_01_f0_ff_ff },
/* Many glibc syscall wrappers (e.g. __libc_recv) have 'syscall'
* followed by
* cmp $-4096,%rax (in glibc-2.18-16.fc20.x86_64) */
{ 0,
6,
{ 0x48, 0x3d, 0x00, 0xf0, 0xff, 0xff },
(uintptr_t)_syscall_hook_trampoline_48_3d_00_f0_ff_ff },
/* Many glibc syscall wrappers (e.g. read) have 'syscall' followed
* by
* mov (%rsp),%rdi (in glibc-2.18-16.fc20.x86_64) */
{ 0,
4,
{ 0x48, 0x8b, 0x3c, 0x24 },
(uintptr_t)_syscall_hook_trampoline_48_8b_3c_24 },
/* __lll_unlock_wake has 'syscall' followed by
* pop %rdx; pop %rsi; ret */
{ 1,
3,
{ 0x5a, 0x5e, 0xc3 },
(uintptr_t)_syscall_hook_trampoline_5a_5e_c3 },
/* posix_fadvise64 has 'syscall' followed by
* mov %eax,%edx; neg %edx (in glibc-2.22-11.fc23.x86_64) */
{ 1,
4,
{ 0x89, 0xc2, 0xf7, 0xda },
(uintptr_t)_syscall_hook_trampoline_89_c2_f7_da },
/* Our VDSO vsyscall patches have 'syscall' followed by "nop; nop;
nop" */
{ 1,
3,
{ 0x90, 0x90, 0x90 },
(uintptr_t)_syscall_hook_trampoline_90_90_90 },
/* glibc-2.22-17.fc23.x86_64 has 'syscall' followed by 'mov $1,%rdx'
* in
* pthread_barrier_wait.
*/
{ 0,
5,
{ 0xba, 0x01, 0x00, 0x00, 0x00 },
(uintptr_t)_syscall_hook_trampoline_ba_01_00_00_00 },
/* pthread_sigmask has 'syscall' followed by 'mov %eax,%ecx; xor
%edx,%edx' */
{ 1,
4,
{ 0x89, 0xc1, 0x31, 0xd2 },
(uintptr_t)_syscall_hook_trampoline_89_c1_31_d2 },
/* getpid has 'syscall' followed by 'retq; nopl 0x0(%rax,%rax,1) */
{ 1,
9,
{ 0xc3, 0x0f, 0x1f, 0x84, 0x00, 0x00, 0x00, 0x00, 0x00 },
(uintptr_t)_syscall_hook_trampoline_c3_0f_1f_84_00_00_00_00_00 },
};
#else
#error Unknown architecture
#endif
assert(sizeof(struct preload_thread_locals) <= PRELOAD_THREAD_LOCALS_SIZE);
if (process_inited) {
return;
}
buffer_enabled = !!getenv(SYSCALLBUF_ENABLED_ENV_VAR);
params.syscallbuf_enabled = buffer_enabled;
#ifdef __i386__
params.syscallhook_vsyscall_entry = (void*)__morestack;
params.get_pc_thunks_start = &_get_pc_thunks_start;
params.get_pc_thunks_end = &_get_pc_thunks_end;
#else
params.syscallhook_vsyscall_entry = NULL;
params.get_pc_thunks_start = NULL;
params.get_pc_thunks_end = NULL;
#endif
params.syscallbuf_code_start = &_syscallbuf_code_start;
params.syscallbuf_code_end = &_syscallbuf_code_end;
params.syscallbuf_final_exit_instruction =
&_syscallbuf_final_exit_instruction;
params.syscall_patch_hook_count =
sizeof(syscall_patch_hooks) / sizeof(syscall_patch_hooks[0]);
params.syscall_patch_hooks = syscall_patch_hooks;
params.globals = &globals;
params.breakpoint_table = &_breakpoint_table_entry_start;
params.breakpoint_table_entry_size =
&_breakpoint_table_entry_end - &_breakpoint_table_entry_start;
privileged_traced_syscall1(SYS_rrcall_init_preload, ¶ms);
process_inited = 1;
}
/**
* syscall hooks start here.
*
* !!! NBB !!!: from here on, all code that executes within the
* critical sections of transactions *MUST KEEP $ip IN THE SYSCALLBUF
* CODE*. That means no calls into libc, even for innocent-looking
* functions like |memcpy()|.
*
* How syscall hooks operate:
*
* 1. The rr tracer monkey-patches __kernel_vsyscall() to jump to
* _syscall_hook_trampoline() above.
* 2. When a call is made to __kernel_vsyscall(), it jumps to
* _syscall_hook_trampoline(), where the syscall params are
* packaged up into a call to syscall_hook() below.
* 3. syscall_hook() dispatches to a syscall processor function.
* 4. The syscall processor prepares a new record in the buffer. See
* struct syscallbuf_record for record fields. If the buffer runs
* out of space, the processor function aborts and makes a traced
* syscall, trapping to rr. rr then flushes the buffer. Records
* are directly saved to trace, and a buffer-flush event is
* recorded without execution info because it's a synthetic event.
* 5. Then, the syscall processor redirects all potential output
* for the syscall to the record (and corrects the overall size of
* the record while it does so).
* 6. The syscall is invoked through a asm helper that does *not*
* ptrace-trap to rr.
* 7. The syscall output, written on the buffer, is copied to the
* original pointers provided by the user. Take notice that this
* part saves us the injection of the data on replay, as we only
* need to push the data to the buffer and the wrapper code will
* copy it to the user address for us.
* 8. The return value and overall size are saved to the record.
*/
/**
* Call this and save the result at the start of every system call we
* want to buffer. The result is a pointer into the record space. You
* can add to this pointer to allocate space in the trace record.
* However, do not read or write through this pointer until
* start_commit_syscall() has been called. And you *must* call
* start_commit_syscall() after this is called, otherwise buffering
* state will be inconsistent between syscalls.
*
* See |sys_clock_gettime()| for a simple example of how this helper
* should be used to buffer outparam data.
*/
static void* prep_syscall(void) {
/* We don't need to worry about a race between testing
* |locked| and setting it here. rr recording is responsible
* for ensuring signals are not delivered during
* syscall_buffer prologue and epilogue code.
*
* XXX except for synchronous signals generated in the syscall
* buffer code, while reading/writing user pointers */
buffer_hdr()->locked |= SYSCALLBUF_LOCKED_TRACEE;
/* "Allocate" space for a new syscall record, not including
* syscall outparam data. */
return buffer_last() + sizeof(struct syscallbuf_record);
}
static int is_bufferable_fd(int fd) {
return fd < 0 || (fd < SYSCALLBUF_FDS_DISABLED_SIZE &&
!globals.syscallbuf_fds_disabled[fd]);
}
/**
* Like prep_syscall, but preps a syscall to operate on a particular fd. If
* syscallbuf is disabled for this fd, returns NULL (in which case
* start_commit_syscall will abort cleanly and a traced syscall will be used).
* Allow negative fds to pass through; they'll either trigger an error or
* receive special treatment by the kernel (e.g. AT_FDCWD).
*/
static void* prep_syscall_for_fd(int fd) {
if (!is_bufferable_fd(fd)) {
return NULL;
}
return prep_syscall();
}
static void arm_desched_event(void) {
/* Don't trace the ioctl; doing so would trigger a flushing
* ptrace trap, which is exactly what this code is trying to
* avoid! :) Although we don't allocate extra space for these
* ioctl's, we do record that we called them; the replayer
* knows how to skip over them. */
if ((int)privileged_untraced_syscall3(SYS_ioctl,
thread_locals->desched_counter_fd,
PERF_EVENT_IOC_ENABLE, 0)) {
fatal("Failed to ENABLE counter");
}
}
static void disarm_desched_event(void) {
/* See above. */
if ((int)privileged_untraced_syscall3(SYS_ioctl,
thread_locals->desched_counter_fd,
PERF_EVENT_IOC_DISABLE, 0)) {
fatal("Failed to DISABLE counter");
}
}
/**
* Return 1 if it's ok to proceed with buffering this system call.
* Return 0 if we should trace the system call.
* This must be checked before proceeding with the buffered system call.
*/
/* (Negative numbers so as to not be valid syscall numbers, in case
* the |int| arguments below are passed in the wrong order.) */
enum { MAY_BLOCK = -1, WONT_BLOCK = -2 };
static int start_commit_buffered_syscall(int syscallno, void* record_end,
int blockness) {
void* record_start;
void* stored_end;
struct syscallbuf_record* rec;
if (!thread_locals->buffer) {
return 0;
}
record_start = buffer_last();
stored_end = record_start + stored_record_size(record_end - record_start);
rec = record_start;
if (stored_end < record_start + sizeof(struct syscallbuf_record)) {
/* Either a catastrophic buffer overflow or
* we failed to lock the buffer. Just bail out. */
return 0;
}
if (stored_end > (void*)buffer_end() - sizeof(struct syscallbuf_record)) {
/* Buffer overflow.
* Unlock the buffer and then execute the system call
* with a trap to rr. Note that we reserve enough
* space in the buffer for the next prep_syscall(). */
buffer_hdr()->locked &= ~SYSCALLBUF_LOCKED_TRACEE;
return 0;
}
/* Store this breadcrumb so that the tracer can find out what
* syscall we're executing if our registers are in a weird
* state. If we end up aborting this syscall, no worry, this
* will just be overwritten later.
*
* NBB: this *MUST* be set before the desched event is
* armed. */
rec->syscallno = syscallno;
rec->desched = MAY_BLOCK == blockness;
rec->size = record_end - record_start;
if (rec->desched) {
pid_t pid = 0;
pid_t tid = 0;
uid_t uid = 0;
if (impose_spurious_desched) {
pid = privileged_untraced_syscall0(SYS_getpid);
tid = privileged_untraced_syscall0(SYS_gettid);
uid = privileged_untraced_syscall0(SYS_getuid);
}
/* NB: the ordering of the next two statements is
* important.
*
* We set this flag to notify rr that it should pay
* attention to desched signals pending for this task.
* We have to set it *before* we arm the notification
* because we can't set the flag atomically with
* arming the event (too bad there's no ioctl() for
* querying the event enabled-ness state). That's
* important because if the notification is armed,
* then rr must be confident that when it disarms the
* event, the tracee is at an execution point that
* *must not* need the desched event.
*
* If we were to set the flag non-atomically after the
* event was armed, then if a desched signal was
* delivered right at the instruction that set the
* flag, rr wouldn't know that it needed to advance
* the tracee to the untraced syscall entry point.
* (And if rr didn't do /that/, then the syscall might
* block without rr knowing it, and the recording
* session would deadlock.) */
buffer_hdr()->desched_signal_may_be_relevant = 1;
arm_desched_event();
if (impose_spurious_desched) {
siginfo_t si;
si.si_code = POLL_IN;
si.si_fd = thread_locals->desched_counter_fd;
si.si_pid = pid;
si.si_uid = uid;
privileged_untraced_syscall4(SYS_rt_tgsigqueueinfo, pid, tid, SIGPWR,
&si);
}
}
return 1;
}
/**
* Commit the record for a buffered system call. record_end can be
* adjusted downward from what was passed to
* start_commit_buffered_syscall, if not all of the initially
* requested space is needed. The result of this function should be
* returned directly by the kernel syscall hook.
*/
static long commit_raw_syscall(int syscallno, void* record_end, long ret) {
void* record_start = buffer_last();
struct syscallbuf_record* rec = record_start;
struct syscallbuf_hdr* hdr = buffer_hdr();
void (*breakpoint_function)(void) = 0;
assert(record_end >= record_start);
rec->size = record_end - record_start;
assert(buffer_hdr()->locked);
/* NB: the ordering of this statement with the
* |disarm_desched_event()| call below is important.
*
* We clear this flag to notify rr that the may-block syscall
* has finished, so there's no danger of blocking anymore.
* (And thus the desched signal is no longer relevant.) We
* have to clear this *before* disarming the event, because if
* rr sees the flag set, it has to PTRACE_SYSCALL this task to
* ensure it reaches an execution point where the desched
* signal is no longer relevant. We have to use the ioctl()
* that disarms the event as a safe "backstop" that can be hit
* by the PTRACE_SYSCALL.
*
* If we were to clear the flag *after* disarming the event,
* and the signal arrived at the instruction that cleared the
* flag, and rr issued the PTRACE_SYSCALL, then this tracee
* could fly off to any unknown execution point, including an
* iloop. So the recording session could livelock. */
hdr->desched_signal_may_be_relevant = 0;
if (rec->syscallno != syscallno) {
fatal("Record syscall number mismatch");
}
if (hdr->abort_commit) {
/* We were descheduled in the middle of a may-block
* syscall, and it was recorded as a normal entry/exit
* pair. So don't record the syscall in the buffer or
* replay will go haywire. */
hdr->abort_commit = 0;
hdr->failed_during_preparation = 0;
/* Clear the return value that rr puts there during replay */
rec->ret = 0;
} else {
int breakpoint_entry_size =
&_breakpoint_table_entry_end - &_breakpoint_table_entry_start;
rec->ret = ret;
// Finish 'rec' first before updating num_rec_bytes, since
// rr might read the record anytime after this update.
hdr->num_rec_bytes += stored_record_size(rec->size);
breakpoint_function =
(void*)(&_breakpoint_table_entry_start +
(hdr->num_rec_bytes / 8) * breakpoint_entry_size);
}
if (rec->desched) {
disarm_desched_event();
}
/* NBB: for may-block syscalls that are descheduled, the
* tracer uses the previous ioctl() as a stable point to reset
* the record counter. Therefore nothing from here on in the
* current txn must touch the record counter (at least, must
* not assume it's unchanged). */
buffer_hdr()->locked &= ~SYSCALLBUF_LOCKED_TRACEE;
if (breakpoint_function) {
/* Call the breakpoint function corresponding to the record we just
* committed. This function just returns, but during replay it gives rr
* a chance to set a breakpoint for when a specific syscallbuf record
* has been processed.
*/
breakpoint_function();
}
return ret;
}
/**
* |ret_size| is the result of a syscall indicating how much data was returned
* in scratch buffer |buf2|; this function copies that data to |buf| and returns
* a pointer to the end of it. If there is no scratch buffer (|buf2| is NULL)
* just returns |ptr|.
*/
static void* copy_output_buffer(int ret_size, void* ptr, void* buf,
void* buf2) {
if (!buf2) {
return ptr;
}
if (ret_size <= 0 || buffer_hdr()->failed_during_preparation) {
return buf2;
}
local_memcpy(buf, buf2, ret_size);
return buf2 + ret_size;
}
/**
* Copy an input parameter to the syscallbuf where the kernel needs to
* read and write it. During replay, we do a no-op self-copy in the buffer
* so that the buffered data is not lost.
* This code is written in assembler to ensure that the registers that receive
* values differing between record and replay (%0, rsi/esi, and flags)
* are reset to values that are the same between record and replay immediately
* afterward. This guards against diverging register values leaking into
* later code.
* Use local_memcpy or plain assignment instead if the kernel is not going to
* overwrite the values.
*/
static void memcpy_input_parameter(void* buf, void* src, int size) {
#if defined(__i386__) || defined(__x86_64__)
unsigned char tmp_in_replay = globals.in_replay;
__asm__ __volatile__("test %0,%0\n\t"
"cmovne %1,%2\n\t"
"rep movsb\n\t"
"xor %0,%0\n\t"
"xor %2,%2\n\t"
: "+a"(tmp_in_replay), "+D"(buf), "+S"(src), "+c"(size)
:
: "cc", "memory");
#else
#error Unknown architecture
#endif
}
/**
* During recording, we copy *real to *buf.
* During replay, we copy *buf to *real.
* Behaves like memcpy_input_parameter in terms of hiding differences between
* recording and replay.
*/
static void copy_futex_int(uint32_t* buf, uint32_t* real) {
#if defined(__i386__) || defined(__x86_64__)
uint32_t tmp_in_replay = globals.in_replay;
__asm__ __volatile__("test %0,%0\n\t"
"mov %2,%0\n\t"
"cmovne %1,%0\n\t"
"mov %0,%1\n\t"
"mov %0,%2\n\t"
/* This instruction is just to clear flags */
"xor %0,%0\n\t"
: "+a"(tmp_in_replay)
: "m"(*buf), "m"(*real)
: "cc", "memory");
#else
#error Unknown architecture