-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfpvm.c
More file actions
2234 lines (1842 loc) · 62.7 KB
/
fpvm.c
File metadata and controls
2234 lines (1842 loc) · 62.7 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
/*
Part of FPVM
Preload that traps and emulates floating point instructions
that round or consume/produce a NAN
Copyright (c) 2018 Peter A. Dinda - see LICENSE
This code does the following:
- installs itself at load time of the target program
- adds hooks for fpe* functions - if any of these are used, the library
deactivates itself
- adds hook for signal installation (individual mode only)
so that it can get out of the way if the target program
establishes its own floating point exception handler
- removes itself at unload time of the target program
A core set of FP exeptions are used to drive the FPVM state machine.
When an exception occurs, control is handed to an emulator. When
the emulator returns, the instruction is skipped.
Concurrency:
- fork() - both parent and child are tracked. Child's FPE state is
cleared any previous abort in parent is inherited
- exec() - Tracking restarts (assuming the environment variables are
inherited) any previous abort is discarded
- pthread_create() - both parent and child are tracked. Child's FPE state
is cleared both have a log file. May not work on a pthread_cancel An abort in
any thread is shared by all the threads
*/
#define _GNU_SOURCE
#include <ctype.h>
#include <dlfcn.h>
#include <errno.h>
#include <fcntl.h>
#include <fenv.h>
#include <pthread.h>
#include <sched.h>
#include <signal.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ptrace.h>
#include <sys/reg.h>
#include <sys/syscall.h>
#include <sys/types.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <time.h>
#include <ucontext.h>
#include <unistd.h>
#include <math.h>
#include <sys/time.h>
#include <fpvm/decoder.h>
#include <fpvm/emulator.h>
#include <fpvm/fpvm_common.h>
#include <fpvm/gc.h>
#include <fpvm/util.h>
#include <fpvm/perf.h>
#include <fpvm/trace.h>
#include <fpvm/fpvm_fenv.h>
#include <fpvm/fpvm_math.h>
#include <fpvm/number_system.h>
#include <fpvm/fpvm_magic.h>
#include <fpvm/config.h>
// support for kernel module
#if CONFIG_TRAP_SHORT_CIRCUITING
#include <sys/ioctl.h>
#include "fpvm/fpvm_ioctl.h"
#endif
volatile static int inited = 0;
volatile static int aborted = 0; // set if the target is doing its own FPE processing
volatile static int exceptmask = FE_ALL_EXCEPT; // which C99 exceptions to handle, default all
volatile static int mxcsrmask_base =
0x3f; // which sse exceptions to handle, default all (using base zero)
#define MXCSR_FLAG_MASK (mxcsrmask_base << 0)
#define MXCSR_MASK_MASK (mxcsrmask_base << 7)
// MXCSR used when *we* are executing floating point code
// All masked, flags zeroed, round nearest, special features off
#define MXCSR_OURS 0x1f80
static int control_mxcsr_round_daz_ftz = 0; // control the rounding bits
static uint32_t orig_mxcsr_round_daz_ftz_mask; // captured at start
static uint32_t our_mxcsr_round_daz_ftz_mask =
0; // as we want to run 0 = round to nearest, no FAZ, no DAZ (IEEE default)
volatile static int kernel = 0;
volatile static int aggressive = 0;
volatile static int disable_pthreads = 0;
static int (*orig_fork)() = 0;
static int (*orig_pthread_create)(
pthread_t *tid, const pthread_attr_t *attr, void *(*start)(void *), void *arg) = 0;
static int (*orig_pthread_exit)(void *ret) __attribute__((noreturn)) = 0;
static sighandler_t (*orig_signal)(int sig, sighandler_t func) = 0;
static int (*orig_sigaction)(int sig, const struct sigaction *act, struct sigaction *oldact) = 0;
// static int (*orig_feenableexcept)(int) = 0 ;
// static int (*orig_fedisableexcept)(int) = 0 ;
// static int (*orig_fegetexcept)() = 0 ;
// static int (*orig_feclearexcept)(int) = 0 ;
// static int (*orig_fegetexceptflag)(fexcept_t *flagp, int excepts) = 0 ;
// static int (*orig_feraiseexcept)(int excepts) = 0;
// static int (*orig_fesetexceptflag)(const fexcept_t *flagp, int excepts) = 0;
// static int (*orig_fetestexcept)(int excepts) = 0;
// static int (*orig_fegetround)(void) = 0;
// static int (*orig_fesetround)(int rounding_mode) = 0;
// static int (*orig_fegetenv)(fenv_t *envp) = 0;
// static int (*orig_feholdexcept)(fenv_t *envp) = 0;
// static int (*orig_fesetenv)(const fenv_t *envp) = 0;
// static int (*orig_feupdateenv)(const fenv_t *envp) = 0;
int (*orig_feenableexcept)(int) = 0;
int (*orig_fedisableexcept)(int) = 0;
int (*orig_fegetexcept)() = 0;
int (*orig_feclearexcept)(int) = 0;
int (*orig_fegetexceptflag)(fexcept_t *flagp, int excepts) = 0;
int (*orig_feraiseexcept)(int excepts) = 0;
int (*orig_fesetexceptflag)(const fexcept_t *flagp, int excepts) = 0;
int (*orig_fetestexcept)(int excepts) = 0;
int (*orig_fegetround)(void) = 0;
int (*orig_fesetround)(int rounding_mode) = 0;
int (*orig_fegetenv)(fenv_t *envp) = 0;
int (*orig_feholdexcept)(fenv_t *envp) = 0;
int (*orig_fesetenv)(const fenv_t *envp) = 0;
int (*orig_feupdateenv)(const fenv_t *envp) = 0;
double (*orig_pow)(double a, double b) = 0;
double (*orig_exp)(double a) = 0;
double (*orig_log)(double a) = 0;
double (*orig_sin)(double a) = 0;
double (*orig_sincos)(double a, double *sin, double *cos) = 0;
double (*orig_cos)(double a) = 0;
double (*orig_tan)(double a) = 0;
double (*orig_log10)(double a) = 0;
double (*orig_ceil)(double a) = 0;
double (*orig_floor)(double a) = 0;
int (*orig_round)(double a) = 0;
long int (*orig_lround)(double a) = 0;
double (*orig_ldexp)(double a, int b) = 0;
double (*orig_sinh)(double a) = 0;
double (*orig_cosh)(double a) = 0;
double (*orig_tanh)(double a) = 0;
double (*orig_asin)(double a) = 0;
double (*orig_acos)(double a) = 0;
double (*orig_atan)(double a) = 0;
double (*orig_asinh)(double a) = 0;
double (*orig_acosh)(double a) = 0;
double (*orig_atanh)(double a) = 0;
double (*orig_atan2)(double a, double b) = 0;
double (*orig___powidf2)(double a, int b) = 0;
static struct sigaction oldsa_fpe, oldsa_trap, oldsa_int, oldsa_segv;
#define ORIG_RETURN(func, ...) \
if (orig_##func) { \
return orig_##func(__VA_ARGS__); \
} else { \
ERROR("cannot call orig_" #func " returning zero\n"); \
return 0; \
}
#define ORIG_IF_CAN(func, ...) \
if (orig_##func) { \
if (!DEBUG_OUTPUT) { \
orig_##func(__VA_ARGS__); \
} else { \
DEBUG("orig_" #func " returns 0x%x\n", orig_##func(__VA_ARGS__)); \
} \
} else { \
DEBUG("cannot call orig_" #func " - skipping\n"); \
}
#define SHOW_CALL_STACK()
#define MAX_CONTEXTS 1024
// make this run-time configurable later
static uint64_t decode_cache_size = DEFAULT_DECODE_CACHE_SIZE;
// This is to allow us to handle multiple threads
// and to follow forks later
typedef struct execution_context {
enum { INIT, AWAIT_FPE, AWAIT_TRAP, ABORT } state;
int aborting_in_trap;
int tid;
uint32_t foreign_return_mxcsr;
void *foreign_return_addr;
uint64_t fp_traps;
uint64_t promotions;
uint64_t demotions;
uint64_t clobbers; // overwriting one of our nans
uint64_t correctness_traps;
uint64_t correctness_foreign_calls;
uint64_t correctness_demotions;
uint64_t emulated_inst;
fpvm_inst_t **decode_cache; // chaining hash - array of pointers to instructions
uint64_t decode_cache_size;
uint64_t decode_cache_hits;
uint64_t decode_cache_unique;
#ifdef CONFIG_INSTR_TRACES
fpvm_instr_trace_context_t *trace_context;
#define INIT_TRACER(c) (c)->trace_context = fpvm_instr_tracer_create()
#define DEINIT_TRACER(c) fpvm_instr_tracer_destroy((c)->trace_context)
#define RECORD_TRACE(c,ec,sa,ic) fpvm_instr_tracer_record((c)->trace_context,TRACE_START_NORMAL,sa,ec,ic)
#define PRINT_TRACES(c) { char _buf[256]; sprintf(_buf,"fpvm info(%8d): trace: ",(c)->tid); fpvm_instr_tracer_print(stderr,_buf,(c)->trace_context,4); }
#else
#define INIT_TRACER(c)
#define DEINIT_TRACER(c)
#define RECORD_TRACE(c,ec,sa,ic)
#define PRINT_TRACES(c)
#endif
#ifdef CONFIG_PERF_STATS
perf_stat_t gc_stat;
perf_stat_t decode_cache_stat;
perf_stat_t decode_stat;
perf_stat_t bind_stat;
perf_stat_t emulate_stat;
perf_stat_t patch_stat;
#define START_PERF(c, x) perf_stat_start(&c->x##_stat)
#define END_PERF(c, x) perf_stat_end(&c->x##_stat)
#define PRINT_PERF(c, x) { char _buf[256]; sprintf(_buf,"fpvm info(%8d): perf: ",(c)->tid); perf_stat_print(&(c)->x##_stat, stderr, _buf); }
#define PRINT_PERFS(c) \
PRINT_PERF(c, gc); \
PRINT_PERF(c, decode_cache); \
PRINT_PERF(c, decode); \
PRINT_PERF(c, bind); \
PRINT_PERF(c, emulate); \
PRINT_PERF(c, patch);
#else
#define START_PERF(c, x)
#define END_PERF(c, x)
#define PRINT_PERF(c, x)
#define PRINT_PERFS(c)
#endif
#if CONFIG_TELEMETRY_PROMOTIONS
#define PRINT_TELEMETRY(c) fprintf(stderr, "fpvm info(%8d): telemetry: %lu fp traps, %lu promotions, %lu demotions, %lu clobbers, %lu correctness traps, %lu correctness foreign calls, %lu correctness demotions, %lu instructions emulated (~%lu per trap), %lu decode cache hits, %lu unique instructions\n",(c)->tid, (c)->fp_traps, (c)->promotions, (c)->demotions, (c)->clobbers, (c)->correctness_traps, (c)->correctness_foreign_calls, (c)->correctness_demotions, (c)->emulated_inst, (c)->emulated_inst/(c)->fp_traps, (c)->decode_cache_hits, (c)->decode_cache_unique)
#else
#define PRINT_TELEMETRY(c) fprintf(stderr, "fpvm info(%8d): telemetry: %lu fp traps, -1 promotions, -1 demotions, -1 clobbers, %lu correctness traps, %lu correctness foreign calls -1 correctness demotions, %lu instructions emulated (~%lu per trap), %lu decode cache hits, %lu unique instructions\n",(c)->tid, (c)->fp_traps, (c)->correctness_traps, (c)->correctness_foreign_calls, (c)->emulated_inst, (c)->emulated_inst/(c)->fp_traps, (c)->decode_cache_hits, (c)->decode_cache_unique)
#endif
} execution_context_t;
typedef union {
uint32_t val;
struct {
uint8_t ie : 1; // detected nan
uint8_t de : 1; // detected denormal
uint8_t ze : 1; // detected divide by zero
uint8_t oe : 1; // detected overflow (infinity)
uint8_t ue : 1; // detected underflow (zero)
uint8_t pe : 1; // detected precision (rounding)
uint8_t daz : 1; // denormals become zeros
uint8_t im : 1; // mask nan exceptions
uint8_t dm : 1; // mask denorm exceptions
uint8_t zm : 1; // mask zero exceptions
uint8_t om : 1; // mask overflow exceptions
uint8_t um : 1; // mask underflow exceptions
uint8_t pm : 1; // mask precision exceptions
uint8_t rounding : 2; // rounding (toward
// 00=>nearest,01=>negative,10=>positive,11=>zero)
uint8_t fz : 1; // flush to zero (denormals are zeros)
uint16_t rest;
} __attribute__((packed));
} __attribute__((packed)) mxcsr_t;
typedef union {
uint64_t val;
struct {
// note that not all of these are visible in user mode
uint8_t cf : 1; // detected carry
uint8_t res1 : 1; // reserved MB1
uint8_t pf : 1; // detected parity
uint8_t res2 : 1; // reserved
uint8_t af : 1; // detected adjust (BCD math)
uint8_t res3 : 1; // resered
uint8_t zf : 1; // detected zero
uint8_t sf : 1; // detected negative
uint8_t tf : 1; // trap enable flag (single stepping)
uint8_t intf : 1; // interrupt enable flag
uint8_t df : 1; // direction flag (1=down);
uint8_t of : 1; // detected overflow
uint8_t iopl : 2; // I/O privilege level (ring)
uint8_t nt : 1; // nested task
uint8_t res4 : 1; // reserved
uint8_t rf : 1; // resume flag;
uint8_t vm : 1; // virtual 8086 mode
uint8_t ac : 1; // alignment check enable
uint8_t vif : 1; // virtual interrupt flag
uint8_t vip : 1; // virtual interrupt pending;
uint8_t id : 1; // have cpuid instruction
uint16_t res5 : 10; // reserved
uint32_t res6; // nothing in top half of rflags yet
} __attribute__((packed));
} __attribute__((packed)) rflags_t;
static int context_lock;
static execution_context_t context[MAX_CONTEXTS];
// faster lookup of execution context
__thread execution_context_t *__fpvm_current_execution_context=0;
static uint32_t get_mxcsr() {
uint32_t val = 0;
__asm__ __volatile__("stmxcsr %0" : "=m"(val) : : "memory");
return val;
}
static void set_mxcsr(uint32_t val) {
__asm__ __volatile__("ldmxcsr %0" : : "m"(val) : "memory");
}
static void mxcsr_disable_save(uint32_t* old) {
uint32_t tmp = get_mxcsr();
*old = tmp;
tmp |= MXCSR_MASK_MASK;
set_mxcsr(tmp);
}
static void mxcsr_restore(uint32_t old) {
set_mxcsr(old);
}
void fpvm_demote_machine_registers(void)
{
ERROR("machine register remotion is UNIMPLEMENTED\n");
}
static inline void fxsave(struct _libc_fpstate *fpvm_fpregs)
{
__asm__ __volatile__("fxsave (%0)" :: "r"(fpvm_fpregs));
}
static inline void fxrstor(const struct _libc_fpstate *fpvm_fpregs)
{
__asm__ __volatile__("fxrstor (%0)" :: "r"(fpvm_fpregs));
}
static void init_execution_contexts() {
memset(context, 0, sizeof(context));
context_lock = 0;
}
static void lock_contexts() {
while (!__sync_bool_compare_and_swap(&context_lock, 0, 1)) {
}
}
static void unlock_contexts() {
__sync_and_and_fetch(&context_lock, 0);
}
static execution_context_t *find_execution_context(int tid) {
int i;
lock_contexts();
for (i = 0; i < MAX_CONTEXTS; i++) {
if (context[i].tid == tid) {
unlock_contexts();
return &context[i];
}
}
unlock_contexts();
return 0;
}
execution_context_t *find_my_execution_context(void)
{
return __fpvm_current_execution_context;
}
static void dump_execution_contexts_info(void)
{
int i;
uint32_t m;
lock_contexts();
// we will internally be using floating point
// and need to guarantee that we don't trap to ourselves
mxcsr_disable_save(&m);
for (i = 0; i < MAX_CONTEXTS; i++) {
if (context[i].tid) {
#if CONFIG_INSTR_TRACES
PRINT_TRACES(&context[i]);
#endif
#if CONFIG_TELEMETRY
PRINT_TELEMETRY(&context[i]);
#endif
#if CONFIG_PERF_STATS
PRINT_PERFS(&context[i]);
#endif
}
}
mxcsr_restore(m);
unlock_contexts();
}
static execution_context_t *alloc_execution_context(int tid) {
int i;
lock_contexts();
for (i = 0; i < MAX_CONTEXTS; i++) {
if (!context[i].tid) {
context[i].tid = tid;
unlock_contexts();
INIT_TRACER(&context[i]);
#ifdef CONFIG_PERF_STATS
perf_stat_init(&context[i].gc_stat, "garbage collector");
perf_stat_init(&context[i].decode_cache_stat, "decode cache");
perf_stat_init(&context[i].decode_stat, "decoder");
perf_stat_init(&context[i].bind_stat, "bind");
perf_stat_init(&context[i].emulate_stat, "emulate");
perf_stat_init(&context[i].patch_stat, "patched trap");
#endif
return &context[i];
}
}
unlock_contexts();
return 0;
}
static void free_execution_context(int tid) {
int i;
lock_contexts();
for (i = 0; i < MAX_CONTEXTS; i++) {
if (context[i].tid == tid) {
DEINIT_TRACER(&context[i]);
context[i].tid = 0;
unlock_contexts();
}
}
unlock_contexts();
}
static void stringify_current_fe_exceptions(char *buf) {
int have = 0;
uint32_t mxcsr = get_mxcsr();
buf[0] = 0;
#define FE_HANDLE(x) \
if (orig_fetestexcept(x)) { \
if (!have) { \
strcat(buf, #x); \
have = 1; \
} else { \
strcat(buf, " " #x); \
} \
}
FE_HANDLE(FE_DIVBYZERO);
FE_HANDLE(FE_INEXACT);
FE_HANDLE(FE_INVALID);
FE_HANDLE(FE_OVERFLOW);
FE_HANDLE(FE_UNDERFLOW);
if (mxcsr & 0x2) { // denorm
if (have) {
strcat(buf, " ");
}
strcat(buf, "FE_DENORM");
have = 1;
}
if (!have) {
strcpy(buf, "NO_EXCEPTIONS_RECORDED");
}
}
/*
static void show_current_fe_exceptions()
{
char buf[80];
stringify_current_fe_exceptions(buf);
INFO("%s\n", buf);
}
*/
static __attribute__((constructor )) void fpvm_init(void);
#if DEBUG_OUTPUT
static void dump_rflags(char *pre, ucontext_t *uc) {
char buf[256];
rflags_t *r = (rflags_t *)&(uc->uc_mcontext.gregs[REG_EFL]);
sprintf(buf, "rflags = %016lx", r->val);
#define EF(x, y) \
if (r->x) { \
strcat(buf, " " #y); \
}
EF(zf, zero);
EF(sf, neg);
EF(cf, carry);
EF(of, over);
EF(pf, parity);
EF(af, adjust);
EF(tf, TRAP);
EF(intf, interrupt);
EF(ac, alignment)
EF(df, down);
DEBUG("%s: %s\n", pre, buf);
}
static void dump_mxcsr(char *pre, ucontext_t *uc) {
char buf[256];
mxcsr_t *m = (mxcsr_t *)&uc->uc_mcontext.fpregs->mxcsr;
sprintf(buf, "mxcsr = %08x flags:", m->val);
#define MF(x, y) \
if (m->x) { \
strcat(buf, " " #y); \
}
MF(ie, NAN);
MF(de, DENORM);
MF(ze, ZERO);
MF(oe, OVER);
MF(ue, UNDER);
MF(pe, PRECISION);
strcat(buf, " masking:");
MF(im, nan);
MF(dm, denorm);
MF(zm, zero);
MF(om, over);
MF(um, under);
MF(pm, precision);
DEBUG("%s: %s rounding: %s %s %s\n", pre, buf,
m->rounding == 0 ? "nearest"
: m->rounding == 1 ? "negative"
: m->rounding == 2 ? "positive"
: "zero",
m->daz ? "DAZ" : "", m->fz ? "FTZ" : "");
}
#endif
// trap should never be enabled... this can probably go
static inline void set_trap_flag_context(ucontext_t *uc, int val) {
if (val) {
uc->uc_mcontext.gregs[REG_EFL] |= 0x100UL;
} else {
uc->uc_mcontext.gregs[REG_EFL] &= ~0x100UL;
}
}
static inline void clear_fp_exceptions_context(ucontext_t *uc) {
uc->uc_mcontext.fpregs->mxcsr &= ~MXCSR_FLAG_MASK;
}
static inline void set_mask_fp_exceptions_context(ucontext_t *uc, int mask) {
if (mask) {
uc->uc_mcontext.fpregs->mxcsr |= MXCSR_MASK_MASK;
} else {
uc->uc_mcontext.fpregs->mxcsr &= ~MXCSR_MASK_MASK;
}
}
static inline void zero_fp_xmm_context(ucontext_t *uc)
{
memset(uc->uc_mcontext.fpregs->_xmm,0,16*16);
}
static void abort_operation(char *reason) {
DEBUG("aborting due to %s inited=%d\n",reason,inited);
if (!inited) {
DEBUG("Initializing before aborting\n");
fpvm_init();
DEBUG("Done with fpvm_preload_init()\n");
}
if (!aborted) {
ORIG_IF_CAN(fedisableexcept, FE_ALL_EXCEPT);
ORIG_IF_CAN(feclearexcept, FE_ALL_EXCEPT);
ORIG_IF_CAN(sigaction, SIGFPE, &oldsa_fpe, 0);
ORIG_IF_CAN(sigaction, SIGINT, &oldsa_int, 0);
ORIG_IF_CAN(sigaction, SIGSEGV, &oldsa_segv, 0);
execution_context_t *mc = find_my_execution_context();
if (!mc) {
ERROR("Cannot find execution context\n");
} else {
mc->state = ABORT;
}
// even if we have no execution context we need to restore
// the mcontext. If we do have a execution context,
// and we are a trap, the mcontext has already been restored
if (!mc || !mc->aborting_in_trap) {
// signal ourselves to restore the FP and TRAP state in the context
kill(gettid(), SIGTRAP);
}
}
// finally remove our trap handler
ORIG_IF_CAN(sigaction, SIGTRAP, &oldsa_trap, 0);
aborted = 1;
DEBUG("Aborted operation because %s\n", reason);
}
static void fpvm_panic(void)
{
abort_operation("panicing!");
abort();
}
static int bringup_execution_context(int tid);
int fork() {
int rc;
DEBUG("fork\n");
rc = orig_fork();
if (aborted) {
return rc;
}
if (rc < 0) {
DEBUG("fork failed\n");
return rc;
}
if (rc == 0) {
// child
// clear exceptions - we will not inherit the current ones from the parent
ORIG_IF_CAN(feclearexcept, exceptmask);
if (bringup_execution_context(gettid())) {
ERROR("Failed to start up execution context at fork\n");
// we won't break, however..
} else {
// we should have inherited all the sighandlers, etc, from our parent
// now kick ourselves to set the sse bits; we are currently in state INIT
kill(gettid(), SIGTRAP);
// we should now be in the right state
}
DEBUG("Done with setup on fork\n");
return rc;
} else {
// parent - nothing to do
return rc;
}
}
struct tramp_context {
void *(*start)(void *);
void *arg;
int done;
};
static void *trampoline(void *p) {
struct tramp_context *c = (struct tramp_context *)p;
void *(*start)(void *) = c->start;
void *arg = c->arg;
void *ret;
// let our wrapper go - this must also be a software barrier
__sync_fetch_and_or(&c->done, 1);
DEBUG("Setting up thread %ld\n", gettid());
// clear exceptions just in case
ORIG_IF_CAN(feclearexcept, exceptmask);
// make new context for individual mode
if (bringup_execution_context(gettid())) {
ERROR("Failed to start up execution context on thread creation\n");
// we won't break, however..
} else {
// we should have inherited all the sighandlers, etc, from the spawning
// thread
// now kick ourselves to set the sse bits; we are currently in state INIT
kill(gettid(), SIGTRAP);
// we should now be in the right state
}
DEBUG("Done with setup on thread creation\n");
DEBUG("leaving trampoline\n");
ret = start(arg);
// if it's returning normally instead of via pthread_exit(), we'll do the
// cleanup here
#if CONFIG_INSTR_TRACES
PRINT_TRACES(find_my_execution_context());
#endif
#if CONFIG_TELEMETRY
PRINT_TELEMETRY(find_my_execution_context());
#endif
#if CONFIG_PERF_STATS
PRINT_PERFS(find_my_execution_context());
#endif
pthread_exit(ret);
}
int pthread_create(pthread_t *tid, const pthread_attr_t *attr, void *(*start)(void *), void *arg) {
struct tramp_context c;
DEBUG("pthread_create\n");
if (aborted) {
return orig_pthread_create(tid, attr, start, arg);
}
c.start = start;
c.arg = arg;
c.done = 0;
int rc = orig_pthread_create(tid, attr, trampoline, &c);
if (!rc) {
// don't race on the tramp context - wait for thread to copy out
while (!__sync_fetch_and_and(&c.done, 1)) {
}
}
DEBUG("pthread_create done\n");
return rc;
}
static int teardown_execution_context(int tid);
__attribute__((noreturn)) void pthread_exit(void *ret) {
DEBUG("pthread_exit(%p)\n", ret);
// we will process this even if we have aborted, since
teardown_execution_context(gettid());
orig_pthread_exit(ret);
}
sighandler_t signal(int sig, sighandler_t func) {
DEBUG("signal(%d,%p)\n", sig, func);
SHOW_CALL_STACK();
if ((sig == SIGFPE || sig == SIGTRAP) && !aborted) {
if (!aggressive) {
abort_operation("target is using sigaction with SIGFPE or SIGTRAP (nonaggressive)");
} else {
// do not override our signal handlers - we are not aborting
DEBUG(
"not overriding SIGFPE or SIGTRAP because we are in aggressive "
"mode\n");
return 0;
}
}
ORIG_RETURN(signal, sig, func);
}
int sigaction(int sig, const struct sigaction *act, struct sigaction *oldact) {
DEBUG("sigaction(%d,%p,%p)\n", sig, act, oldact);
SHOW_CALL_STACK();
if ((sig == SIGFPE || sig == SIGTRAP) && !aborted) {
if (!aggressive) {
abort_operation("target is using sigaction with SIGFPE or SIGTRAP");
} else {
// do not override our signal handlers - we are not aborting
DEBUG(
"not overriding SIGFPE or SIGTRAP because we are in aggressive "
"mode\n");
return 0;
}
}
ORIG_RETURN(sigaction, sig, act, oldact);
}
int feclearexcept(int excepts) {
DEBUG("feclearexcept(0x%x)\n", excepts);
SHOW_CALL_STACK();
abort_operation("target is using feclearexcept");
ORIG_RETURN(feclearexcept, excepts);
}
int feenableexcept(int excepts) {
DEBUG("feenableexcept(0x%x)\n", excepts);
SHOW_CALL_STACK();
abort_operation("target is using feenableexcept");
ORIG_RETURN(feenableexcept, excepts);
}
int fedisableexcept(int excepts) {
DEBUG("fedisableexcept(0x%x)\n", excepts);
SHOW_CALL_STACK();
abort_operation("target is using fedisableexcept");
ORIG_RETURN(fedisableexcept, excepts);
}
int fegetexcept(void) {
DEBUG("fegetexcept()\n");
SHOW_CALL_STACK();
abort_operation("target is using fegetexcept");
ORIG_RETURN(fegetexcept);
}
int fegetexceptflag(fexcept_t *flagp, int excepts) {
DEBUG("fegetexceptflag(%p,0x%x)\n", flagp, excepts);
SHOW_CALL_STACK();
abort_operation("target is using fegetexceptflag");
ORIG_RETURN(fegetexceptflag, flagp, excepts);
}
int feraiseexcept(int excepts) {
DEBUG("feraiseexcept(0x%x)\n", excepts);
SHOW_CALL_STACK();
abort_operation("target is using feraiseexcept");
ORIG_RETURN(feraiseexcept, excepts);
}
int fesetexceptflag(const fexcept_t *flagp, int excepts) {
DEBUG("fesetexceptflag(%p,0x%x\n", flagp, excepts);
SHOW_CALL_STACK();
abort_operation("target is using fesetexceptflag");
ORIG_RETURN(fesetexceptflag, flagp, excepts);
}
int fetestexcept(int excepts) {
DEBUG("fesetexcept(0x%x)\n", excepts);
SHOW_CALL_STACK();
abort_operation("target is using fetestexcept");
ORIG_RETURN(fetestexcept, excepts);
}
int fegetround(void) {
DEBUG("fegetround()\n");
SHOW_CALL_STACK();
abort_operation("target is using fegetround");
ORIG_RETURN(fegetround);
}
int fesetround(int rounding_mode) {
DEBUG("fesetround(0x%x)\n", rounding_mode);
SHOW_CALL_STACK();
abort_operation("target is using fesetround");
ORIG_RETURN(fesetround, rounding_mode);
}
int fegetenv(fenv_t *envp) {
DEBUG("fegetenv(%p)\n", envp);
SHOW_CALL_STACK();
abort_operation("target is using fegetenv");
ORIG_RETURN(fegetenv, envp);
}
int feholdexcept(fenv_t *envp) {
DEBUG("feholdexcept(%p)\n", envp);
SHOW_CALL_STACK();
abort_operation("target is using feholdexcept");
ORIG_RETURN(feholdexcept, envp);
}
int fesetenv(const fenv_t *envp) {
DEBUG("fesetenv(%p)\n", envp);
SHOW_CALL_STACK();
abort_operation("target is using fesetenv");
ORIG_RETURN(fesetenv, envp);
}
int feupdateenv(const fenv_t *envp) {
DEBUG("feupdateenv(%p)\n", envp);
SHOW_CALL_STACK();
abort_operation("target is using feupdateenv");
ORIG_RETURN(feupdateenv, envp);
}
static int setup_shims() {
#define SHIMIFY(x) \
if (!(orig_##x = dlsym(RTLD_NEXT, #x))) { \
ERROR("Failed to setup SHIM for " #x "\n"); \
return -1; \
}
if (disable_pthreads == 0) {
SHIMIFY(pthread_create);
SHIMIFY(pthread_exit);
}
SHIMIFY(fork);
SHIMIFY(signal);
SHIMIFY(sigaction);
if (!getenv("FPVM_NO_LIBM")) {
SHIMIFY(feclearexcept);
SHIMIFY(feenableexcept);
SHIMIFY(fedisableexcept);
SHIMIFY(fegetexcept);
SHIMIFY(fegetexceptflag);
SHIMIFY(feraiseexcept);
SHIMIFY(fesetexceptflag);
SHIMIFY(fetestexcept);
SHIMIFY(fegetround);
SHIMIFY(fesetround);
SHIMIFY(fegetenv);
SHIMIFY(feholdexcept);
SHIMIFY(fesetenv);
SHIMIFY(feupdateenv);
SHIMIFY(pow);
SHIMIFY(exp);
SHIMIFY(log);
SHIMIFY(sin);
SHIMIFY(sincos);
SHIMIFY(cos);
SHIMIFY(tan);
SHIMIFY(log10);
SHIMIFY(ceil);
SHIMIFY(floor);
SHIMIFY(round);
SHIMIFY(lround);
SHIMIFY(ldexp);
SHIMIFY(__powidf2);
SHIMIFY(sinh);
SHIMIFY(cosh);
SHIMIFY(tanh);
SHIMIFY(asin);
SHIMIFY(acos);
SHIMIFY(atan);
SHIMIFY(atan2);
SHIMIFY(asinh);
SHIMIFY(acosh);
SHIMIFY(atanh);
}
return 0;
}
#define MXCSR_ROUND_DAZ_FTZ_MASK (~(0xe040UL))
static uint32_t get_mxcsr_round_daz_ftz(ucontext_t *uc) {
uint32_t mxcsr = uc->uc_mcontext.fpregs->mxcsr;
uint32_t mxcsr_round = mxcsr & MXCSR_ROUND_DAZ_FTZ_MASK;
DEBUG("mxcsr (0x%08x) round faz dtz at 0x%08x\n", mxcsr, mxcsr_round);
// dump_mxcsr("get_mxcsr_round_daz_ftz: ", uc);
return mxcsr_round;
}
static void set_mxcsr_round_daz_ftz(ucontext_t *uc, uint32_t mask) {
if (control_mxcsr_round_daz_ftz) {
uc->uc_mcontext.fpregs->mxcsr &= MXCSR_ROUND_DAZ_FTZ_MASK;
uc->uc_mcontext.fpregs->mxcsr |= mask;
DEBUG("mxcsr masked to 0x%08x after round daz ftz update (0x%08x)\n",
uc->uc_mcontext.fpregs->mxcsr, mask);
// dump_mxcsr("set_mxcsr_round_daz_ftz: ", uc);
}
}
inline static fpvm_inst_t *decode_cache_lookup(execution_context_t *c, void *rip);
inline static void decode_cache_insert(execution_context_t *c, fpvm_inst_t *inst);
// we got here from a correctness trap produced by
// a patch on the application binary. uc is expected to
// be pointing to the faulting instruction (the patch
// should trigger us before the faulting instruction has
// been executed.
static int correctness_handler(ucontext_t *uc, execution_context_t *mc)