-
Notifications
You must be signed in to change notification settings - Fork 3
/
smtgcc.py
2134 lines (1900 loc) · 79.6 KB
/
smtgcc.py
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
import gcc
from z3 import *
# Solver memory limit (in megabytes) or 0 for "no limit".
SOLVER_MAX_MEMORY = 25 * 1024
# Solver timeout (in seconds) or 0 for "no limit".
SOLVER_TIMEOUT = 5 * 60
# Size of anonymous memory size blocks we may need to introduce (for example,
# so that function pointer arguments have memory to point to).
ANON_MEM_SIZE = 64
# How many bytes load, store, __builtin_memset, etc. can expand.
MAX_MEMORY_UNROLL_LIMIT = 10000
# How the pointer bits are divided between id and offset.
PTR_OFFSET_BITS = 40
PTR_ID_BITS = 24
assert PTR_ID_BITS + PTR_OFFSET_BITS == 64
class NotImplementedError(Exception):
"""Raised when encountering unimplemented constructs."""
def __init__(self, string, location=None):
self.location = location
Exception.__init__(self, string)
class Error(Exception):
"""Raised when being passed incorrect input, etc."""
def __init__(self, string, location=None):
self.location = location
Exception.__init__(self, string)
class CommonState:
"""Things that are common for the source and target functions."""
def __init__(
self,
global_memory,
decl_to_memory,
const_mem_ids,
next_id,
ptr_constraints,
memory,
mem_sizes,
mem_id_eol,
is_initialized,
fun_args,
):
self.global_memory = global_memory
self.const_mem_ids = const_mem_ids
self.local_memory = None
self.next_id = next_id
self.ptr_constraints = ptr_constraints
self.memory = memory
self.is_initialized = is_initialized
self.mem_sizes = mem_sizes
self.mem_id_eol = mem_id_eol
self.decl_to_memory = decl_to_memory
self.fun_args = fun_args
self.retval = None
class MemoryBlock:
def __init__(self, decl, size, mem_id):
if size > (1 << PTR_OFFSET_BITS):
if decl is not None:
location = decl.location
else:
location = None
raise NotImplementedError("Too big memory block", location)
self.size = size
self.decl = decl
self.mem_id = mem_id
class SmtPointer:
def __init__(self, mem_id, offset):
assert mem_id.sort() == BitVecSort(PTR_ID_BITS)
assert offset.sort() == BitVecSort(PTR_OFFSET_BITS)
self.mem_id = mem_id
self.offset = offset
def bitvector(self):
return Concat([self.mem_id, self.offset])
class SmtFunction:
def __init__(self, fun, state):
self.fun = fun
self.name = fun.decl.name
self.tree_to_smt = {}
self.tree_is_initialized = {}
self.decl_to_id = {}
self.bb2smt = {}
self.state = state
# Function return
self.retval = None
self.retval_is_valid = None
self.invokes_ub = None
self.memory = None
self.mem_sizes = None
self.is_initialized = None
def add_ub(self, smt_is_executed, smt):
if is_true(self.invokes_ub):
# This function always invoke UB, so no need to add more
# checks.
return
if is_false(smt) or is_false(smt_is_executed):
# The basic block cannot invoke UB, so no need to add a
# check that always evaluete to false.
return
if is_true(smt):
smt = smt_is_executed
elif not is_true(smt_is_executed):
smt = And(smt_is_executed, smt)
if self.invokes_ub is None or is_true(smt):
self.invokes_ub = smt
else:
self.invokes_ub = Or(self.invokes_ub, smt)
class SmtBB:
def __init__(self, bb, smt_fun, mem_sizes):
self.bb = bb
self.smt_fun = smt_fun
self.invokes_ub = None
self.smtcond = None
self.retval = None
self.labels = self._find_labels()
self.switch_label_to_cond = None
smt_fun.bb2smt[bb] = self
if len(bb.preds) == 0:
self.memory = smt_fun.state.memory
self.mem_sizes = mem_sizes
self.mem_id_eol = smt_fun.state.mem_id_eol
self.is_initialized = smt_fun.state.is_initialized
else:
memory = []
mem_sizes = []
is_initialized = []
mem_id_eol = []
for edge in bb.preds:
src_smt_bb = smt_fun.bb2smt[edge.src]
memory.append((src_smt_bb.memory, edge))
mem_sizes.append((src_smt_bb.mem_sizes, edge))
mem_id_eol.append((src_smt_bb.mem_id_eol, edge))
is_initialized.append((src_smt_bb.is_initialized, edge))
self.memory = process_phi_smt_args(memory, smt_fun)
self.mem_sizes = process_phi_smt_args(mem_sizes, smt_fun)
self.mem_id_eol = process_phi_smt_args(mem_id_eol, smt_fun)
self.is_initialized = process_phi_smt_args(is_initialized, smt_fun)
# Create condition telling if this BB is executed or not.
if len(bb.preds) == 0:
# The entry block is always executed.
self.is_executed = BoolVal(True)
else:
# The block is executed if any of the edges are executed.
is_executed = None
for edge in bb.preds:
cond = build_full_edge_cond(edge, smt_fun)
if is_executed is None:
is_executed = cond
else:
is_executed = Or(is_executed, cond)
self.is_executed = is_executed
def _find_labels(self):
labels = []
for stmt in self.bb.gimple:
if isinstance(stmt, gcc.GimpleLabel):
labels.append(stmt.label)
return labels
def add_ub(self, smt):
if is_true(self.invokes_ub):
# This basic block always invoke UB, so no need to add more
# checks.
return
if is_false(smt):
# This does not invoke UB, so no need to add a
# check that always evaluete to false.
return
if self.invokes_ub is None or is_true(smt):
self.invokes_ub = smt
else:
self.invokes_ub = Or(self.invokes_ub, smt)
def build_switch_label_to_cond(stmt, smt_bb):
"Build SMT conditions corresponding to the case(s) jumping to each label."
assert isinstance(stmt, gcc.GimpleSwitch)
assert isinstance(stmt.indexvar.type, gcc.IntegerType)
label_to_cond = {}
default_cond = None
indexvar = get_tree_as_smt(stmt.indexvar, smt_bb)
for expr in stmt.labels[1:]:
low = get_tree_as_smt(expr.low, smt_bb)
# The case type may be of a lower precision. If so, extend it.
if stmt.indexvar.type.precision > expr.low.type.precision:
extbits = stmt.indexvar.type.precision - expr.low.type.precision
if expr.low.type.unsigned:
low = ZeroExt(extbits, low)
else:
low = SignExt(extbits, low)
if expr.high is not None:
high = get_tree_as_smt(expr.high, smt_bb)
if stmt.indexvar.type.precision > expr.high.type.precision:
extbits = stmt.indexvar.type.precision - expr.high.type.precision
if expr.high.type.unsigned:
high = ZeroExt(extbits, high)
else:
high = SignExt(extbits, high)
if stmt.indexvar.type.unsigned:
low_cond = ULE(low, indexvar)
high_cond = ULE(indexvar, high)
else:
low_cond = low <= indexvar
high_cond = indexvar <= high
cond = And(low_cond, high_cond)
else:
cond = indexvar == low
label = expr.target
if label in label_to_cond:
label_to_cond[label] = Or(label_to_cond[label], cond)
else:
label_to_cond[label] = cond
if default_cond is None:
default_cond = Not(cond)
else:
default_cond = And(default_cond, Not(cond))
default_label = stmt.labels[0].target
if default_label in label_to_cond:
label_to_cond[default_label] = Or(label_to_cond[default_label], default_cond)
else:
label_to_cond[default_label] = default_cond
return label_to_cond
def get_smt_sort(type):
"""Return the SMT sort for the GCC type."""
if isinstance(type, gcc.IntegerType):
return BitVecSort(type.precision)
if isinstance(type, gcc.BooleanType):
return BoolSort()
if isinstance(type, gcc.RealType):
if type.precision == 16:
return Float16()
if type.precision == 32:
return Float32()
if type.precision == 64:
return Float64()
if type.precision == 80:
# 80-bit floats does not follow the IEEE standard, so this is
# "wrong". But GCC does not do any optimizations on GIMPLE that
# depend on the properties that differ, so this is OK for now.
return FPSort(15, 64)
if type.precision == 128:
return Float128()
raise NotImplementedError(f"get_smt_sort {type.__class__}")
def load_bytes(mem_id, offset, size, smt_bb):
assert size > 0
if size > MAX_MEMORY_UNROLL_LIMIT:
raise NotImplementedError(f"load_bytes too big ({size})")
out_of_bound_ub_check(mem_id, offset, size, smt_bb)
# Load the "byte" values from memory.
bytes = []
is_initialized = []
ptr = Concat([mem_id, offset])
if is_bv_value(mem_id) and is_bv_value(offset):
ptr = simplify(ptr)
for i in range(0, size):
p = ptr + i
if is_bv_value(ptr):
p = simplify(p)
bytes.insert(0, Select(smt_bb.memory, p))
is_initialized.append(Select(smt_bb.is_initialized, p))
# Construct a bit-vector for the loaded value.
if size == 1:
result = bytes[0]
else:
result = Concat(bytes)
return result, is_initialized
def load_value(expr, smt_bb):
mem_id, offset = build_smt_addr(expr, smt_bb)
result, is_initialized = load_bytes(mem_id, offset, expr.type.sizeof, smt_bb)
# Convert the bit-vector to the correct type.
if isinstance(expr.type, gcc.RealType):
if expr.type.precision == 80:
result = Extract(78, 0, result)
result = fpBVToFP(result, get_smt_sort(expr.type))
elif isinstance(expr.type, gcc.BooleanType):
result = result != 0
elif isinstance(expr.type, gcc.PointerType):
mem_id = Extract(63, PTR_OFFSET_BITS, result)
offset = Extract(PTR_OFFSET_BITS - 1, 0, result)
result = SmtPointer(mem_id, offset)
elif not isinstance(expr.type, gcc.IntegerType):
raise NotImplementedError(f"load {expr.type.__class__}")
return result, is_initialized
def load_bitfield(expr, smt_bb):
assert is_bitfield(expr)
if isinstance(expr, gcc.BitFieldRef):
bitoffset = expr.position.constant & 7
else:
bitoffset = expr.bitoffset
size = (bitoffset + expr.type.precision + 7) // 8
mem_id, offset = build_smt_addr(expr, smt_bb)
bytes, is_initialized = load_bytes(mem_id, offset, size, smt_bb)
result = Extract(bitoffset + expr.type.precision - 1, bitoffset, bytes)
# The value in is_initialized may be of the wrong size; for example, when
# loading a 16-bit value (2 bytes) from a misaligned 16-bit bitfield
# (3 bytes).
if len(is_initialized) == 1:
is_init = is_initialized[0]
else:
is_init = And(is_initialized)
is_initialized = [is_init] * ((expr.type.precision + 7) // 8)
return result, is_initialized
def load(stmt, smt_bb):
if isinstance(stmt, gcc.GimpleReturn):
expr = stmt.retval
else:
expr = stmt.rhs[0]
if is_bitfield(expr):
res, is_initialized = load_bitfield(expr, smt_bb)
else:
res, is_initialized = load_value(expr, smt_bb)
return res, is_initialized
def out_of_bound_ub_check(mem_id, offset, size, smt_bb):
is_valid_mem_id = UGE(mem_id, smt_bb.smt_fun.state.next_id)
if is_bv_value(mem_id):
is_valid_mem_id = simplify(is_valid_mem_id)
smt_bb.add_ub(is_valid_mem_id)
smt_size = Select(smt_bb.mem_sizes, mem_id)
if is_bv_value(mem_id):
smt_size = simplify(smt_size)
is_out_of_bound = Or(UGT(offset + size, smt_size), UGE(offset, offset + size))
if is_bv_value(smt_size) and is_bv_value(offset):
is_out_of_bound = simplify(is_out_of_bound)
smt_bb.add_ub(is_out_of_bound)
def const_mem_ub_check(mem_id, smt_bb):
const_mem_ids = smt_bb.smt_fun.state.const_mem_ids
if const_mem_ids:
is_ub = mem_id == const_mem_ids[0]
for cmem_id in const_mem_ids[1:]:
is_ub = Or(is_ub, mem_id == cmem_id)
if is_bv_value(mem_id):
is_ub = simplify(is_ub)
smt_bb.add_ub(is_ub)
def store_bytes(mem_id, offset, size, value, is_initialized, smt_bb):
assert size > 0
assert len(is_initialized) == size
if size > MAX_MEMORY_UNROLL_LIMIT:
raise NotImplementedError(f"store_bytes too big ({size})")
out_of_bound_ub_check(mem_id, offset, size, smt_bb)
const_mem_ub_check(mem_id, smt_bb)
ptr = Concat([mem_id, offset])
if is_bv_value(mem_id) and is_bv_value(offset):
ptr = simplify(ptr)
for i in range(0, size):
byte_value = Extract(i * 8 + 7, i * 8, value)
if is_bv_value(value):
byte_value = simplify(byte_value)
p = ptr + i
if is_bv_value(ptr):
p = simplify(p)
smt_bb.memory = Store(smt_bb.memory, p, byte_value)
smt_bb.is_initialized = Store(smt_bb.is_initialized, p, is_initialized[i])
def store_value(expr, value, smt_bb):
# Create a bit-vector for the value to store.
type = expr.type
if isinstance(type, gcc.RealType):
value = fpToIEEEBV(value)
if type.precision == 80:
value = Concat([BitVecVal(0, 49), value])
elif isinstance(type, gcc.BooleanType):
bv0 = BitVecVal(0, 8)
bv1 = BitVecVal(1, 8)
value = If(value, bv1, bv0)
elif isinstance(type, gcc.PointerType):
value = value.bitvector()
elif not isinstance(type, gcc.IntegerType):
raise NotImplementedError(f"store {type.__class__}")
mem_id, offset = build_smt_addr(expr, smt_bb)
if expr in smt_bb.smt_fun.tree_is_initialized:
is_initialized = smt_bb.smt_fun.tree_is_initialized[expr]
else:
is_initialized = [BoolVal(True)] * type.sizeof
store_bytes(mem_id, offset, type.sizeof, value, is_initialized, smt_bb)
def store_bitfield(expr, value, smt_bb):
assert is_bitfield(expr)
mem_id, offset = build_smt_addr(expr, smt_bb)
if is_bool(value):
assert expr.type.precision == 1
value = If(value, BitVecVal(1, 1), BitVecVal(0, 1))
if isinstance(expr, gcc.BitFieldRef):
bitoffset = expr.position.constant & 7
else:
bitoffset = expr.bitoffset
size = (bitoffset + expr.type.precision + 7) // 8
result, _ = load_bytes(mem_id, offset, size, smt_bb)
parts = []
if bitoffset + expr.type.precision != size * 8:
nof_bits = size * 8
parts.append(Extract(nof_bits - 1, bitoffset + expr.type.precision, result))
parts.append(value)
if bitoffset != 0:
parts.append(Extract(bitoffset - 1, 0, result))
if len(parts) == 1:
value = parts[0]
else:
value = Concat(parts)
if expr in smt_bb.smt_fun.tree_is_initialized:
is_initialized = smt_bb.smt_fun.tree_is_initialized[expr]
# The value store in tree_is_initialized may be of the wrong size;
# for example, when storing a 16-bit value (2 bytes) in a misaligned
# 16-bit bitfield (3 bytes).
if len(is_initialized) == 1:
is_init = is_initialized[0]
else:
is_init = And(is_initialized)
is_initialized = [is_init] * size
else:
is_initialized = [BoolVal(True)] * size
store_bytes(mem_id, offset, size, value, is_initialized, smt_bb)
def store(stmt, smt_bb):
if stmt.exprcode == gcc.Constructor:
if not (stmt.rhs[0].is_clobber or len(stmt.rhs[0].elements) == 0):
raise NotImplementedError("store constructor that is not a clobber")
size = stmt.rhs[0].type.sizeof
if size > MAX_MEMORY_UNROLL_LIMIT:
raise NotImplementedError(f"store large constructor ({size} bytes)")
mem_id, smt_offset = build_smt_addr(stmt.lhs, smt_bb)
if stmt.rhs[0].is_clobber_eol:
smt_bb.mem_id_eol = Store(smt_bb.mem_id_eol, mem_id, True)
smt_bb.mem_sizes = Store(smt_bb.mem_sizes, mem_id, 0)
elif stmt.rhs[0].is_clobber:
smt_bb.is_initialized = mark_mem_uninitialized(
mem_id, smt_offset, size, smt_bb.is_initialized
)
else:
is_initialized = [BoolVal(True)] * size
rhs = BitVecVal(0, size * 8)
store_bytes(mem_id, smt_offset, size, rhs, is_initialized, smt_bb)
return
value = process_unary(stmt, smt_bb, False)
if is_bitfield(stmt.lhs):
store_bitfield(stmt.lhs, value, smt_bb)
else:
store_value(stmt.lhs, value, smt_bb)
def has_loop(fun):
"Does the function contain a loop?"
seen_bbs = []
for bb in fun.cfg.reverse_post_order:
seen_bbs.append(bb)
for succ in bb.succs:
if succ.dest in seen_bbs:
return True
return False
def uninit_var_to_smt(expr):
"Build a Const representing read from an uninitialized variable."
# Variables generated by the compiler gets None as expr.var.name.
# So generate the Const name by using str(expr.var) instead.
name = f".undef.{expr.var}"
if isinstance(expr.type, gcc.PointerType):
ptr = Const(name, BitVecSort(64))
mem_id = Extract(63, PTR_OFFSET_BITS, ptr)
offset = Extract(PTR_OFFSET_BITS - 1, 0, ptr)
return SmtPointer(mem_id, offset)
return Const(name, get_smt_sort(expr.type))
def get_tree_as_smt(expr, smt_bb, uninit_is_ub=True):
if uninit_is_ub and expr in smt_bb.smt_fun.tree_is_initialized:
is_initialized = smt_bb.smt_fun.tree_is_initialized[expr]
if len(is_initialized) == 1:
is_uninitialized = Not(is_initialized[0])
else:
is_uninitialized = Not(And(is_initialized))
smt_bb.add_ub(is_uninitialized)
if isinstance(expr, gcc.ParmDecl):
return smt_bb.smt_fun.tree_to_smt[expr]
if isinstance(expr, gcc.SsaName):
if expr in smt_bb.smt_fun.tree_to_smt:
return smt_bb.smt_fun.tree_to_smt[expr]
if isinstance(expr.var, gcc.ParmDecl):
if (
expr.var not in smt_bb.smt_fun.tree_to_smt
and expr.var.is_artificial
and expr.var.name[:5] == "CHAIN"
):
raise NotImplementedError("get_tree_as_smt nested functions")
return smt_bb.smt_fun.tree_to_smt[expr.var]
if isinstance(expr.var, gcc.VarDecl):
# We are reading from an uninitialized local variable.
# Mark this as uninitialized, and create a new unconstrained
# constant to make the generated SMT typecheck.
if uninit_is_ub:
smt_bb.add_ub(BoolVal(True))
else:
is_initialized = [BoolVal(False)] * expr.var.type.sizeof
smt_bb.smt_fun.tree_is_initialized[expr] = is_initialized
return uninit_var_to_smt(expr)
raise NotImplementedError(f"get_tree_as_smt SsaName {expr}")
if isinstance(expr, gcc.IntegerCst):
if isinstance(expr.type, gcc.BooleanType):
return BoolVal(expr.constant != 0)
if isinstance(expr.type, gcc.IntegerType):
return BitVecVal(expr.constant, expr.type.precision)
if isinstance(expr.type, gcc.PointerType):
cst = BitVecVal(expr.constant, 64)
mem_id = Extract(63, PTR_OFFSET_BITS, cst)
offset = Extract(PTR_OFFSET_BITS - 1, 0, cst)
return SmtPointer(mem_id, offset)
if isinstance(expr, gcc.ViewConvertExpr):
# Ignore uninit_is_ub as we are doing an operation on the value,
# which is UB if iti is uninitialized.
value = get_tree_as_smt(expr.operand, smt_bb, True)
return bit_cast(value, expr.operand.type, expr.type)
if isinstance(expr, gcc.RealCst):
return FPVal(expr.constant, get_smt_sort(expr.type))
if isinstance(expr, gcc.AddrExpr):
mem_id, offset = build_smt_addr(expr.operand, smt_bb)
return SmtPointer(mem_id, offset)
raise NotImplementedError(f"get_tree_as_smt {expr.__class__} {expr.type.__class__}")
def is_bitfield(expr):
"Return true if expr is a gcc.ComponentRef for a bitfield."
if not isinstance(expr, (gcc.ComponentRef, gcc.BitFieldRef)):
return False
if not isinstance(expr.type, gcc.IntegerType):
return False
if isinstance(expr, gcc.BitFieldRef):
bitoffset = expr.position.constant & 7
else:
bitoffset = expr.bitoffset
if bitoffset != 0:
return True
# If a bit field with a size that is a multiple of a byte, and the field
# is byte aligned, then we can treat it as a normal load/store.
return expr.type.precision != expr.type.sizeof * 8
def process_comparison(stmt, smt_bb):
if isinstance(stmt, gcc.GimpleCond):
type = stmt.lhs.type
rhs0 = get_tree_as_smt(stmt.lhs, smt_bb)
rhs1 = get_tree_as_smt(stmt.rhs, smt_bb)
else:
assert isinstance(stmt, gcc.GimpleAssign)
type = stmt.rhs[0].type
rhs0 = get_tree_as_smt(stmt.rhs[0], smt_bb)
rhs1 = get_tree_as_smt(stmt.rhs[1], smt_bb)
if isinstance(type, gcc.IntegerType):
is_unsigned = type.unsigned
elif isinstance(type, gcc.RealType):
pass
elif isinstance(type, gcc.BooleanType):
if stmt.exprcode not in [gcc.EqExpr, gcc.NeExpr]:
# The SMT solver API does not handle <, <=, >, >= for Boolean
# values, so we convert them to bit-vectors.
is_unsigned = True
one = BitVecVal(1, 1)
zero = BitVecVal(0, 1)
rhs0 = If(rhs0, one, zero)
rhs1 = If(rhs1, one, zero)
elif isinstance(type, gcc.PointerType):
is_unsigned = True
rhs0 = rhs0.bitvector()
rhs1 = rhs1.bitvector()
else:
raise NotImplementedError(f"process_comparison {type.__class__}", stmt.loc)
if isinstance(type, gcc.RealType):
if stmt.exprcode == gcc.LtExpr:
return fpLT(rhs0, rhs1)
if stmt.exprcode == gcc.LeExpr:
return fpLEQ(rhs0, rhs1)
if stmt.exprcode == gcc.GtExpr:
return fpGT(rhs0, rhs1)
if stmt.exprcode == gcc.GeExpr:
return fpGEQ(rhs0, rhs1)
if stmt.exprcode == gcc.EqExpr:
return fpEQ(rhs0, rhs1)
if stmt.exprcode == gcc.NeExpr:
return fpNEQ(rhs0, rhs1)
if stmt.exprcode == gcc.UneqExpr:
return Or(Or(fpIsNaN(rhs0), fpIsNaN(rhs1)), fpEQ(rhs0, rhs1))
if stmt.exprcode == gcc.UnltExpr:
return Or(Or(fpIsNaN(rhs0), fpIsNaN(rhs1)), fpLT(rhs0, rhs1))
if stmt.exprcode == gcc.UnleExpr:
return Or(Or(fpIsNaN(rhs0), fpIsNaN(rhs1)), fpLEQ(rhs0, rhs1))
if stmt.exprcode == gcc.UngtExpr:
return Or(Or(fpIsNaN(rhs0), fpIsNaN(rhs1)), fpGT(rhs0, rhs1))
if stmt.exprcode == gcc.UngeExpr:
return Or(Or(fpIsNaN(rhs0), fpIsNaN(rhs1)), fpGEQ(rhs0, rhs1))
if stmt.exprcode == gcc.UnorderedExpr:
return Or(fpIsNaN(rhs0), fpIsNaN(rhs1))
if stmt.exprcode == gcc.OrderedExpr:
return Not(Or(fpIsNaN(rhs0), fpIsNaN(rhs1)))
if stmt.exprcode == gcc.LtgtExpr:
return Or(fpLT(rhs0, rhs1), fpGT(rhs0, rhs1))
else:
if stmt.exprcode == gcc.LtExpr:
if is_unsigned:
return ULT(rhs0, rhs1)
return rhs0 < rhs1
if stmt.exprcode == gcc.LeExpr:
if is_unsigned:
return ULE(rhs0, rhs1)
return rhs0 <= rhs1
if stmt.exprcode == gcc.GtExpr:
if is_unsigned:
return UGT(rhs0, rhs1)
return rhs0 > rhs1
if stmt.exprcode == gcc.GeExpr:
if is_unsigned:
return UGE(rhs0, rhs1)
return rhs0 >= rhs1
if stmt.exprcode == gcc.EqExpr:
return rhs0 == rhs1
if stmt.exprcode == gcc.NeExpr:
return rhs0 != rhs1
raise NotImplementedError(f"process_comparison {stmt.exprcode}", stmt.loc)
def process_integer_binary(stmt, smt_bb):
assert len(stmt.rhs) == 2
type = stmt.lhs.type
rhs0 = get_tree_as_smt(stmt.rhs[0], smt_bb)
rhs1 = get_tree_as_smt(stmt.rhs[1], smt_bb)
if stmt.exprcode == gcc.PlusExpr:
res = rhs0 + rhs1
if not type.overflow_wraps:
erhs0 = SignExt(1, rhs0)
erhs1 = SignExt(1, rhs1)
eres = erhs0 + erhs1
smt_bb.add_ub(SignExt(1, res) != eres)
return res
if stmt.exprcode == gcc.MinusExpr:
res = rhs0 - rhs1
if not type.overflow_wraps:
erhs0 = SignExt(1, rhs0)
erhs1 = SignExt(1, rhs1)
eres = erhs0 - erhs1
smt_bb.add_ub(SignExt(1, res) != eres)
return res
if stmt.exprcode == gcc.MultExpr:
res = rhs0 * rhs1
if not type.overflow_wraps:
erhs0 = SignExt(type.precision, rhs0)
erhs1 = SignExt(type.precision, rhs1)
eres = erhs0 * erhs1
smt_bb.add_ub(SignExt(type.precision, res) != eres)
return res
if stmt.exprcode == gcc.WidenMultExpr:
if stmt.rhs[0].type.unsigned:
rhs0 = ZeroExt(stmt.rhs[0].type.precision, rhs0)
else:
rhs0 = SignExt(stmt.rhs[0].type.precision, rhs0)
if stmt.rhs[1].type.unsigned:
rhs1 = ZeroExt(stmt.rhs[1].type.precision, rhs1)
else:
rhs1 = SignExt(stmt.rhs[1].type.precision, rhs1)
return rhs0 * rhs1
if stmt.exprcode == gcc.MultHighpartExpr:
precision = stmt.rhs[0].type.precision
if stmt.rhs[0].type.unsigned:
rhs0 = ZeroExt(precision, rhs0)
else:
rhs0 = SignExt(precision, rhs0)
if stmt.rhs[1].type.unsigned:
rhs1 = ZeroExt(precision, rhs1)
else:
rhs1 = SignExt(precision, rhs1)
result = rhs0 * rhs1
return Extract(2 * precision - 1, precision, result)
if stmt.exprcode == gcc.TruncDivExpr:
if type.unsigned:
res = UDiv(rhs0, rhs1)
else:
res = rhs0 / rhs1
if not type.overflow_wraps:
ub = And(rhs0 == type.min_value.constant, rhs1 == -1)
smt_bb.add_ub(ub)
smt_bb.add_ub(rhs1 == 0)
return res
if stmt.exprcode == gcc.ExactDivExpr:
if type.unsigned:
res = UDiv(rhs0, rhs1)
else:
res = rhs0 / rhs1
if not type.overflow_wraps:
ub = And(rhs0 == type.min_value.constant, rhs1 == -1)
smt_bb.add_ub(ub)
if type.unsigned:
smt_bb.add_ub(URem(rhs0, rhs1) != 0)
else:
smt_bb.add_ub(SRem(rhs0, rhs1) != 0)
smt_bb.add_ub(rhs1 == 0)
return res
if stmt.exprcode == gcc.TruncModExpr:
if type.unsigned:
res = URem(rhs0, rhs1)
else:
res = SRem(rhs0, rhs1)
if not type.overflow_wraps:
smt_bb.add_ub(And(rhs0 == type.min_value.constant, rhs1 == -1))
smt_bb.add_ub(rhs1 == 0)
return res
if stmt.exprcode == gcc.BitIorExpr:
return rhs0 | rhs1
if stmt.exprcode == gcc.BitAndExpr:
return rhs0 & rhs1
if stmt.exprcode == gcc.BitXorExpr:
return rhs0 ^ rhs1
if stmt.exprcode == gcc.LshiftExpr:
smt_bb.add_ub(UGE(rhs1, type.precision))
if stmt.rhs[0].type.precision != stmt.rhs[1].type.precision:
rhs1 = convert_to_integer(rhs1, stmt.rhs[1].type, stmt.rhs[0].type)
return rhs0 << rhs1
if stmt.exprcode == gcc.RshiftExpr:
smt_bb.add_ub(UGE(rhs1, type.precision))
if stmt.rhs[0].type.precision != stmt.rhs[1].type.precision:
rhs1 = convert_to_integer(rhs1, stmt.rhs[1].type, stmt.rhs[0].type)
if type.unsigned:
res = LShR(rhs0, rhs1)
else:
res = rhs0 >> rhs1
return res
if stmt.exprcode == gcc.MaxExpr:
if type.unsigned:
cmp = UGE(rhs0, rhs1)
else:
cmp = rhs0 >= rhs1
return If(cmp, rhs0, rhs1)
if stmt.exprcode == gcc.MinExpr:
if type.unsigned:
cmp = ULE(rhs0, rhs1)
else:
cmp = rhs0 <= rhs1
return If(cmp, rhs0, rhs1)
if stmt.exprcode == gcc.LrotateExpr:
smt_bb.add_ub(UGE(rhs1, type.precision))
if stmt.rhs[0].type.precision != stmt.rhs[1].type.precision:
rhs1 = convert_to_integer(rhs1, stmt.rhs[1].type, stmt.rhs[0].type)
return RotateLeft(rhs0, rhs1)
if stmt.exprcode == gcc.RrotateExpr:
smt_bb.add_ub(UGE(rhs1, type.precision))
if stmt.rhs[0].type.precision != stmt.rhs[1].type.precision:
rhs1 = convert_to_integer(rhs1, stmt.rhs[1].type, stmt.rhs[0].type)
return RotateRight(rhs0, rhs1)
if stmt.exprcode == gcc.PointerDiffExpr:
assert type.precision == 64
bv0 = rhs0.bitvector()
bv1 = rhs1.bitvector()
return bv0 - bv1
raise NotImplementedError(f"process_integer_binary {stmt.exprcode}", stmt.loc)
def process_boolean_binary(stmt, smt_bb):
assert len(stmt.rhs) == 2
rhs0 = get_tree_as_smt(stmt.rhs[0], smt_bb)
rhs1 = get_tree_as_smt(stmt.rhs[1], smt_bb)
if stmt.exprcode in [
gcc.LtExpr,
gcc.LeExpr,
gcc.GtExpr,
gcc.GeExpr,
gcc.EqExpr,
gcc.NeExpr,
gcc.UneqExpr,
gcc.UnltExpr,
gcc.UnleExpr,
gcc.UngtExpr,
gcc.UngeExpr,
gcc.UnorderedExpr,
gcc.OrderedExpr,
gcc.LtgtExpr,
]:
return process_comparison(stmt, smt_bb)
rhs0 = canonicalize_bool(rhs0)
rhs1 = canonicalize_bool(rhs1)
if stmt.exprcode in (gcc.BitIorExpr, gcc.MaxExpr):
return Or(rhs0, rhs1)
if stmt.exprcode in (gcc.BitAndExpr, gcc.MinExpr):
return And(rhs0, rhs1)
if stmt.exprcode == gcc.BitXorExpr:
return Xor(rhs0, rhs1)
raise NotImplementedError(f"process_boolean_binary {stmt.exprcode}", stmt.loc)
def process_float_binary(stmt, smt_bb):
assert len(stmt.rhs) == 2
rhs0 = get_tree_as_smt(stmt.rhs[0], smt_bb)
rhs1 = get_tree_as_smt(stmt.rhs[1], smt_bb)
if stmt.exprcode == gcc.PlusExpr:
return rhs0 + rhs1
if stmt.exprcode == gcc.MinusExpr:
return rhs0 - rhs1
if stmt.exprcode == gcc.MultExpr:
return rhs0 * rhs1
if stmt.exprcode == gcc.RdivExpr:
return rhs0 / rhs1
raise NotImplementedError(f"process_float_binary {stmt.exprcode}", stmt.loc)
def process_pointer_binary(stmt, smt_bb):
assert len(stmt.rhs) == 2
rhs0 = get_tree_as_smt(stmt.rhs[0], smt_bb)
rhs1 = get_tree_as_smt(stmt.rhs[1], smt_bb)
if stmt.exprcode == gcc.PointerPlusExpr:
assert rhs1.sort() == BitVecSort(64)
# Note: add_to_offset adds the UB check.
offset = add_to_offset(rhs0.offset, rhs1, smt_bb)
return SmtPointer(rhs0.mem_id, offset)
if stmt.exprcode == gcc.MinExpr:
bv0 = rhs0.bitvector()
bv1 = rhs1.bitvector()
return build_if(bv0 < bv1, rhs0, rhs1)
if stmt.exprcode == gcc.MaxExpr:
bv0 = rhs0.bitvector()
bv1 = rhs1.bitvector()
return build_if(bv0 >= bv1, rhs0, rhs1)
if stmt.exprcode == gcc.BitAndExpr:
mem_id = rhs0.mem_id & rhs1.mem_id
offset = rhs0.offset & rhs1.offset
return SmtPointer(mem_id, offset)
raise NotImplementedError(f"process_pointer_binary {stmt.exprcode}", stmt.loc)
def canonicalize_bool(expr):
"""Change BitVecSort(1) to BoolSort().
Some passes treat <unnamed-unsigned:1> as _Bool, and we may end up with,
for example, xor of a BitVecSort(1) and BoolSort()."""
if expr.sort() == BitVecSort(1):
return expr != 0
assert expr.sort() == BoolSort()
return expr
def add_to_offset(offset, val, smt_bb):
"Add a 64bit value to a pointer offset, and report UB on overflow."
assert offset.sort() == BitVecSort(PTR_OFFSET_BITS)
assert val.sort() == BitVecSort(64)
is_constant = is_bv_value(offset)
offset = ZeroExt(64 - PTR_OFFSET_BITS, offset)
offset = offset + val
is_ub = UGE(offset, (1 << PTR_OFFSET_BITS))
if is_constant:
is_ub = simplify(is_ub)
smt_bb.add_ub(is_ub)
offset = Extract(PTR_OFFSET_BITS - 1, 0, offset)
if is_constant:
offset = simplify(offset)
return offset
def bit_cast(value, src_type, dest_type):
if isinstance(src_type, gcc.RealType):
value = fpToIEEEBV(value)
elif isinstance(src_type, gcc.PointerType):
value = value.bitvector()
elif not isinstance(src_type, gcc.IntegerType):
raise NotImplementedError(f"bit_cast src_type {src_type.__class__}")
if isinstance(dest_type, gcc.RealType):
return fpBVToFP(value, get_smt_sort(dest_type))
if isinstance(dest_type, gcc.PointerType):
mem_id = Extract(63, PTR_OFFSET_BITS, value)
offset = Extract(PTR_OFFSET_BITS - 1, 0, value)
return SmtPointer(mem_id, offset)
if isinstance(dest_type, gcc.IntegerType):
return value
raise NotImplementedError(f"bit_cast dest_type {dest_type.__class__}")
def convert_to_integer(value, src_type, dest_type):
assert isinstance(dest_type, gcc.IntegerType)
if isinstance(src_type, gcc.IntegerType):
if src_type.precision > dest_type.precision:
return Extract(dest_type.precision - 1, 0, value)
if src_type.precision < dest_type.precision:
extbits = dest_type.precision - src_type.precision
if src_type.unsigned:
return ZeroExt(extbits, value)
return SignExt(extbits, value)
return value
if isinstance(src_type, gcc.BooleanType):
if value.sort() == BitVecSort(1):
return ZeroExt(dest_type.precision - 1, value)
bv0 = BitVecVal(0, dest_type.precision)
bv1 = BitVecVal(1, dest_type.precision)
return If(value, bv1, bv0)
if isinstance(src_type, gcc.PointerType):
res = value.bitvector()
if dest_type.precision < 64:
res = Extract(dest_type.precision - 1, 0, res)
elif dest_type.precision > 64:
res = ZeroExt(dest_type.precision - 64, res)
return res
raise NotImplementedError(f"convert_to_integer {src_type.__class__}")
def convert_to_pointer(value, src_type, dest_type):
assert isinstance(dest_type, gcc.PointerType)
if isinstance(src_type, gcc.BooleanType):
mem_id = BitVecVal(0, PTR_ID_BITS)
bv0 = BitVecVal(0, PTR_OFFSET_BITS)
bv1 = BitVecVal(1, PTR_OFFSET_BITS)
offset = If(value, bv1, bv0)
return SmtPointer(mem_id, offset)
if isinstance(src_type, gcc.IntegerType):
if src_type.precision < 64:
extbits = 64 - src_type.precision
if src_type.unsigned:
value = ZeroExt(extbits, value)
else:
value = SignExt(extbits, value)
mem_id = Extract(63, PTR_OFFSET_BITS, value)
offset = Extract(PTR_OFFSET_BITS - 1, 0, value)