Source file senv.ml
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
let solvers =
let open Formula_options in
[ Bitwuzla; Boolector; Z3; CVC4; Yices ]
let map =
let open Formula_options in
let open Smt_options in
function
| Auto | Bitwuzla_native -> assert false
| Bitwuzla_smtlib -> Bitwuzla
| Boolector_smtlib -> Boolector
| Z3_smtlib -> Z3
| CVC4_smtlib -> CVC4
| Yices_smtlib -> Yices
let get_solver_factory () =
let open Formula_options in
let open Smt_options in
match Smt_options.SMTSolver.get () with
| (Smt_options.Auto | Smt_options.Bitwuzla_native) when Smt_bitwuzla.available
->
(module Native_solver.Solver : Solver_sig.FACTORY)
| Auto -> (
try
let solver = List.find Prover.ping solvers in
Logger.info "Found %a in the path." Prover.pp solver;
Solver.set solver;
(module Smt2_solver.Solver : Solver_sig.FACTORY)
with Not_found -> Logger.fatal "No SMT solver found.")
| Bitwuzla_native ->
Logger.fatal "Native bitwuzla binding is required but not available."
| solver when Prover.ping (map solver) ->
Solver.set (map solver);
(module Smt2_solver.Solver : Solver_sig.FACTORY)
| solver ->
Logger.fatal "%a is required but not available in path." Prover.pp
(map solver)
exception Undef = Types.Undef
exception Uninterp = Types.Uninterp
exception Unknown = Types.Unknown
exception Non_unique = Types.Non_unique
exception Non_mergeable = Types.Non_mergeable
type 'a test = 'a Types.test =
| True of 'a
| False of 'a
| Both of { t : 'a; f : 'a }
let byte_size = Natural.to_int Basic_types.Constants.bytesize
module BiMap = Basic_types.BigInt.Map
module NiTbl = Basic_types.Int.Htbl
module Sname = Suid
open Sexpr
module BiItM = Imap
module BvSet = Set.Make (Expr)
module S = Basic_types.String.Map
module I = Basic_types.Int.Map
module R = Basic_types.Int.Htbl
module State (F : Solver_sig.FACTORY) (QS : Types.QUERY_STATISTICS) = struct
type t = {
constraints : Expr.t list;
constset : BvSet.t;
vsymbols : Expr.t I.t;
varrays : Memory.t S.t;
vmemory : Memory.t;
fid : Sname.t;
fvariables : Expr.t list S.t;
farrays : Memory.t S.t;
ilocs : (Z.t * Loader_buf.t) BiItM.t;
alocs : (Z.t * char) list ref;
model : Model.t;
}
let pp ppf state =
Model.pp ppf state.fvariables
(Kernel_options.Machine.word_size ())
state.model
let empty () =
{
constraints = [];
constset = BvSet.empty;
vsymbols = I.empty;
varrays = S.empty;
vmemory = Memory.Root;
fid = Sname.(incr zero);
fvariables = S.empty;
farrays = S.empty;
ilocs = BiItM.empty;
alocs = ref [];
model = Model.empty ();
}
let fresh ({ id; name; size; _ } : Types.Var.t) state =
let v = Expr.var (Sname.to_string state.fid) size name in
let fid = Sname.incr state.fid in
let h =
match S.find name state.fvariables with
| exception Not_found -> [ v ]
| h -> v :: h
in
let fvariables = S.add name h state.fvariables in
let vsymbols = I.add id v state.vsymbols in
{ state with vsymbols; fid; fvariables }
let alloc ~array state =
let symbol = Memory.Symbol array in
{
state with
varrays = S.add array symbol state.varrays;
farrays = S.add array symbol state.farrays;
}
let assign ({ id; _ } : Types.Var.t) value state =
{ state with vsymbols = I.add id value state.vsymbols }
let write ~addr value dir state =
{ state with vmemory = Memory.write ~addr value dir state.vmemory }
let store name ~addr value dir state =
try
let ar = S.find name state.varrays in
{
state with
varrays = S.add name (Memory.write ~addr value dir ar) state.varrays;
}
with Not_found -> raise_notrace (Uninterp name)
let read ~addr bytes dir state =
let bytes, vmemory = Memory.read ~addr bytes dir state.vmemory in
if state.vmemory == vmemory then (bytes, state)
else (bytes, { state with vmemory })
let select name ~addr bytes dir state =
try
let array = S.find name state.varrays in
let bytes, array' = Memory.read ~addr bytes dir array in
if array == array' then (bytes, state)
else (bytes, { state with varrays = S.add name array' state.varrays })
with Not_found -> raise_notrace (Uninterp name)
let memcpy ~addr len orig state =
let base = Bv.value_of addr in
let ilocs = BiItM.add ~base len (Bv.value_of addr, orig) state.ilocs in
let vmemory =
Memory.source ~addr:(Expr.constant addr) ~len orig state.vmemory
in
{ state with ilocs; vmemory }
module Engine (Solver : Solver_sig.S) = struct
type result = Unsat | Sat of t
let state =
match Solver.get_array Memory.Root with
| (exception Not_found) | [||] -> (BiTbl.create 0, !(state.alocs))
| assignment ->
let memory = BiTbl.create (Array.length assignment) in
let alocs =
Array.fold_left
(fun alocs (addr, value) ->
match BiItM.find addr state.ilocs with
| exception Not_found ->
BiTbl.add memory addr value;
alocs
| base, img ->
let offset = Z.to_int (Z.sub addr base) in
let value' =
Char.unsafe_chr
(if offset < Bigarray.Array1.dim img then
Bigarray.Array1.get img offset
else 0)
in
if value <> value' then (addr, value') :: alocs else alocs)
!(state.alocs) assignment
in
(memory, alocs)
let name =
match Solver.get_array name with
| (exception Not_found) | [||] -> BiTbl.create 0
| assignment ->
let array = BiTbl.create (Array.length assignment) in
Array.iter
(fun (addr, value) -> BiTbl.add array addr value)
assignment;
array
let state =
let arrays = StTbl.create 5 in
S.iter
(fun name symbol -> StTbl.add arrays name (extract_array symbol))
state.farrays;
arrays
let state =
let vars = BvTbl.create 32 in
S.iter
(fun _ ->
List.iter (fun bv ->
match Solver.get bv with
| exception Not_found -> ()
| x ->
BvTbl.add vars bv
(Bitvector.create Solver.(get_value x) (Expr.sizeof bv))))
state.fvariables;
vars
let rec force_lazy_init alocs state =
if alocs == !(state.alocs) = false then
match alocs with
| [] -> ()
| (addr, value) :: alocs ->
Solver.set_memory ~addr (Z.of_int (Char.code value));
force_lazy_init alocs state
let enumerate =
let rec iter state e expr size n enum =
if n = 0 then enum
else
match Solver.check_sat () with
| Unknown ->
QS.Solver.incr_err ();
raise Unknown
| Unsat ->
QS.Solver.incr_unsat ();
enum
| Sat ->
QS.Solver.incr_sat ();
let memory, alocs = extract_memory state in
if alocs == !(state.alocs) = false then (
force_lazy_init alocs state;
state.alocs := alocs;
iter state e expr size n enum)
else
let x = Solver.get_value expr in
let b = Bv.create x size in
let cond = Expr.equal e (Expr.constant b) in
let state' =
{
state with
constraints = cond :: state.constraints;
constset = BvSet.add cond state.constset;
model = (extract_vars state, memory, extract_arrays state);
}
in
Solver.neq expr x;
iter state e expr size (n - 1) ((b, state') :: enum)
in
fun e ?(n = (1 lsl Expr.sizeof e) - 1) ?(except = []) state ->
let size = Expr.sizeof e in
let expr = Solver.bind state.fid e state.constraints in
List.iter
(fun (addr, value) ->
Solver.set_memory ~addr (Z.of_int (Char.code value)))
!(state.alocs);
let init =
let bv = Model.eval state.model e in
if List.mem bv except then []
else (
QS.Preprocess.incr_const ();
Solver.neq expr (Bitvector.value_of bv);
let cond = Expr.equal e (Expr.constant bv) in
[
( bv,
{
state with
constraints = cond :: state.constraints;
constset = BvSet.add cond state.constset;
} );
])
in
List.iter (fun bv -> Solver.neq expr (Bitvector.value_of bv)) except;
iter state e expr size (n - 1) init
let check_sat =
let rec check_sat_true state =
match Solver.check_sat () with
| Unknown -> raise Unknown
| Unsat -> Unsat
| Sat ->
let memory, alocs = extract_memory state in
if alocs == !(state.alocs) = false then (
force_lazy_init alocs state;
state.alocs := alocs;
check_sat_true state)
else
Sat
{
state with
model = (extract_vars state, memory, extract_arrays state);
}
in
fun state ->
Solver.put state.fid state.constraints;
List.iter
(fun (addr, value) ->
Solver.set_memory ~addr (Z.of_int (Char.code value)))
!(state.alocs);
check_sat_true state
let close () = Solver.close ()
end
let assume cond state =
if Expr.is_equal cond Expr.one then (
QS.Preprocess.incr_sat ();
Some state)
else if Expr.is_equal cond Expr.zero then (
QS.Preprocess.incr_unsat ();
None)
else if BvSet.mem cond state.constset then (
QS.Preprocess.incr_sat ();
Some state)
else if BvSet.mem (Expr.lognot cond) state.constset then (
QS.Preprocess.incr_unsat ();
None)
else
let state =
{
state with
constraints = cond :: state.constraints;
constset = BvSet.add cond state.constset;
}
in
if Bitvector.zero = Model.eval state.model cond then (
QS.Solver.start_timer ();
let open Engine (F ()) in
let r =
match check_sat state with
| exception Unknown ->
QS.Solver.incr_err ();
raise Unknown
| Unsat ->
QS.Solver.incr_unsat ();
None
| Sat state ->
QS.Solver.incr_sat ();
Some state
in
close ();
QS.Solver.stop_timer ();
r)
else (
QS.Preprocess.incr_sat ();
Some state)
let test cond state =
if Expr.is_equal cond Expr.one then (
QS.Preprocess.incr_sat ();
True state)
else if Expr.is_equal cond Expr.zero then (
QS.Preprocess.incr_unsat ();
False state)
else if BvSet.mem cond state.constset then (
QS.Preprocess.incr_sat ();
True state)
else if BvSet.mem (Expr.lognot cond) state.constset then (
QS.Preprocess.incr_unsat ();
False state)
else
let t =
{
state with
constraints = cond :: state.constraints;
constset = BvSet.add cond state.constset;
}
in
let ncond = Expr.lognot cond in
let f =
{
state with
constraints = ncond :: state.constraints;
constset = BvSet.add ncond state.constset;
}
in
let e = Model.eval state.model cond in
let s = if Bv.is_zero e then t else f in
QS.Solver.start_timer ();
let open Engine (F ()) in
let r =
match check_sat s with
| exception Unknown ->
QS.Solver.incr_err ();
raise Unknown
| Unsat ->
QS.Solver.incr_unsat ();
if Bv.is_zero e then False f else True t
| Sat state ->
QS.Solver.incr_sat ();
if Bv.is_zero e then Both { t = state; f }
else Both { t; f = state }
in
close ();
QS.Solver.stop_timer ();
r
let enumerate =
let with_solver e ?n ?except state =
QS.Solver.start_timer ();
let open Engine (F ()) in
let r = enumerate e ?n ?except state in
close ();
QS.Solver.stop_timer ();
r
in
fun e ?n ?(except = []) state ->
match (e, n) with
| Expr.Cst bv, _ when List.mem bv except = false ->
QS.Preprocess.incr_const ();
[ (bv, state) ]
| Expr.Cst _, _ ->
QS.Preprocess.incr_const ();
[]
| _, Some 1 ->
let bv = Model.eval state.model e in
if List.mem bv except then with_solver e ?n ~except state
else (
QS.Preprocess.incr_const ();
let cond = Expr.equal e (Expr.constant bv) in
[
( bv,
{
state with
constraints = cond :: state.constraints;
constset = BvSet.add cond state.constset;
} );
])
| _, _ -> with_solver e ?n ~except state
let merge t t' =
if t == t' then t
else if
t.fid = t'.fid
&& t.fvariables == t'.fvariables
&& t.farrays == t'.farrays && t.ilocs == t'.ilocs
then
match (t.constraints, t'.constraints) with
| c :: constraints, c' :: constraints'
when constraints == constraints' && Expr.is_equal c (Expr.lognot c') ->
let constset = BvSet.remove c t.constset
and vsymbols =
if t.vsymbols == t'.vsymbols then t.vsymbols
else
I.merge
(fun _ o0 o1 ->
match (o0, o1) with
| Some e0, Some e1 ->
if Expr.is_equal e0 e1 then o0
else Some (Expr.ite c e0 e1)
| (Some _ | None), (Some _ | None) ->
raise_notrace Non_mergeable)
t.vsymbols t'.vsymbols
and varrays =
if t.varrays == t'.varrays then t.varrays
else
S.merge
(fun _ o0 o1 ->
match (o0, o1) with
| Some a0, Some a1 -> Some (Memory.merge c a0 a1)
| (Some _ | None), (Some _ | None) ->
raise_notrace Non_mergeable)
t.varrays t'.varrays
and vmemory = Memory.merge c t.vmemory t'.vmemory
and fid = t.fid
and fvariables = t.fvariables
and farrays = t.farrays
and ilocs = t.ilocs
and alocs = t.alocs
and model = t.model in
{
constraints;
constset;
vsymbols;
varrays;
vmemory;
fid;
fvariables;
farrays;
ilocs;
alocs;
model;
}
| _ -> raise_notrace Non_mergeable
else raise_notrace Non_mergeable
module Value = struct
type t = Expr.t
let constant = Expr.constant
let lookup ({ id; _ } as var : Types.Var.t) t =
try I.find id t.vsymbols with Not_found -> raise_notrace (Undef var)
let read = read
let select = select
let unary = Expr.unary
let binary = Expr.binary
let ite = Expr.ite
let uop e = function
| Dba.Unary_op.Not -> Term.Not
| Dba.Unary_op.UMinus -> Term.Minus
| Dba.Unary_op.Sext n -> Term.Sext (n - Dba.Expr.size_of e)
| Dba.Unary_op.Uext n -> Term.Uext (n - Dba.Expr.size_of e)
| Dba.Unary_op.Restrict interval -> Term.Restrict interval
let bop op =
let open Dba.Binary_op in
match op with
| Plus -> Term.Plus
| Minus -> Term.Minus
| Mult -> Term.Mul
| DivU -> Term.Udiv
| DivS -> Term.Sdiv
| ModU -> Term.Umod
| ModS -> Term.Smod
| Eq -> Term.Eq
| Diff -> Term.Diff
| LeqU -> Term.Ule
| LtU -> Term.Ult
| GeqU -> Term.Uge
| GtU -> Term.Ugt
| LeqS -> Term.Sle
| LtS -> Term.Slt
| GeqS -> Term.Sge
| GtS -> Term.Sgt
| Xor -> Term.Xor
| And -> Term.And
| Or -> Term.Or
| Concat -> Term.Concat
| LShift -> Term.Lsl
| RShiftU -> Term.Lsr
| RShiftS -> Term.Asr
| LeftRotate -> Term.Rol
| RightRotate -> Term.Ror
let rec eval (e : Types.Expr.t) t =
match e with
| Cst bv | Var { info = Symbol (_, (lazy bv)); _ } -> constant bv
| Var var -> lookup var t
| Load (len, dir, addr, None) -> fst (read ~addr:(eval addr t) len dir t)
| Load (len, dir, addr, Some name) ->
fst (select name ~addr:(eval addr t) len dir t)
| Unary (f, x) -> unary (uop x f) (eval x t)
| Binary (f, x, y) -> binary (bop f) (eval x t) (eval y t)
| Ite (c, r, e) -> ite (eval c t) (eval r t) (eval e t)
end
let get_value (e : Expr.t) _ =
match e with Cst bv -> bv | _ -> raise_notrace Non_unique
let pp_smt (target : Types.target) ppf t =
let module P = Smt2_solver.Printer in
let ctx =
P.create ~debug:(fun ~name ~label -> label ^ name) ~next_id:t.fid ()
in
List.iter (P.visit_bl ctx) t.constraints;
let defs =
match target with
| Some defs ->
let rec proceed defs t =
try
List.map
(fun (expr, name) ->
let expr = Value.eval expr t in
P.visit_bv ctx expr;
(expr, name))
defs
with
| Undef var -> proceed defs (fresh var t)
| Uninterp array -> proceed defs (alloc ~array t)
in
proceed defs t
| None ->
P.visit_ax ctx t.vmemory;
List.rev
(I.fold
(fun id expr defs ->
P.visit_bv ctx expr;
(expr, (Dba.Var.from_id id).name) :: defs)
t.vsymbols [])
in
Format.pp_open_vbox ppf 0;
P.pp_print_decls ppf ctx;
P.pp_print_defs ppf ctx;
List.iter
(fun (bv, name) ->
Format.fprintf ppf "@[<h>(define-fun %s () (_ BitVec %d)@ " name
(Expr.sizeof bv);
P.pp_print_bv ctx ppf bv;
Format.fprintf ppf ")@]@ ")
defs;
if target = None then
Format.fprintf ppf
"@[<h>(define-fun memory () (Array (_ BitVec %d) (_ BitVec 8))@ %a)@]"
(Kernel_options.Machine.word_size ())
(P.pp_print_ax ctx) t.vmemory;
List.iter
(fun bl ->
Format.pp_open_hbox ppf ();
Format.pp_print_string ppf "(assert ";
P.pp_print_bl ctx ppf bl;
Format.pp_print_char ppf ')';
Format.pp_close_box ppf ();
Format.pp_print_space ppf ())
t.constraints;
Format.pp_close_box ppf ()
let as_ascii ~name t =
let buf = Buffer.create 16 in
List.iter (fun var ->
assert (Expr.sizeof var mod byte_size = 0);
let rec iter bv =
let size = Bitvector.size_of bv in
if size = byte_size then Buffer.add_char buf (Bitvector.to_char bv)
else
let byte = Bitvector.extract bv { Interval.lo = 0; hi = 7 } in
Buffer.add_char buf (Bitvector.to_char byte);
iter (Bitvector.extract bv { Interval.lo = 8; hi = size - 1 })
in
iter (Model.eval t.model var))
@@ List.rev @@ S.find name t.fvariables;
Buffer.contents buf
let as_c_string ~name t =
try
let ar = S.find name t.varrays in
let buf = Buffer.create 16 in
let rec iter addr =
let byte =
Model.eval t.model (fst (Memory.read ~addr 1 Machine.LittleEndian ar))
in
if Bitvector.is_zeros byte then Buffer.contents buf
else (
Buffer.add_char buf (Bitvector.to_char byte);
iter (Expr.addi addr 1))
in
iter (Expr.zeros (Kernel_options.Machine.word_size ()))
with Not_found -> ""
let to_formula t =
let module C = Smt2_solver.Cross in
let ctx =
C.create ~debug:(fun ~name ~label -> label ^ name) ~next_id:t.fid ()
in
List.iter (C.assert_bl ctx) t.constraints;
C.define_ax ctx "memory" t.vmemory;
I.iter
(fun id expr -> C.define_bv ctx (Dba.Var.from_id id).name expr)
t.vsymbols;
C.to_formula ctx
end