MemTyped.ml 40.9 KB
Newer Older
Loïc Correnson's avatar
Loïc Correnson committed
1
2
3
4
(**************************************************************************)
(*                                                                        *)
(*  This file is part of WP plug-in of Frama-C.                           *)
(*                                                                        *)
Andre Maroneze's avatar
Andre Maroneze committed
5
(*  Copyright (C) 2007-2020                                               *)
Loïc Correnson's avatar
Loïc Correnson committed
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
(*    CEA (Commissariat a l'energie atomique et aux energies              *)
(*         alternatives)                                                  *)
(*                                                                        *)
(*  you can redistribute it and/or modify it under the terms of the GNU   *)
(*  Lesser General Public License as published by the Free Software       *)
(*  Foundation, version 2.1.                                              *)
(*                                                                        *)
(*  It is distributed in the hope that it will be useful,                 *)
(*  but WITHOUT ANY WARRANTY; without even the implied warranty of        *)
(*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *)
(*  GNU Lesser General Public License for more details.                   *)
(*                                                                        *)
(*  See the GNU Lesser General Public License version 2.1                 *)
(*  for more details (enclosed in the file licenses/LGPLv2.1).            *)
(*                                                                        *)
(**************************************************************************)

(* -------------------------------------------------------------------------- *)
(* --- Empty Memory Model                                                 --- *)
(* -------------------------------------------------------------------------- *)

open Cil_types
open Cil_datatype
open Ctypes
open Lang
open Lang.F
open Sigs
open Definitions
34
open MemMemory
Loïc Correnson's avatar
Loïc Correnson committed
35
36
37
38
39

let dkey_layout = Wp_parameters.register_category "layout"

module L = Qed.Logic

40
41
42
43
(* -------------------------------------------------------------------------- *)
(* --- Model Configuration                                                --- *)
(* -------------------------------------------------------------------------- *)

Loïc Correnson's avatar
Loïc Correnson committed
44
let datatype = "MemTyped"
45
let hypotheses p = p
46
47
let configure () =
  begin
Loïc Correnson's avatar
Loïc Correnson committed
48
    let orig_pointer = Context.push Lang.pointer t_addr in
49
50
51
52
53
54
    let orig_null    = Context.push Cvalues.null (p_equal a_null) in
    let rollback () =
      Context.pop Lang.pointer orig_pointer ;
      Context.pop Cvalues.null orig_null ;
    in
    rollback
55
  end
56

57
58
59
60
61
62
63
64
65
66
67
68
69
70
let configure_ia =
  let no_binder = { bind = fun _ f v -> f v } in
  fun _vertex -> no_binder

(* -------------------------------------------------------------------------- *)
(* --- Model Parameters                                                   --- *)
(* -------------------------------------------------------------------------- *)

type pointer = NoCast | Fits | Unsafe
let pointer = Context.create "MemTyped.pointer"

(* -------------------------------------------------------------------------- *)
(* --- Model Semantics                                                    --- *)
(* -------------------------------------------------------------------------- *)
Loïc Correnson's avatar
Loïc Correnson committed
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

(*

   the semantic is defined using these notions:
    - base, offset: has the usual C semantic

    - memory model consists of:
         - an allocation table A : base -> int
         - for each kind of cell (char,int,float,pointer(ptr)) with type T, a map (M_T) : addr -> T

    - a pointer is record { base ; offset }, offset are in number of cells

    - allocation table: indicate the size (in number of cell not sizeof)
       allocated of each base.
         - = 0 : free
         - > 0 : allocated read-write
         - < 0 : allocated read only

   semantic of all these functions:

    - region(base -> int): the regions represent the natural partition of the memory
       by the time when it have been allocated. So the regions are
       identified by a number. So the addresses in one base are all in
       the same region. Caveat the [region] function doesn't associate
       the base to its region directly but to a congruence class that
       depend of each function but which keeps the order:
        - = 1 : regions corresponds to formals
        - = 2 : regions corresponds to locals
        - > 2 : freshly allocated bases (malloc)
        - = 0 : globals (except string literals)
        - < 0 : string literals (-its id)

    - framed(M_ptr): All pointer values accessible from the memory M (of pointers),
      lives in region <= 0. Hence separated from locals, formals, and
      freshly allocated in the current function.

    - linked(A): The proposition [linked] indicate that an allocation
      table were the globals are allocated.

    - sconst(M_char): Indicate that the memory M (of chars) contains the values of
      string literals at their bases.

*)

(* -------------------------------------------------------------------------- *)
(* --- Chunks                                                             --- *)
(* -------------------------------------------------------------------------- *)

type chunk =
120
  | M_int of Ctypes.c_int
Loïc Correnson's avatar
Loïc Correnson committed
121
  | M_char
122
123
  | M_f32
  | M_f64
Loïc Correnson's avatar
Loïc Correnson committed
124
125
  | M_pointer
  | T_alloc
Allan Blanchard's avatar
Allan Blanchard committed
126
  | T_init
Loïc Correnson's avatar
Loïc Correnson committed
127
128
129
130
131

module Chunk =
struct
  type t = chunk
  let self = "typed"
132
133
  let int_rank = function
    | CBool -> 0
134
135
136
137
138
139
140
141
    | UInt8 -> 1
    | SInt8 -> 2
    | UInt16 -> 3
    | SInt16 -> 4
    | UInt32 -> 5
    | SInt32 -> 6
    | UInt64 -> 7
    | SInt64 -> 8
142

Loïc Correnson's avatar
Loïc Correnson committed
143
  let rank = function
144
145
    | M_char -> -1
    | M_int i -> int_rank i
146
147
148
149
    | M_f32 -> 9
    | M_f64 -> 10
    | M_pointer -> 11
    | T_alloc -> 12
Allan Blanchard's avatar
Allan Blanchard committed
150
    | T_init -> 13
Loïc Correnson's avatar
Loïc Correnson committed
151
152
  let hash = rank
  let name = function
153
    | M_int _ -> "Mint"
Loïc Correnson's avatar
Loïc Correnson committed
154
    | M_char -> "Mchar"
155
156
    | M_f32 -> "Mf32"
    | M_f64 -> "Mf64"
Loïc Correnson's avatar
Loïc Correnson committed
157
158
    | M_pointer -> "Mptr"
    | T_alloc -> "Malloc"
Allan Blanchard's avatar
Allan Blanchard committed
159
    | T_init -> "Init"
Loïc Correnson's avatar
Loïc Correnson committed
160
161
162
  let compare a b = rank a - rank b
  let equal = (=)
  let pretty fmt c = Format.pp_print_string fmt (name c)
163
164
165
  let detailed_pretty fmt = function
    | M_int i -> Format.fprintf fmt "M%a" Ctypes.pp_int i
    | m -> Format.pp_print_string fmt (name m)
Loïc Correnson's avatar
Loïc Correnson committed
166
  let val_of_chunk = function
167
    | M_int _ | M_char -> L.Int
168
169
    | M_f32 -> Cfloat.tau_of_float Ctypes.Float32
    | M_f64 -> Cfloat.tau_of_float Ctypes.Float64
Loïc Correnson's avatar
Loïc Correnson committed
170
171
    | M_pointer -> t_addr
    | T_alloc -> L.Int
Allan Blanchard's avatar
Allan Blanchard committed
172
    | T_init -> L.Bool
173
  let tau_of_chunk = function
174
    | M_int _ | M_char -> L.Array(t_addr,L.Int)
175
176
177
    | M_pointer -> L.Array(t_addr,t_addr)
    | M_f32 -> L.Array(t_addr,Cfloat.tau_of_float Ctypes.Float32)
    | M_f64 -> L.Array(t_addr,Cfloat.tau_of_float Ctypes.Float64)
178
179
    | T_alloc -> t_malloc
    | T_init -> t_init
Loïc Correnson's avatar
Loïc Correnson committed
180
181
182
183
184
185
186
187
188
189
190
191
192
  let basename_of_chunk = name
  let is_framed _ = false
end

module Heap = Qed.Collection.Make(Chunk)
module Sigma = Sigma.Make(Chunk)(Heap)

type loc = term (* of type addr *)

(* -------------------------------------------------------------------------- *)
(* --- Utilities on locations                                             --- *)
(* -------------------------------------------------------------------------- *)

193
let m_int i = if Ctypes.is_char i then M_char else M_int i
194
let m_float = function Float32 -> M_f32 | Float64 -> M_f64
Loïc Correnson's avatar
Loïc Correnson committed
195
196
197

let rec footprint = function
  | C_int i -> Heap.Set.singleton (m_int i)
198
  | C_float f -> Heap.Set.singleton (m_float f)
Loïc Correnson's avatar
Loïc Correnson committed
199
200
201
202
203
204
205
206
207
208
  | C_pointer _ -> Heap.Set.singleton M_pointer
  | C_array a -> footprint (object_of a.arr_element)
  | C_comp c -> footprint_comp c

and footprint_comp c =
  List.fold_left
    (fun ft f ->
       Heap.Set.union ft (footprint (object_of f.ftype))
    ) Heap.Set.empty c.cfields

209
210
let init_footprint _ _ = Heap.Set.singleton T_init
let value_footprint obj _l = footprint obj
Loïc Correnson's avatar
Loïc Correnson committed
211

212
let rec length_of_object = function
Loïc Correnson's avatar
Loïc Correnson committed
213
  | C_int _ | C_float _ | C_pointer _ -> 1
214
  | C_comp c -> length_of_comp c
Loïc Correnson's avatar
Loïc Correnson committed
215
  | C_array { arr_flat = Some { arr_size = n } ; arr_element = elt } ->
216
      n * (length_of_typ elt)
Loïc Correnson's avatar
Loïc Correnson committed
217
218
219
220
221
222
223
  | C_array _ as a ->
      if Wp_parameters.ExternArrays.get () then
        max_int
      else
        Warning.error ~source:"Typed Model"
          "Undefined array-size (%a)" Ctypes.pretty a

224
225
226
and length_of_typ t = length_of_object (object_of t)
and length_of_field f = length_of_typ f.ftype
and length_of_comp c =
227
  (* union field are considered as struct field *)
Loïc Correnson's avatar
Loïc Correnson committed
228
  List.fold_left
229
    (fun s f -> s + length_of_field f)
Loïc Correnson's avatar
Loïc Correnson committed
230
231
    0 c.cfields

232
let position_of_field f =
Loïc Correnson's avatar
Loïc Correnson committed
233
234
235
236
  let rec fnext k f = function
    | [] -> assert false
    | g::gs ->
        if Fieldinfo.equal f g then k
237
        else fnext (k + length_of_field g) f gs
Loïc Correnson's avatar
Loïc Correnson committed
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
  in fnext 0 f f.fcomp.cfields

(* -------------------------------------------------------------------------- *)
(* --- Utilities on loc-as-term                                           --- *)
(* -------------------------------------------------------------------------- *)

type sigma = Sigma.t
type domain = Sigma.domain
type segment = loc rloc

let pretty fmt l = F.pp_term fmt l
let vars l = F.vars l
let occurs x l = F.occurs x l

(* -------------------------------------------------------------------------- *)
(* --- Generated Axiomatization                                           --- *)
(* -------------------------------------------------------------------------- *)

let cluster_globals () =
  Definitions.cluster ~id:"Globals" ~title:"Global Variables" ()

259
260
261
type shift =
  | RS_Field of fieldinfo * int (* offset of the field *)
  | RS_Index of int  (* size of the shift *)
Loïc Correnson's avatar
Loïc Correnson committed
262

263
264
265
266
267
268
269
270
271
272
273
274
let phi_base = function
  | p::_ -> a_base p
  | _ -> raise Not_found

let phi_field offset = function
  | [p] -> e_add (a_offset p) (F.e_int offset)
  | _ -> raise Not_found

let phi_index size = function
  | [p;k] -> e_add (a_offset p) (F.e_fact size k)
  | _ -> raise Not_found

275
module RegisterShift = WpContext.Static
276
277
278
279
280
281
    (struct
      type key = lfun
      type data = shift
      let name = "MemTyped.RegisterShift"
      include Lang.Fun
    end)
Loïc Correnson's avatar
Loïc Correnson committed
282

283
module ShiftFieldDef = WpContext.StaticGenerator(Cil_datatype.Fieldinfo)
Loïc Correnson's avatar
Loïc Correnson committed
284
285
286
287
288
289
290
291
    (struct
      let name = "MemTyped.ShiftFieldDef"
      type key = fieldinfo
      type data = dfun

      let generate f =
        let result = t_addr in
        let lfun = Lang.generated_f ~result "shiftfield_%s" (Lang.field_id f) in
292
        let position = position_of_field f in
Loïc Correnson's avatar
Loïc Correnson committed
293
294
295
        (* Since its a generated it is the unique name given *)
        let xloc = Lang.freshvar ~basename:"p" t_addr in
        let loc = e_var xloc in
296
        let def = a_shift loc (F.e_int position) in
Loïc Correnson's avatar
Loïc Correnson committed
297
        let dfun = Definitions.Function( result , Def , def) in
298
299
        RegisterShift.define lfun (RS_Field(f,position)) ;
        MemMemory.register ~base:phi_base ~offset:(phi_field position) lfun ;
Loïc Correnson's avatar
Loïc Correnson committed
300
301
302
303
        {
          d_lfun = lfun ; d_types = 0 ;
          d_params = [xloc] ;
          d_definition = dfun ;
304
          d_cluster = Definitions.dummy () ;
Loïc Correnson's avatar
Loïc Correnson committed
305
306
307
308
309
        }

      let compile = Lang.local generate
    end)

310
module ShiftField = WpContext.Generator(Cil_datatype.Fieldinfo)
Loïc Correnson's avatar
Loïc Correnson committed
311
312
313
314
315
316
    (struct
      let name = "MemTyped.ShiftField"
      type key = fieldinfo
      type data = lfun
      let compile fd =
        let dfun = ShiftFieldDef.get fd in
317
        let d_cluster = MemLoader.cluster () in
Loïc Correnson's avatar
Loïc Correnson committed
318
319
320
321
322
323
324
325
326
327
328
329
330
        Definitions.define_symbol { dfun with d_cluster } ;
        dfun.d_lfun
    end)

module Cobj =
struct
  type t = c_object
  let pretty = C_object.pretty
  let compare = compare_ptr_conflated
end

(* This is a model-independent generator,
   which will be inherited from the model-dependent clusters *)
331
module ShiftGen = WpContext.StaticGenerator(Cobj)
Loïc Correnson's avatar
Loïc Correnson committed
332
333
334
335
336
337
338
339
340
    (struct
      let name = "MemTyped.ShiftDef"
      type key = c_object
      type data = dfun

      let rec c_object_id fmt = function
        | C_int i -> pp_int fmt i
        | C_float f -> pp_float fmt f
        | C_pointer _ -> Format.fprintf fmt "PTR"
341
        | C_comp c -> Format.pp_print_string fmt (Lang.comp_id c)
Loïc Correnson's avatar
Loïc Correnson committed
342
343
344
345
346
347
348
349
350
351
352
        | C_array a ->
            let te = object_of a.arr_element in
            match a.arr_flat with
            | None -> Format.fprintf fmt "A_%a" c_object_id te
            | Some f -> Format.fprintf fmt "A%d_%a" f.arr_size c_object_id te

      let c_object_id c = Format.asprintf "%a@?" c_object_id c

      let generate obj =
        let result = t_addr in
        let shift = Lang.generated_f ~result "shift_%s" (c_object_id obj) in
353
        let size = length_of_object obj in
Loïc Correnson's avatar
Loïc Correnson committed
354
355
356
357
358
        (* Since its a generated it is the unique name given *)
        let xloc = Lang.freshvar ~basename:"p" t_addr in
        let loc = e_var xloc in
        let xk = Lang.freshvar ~basename:"k" Qed.Logic.Int in
        let k = e_var xk in
359
        let def = a_shift loc (F.e_fact size k) in
Loïc Correnson's avatar
Loïc Correnson committed
360
        let dfun = Definitions.Function( result , Def , def) in
361
362
363
        RegisterShift.define shift (RS_Index size) ;
        MemMemory.register ~base:phi_base ~offset:(phi_index size)
          ~linear:true shift ;
Loïc Correnson's avatar
Loïc Correnson committed
364
365
366
367
        {
          d_lfun = shift ; d_types = 0 ;
          d_params = [xloc;xk] ;
          d_definition = dfun ;
368
          d_cluster = Definitions.dummy () ;
Loïc Correnson's avatar
Loïc Correnson committed
369
370
371
372
373
374
        }

      let compile = Lang.local generate
    end)

(* The model-dependent derivation of model-independent ShiftDef *)
375
module Shift = WpContext.Generator(Cobj)
Loïc Correnson's avatar
Loïc Correnson committed
376
377
378
379
380
381
    (struct
      let name = "MemTyped.Shift"
      type key = c_object
      type data = lfun
      let compile obj =
        let dfun = ShiftGen.get obj in
382
        let d_cluster = MemLoader.cluster () in
Loïc Correnson's avatar
Loïc Correnson committed
383
384
385
386
387
388
389
390
391
392
        Definitions.define_symbol { dfun with d_cluster } ;
        dfun.d_lfun
    end)

let field l f = e_fun (ShiftField.get f) [l]
let shift l obj k = e_fun (Shift.get obj) [l;k]

module LITERAL =
struct
  type t = int * Cstring.cst
393
  let compare (a:t) (b:t) = Stdlib.compare (fst a) (fst b)
Loïc Correnson's avatar
Loïc Correnson committed
394
395
396
397
398
399
400
401
402
403
  let pretty fmt (eid,cst) = Format.fprintf fmt "%a@%d" Cstring.pretty cst eid
end

module EID = State_builder.Ref(Datatype.Int)
    (struct
      let name = "Wp.MemTyped.EID"
      let dependencies = [Ast.self]
      let default () = 0
    end)

404
module STRING = WpContext.Generator(LITERAL)
Loïc Correnson's avatar
Loïc Correnson committed
405
406
407
408
409
410
411
412
413
414
415
416
417
    (struct
      let name = "MemTyped.STRING"
      type key = LITERAL.t
      type data = term

      let linked prefix base cst =
        let name = prefix ^ "_linked" in
        let a = Lang.freshvar ~basename:"alloc" (Chunk.tau_of_chunk T_alloc) in
        let m = e_var a in
        let m_linked = p_call p_linked [m] in
        let alloc = F.e_get m base in (* The size is alloc-1 *)
        let sized = Cstring.str_len cst (F.e_add alloc F.e_minus_one) in
        Definitions.define_lemma {
Loïc Correnson's avatar
Loïc Correnson committed
418
          l_kind = `Axiom ;
Loïc Correnson's avatar
Loïc Correnson committed
419
420
421
422
423
424
425
426
427
428
          l_name = name ; l_types = 0 ;
          l_triggers = [] ; l_forall = [] ;
          l_lemma = p_forall [a] (p_imply m_linked sized) ;
          l_cluster = Cstring.cluster () ;
        }

      let region prefix base cst =
        let name = prefix ^ "_region" in
        let re = - Cstring.str_id cst in
        Definitions.define_lemma {
Loïc Correnson's avatar
Loïc Correnson committed
429
          l_kind = `Axiom ;
Loïc Correnson's avatar
Loïc Correnson committed
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
          l_name = name ; l_types = 0 ; l_triggers = [] ; l_forall = [] ;
          l_lemma = p_equal (e_fun f_region [base]) (e_int re) ;
          l_cluster = Cstring.cluster () ;
        }

      let sconst prefix base cst =
        (** describe the content of literal strings *)
        let name = prefix ^ "_literal" in
        let i = Lang.freshvar ~basename:"i" L.Int in
        let c = Cstring.char_at cst (e_var i) in
        let addr = shift (a_global base) (C_int (Ctypes.c_char ())) (e_var i) in
        let m = Lang.freshvar ~basename:"mchar" (Chunk.tau_of_chunk M_char) in
        let m_sconst = F.p_call p_sconst [e_var m] in
        let v = F.e_get (e_var m) addr in
        let read = F.p_equal c v in
        Definitions.define_lemma {
Loïc Correnson's avatar
Loïc Correnson committed
446
          l_kind = `Axiom ;
Loïc Correnson's avatar
Loïc Correnson committed
447
448
449
450
451
452
453
454
455
          l_name = name ; l_types = 0 ; l_triggers = [] ;
          l_forall = [m;i] ;
          l_cluster = Cstring.cluster () ;
          l_lemma = F.p_imply m_sconst read ;
        }

      let fresh () =
        let eid = succ (EID.get ()) in
        EID.set eid ; eid
Loïc Correnson's avatar
Loïc Correnson committed
456

Loïc Correnson's avatar
Loïc Correnson committed
457
458
459
460
461
462
463
464
465
466
467
468
469
      let compile (_,cst) =
        let eid = fresh () in
        let lfun = Lang.generated_f ~result:L.Int "Str_%d" eid in
        (* Since its a generated it is the unique name given *)
        let prefix = Lang.Fun.debug lfun in
        let base = F.e_fun lfun [] in
        Definitions.define_symbol {
          d_lfun = lfun ; d_types = 0 ; d_params = [] ;
          d_definition = Logic L.Int ;
          d_cluster = Cstring.cluster () ;
        } ;
        Definitions.define_lemma {
          l_name = prefix ^ "_base" ;
Loïc Correnson's avatar
Loïc Correnson committed
470
          l_kind = `Axiom ;
Loïc Correnson's avatar
Loïc Correnson committed
471
472
473
474
475
476
477
478
479
480
481
          l_types = 0 ; l_triggers = [] ; l_forall = [] ;
          l_lemma = F.p_lt base F.e_zero ;
          l_cluster = Cstring.cluster () ;
        } ;
        region prefix base cst ;
        linked prefix base cst ;
        sconst prefix base cst ;
        base

    end)

482
483
484
485
(* -------------------------------------------------------------------------- *)
(* --- Base Registration                                                  --- *)
(* -------------------------------------------------------------------------- *)

486
module RegisterBASE = WpContext.Index
Loïc Correnson's avatar
Loïc Correnson committed
487
488
489
490
491
492
493
    (struct
      type key = lfun
      type data = varinfo
      let name = "MemTyped.RegisterBASE"
      include Lang.Fun
    end)

494
module BASE = WpContext.Generator(Varinfo)
Loïc Correnson's avatar
Loïc Correnson committed
495
496
497
498
499
500
501
502
503
    (struct
      let name = "MemTyped.BASE"
      type key = varinfo
      type data = term

      let region prefix x base =
        let name = prefix ^ "_region" in
        let re = if x.vglob then 0 else if x.vformal then 1 else 2 in
        Definitions.define_lemma {
Loïc Correnson's avatar
Loïc Correnson committed
504
          l_kind = `Axiom ;
Loïc Correnson's avatar
Loïc Correnson committed
505
506
507
508
509
          l_name = name ; l_types = 0 ; l_triggers = [] ; l_forall = [] ;
          l_lemma = p_equal (e_fun f_region [base]) (e_int re) ;
          l_cluster = cluster_globals () ;
        }

510
511
512
513
514
515
516
      let sizeof x =
        Warning.handle
          ~handler:(fun _ -> None)
          ~effect:(Printf.sprintf "No allocation size for variable '%s'" x.vname)
          (fun obj -> Some (length_of_object obj))
          (Ctypes.object_of x.vtype)

Loïc Correnson's avatar
Loïc Correnson committed
517
518
      let linked prefix x base =
        let name = prefix ^ "_linked" in
519
        let size = if x.vglob then sizeof x else Some 0 in
Loïc Correnson's avatar
Loïc Correnson committed
520
521
522
        match size with
        | None -> ()
        | Some size ->
523
            let a = Lang.freshvar ~basename:"alloc" t_malloc in
Loïc Correnson's avatar
Loïc Correnson committed
524
525
526
527
            let m = e_var a in
            let m_linked = p_call p_linked [m] in
            let base_size = p_equal (F.e_get m base) (e_int size) in
            Definitions.define_lemma {
Loïc Correnson's avatar
Loïc Correnson committed
528
              l_kind = `Axiom ;
Loïc Correnson's avatar
Loïc Correnson committed
529
530
531
532
533
534
              l_name = name ; l_types = 0 ;
              l_triggers = [] ; l_forall = [] ;
              l_lemma = p_forall [a] (p_imply m_linked base_size) ;
              l_cluster = cluster_globals () ;
            }

535
536
537
538
539
540
541
542
543
544
545
546
547
548
      let initialization prefix x base =
        match sizeof x with
        | Some size when x.vformal || x.vglob ->
            let a = Lang.freshvar ~basename:"init" t_init in
            let m = e_var a in
            let init_access =
              if size = 1 then
                p_bool (F.e_get m (a_addr base e_zero))
              else
                F.p_call p_is_init_r [ m ; a_addr base e_zero ; e_int size ]
            in
            let m_init = p_call p_cinits [m] in
            let init_prop = p_forall [a] (p_imply m_init init_access) in
            Definitions.define_lemma {
549
              l_kind = `Axiom ;
550
551
552
553
554
555
556
              l_name = prefix ^ "_init" ; l_types = 0 ;
              l_triggers = [] ; l_forall = [] ;
              l_lemma = init_prop ;
              l_cluster = cluster_globals () ;
            }
        | _ -> ()

Loïc Correnson's avatar
Loïc Correnson committed
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
      let generate x =
        let acs_rd = Cil.typeHasQualifier "const" x.vtype in
        let prefix =
          if x.vglob
          then if acs_rd then "K" else "G"
          else if x.vformal then "P" else "L" in
        let lfun = Lang.generated_f
            ~category:L.Constructor ~result:L.Int "%s_%s_%d"
            prefix x.vorig_name x.vid in
        (* Since its a generated it is the unique name given *)
        let prefix = Lang.Fun.debug lfun in
        let vid = if acs_rd then (-x.vid-1) else succ x.vid in
        let dfun = Definitions.Function( L.Int , Def , e_int vid ) in
        Definitions.define_symbol {
          d_lfun = lfun ; d_types = 0 ; d_params = [] ; d_definition = dfun ;
          d_cluster = cluster_globals () ;
        } ;
        let base = e_fun lfun [] in
        RegisterBASE.define lfun x ;
        region prefix x base ;
        linked prefix x base ;
578
        initialization prefix x base ;
Loïc Correnson's avatar
Loïc Correnson committed
579
580
581
582
583
584
585
586
587
588
589
590
591
592
        base

      let compile = Lang.local generate
    end)

(* -------------------------------------------------------------------------- *)
(* --- Locations                                                          --- *)
(* -------------------------------------------------------------------------- *)

let null = a_null (* as a loc *)

let literal ~eid cst =
  shift (a_global (STRING.get (eid,cst))) (C_int (Ctypes.c_char ())) e_zero

593
let cvar x = a_global (BASE.get x)
Loïc Correnson's avatar
Loïc Correnson committed
594
595
596
597

let pointer_loc t = t
let pointer_val t = t

598
let allocated sigma l = F.e_get (Sigma.value sigma T_alloc) (a_base l)
Loïc Correnson's avatar
Loïc Correnson committed
599
600

let base_addr l = a_addr (a_base l) e_zero
601
let base_offset l = a_base_offset (a_base l) (a_offset l)
Loïc Correnson's avatar
Loïc Correnson committed
602
let block_length sigma obj l =
603
  e_fact (Ctypes.sizeof_object obj) (allocated sigma l)
Loïc Correnson's avatar
Loïc Correnson committed
604
605
606
607
608

(* -------------------------------------------------------------------------- *)
(* --- Cast                                                               --- *)
(* -------------------------------------------------------------------------- *)

Patrick Baudin's avatar
Patrick Baudin committed
609
610
611
612
613
module Layout : sig
  val pretty : Format.formatter -> c_object -> unit

  val fits: dst:c_object -> src:c_object -> bool
  (* returns [true] in these cases:
614
615
     - [dst] fits into [src] (exists cobj; [src] = [dst] concat cobj)
     - [dst] equals    [src] ([dst] = [src]) *)
Patrick Baudin's avatar
Patrick Baudin committed
616
end =
Loïc Correnson's avatar
Loïc Correnson committed
617
618
struct

619
  type atom = P of typ | I of c_int | F of c_float
Loïc Correnson's avatar
Loïc Correnson committed
620
621
622
623
624
625

  let pp_atom fmt = function
    | P ty -> Printer.pp_typ fmt (TPtr(ty,[]))
    | I i -> Ctypes.pp_int fmt i
    | F f -> Ctypes.pp_float fmt f

626
  let eq_atom a1 a2 =
Loïc Correnson's avatar
Loïc Correnson committed
627
628
    match a1 , a2 with
    | P _ , P _ -> true
629
630
631
    | I i1 , I i2 -> i1 = i2
    | F f1 , F f2 -> f1 = f2
    | _ -> false
Loïc Correnson's avatar
Loïc Correnson committed
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
  type slot = A of atom
            | S of Cil_types.compinfo (* delayed layout of a C struct *)
            | U of Cil_types.compinfo (* delayed layout of a C union *)

  let pp_slot fmt = function
    | A a -> pp_atom fmt a
    | S s -> Format.fprintf fmt "{struct %a}" Printer.pp_compinfo s
    | U u -> Format.fprintf fmt "{union %a}" Printer.pp_compinfo u

  let eq_slot a1 a2 = (* syntactic equality *)
    match a1 , a2 with
    | A a1 , A a2 -> eq_atom a1 a2
    | S c1 , S c2 | U c1, U c2 -> Compinfo.equal c1 c2
    | _ -> false

  let rec get_slot = function
    | C_int i -> A (I i)
    | C_float f -> A (F f)
    | C_pointer t -> A (P t)
    | C_comp ( { cfields = [f] } as c ) ->
        begin (* union having only one field is equivalent to a struct *)
          match Ctypes.object_of f.ftype with
          | C_array _ -> (if c.cstruct then S c else U c)
          | cobj -> get_slot cobj
        end
    | C_comp c -> if c.cstruct then S c else U c
    | C_array _ -> assert false

Loïc Correnson's avatar
Loïc Correnson committed
661
  type block =
662
663
    | Str of slot * int
    | Arr of c_object * int (* delayed layout of a C type *)
Loïc Correnson's avatar
Loïc Correnson committed
664
665
    | Garbled

666
667
668
669
  let pp_block fmt = function
    | Str(a,n) when n=1 -> pp_slot fmt a
    | Str(a,n) -> Format.fprintf fmt "%a[%d]" pp_slot a n
    | Arr(o,n) -> Format.fprintf fmt "{ctype %a}[%d]" Ctypes.pretty o n
Loïc Correnson's avatar
Loïc Correnson committed
670
671
    | Garbled -> Format.fprintf fmt "..."

672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
  let add_slot a n w =
    assert (n >= 1) ;
    match w with
    | Str(b,m) :: w when eq_slot a b -> Str(b,m+n)::w
    | _ -> Str(a,n) :: w

  let add_block p w =
    match p , w with
    | Str(a,n) , Str(b,m)::w when eq_slot a b -> Str(b,n+m)::w
    | Garbled , Garbled::_ -> w
    | _ -> p :: w

  type layout = block list

  let pp_layout fmt = function
Loïc Correnson's avatar
Loïc Correnson committed
687
688
689
690
691
692
693
694
695
    | [b] -> pp_block fmt b
    | bs ->
        begin
          Format.fprintf fmt "@[<hov 2>{" ;
          List.iter (fun b -> Format.fprintf fmt "@ %a" pp_block b) bs ;
          Format.fprintf fmt " }@]" ;
        end

  (* requires n > 1 *)
696
697
698
699
700
701
702
703
704
705
  let rec add_many cobj n w = (* returns [layout obj]*n @ [w] *)
    assert (n > 1) ;
    match cobj, w with
    | C_array { arr_flat = Some a }, _ when a.arr_cell_nbr = 1 ->
        add_many (Ctypes.object_of a.arr_cell) n w
    | C_array _, Arr(o, m)::w when 0 = compare_ptr_conflated o cobj -> Arr(o, m+n)::w
    | C_array _, _ -> Arr(cobj, n)::w
    | _  -> add_slot (get_slot cobj) n w

  let rec rlayout w = function (* returns [layout obj] @ [w] *)
Loïc Correnson's avatar
Loïc Correnson committed
706
    | C_array { arr_flat = Some a } ->
707
        let cobj = Ctypes.object_of a.arr_cell in
Loïc Correnson's avatar
Loïc Correnson committed
708
        if a.arr_cell_nbr = 1
709
710
        then rlayout w cobj
        else add_many cobj a.arr_cell_nbr w
Loïc Correnson's avatar
Loïc Correnson committed
711
712
    | C_array { arr_element = e } ->
        if Wp_parameters.ExternArrays.get () then
713
          add_many (Ctypes.object_of e) max_int w
Loïc Correnson's avatar
Loïc Correnson committed
714
715
        else
          add_block Garbled w
716
    | cobj -> add_slot (get_slot cobj) 1 w
Loïc Correnson's avatar
Loïc Correnson committed
717

718
  let layout (obj : c_object) : layout = rlayout [] obj
Loïc Correnson's avatar
Loïc Correnson committed
719

720
721
722
  let clayout (c: Cil_types.compinfo) : layout =
    let flayout w f = rlayout w (Ctypes.object_of f.ftype) in
    List.fold_left flayout [] (List.rev c.cfields)
Loïc Correnson's avatar
Loïc Correnson committed
723

724
  type comparison = Srem of layout | Drem of layout | Equal | Mismatch
725

726
727
728
  let add_array o n w =
    assert (n > 0) ;
    if n=1 then rlayout w o else Arr(o, n)::w
729

730
731
732
  let decr_slot a n w =
    assert (n >= 1);
    if n=1 then w else Str(a, n-1)::w
Loïc Correnson's avatar
Loïc Correnson committed
733

734
735
736
737
738
739
740
741
742
743
744
745
746
747
  let rec equal u v =
    match compare ~dst:u ~src:v with
    | Equal -> true
    | _ -> false
  and compare_slot ~dst ~src =
    match dst, src with
    | A a1, A a2 -> if eq_atom a1 a2 then Equal else Mismatch
    | S c1, S c2 | U c1, U c2 when Compinfo.equal c1 c2 -> Equal
    | S c1, _    -> compare ~dst:(clayout c1) ~src:[Str(src,1)]
    |    _, S c2 -> compare ~dst:[Str(dst,1)] ~src:(clayout c2)
    | U c1, U c2 ->  (* for union, the layouts must be equal *)
        if equal (clayout c1) (clayout c2) then Equal else Mismatch
    | U _, A _ -> Mismatch
    | A _, U _ -> Mismatch
748
  and compare ~dst ~src =
Patrick Baudin's avatar
Patrick Baudin committed
749
    match dst , src with
750
751
752
    | [] , [] -> Equal     (* src = dst *)
    | [] , obj -> Srem obj (* src = dst @ obj *)
    | obj , [] -> Drem obj (* dst = src @ obj *)
Loïc Correnson's avatar
Loïc Correnson committed
753
754
755
756
    | p::w1 , q::w2 ->
        match p , q with
        | Garbled , _ | _ , Garbled -> Mismatch
        | Str(a,n) , Str(b,m) ->
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
            begin
              match compare_slot a b with
              | Mismatch -> Mismatch
              | Drem a'->
                  let w1 = a' @ decr_slot a n w1 in
                  let w2 =      decr_slot b m w2 in
                  compare w1 w2
              | Srem b' ->
                  let w1 =      decr_slot a n w1 in
                  let w2 = b' @ decr_slot b m w2 in
                  compare w1 w2
              | Equal ->
                  if n < m then
                    let w2 = Str(a,m-n)::w2 in
                    compare w1 w2
                  else if n > m then
                    let w1 = Str(a,n-m)::w1 in
                    compare w1 w2
                  else
                    (* n = m *)
                    compare w1 w2
            end
Loïc Correnson's avatar
Loïc Correnson committed
779
780
        | Arr(u,n) , Arr(v,m) ->
            begin
781
              match compare ~dst:(layout u) ~src:(layout v) with
Loïc Correnson's avatar
Loïc Correnson committed
782
              | Mismatch -> Mismatch
783
              | Drem u' ->
784
                  let w1 = u' @ add_array u (n-1) w1 in
785
                  let w2 =      add_array v (m-1) w2 in
786
                  compare w1 w2
787
              | Srem v' ->
788
                  let w1 =      add_array u (n-1) w1 in
789
790
                  let w2 = v' @ add_array v (m-1) w2 in
                  compare w1 w2
Loïc Correnson's avatar
Loïc Correnson committed
791
792
793
794
795
796
797
798
799
800
801
              | Equal ->
                  if n < m then
                    let w2 = add_array v (m-n) w2 in
                    compare w1 w2
                  else if n > m then
                    let w1 = add_array u (n-m) w1 in
                    compare w1 w2
                  else
                    (* n = m *)
                    compare w1 w2
            end
802
803
        | Arr(u,n) , Str _ ->
            compare ~dst:((layout u) @ add_array u (n-1) w1) ~src
Loïc Correnson's avatar
Loïc Correnson committed
804
        | Str _ , Arr(v,n) ->
805
            compare ~dst ~src:((layout v) @ add_array v (n-1) w2)
Loïc Correnson's avatar
Loïc Correnson committed
806

807
808
809
810
811
812
813
814
815
  let rec repeated ~dst ~src =
    match dst , src with
    | [] , [] -> true (* src = dst *)
    | _ , [] -> false  (* empty source layout *)
    | [] , _ -> false  (* empty destination layout *)
    | [p] , [q] -> begin
        match p , q with
        | Garbled , _ | _ , Garbled -> false
        | Str(a,n) , Str(b,m) -> (* dst =?= repeated(src,n/m) *)
816
817
818
819
820
821
822
823
824
825
826
827
828
            begin
              match compare_slot ~dst:a ~src:b with
              | Mismatch -> false
              | Drem a' ->
                  let w1 = a' @ decr_slot a n [] in
                  let w2 =      decr_slot b m [] in
                  let cmp = compare ~dst:w1 ~src:w2 in
                  repeated_result ~src cmp
              | Srem _ ->
                  false
              | Equal -> (* dst =?= repeated(src,n/m) *)
                  n >= m && (n mod m = 0)
            end
829
830
        | Arr(u,n) , Arr(v,m) ->
            begin
831
              match compare ~dst:(layout u) ~src:(layout v) with
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
              | Mismatch -> false
              | Drem u' ->
                  let w1 = u' @ add_array u (n-1) [] in
                  let w2 = add_array v (m-1) [] in
                  let cmp = compare ~dst:w1 ~src:w2 in
                  repeated_result ~src cmp
              | Srem _ ->
                  false
              | Equal -> (* dst =?= repeated(src,n/m) *)
                  n >= m && (n mod m = 0)
            end
        | _ , _ -> repeated_compare ~dst ~src
      end
    | _ , _ -> repeated_compare ~dst ~src
  and repeated_compare ~dst ~src = repeated_result ~src (compare ~dst ~src)
  and repeated_result ~src = function
    | Equal -> true
    | Mismatch | Srem _ -> false
    | Drem dst -> repeated ~dst ~src

Patrick Baudin's avatar
Patrick Baudin committed
852
853
  let fits ~dst ~src =
    match dst , src with
Loïc Correnson's avatar
Loïc Correnson committed
854
855
856
857
858
    | C_int i1 , C_int i2 -> i1 = i2
    | C_float f1 , C_float f2 -> f1 = f2
    | C_comp c , C_comp d when Compinfo.equal c d -> true
    | C_pointer _ , C_pointer _ -> true
    | _ ->
859
860
        let src = layout src in
        match compare ~dst:(layout dst) ~src with
861
        | Equal | Srem _ -> true
862
863
        | Mismatch -> false
        | Drem dst -> repeated dst src
Loïc Correnson's avatar
Loïc Correnson committed
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

  let rec pretty fmt = function
    | C_pointer ty -> Format.fprintf fmt "%a*" pretty (Ctypes.object_of ty)
    | obj -> pp_layout fmt (layout obj)

end


let pp_mismatch fmt s =
  if Context.get pointer <> NoCast && Wp_parameters.has_dkey dkey_layout then
    Format.fprintf fmt
      "Cast with incompatible pointers types@\n\
       @[@[Source: %a*@]@ @[(layout: %a)@]@]@\n\
       @[@[Target: %a*@]@ @[(layout: %a)@]@]"
      Ctypes.pretty s.pre Layout.pretty s.pre
      Ctypes.pretty s.post Layout.pretty s.post
  else
    Format.fprintf fmt
      "@[<hov 3>Cast with incompatible pointers types\
       @ (source: %a*)@ (target: %a*)@]"
      Ctypes.pretty s.pre Ctypes.pretty s.post

let cast s l =
  if l==null then null else
    begin
      match Context.get pointer with
      | NoCast -> Warning.error ~source:"Typed Model" "%a" pp_mismatch s
      | Fits ->
Patrick Baudin's avatar
Patrick Baudin committed
892
          if Layout.fits ~dst:s.post ~src:s.pre then l else
Loïc Correnson's avatar
Loïc Correnson committed
893
894
            Warning.error ~source:"Typed Model" "%a" pp_mismatch s
      | Unsafe ->
Patrick Baudin's avatar
Patrick Baudin committed
895
          if not (Layout.fits ~dst:s.post ~src:s.pre) then
Loïc Correnson's avatar
Loïc Correnson committed
896
897
898
899
900
            Warning.emit ~severe:false ~source:"Typed Model"
              ~effect:"Keep pointer value"
              "%a" pp_mismatch s ; l
    end

901
902
let loc_of_int _ v = F.e_fun f_addr_of_int [v]
let int_of_loc _ l = F.e_fun f_int_of_addr [l]
Loïc Correnson's avatar
Loïc Correnson committed
903
904

(* -------------------------------------------------------------------------- *)
905
(* --- Frames                                                             --- *)
Loïc Correnson's avatar
Loïc Correnson committed
906
907
(* -------------------------------------------------------------------------- *)

908
909
910
911
912
913
914
915
let frames obj addr = function
  | T_alloc -> []
  | m ->
      let offset = F.e_int (length_of_object obj) in
      let sizeof = F.e_one in
      let tau = Chunk.val_of_chunk m in
      let basename = Chunk.basename_of_chunk m in
      MemMemory.frames ~addr ~offset ~sizeof ~basename tau
Loïc Correnson's avatar
Loïc Correnson committed
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
(* -------------------------------------------------------------------------- *)
(* --- Chunk element type                                                 --- *)
(* -------------------------------------------------------------------------- *)

module ChunkContent = WpContext.Generator(Chunk)
    (struct
      let name = "MemTyped.ChunkContent"
      type key = Chunk.t
      type data = lfun

      let int_kind = function
        | M_char -> Ctypes.c_char ()
        | M_int k -> k
        | _ -> failwith "MemTyped asked constraint for non int type"

      let generate c =
        let k = int_kind c in
        let p = Lang.freshvar ~basename:"m" (Chunk.tau_of_chunk c) in
        let m = e_var p in
        let name = Format.asprintf "is_%a_chunk" Ctypes.pp_int k in
        let lfun = Lang.generated_p name in
        let l = Lang.freshvar ~basename:"l" (Lang.t_addr()) in
        let is_int = Cint.range k in
        let def = p_forall [l] (is_int (F.e_get m (e_var l))) in
        Definitions.define_symbol {
          d_lfun = lfun ; d_types = 0 ;
          d_params = [p] ;
          d_definition = Predicate(Def, def) ;
          d_cluster = cluster ~id:"Chunk" ~title:"Chunk type constraint" () ;
        } ;
        lfun

      let compile = Lang.local generate
    end)

let is_chunk sigma = function
  | M_int _ | M_char as m ->
      F.p_call (ChunkContent.get m) [ Sigma.value sigma m ]
  | _ ->
      p_true

let is_well_formed sigma =
  let open Sigma in
  p_conj (Chunk.Set.fold (fun c l -> is_chunk sigma c :: l) (domain sigma) [])

Loïc Correnson's avatar
Loïc Correnson committed
962
(* -------------------------------------------------------------------------- *)
963
(* --- Loader                                                             --- *)
Loïc Correnson's avatar
Loïc Correnson committed
964
965
(* -------------------------------------------------------------------------- *)

966
967
968
969
970
971
972
973
974
module MODEL =
struct
  module Chunk = Chunk
  module Sigma = Sigma
  let name = "MemTyped.LOADER"
  type nonrec loc = loc
  let field = field
  let shift = shift
  let sizeof = length_of_object
975
976
  let init_footprint = init_footprint
  let value_footprint = value_footprint
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
  let frames = frames
  let to_addr l = l
  let to_region_pointer l = 0,l
  let of_region_pointer _ _ l = l

  let load_int sigma i l = F.e_get (Sigma.value sigma (m_int i)) l
  let load_float sigma f l = F.e_get (Sigma.value sigma (m_float f)) l
  let load_pointer sigma _t l = F.e_get (Sigma.value sigma M_pointer) l

  let last sigma obj l =
    let n = length_of_object obj in
    e_sub (F.e_div (allocated sigma l) (F.e_int n)) e_one

  let havoc obj loc ~length chunk ~fresh ~current =
    if chunk <> T_alloc then
      let n = F.e_fact (length_of_object obj) length in
      F.e_fun f_havoc [fresh;current;loc;n]
    else fresh

  let eqmem obj loc _chunk m1 m2 =
    F.p_call p_eqmem [m1;m2;loc;e_int (length_of_object obj)]

  let eqmem_forall obj loc _chunk m1 m2 =
    let xp = Lang.freshvar ~basename:"p" t_addr in
    let p = F.e_var xp in
    let n = F.e_int (length_of_object obj) in
    let separated = F.p_call p_separated [p;e_one;loc;n] in
    let equal = p_equal (e_get m1 p) (e_get m2 p) in
    [xp],separated,equal
Loïc Correnson's avatar
Loïc Correnson committed
1006

1007
  let updated sigma c l v = c , F.e_set (Sigma.value sigma c) l v
Loïc Correnson's avatar
Loïc Correnson committed
1008

1009
1010
1011
  let store_int sigma i l v = updated sigma (m_int i) l v
  let store_float sigma f l v = updated sigma (m_float f) l v
  let store_pointer sigma _ty l v = updated sigma M_pointer l v
Loïc Correnson's avatar
Loïc Correnson committed
1012

1013
  let set_init_atom sigma l v = updated sigma T_init l v
1014
1015
  let is_init_atom sigma l = F.e_get (Sigma.value sigma T_init) l

1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
  let is_init_range sigma obj loc length =
    let n = F.e_fact (length_of_object obj) length in
    F.p_call p_is_init_r [ Sigma.value sigma T_init ; loc ; n ]

  let set_init obj loc ~length _chunk ~current =
    let n = F.e_fact (length_of_object obj) length in
    F.e_fun f_set_init [current;loc;n]

  let monotonic_init s1 s2 =
    let m1 = Sigma.value s1 T_init in
    let m2 = Sigma.value s2 T_init in
    F.p_call p_monotonic [m1; m2]

1029
1030
1031
1032
1033
1034
1035
1036
end

module LOADER = MemLoader.Make(MODEL)

let load = LOADER.load
let stored = LOADER.stored
let copied = LOADER.copied
let assigned = LOADER.assigned
1037
let initialized = LOADER.initialized
1038
let domain = LOADER.domain
Loïc Correnson's avatar
Loïc Correnson committed
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051

(* -------------------------------------------------------------------------- *)
(* --- Loc Comparison                                                     --- *)
(* -------------------------------------------------------------------------- *)

let loc_compare f_cmp i_cmp p q =
  match F.is_equal (a_base p) (a_base q) with
  | L.Yes -> i_cmp (a_offset p) (a_offset q)
  | L.Maybe | L.No -> p_call f_cmp [p;q]

let is_null l = p_equal l null
let loc_eq = p_equal
let loc_neq = p_neq
1052
1053
let loc_lt = loc_compare p_addr_lt p_lt
let loc_leq = loc_compare p_addr_le p_leq
Loïc Correnson's avatar
Loïc Correnson committed
1054
1055
let loc_diff obj p q =
  let delta = e_sub (a_offset p) (a_offset q) in
1056
  let size = e_int (length_of_object obj) in
Loïc Correnson's avatar
Loïc Correnson committed
1057
1058
1059
1060
1061
1062
1063
  e_div delta size

(* -------------------------------------------------------------------------- *)
(* --- Validity                                                           --- *)
(* -------------------------------------------------------------------------- *)

let s_valid sigma acs p n =
1064
1065
1066
1067
1068
  let p_valid = match acs with
    | RW -> p_valid_rw
    | RD -> p_valid_rd
    | OBJ -> p_valid_obj
  in
Loïc Correnson's avatar
Loïc Correnson committed
1069
1070
1071
1072
1073
1074
1075
  p_call p_valid [Sigma.value sigma T_alloc;p;n]

let s_invalid sigma p n =
  p_call p_invalid [Sigma.value sigma T_alloc;p;n]

let segment phi = function
  | Rloc(obj,l) ->
1076
      phi l (e_int (length_of_object obj))
Loïc Correnson's avatar
Loïc Correnson committed
1077
1078
  | Rrange(l,obj,Some a,Some b) ->
      let l = shift l obj a in
1079
      let n = e_fact (length_of_object obj) (e_range a b) in
Loïc Correnson's avatar
Loïc Correnson committed
1080
1081
1082
1083
1084
1085
1086
1087
      phi l n
  | Rrange(l,_,a,b) ->
      Wp_parameters.abort ~current:true
        "Invalid infinite range @[<hov 2>%a+@,(%a@,..%a)@]"
        F.pp_term l Vset.pp_bound a Vset.pp_bound b

let valid sigma acs = segment (s_valid sigma acs)
let invalid sigma = segment (s_invalid sigma)
1088

Loïc Correnson's avatar
Loïc Correnson committed
1089
1090
1091
1092
1093
1094
1095
let frame sigma =
  let wellformed_frame phi chunk =
    if Sigma.mem sigma chunk
    then [ p_call phi [Sigma.value sigma chunk] ]
    else []
  in
  wellformed_frame p_linked T_alloc @
1096
  wellformed_frame p_cinits T_init @
Loïc Correnson's avatar
Loïc Correnson committed
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
  wellformed_frame p_sconst M_char @
  wellformed_frame p_framed M_pointer

let alloc sigma xs =
  if xs = [] then sigma else Sigma.havoc_chunk sigma T_alloc

let scope seq scope xs =
  if xs = [] then [] else
    let alloc =
      List.fold_left
        (fun m x ->
           let size = match scope with
             | Sigs.Leave -> 0
1110
             | Sigs.Enter -> length_of_typ x.vtype
Loïc Correnson's avatar
Loïc Correnson committed
1111
1112
1113
1114
1115
1116
1117
           in F.e_set m (BASE.get x) (e_int size))
        (Sigma.value seq.pre T_alloc) xs in
    [ p_equal (Sigma.value seq.post T_alloc) alloc ]

let global _sigma p = p_leq (e_fun f_region [a_base p]) e_zero

(* -------------------------------------------------------------------------- *)
1118
(* --- Segments                                                           --- *)
Loïc Correnson's avatar
Loïc Correnson committed
1119
1120
(* -------------------------------------------------------------------------- *)

1121
1122
1123
1124
let included =
  let addrof l = l in
  let sizeof = length_of_object in
  MemMemory.included ~shift ~addrof ~sizeof
Loïc Correnson's avatar
Loïc Correnson committed
1125

1126
1127
1128
1129
let separated =
  let addrof l = l in
  let sizeof = length_of_object in
  MemMemory.separated ~shift ~addrof ~sizeof
Loïc Correnson's avatar
Loïc Correnson committed
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145

(* -------------------------------------------------------------------------- *)
(* --- State Model                                                        --- *)
(* -------------------------------------------------------------------------- *)

type state = chunk Tmap.t

let rec lookup_a e =
  match F.repr e with
  | L.Fun( f , [e] ) when f == f_global -> lookup_a e
  | L.Fun( f , es ) -> lookup_f f es
  | _ -> raise Not_found

and lookup_f f es =
  try match RegisterShift.find f , es with
    | RS_Field(fd,_) , [e] -> Mstate.field (lookup_lv e) fd
1146
    | RS_Index _ , [e;k] -> Mstate.index (lookup_lv e) k
Loïc Correnson's avatar
Loïc Correnson committed
1147
    | _ -> raise Not_found
Loïc Correnson's avatar
Loïc Correnson committed
1148
  with Not_found when es = [] ->
Loïc Correnson's avatar
Loïc Correnson committed
1149
1150
1151
1152
    Sigs.(Mvar (RegisterBASE.find f),[])

and lookup_lv e = try lookup_a e with Not_found -> Sigs.(Mmem e,[])

1153
1154
1155
let mchunk c =
  match c with
  | T_init -> Sigs.Mchunk (Pretty_utils.to_string Chunk.pretty c, KInit)
1156
  | _ -> Sigs.Mchunk (Pretty_utils.to_string Chunk.detailed_pretty c, KValue)
Loïc Correnson's avatar
Loïc Correnson committed
1157
1158
1159
1160
1161
1162

let lookup s e =
  try mchunk (Tmap.find e s)
  with Not_found ->
  try match F.repr e with
    | L.Fun( f , es ) -> Sigs.Maddr (lookup_f f es)
1163
1164
1165
1166
    | L.Aget( m , k ) when Tmap.find m s = T_init ->
        Sigs.Mlval (lookup_lv k, KInit)
    | L.Aget( m , k ) when Tmap.find m s <> T_alloc ->
        Sigs.Mlval (lookup_lv k, KValue)
Loïc Correnson's avatar
Loïc Correnson committed
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
    | _ -> Sigs.Mterm
  with Not_found -> Sigs.Mterm

let apply f s =
  Tmap.fold (fun m c w -> Tmap.add (f m) c w) s Tmap.empty

let iter f s = Tmap.iter (fun m c -> f (mchunk c) m) s

let state (sigma : sigma) =
  let s = ref Tmap.empty in
  Sigma.iter (fun c x -> s := Tmap.add (e_var x) c !s) sigma ; !s

let heap domain state =
  Tmap.fold (fun m c w ->
      if Vars.intersect (F.vars m) domain
      then Heap.Map.add c m w else w
    ) state Heap.Map.empty

let rec diff v1 v2 =
  if v1 == v2 then Bag.empty else
    match F.repr v2 with
    | L.Aset( m , k , v ) ->
        let lv = lookup_lv k in
        let upd = Mstore( lv , v ) in
        Bag.append (diff v1 m) upd
    | _ ->
        Bag.empty

let updates seq domain =
  let pool = ref Bag.empty in
  let pre = heap domain seq.pre in
  let post = heap domain seq.post in
  Heap.Map.iter2
    (fun chunk v1 v2 ->
       if chunk <> T_alloc then
         match v1 , v2 with
         | Some v1 , Some v2 -> pool := Bag.concat (diff v1 v2) !pool
         | _ -> ())
    pre post ;
  !pool

(* -------------------------------------------------------------------------- *)