-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathGeneric.hs
1888 lines (1723 loc) · 78.4 KB
/
Generic.hs
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
------------------------------------------------------------------------
-- |
-- Module : Lang.Crucible.LLVM.MemModel.Generic
-- Description : Core definitions of the symbolic C memory model
-- Copyright : (c) Galois, Inc 2011-2016
-- License : BSD3
-- Maintainer : Rob Dockins <[email protected]>
-- Stability : provisional
------------------------------------------------------------------------
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE UndecidableInstances #-}
module Lang.Crucible.LLVM.MemModel.Generic
( Mem
, emptyMem
, AllocType(..)
, Mutability(..)
, AllocInfo(..)
, MemAllocs
, memAllocs
, memEndian
, memAllocCount
, memWriteCount
, allocMem
, allocAndWriteMem
, readMem
, isValidPointer
, isAllocatedMutable
, isAllocatedAlignedPointer
, notAliasable
, writeMem
, writeConstMem
, copyMem
, setMem
, invalidateMem
, writeArrayMem
, writeArrayConstMem
, pushStackFrameMem
, popStackFrameMem
, freeMem
, branchMem
, branchAbortMem
, mergeMem
, asMemAllocationArrayStore
, asMemMatchingArrayStore
, isAligned
, SomeAlloc(..)
, possibleAllocs
, possibleAllocInfo
, ppSomeAlloc
-- * Pretty printing
, ppType
, ppPtr
, ppAllocs
, ppMem
, ppTermExpr
) where
import Prelude hiding (pred)
import Control.Lens
import Control.Monad
import Control.Monad.State.Strict
import Control.Monad.Trans.Maybe
import Data.IORef
import Data.Maybe
import qualified Data.List as List
import qualified Data.Map as Map
import Data.IntMap (IntMap)
import qualified Data.IntMap as IntMap
import Data.Monoid
import Data.Text (Text)
import Numeric.Natural
import Prettyprinter
import Lang.Crucible.Panic (panic)
import Data.BitVector.Sized (BV)
import qualified Data.BitVector.Sized as BV
import Data.Parameterized.Classes
import qualified Data.Parameterized.Context as Ctx
import Data.Parameterized.Ctx (SingleCtx)
import Data.Parameterized.Some
import What4.Interface
import qualified What4.Concrete as W4
import Lang.Crucible.Backend
import Lang.Crucible.LLVM.Bytes
import Lang.Crucible.LLVM.DataLayout
import Lang.Crucible.LLVM.Errors.MemoryError (MemErrContext, MemoryErrorReason(..), MemoryOp(..))
import qualified Lang.Crucible.LLVM.Errors.UndefinedBehavior as UB
import Lang.Crucible.LLVM.MemModel.CallStack (getCallStack)
import Lang.Crucible.LLVM.MemModel.Common
import Lang.Crucible.LLVM.MemModel.Options
import Lang.Crucible.LLVM.MemModel.MemLog
import Lang.Crucible.LLVM.MemModel.Pointer
import Lang.Crucible.LLVM.MemModel.Type
import Lang.Crucible.LLVM.MemModel.Value
import Lang.Crucible.LLVM.MemModel.Partial (PartLLVMVal, HasLLVMAnn)
import qualified Lang.Crucible.LLVM.MemModel.Partial as Partial
import Lang.Crucible.LLVM.Utils
import Lang.Crucible.Simulator.RegMap (RegValue'(..))
--------------------------------------------------------------------------------
-- Reading from memory
tgAddPtrC :: (1 <= w, IsExprBuilder sym) => sym -> NatRepr w -> LLVMPtr sym w -> Addr -> IO (LLVMPtr sym w)
tgAddPtrC sym w x y = ptrAdd sym w x =<< constOffset sym w y
-- | An environment used to interpret 'OffsetExpr's, 'IntExpr's, and 'Cond's.
-- These data structures may contain uninterpreted variables to be filled in
-- with the offset address of a load or store, or the size of the current
-- region. Since regions may be unbounded in size, the size argument is a
-- 'Maybe' type.
data ExprEnv sym w = ExprEnv { loadOffset :: SymBV sym w
, storeOffset :: SymBV sym w
, sizeData :: Maybe (SymBV sym w) }
ppExprEnv :: IsExprBuilder sym => ExprEnv sym w -> Doc ann
ppExprEnv f =
vcat
[ "ExprEnv"
, indent 4 $ vcat
[ "loadOffset:" <+> printSymExpr (loadOffset f)
, "storeOffset:" <+> printSymExpr (storeOffset f)
, "sizeData:" <+> maybe mempty printSymExpr (sizeData f)
]
]
-- | Interpret an 'OffsetExpr' as a 'SymBV'. Although 'OffsetExpr's may contain
-- 'IntExpr's, which may be undefined if they refer to the size of an unbounded
-- memory region, this function will panic if both (1) the 'sizeData'
-- in the 'ExprEnv' is 'Nothing' and (2) 'StoreSize' occurs anywhere in the
-- 'OffsetExpr'.
genOffsetExpr ::
(1 <= w, IsSymInterface sym) =>
sym -> NatRepr w ->
ExprEnv sym w ->
OffsetExpr ->
IO (SymBV sym w)
genOffsetExpr sym w f@(ExprEnv load store _size) expr =
case expr of
OffsetAdd pe ie -> do
pe' <- genOffsetExpr sym w f pe
ie' <- genIntExpr sym w f ie
case ie' of
Nothing -> panic "Generic.genOffsetExpr"
[ "Cannot construct an offset that references the size of an unbounded region"
, "*** Invalid offset expression: " ++ show expr
, "*** Under environment: " ++ show (ppExprEnv f)
]
Just ie'' -> bvAdd sym pe' ie''
Load -> return load
Store -> return store
-- | Interpret an 'IntExpr' as a 'SymBV'. If the 'IntExpr' contains an
-- occurrence of 'StoreSize' and the store size in the 'ExprEnv' is unbounded,
-- will return 'Nothing'.
genIntExpr ::
(1 <= w, IsSymInterface sym) =>
sym ->
NatRepr w ->
ExprEnv sym w ->
IntExpr ->
IO (Maybe (SymBV sym w))
genIntExpr sym w f@(ExprEnv _load _store size) expr =
case expr of
OffsetDiff e1 e2 -> do
e1' <- genOffsetExpr sym w f e1
e2' <- genOffsetExpr sym w f e2
Just <$> bvSub sym e1' e2'
IntAdd e1 e2 -> do
e1' <- genIntExpr sym w f e1
e2' <- genIntExpr sym w f e2
case (e1', e2') of
(Just e1'', Just e2'') -> Just <$> bvAdd sym e1'' e2''
_ -> return Nothing -- Unbounded space added to anything is unbounded
CValue i -> Just <$> bvLit sym w (bytesToBV w i)
StoreSize -> return size
-- | Interpret a conditional as a symbolic predicate.
genCondVar :: forall sym w.
(1 <= w, IsSymInterface sym) =>
sym -> NatRepr w ->
ExprEnv sym w ->
Cond ->
IO (Pred sym)
genCondVar sym w inst c =
case c of
OffsetEq x y -> join $ bvEq sym <$> genOffsetExpr sym w inst x <*> genOffsetExpr sym w inst y
OffsetLe x y -> join $ bvUle sym <$> genOffsetExpr sym w inst x <*> genOffsetExpr sym w inst y
IntEq x y -> join $ maybeBVEq sym <$> genIntExpr sym w inst x <*> genIntExpr sym w inst y
IntLe x y -> join $ maybeBVLe sym <$> genIntExpr sym w inst x <*> genIntExpr sym w inst y
And x y -> join $ andPred sym <$> genCondVar sym w inst x <*> genCondVar sym w inst y
Or x y -> join $ orPred sym <$> genCondVar sym w inst x <*> genCondVar sym w inst y
-- | Compare the equality of two @Maybe SymBV@s
maybeBVEq :: (1 <= w, IsExprBuilder sym)
=> sym -> Maybe (SymBV sym w) -> Maybe (SymBV sym w) -> IO (Pred sym)
maybeBVEq sym (Just x) (Just y) = bvEq sym x y
maybeBVEq sym Nothing Nothing = return $ truePred sym
maybeBVEq sym _ _ = return $ falsePred sym
-- | Compare two @Maybe SymBV@s
maybeBVLe :: (1 <= w, IsExprBuilder sym)
=> sym -> Maybe (SymBV sym w) -> Maybe (SymBV sym w) -> IO (Pred sym)
maybeBVLe sym (Just x) (Just y) = bvSle sym x y
maybeBVLe sym _ Nothing = return $ truePred sym
maybeBVLe sym Nothing (Just _) = return $ falsePred sym
-- | Given a 'ValueCtor' (of partial LLVM values), recursively traverse the
-- 'ValueCtor' to reconstruct the partial value as directed (while respecting
-- endianness)
genValueCtor :: forall sym w.
(IsSymInterface sym, HasLLVMAnn sym, 1 <= w) =>
sym ->
EndianForm ->
MemoryOp sym w ->
ValueCtor (PartLLVMVal sym) ->
IO (PartLLVMVal sym)
genValueCtor sym end errCtx v =
case v of
ValueCtorVar x -> return x
ConcatBV vcl vch ->
do vl <- genValueCtor sym end errCtx vcl
vh <- genValueCtor sym end errCtx vch
case end of
BigEndian -> Partial.bvConcat sym errCtx vh vl
LittleEndian -> Partial.bvConcat sym errCtx vl vh
ConsArray vc1 vc2 ->
do lv1 <- genValueCtor sym end errCtx vc1
lv2 <- genValueCtor sym end errCtx vc2
Partial.consArray sym errCtx lv1 lv2
AppendArray vc1 vc2 ->
do lv1 <- genValueCtor sym end errCtx vc1
lv2 <- genValueCtor sym end errCtx vc2
Partial.appendArray sym errCtx lv1 lv2
MkArray tp vv ->
Partial.mkArray sym tp =<<
traverse (genValueCtor sym end errCtx) vv
MkStruct vv ->
Partial.mkStruct sym =<<
traverse (traverse (genValueCtor sym end errCtx)) vv
BVToFloat x ->
Partial.bvToFloat sym errCtx =<< genValueCtor sym end errCtx x
BVToDouble x ->
Partial.bvToDouble sym errCtx =<< genValueCtor sym end errCtx x
BVToX86_FP80 x ->
Partial.bvToX86_FP80 sym errCtx =<< genValueCtor sym end errCtx x
-- | Compute the actual value of a value deconstructor expression.
applyView ::
(IsSymInterface sym, HasLLVMAnn sym, 1 <= w) =>
sym ->
EndianForm ->
MemErrContext sym w ->
PartLLVMVal sym ->
ValueView ->
IO (PartLLVMVal sym)
applyView sym end errCtx t val =
case val of
ValueViewVar _ ->
return t
SelectPrefixBV i j v ->
do t' <- applyView sym end errCtx t v
case end of
BigEndian -> Partial.selectHighBv sym errCtx j i t'
LittleEndian -> Partial.selectLowBv sym errCtx i j t'
SelectSuffixBV i j v ->
do t' <- applyView sym end errCtx t v
case end of
BigEndian -> Partial.selectLowBv sym errCtx j i t'
LittleEndian -> Partial.selectHighBv sym errCtx i j t'
FloatToBV v ->
Partial.floatToBV sym errCtx =<< applyView sym end errCtx t v
DoubleToBV v ->
Partial.doubleToBV sym errCtx =<< applyView sym end errCtx t v
X86_FP80ToBV v ->
Partial.fp80ToBV sym errCtx =<< applyView sym end errCtx t v
ArrayElt sz tp idx v ->
Partial.arrayElt sym errCtx sz tp idx =<< applyView sym end errCtx t v
FieldVal flds idx v ->
Partial.fieldVal sym errCtx flds idx =<< applyView sym end errCtx t v
evalMuxValueCtor ::
forall u sym w .
(1 <= w, IsSymInterface sym, HasLLVMAnn sym) =>
sym ->
NatRepr w ->
EndianForm ->
MemErrContext sym w ->
ExprEnv sym w {- ^ Evaluation function -} ->
(u -> ReadMem sym (PartLLVMVal sym)) {- ^ Function for reading specific subranges -} ->
Mux (ValueCtor u) ->
ReadMem sym (PartLLVMVal sym)
evalMuxValueCtor sym _w end errCtx _vf subFn (MuxVar v) =
do v' <- traverse subFn v
liftIO $ genValueCtor sym end errCtx v'
evalMuxValueCtor sym w end errCtx vf subFn (Mux c t1 t2) =
do c' <- liftIO $ genCondVar sym w vf c
case asConstantPred c' of
Just True -> evalMuxValueCtor sym w end errCtx vf subFn t1
Just False -> evalMuxValueCtor sym w end errCtx vf subFn t2
Nothing ->
do t1' <- evalMuxValueCtor sym w end errCtx vf subFn t1
t2' <- evalMuxValueCtor sym w end errCtx vf subFn t2
liftIO $ Partial.muxLLVMVal sym c' t1' t2'
evalMuxValueCtor sym w end errCtx vf subFn (MuxTable a b m t) =
do m' <- traverse (evalMuxValueCtor sym w end errCtx vf subFn) m
t' <- evalMuxValueCtor sym w end errCtx vf subFn t
-- TODO: simplification?
Map.foldrWithKey f (return t') m'
where
f :: Bytes -> PartLLVMVal sym -> ReadMem sym (PartLLVMVal sym) -> ReadMem sym (PartLLVMVal sym)
f n t1 k =
do c' <- liftIO $ genCondVar sym w vf (OffsetEq (aOffset n) b)
case asConstantPred c' of
Just True -> return t1
Just False -> k
Nothing -> liftIO . Partial.muxLLVMVal sym c' t1 =<< k
aOffset :: Bytes -> OffsetExpr
aOffset n = OffsetAdd a (CValue n)
-- | Read from a memory with a memcopy to the same block we are reading.
readMemCopy ::
forall sym w.
(1 <= w, IsSymInterface sym, HasLLVMAnn sym) =>
sym ->
NatRepr w ->
EndianForm ->
MemoryOp sym w ->
LLVMPtr sym w {- ^ The loaded offset -} ->
StorageType {- ^ The type we are reading -} ->
SymBV sym w {- ^ The destination of the memcopy -} ->
LLVMPtr sym w {- ^ The source of the copied region -} ->
SymBV sym w {- ^ The length of the copied region -} ->
(StorageType -> LLVMPtr sym w -> ReadMem sym (PartLLVMVal sym)) ->
ReadMem sym (PartLLVMVal sym)
readMemCopy sym w end mop (LLVMPointer blk off) tp d src sz readPrev =
do let ld = BV.asUnsigned <$> asBV off
let dd = BV.asUnsigned <$> asBV d
let varFn = ExprEnv off d (Just sz)
case (ld, dd) of
-- Offset if known
(Just lo, Just so) ->
do let subFn :: RangeLoad Addr Addr -> ReadMem sym (PartLLVMVal sym)
subFn (OutOfRange o tp') = do
o' <- liftIO $ bvLit sym w (bytesToBV w o)
readPrev tp' (LLVMPointer blk o')
subFn (InRange o tp') =
readPrev tp' =<< liftIO (tgAddPtrC sym w src o)
case BV.asUnsigned <$> asBV sz of
Just csz -> do
let s = R (fromInteger so) (fromInteger (so + csz))
let vcr = rangeLoad (fromInteger lo) tp s
liftIO . genValueCtor sym end mop =<< traverse subFn vcr
_ ->
evalMuxValueCtor sym w end mop varFn subFn $
fixedOffsetRangeLoad (fromInteger lo) tp (fromInteger so)
-- Symbolic offsets
_ ->
do let subFn :: RangeLoad OffsetExpr IntExpr -> ReadMem sym (PartLLVMVal sym)
subFn (OutOfRange o tp') =
do o' <- liftIO $ genOffsetExpr sym w varFn o
readPrev tp' (LLVMPointer blk o')
subFn (InRange o tp') = do
oExpr <- liftIO $ genIntExpr sym w varFn o
srcPlusO <- case oExpr of
Just oExpr' -> liftIO $ ptrAdd sym w src oExpr'
Nothing -> panic "Generic.readMemCopy"
["Cannot use an unbounded bitvector expression as an offset"
,"*** In offset epxression: " ++ show o
,"*** Under environment: " ++ show (ppExprEnv varFn)
]
readPrev tp' srcPlusO
let pref | Just{} <- dd = FixedStore
| Just{} <- ld = FixedLoad
| otherwise = NeitherFixed
let mux0 | Just csz <- BV.asUnsigned <$> asBV sz =
fixedSizeRangeLoad pref tp (fromInteger csz)
| otherwise =
symbolicRangeLoad pref tp
evalMuxValueCtor sym w end mop varFn subFn mux0
readMemSet ::
forall sym w .
(1 <= w, IsSymInterface sym, HasLLVMAnn sym) =>
sym ->
NatRepr w ->
EndianForm ->
MemoryOp sym w ->
LLVMPtr sym w {- ^ The loaded offset -} ->
StorageType {- ^ The type we are reading -} ->
SymBV sym w {- ^ The destination of the memset -} ->
SymBV sym 8 {- ^ The fill byte that was set -} ->
SymBV sym w {- ^ The length of the set region -} ->
(StorageType -> LLVMPtr sym w -> ReadMem sym (PartLLVMVal sym)) ->
ReadMem sym (PartLLVMVal sym)
readMemSet sym w end mop (LLVMPointer blk off) tp d byte sz readPrev =
do let ld = BV.asUnsigned <$> asBV off
let dd = BV.asUnsigned <$> asBV d
let varFn = ExprEnv off d (Just sz)
case (ld, dd) of
-- Offset if known
(Just lo, Just so) ->
do let subFn :: RangeLoad Addr Addr -> ReadMem sym (PartLLVMVal sym)
subFn (OutOfRange o tp') = do
o' <- liftIO $ bvLit sym w (bytesToBV w o)
readPrev tp' (LLVMPointer blk o')
subFn (InRange _o tp') = do
blk0 <- liftIO $ natLit sym 0
let val = LLVMValInt blk0 byte
let b = Partial.totalLLVMVal sym val
liftIO $ genValueCtor sym end mop (memsetValue b tp')
case BV.asUnsigned <$> asBV sz of
Just csz -> do
let s = R (fromInteger so) (fromInteger (so + csz))
let vcr = rangeLoad (fromInteger lo) tp s
liftIO . genValueCtor sym end mop =<< traverse subFn vcr
_ -> evalMuxValueCtor sym w end mop varFn subFn $
fixedOffsetRangeLoad (fromInteger lo) tp (fromInteger so)
-- Symbolic offsets
_ ->
do let subFn :: RangeLoad OffsetExpr IntExpr -> ReadMem sym (PartLLVMVal sym)
subFn (OutOfRange o tp') =
do o' <- liftIO $ genOffsetExpr sym w varFn o
readPrev tp' (LLVMPointer blk o')
subFn (InRange _o tp') = liftIO $
do blk0 <- natLit sym 0
let val = LLVMValInt blk0 byte
let b = Partial.totalLLVMVal sym val
genValueCtor sym end mop (memsetValue b tp')
let pref | Just{} <- dd = FixedStore
| Just{} <- ld = FixedLoad
| otherwise = NeitherFixed
let mux0 | Just csz <- BV.asUnsigned <$> asBV sz =
fixedSizeRangeLoad pref tp (fromInteger csz)
| otherwise =
symbolicRangeLoad pref tp
evalMuxValueCtor sym w end mop varFn subFn mux0
-- | Read from a memory with a store to the same block we are reading.
readMemStore ::
forall sym w.
(1 <= w, IsSymInterface sym, HasLLVMAnn sym) =>
sym ->
NatRepr w ->
EndianForm ->
MemoryOp sym w ->
LLVMPtr sym w {- ^ The loaded address -} ->
StorageType {- ^ The type we are reading -} ->
SymBV sym w {- ^ The destination of the store -} ->
LLVMVal sym {- ^ The value that was stored -} ->
StorageType {- ^ The type of value that was written -} ->
Alignment {- ^ The alignment of the pointer we are reading from -} ->
Alignment {- ^ The alignment of the store from which we are reading -} ->
(StorageType -> LLVMPtr sym w -> ReadMem sym (PartLLVMVal sym))
{- ^ A callback function for when reading fails -} ->
ReadMem sym (PartLLVMVal sym)
readMemStore sym w end mop (LLVMPointer blk off) ltp d t stp loadAlign storeAlign readPrev =
do ssz <- liftIO $ bvLit sym w (bytesToBV w (storageTypeSize stp))
let varFn = ExprEnv off d (Just ssz)
let ld = BV.asUnsigned <$> asBV off
let dd = BV.asUnsigned <$> asBV d
case (ld, dd) of
-- Offset if known
(Just lo, Just so) ->
do let subFn :: ValueLoad Addr -> ReadMem sym (PartLLVMVal sym)
subFn (OldMemory o tp') =
readPrev tp' . LLVMPointer blk =<<
liftIO (bvLit sym w (bytesToBV w o))
subFn (LastStore v) = liftIO $
applyView sym end mop (Partial.totalLLVMVal sym t) v
subFn (InvalidMemory tp) = liftIO (Partial.partErr sym mop $ Invalid tp)
let vcr = valueLoad (fromInteger lo) ltp (fromInteger so) (ValueViewVar stp)
liftIO . genValueCtor sym end mop =<< traverse subFn vcr
-- Symbolic offsets
_ ->
do let subFn :: ValueLoad OffsetExpr -> ReadMem sym (PartLLVMVal sym)
subFn (OldMemory o tp') = do
o' <- liftIO $ genOffsetExpr sym w varFn o
readPrev tp' (LLVMPointer blk o')
subFn (LastStore v) = liftIO $
applyView sym end mop (Partial.totalLLVMVal sym t) v
subFn (InvalidMemory tp) = liftIO (Partial.partErr sym mop $ Invalid tp)
let pref | Just{} <- dd = FixedStore
| Just{} <- ld = FixedLoad
| otherwise = NeitherFixed
let alignStride = fromAlignment $ min loadAlign storeAlign
-- compute the linear form of (load offset - store offset)
let (diffStride, diffDelta)
| Just (load_a, _x, load_b) <- asAffineVar off
, Just (store_a, _y, store_b) <- asAffineVar d = do
let stride' = gcd
(BV.asUnsigned (W4.fromConcreteBV load_a))
(BV.asUnsigned (W4.fromConcreteBV store_a))
-- mod returns a non-negative integer
let delta' = mod
(BV.asUnsigned (W4.fromConcreteBV load_b) -
BV.asUnsigned (W4.fromConcreteBV store_b))
stride'
(fromInteger stride', fromInteger delta')
| Just (load_a, _x, load_b) <- asAffineVar off
, Just store_b <- BV.asUnsigned <$> asBV d = do
let stride' = BV.asUnsigned (W4.fromConcreteBV load_a)
let delta' = mod (BV.asUnsigned (W4.fromConcreteBV load_b) - store_b) stride'
(fromInteger stride', fromInteger delta')
| Just load_b <- BV.asUnsigned <$> asBV off
, Just (store_a, _y, store_b) <- asAffineVar d = do
let stride' = BV.asUnsigned (W4.fromConcreteBV store_a)
let delta' = mod (load_b - BV.asUnsigned (W4.fromConcreteBV store_b)) stride'
(fromInteger stride', fromInteger delta')
| otherwise = (1, 0)
let (stride, delta) = if diffStride >= alignStride
then (diffStride, diffDelta)
else (alignStride, 0)
diff <- liftIO $ bvSub sym off d
-- skip computing the mux tree if it would be empty
if storageTypeSize stp <= delta && (typeEnd 0 ltp) <= (stride - delta)
then readPrev ltp $ LLVMPointer blk off
else evalMuxValueCtor sym w end mop varFn subFn $
symbolicValueLoad
pref
ltp
(signedBVBounds diff)
(ValueViewVar stp)
(LinearLoadStoreOffsetDiff stride delta)
-- | Read from a memory with an array store to the same block we are reading.
--
-- NOTE: This case should only fire if a write is straddling an array store and
-- another write, as the top-level case of 'readMem' should handle the case
-- where a read is completely covered by a write to an array.
readMemArrayStore
:: forall sym w
. (1 <= w, IsSymInterface sym, HasLLVMAnn sym)
=> sym
-> NatRepr w
-> EndianForm
-> MemoryOp sym w
-> LLVMPtr sym w {- ^ The loaded offset -}
-> StorageType {- ^ The type we are reading -}
-> SymBV sym w {- ^ The offset of the mem array store from the base pointer -}
-> SymArray sym (SingleCtx (BaseBVType w)) (BaseBVType 8) {- ^ The stored array -}
-> Maybe (SymBV sym w) {- ^ The length of the stored array -}
-> (StorageType -> LLVMPtr sym w -> ReadMem sym (PartLLVMVal sym))
-> ReadMem sym (PartLLVMVal sym)
readMemArrayStore sym w end mop (LLVMPointer blk read_off) tp write_off arr size read_prev = do
let loadFn :: SymBV sym w -> StorageType -> ReadMem sym (PartLLVMVal sym)
loadFn base tp' = liftIO $ do
let loadArrayByteFn :: Offset -> IO (PartLLVMVal sym)
loadArrayByteFn off = do
blk0 <- natLit sym 0
idx <- bvAdd sym base =<< bvLit sym w (bytesToBV w off)
byte <- arrayLookup sym arr $ Ctx.singleton idx
return $ Partial.totalLLVMVal sym $ LLVMValInt blk0 byte
genValueCtor sym end mop =<< loadTypedValueFromBytes 0 tp' loadArrayByteFn
let varFn = ExprEnv read_off write_off size
case (BV.asUnsigned <$> asBV read_off, BV.asUnsigned <$> asBV write_off) of
-- In this case, both the read and write offsets are concrete
(Just lo, Just so) -> do
let subFn :: RangeLoad Addr Addr -> ReadMem sym (PartLLVMVal sym)
subFn = \case
OutOfRange o tp' -> do
o' <- liftIO $ bvLit sym w $ bytesToBV w o
read_prev tp' $ LLVMPointer blk o'
InRange o tp' -> do
o' <- liftIO $ bvLit sym w $ bytesToBV w o
loadFn o' tp'
case BV.asUnsigned <$> (asBV =<< size) of
-- The size of the backing SMT array is also concrete, so we can generate a mux-free value
Just concrete_size -> do
let s = R (fromInteger so) (fromInteger (so + concrete_size))
let vcr = rangeLoad (fromInteger lo) tp s
liftIO . genValueCtor sym end mop =<< traverse subFn vcr
-- Otherwise, the size of the array is unbounded or symbolic
--
-- The generated mux covers the possible cases where the read straddles
-- the store in various configurations
--
-- FIXME/Question: Does this properly handle the unbounded array case? Does it
-- need special handling of that case at all?
_ -> evalMuxValueCtor sym w end mop varFn subFn $
fixedOffsetRangeLoad (fromInteger lo) tp (fromInteger so)
-- Otherwise, at least one of the offsets is symbolic (and we will have to generate additional muxes)
_ -> do
let subFn :: RangeLoad OffsetExpr IntExpr -> ReadMem sym (PartLLVMVal sym)
subFn = \case
OutOfRange o tp' -> do
o' <- liftIO $ genOffsetExpr sym w varFn o
read_prev tp' $ LLVMPointer blk o'
InRange o tp' -> do
o' <- liftIO $ genIntExpr sym w varFn o
-- should always produce a defined value
case o' of
Just o'' -> loadFn o'' tp'
Nothing -> panic "Generic.readMemArrayStore"
[ "Unexpected unbounded size in RangeLoad"
, "*** Integer expression: " ++ show o
, "*** Under environment: " ++ show (ppExprEnv varFn)
]
let pref
| Just{} <- BV.asUnsigned <$> asBV write_off = FixedStore
| Just{} <- BV.asUnsigned <$> asBV read_off = FixedLoad
| otherwise = NeitherFixed
let rngLd
-- if the size of the data is bounded, use symbolicRangeLoad
| Just _ <- size = symbolicRangeLoad pref tp
-- otherwise, use symbolicUnboundedRangeLoad
| Nothing <- size = symbolicUnboundedRangeLoad pref tp
evalMuxValueCtor sym w end mop varFn subFn rngLd
readMemInvalidate ::
forall sym w .
( 1 <= w, IsSymInterface sym, HasLLVMAnn sym
, ?memOpts :: MemOptions ) =>
sym -> NatRepr w ->
EndianForm ->
MemoryOp sym w ->
LLVMPtr sym w {- ^ The loaded offset -} ->
StorageType {- ^ The type we are reading -} ->
SymBV sym w {- ^ The destination of the invalidation -} ->
Text {- ^ The error message -} ->
SymBV sym w {- ^ The length of the set region -} ->
(StorageType -> LLVMPtr sym w -> ReadMem sym (PartLLVMVal sym)) ->
ReadMem sym (PartLLVMVal sym)
readMemInvalidate sym w end mop (LLVMPointer blk off) tp d msg sz readPrev =
do let ld = BV.asUnsigned <$> asBV off
let dd = BV.asUnsigned <$> asBV d
let varFn = ExprEnv off d (Just sz)
case (ld, dd) of
-- Offset if known
(Just lo, Just so) ->
do let subFn :: RangeLoad Addr Addr -> ReadMem sym (PartLLVMVal sym)
subFn (OutOfRange o tp') = do
o' <- liftIO $ bvLit sym w (bytesToBV w o)
readPrev tp' (LLVMPointer blk o')
subFn (InRange _o tp') =
readInRange tp'
case BV.asUnsigned <$> asBV sz of
Just csz -> do
let s = R (fromInteger so) (fromInteger (so + csz))
let vcr = rangeLoad (fromInteger lo) tp s
liftIO . genValueCtor sym end mop =<< traverse subFn vcr
_ -> evalMuxValueCtor sym w end mop varFn subFn $
fixedOffsetRangeLoad (fromInteger lo) tp (fromInteger so)
-- Symbolic offsets
_ ->
do let subFn :: RangeLoad OffsetExpr IntExpr -> ReadMem sym (PartLLVMVal sym)
subFn (OutOfRange o tp') = do
o' <- liftIO $ genOffsetExpr sym w varFn o
readPrev tp' (LLVMPointer blk o')
subFn (InRange _o tp') =
readInRange tp'
let pref | Just{} <- dd = FixedStore
| Just{} <- ld = FixedLoad
| otherwise = NeitherFixed
let mux0 | Just csz <- BV.asUnsigned <$> asBV sz =
fixedSizeRangeLoad pref tp (fromInteger csz)
| otherwise =
symbolicRangeLoad pref tp
evalMuxValueCtor sym w end mop varFn subFn mux0
where
readInRange :: StorageType -> ReadMem sym (PartLLVMVal sym)
readInRange tp'
| laxLoadsAndStores ?memOpts &&
indeterminateLoadBehavior ?memOpts == UnstableSymbolic
= liftIO (Partial.totalLLVMVal sym <$> freshLLVMVal sym tp')
| otherwise
= liftIO (Partial.partErr sym mop $ Invalidated msg)
-- | Read a value from memory.
readMem :: forall sym w.
( 1 <= w, IsSymInterface sym, HasLLVMAnn sym
, ?memOpts :: MemOptions ) =>
sym ->
NatRepr w ->
Maybe String ->
LLVMPtr sym w ->
StorageType ->
Alignment ->
Mem sym ->
IO (PartLLVMVal sym)
readMem sym w gsym l tp alignment m = do
sz <- bvLit sym w (bytesToBV w (typeEnd 0 tp))
p1 <- isAllocated sym w alignment l (Just sz) m
p2 <- isAligned sym w l alignment
maybe_allocation_array <- asMemAllocationArrayStore sym w l m
let mop = MemLoadOp tp gsym l m
part_val <- case maybe_allocation_array of
-- If this read is inside an allocation backed by a SMT array store,
-- then decompose this read into reading the individual bytes and
-- assembling them to obtain the value, without introducing any
-- ite operations
Just (ok, arr, _arr_sz) | Just True <- asConstantPred ok -> do
let loadArrayByteFn :: Offset -> IO (PartLLVMVal sym)
loadArrayByteFn off = do
blk0 <- natLit sym 0
idx <- bvAdd sym (llvmPointerOffset l)
=<< bvLit sym w (bytesToBV w off)
byte <- arrayLookup sym arr $ Ctx.singleton idx
return $ Partial.totalLLVMVal sym $ LLVMValInt blk0 byte
genValueCtor sym (memEndianForm m) mop
=<< loadTypedValueFromBytes 0 tp loadArrayByteFn
-- Otherwise, fall back to the less-optimized read case
_ -> readMem' sym w (memEndianForm m) gsym l m tp alignment (memWrites m)
let stack = getCallStack (m ^. memState)
part_val' <- applyUnless (laxLoadsAndStores ?memOpts)
(Partial.attachSideCondition sym stack p2 (UB.ReadBadAlignment (RV l) alignment))
part_val
applyUnless (laxLoadsAndStores ?memOpts)
(Partial.attachMemoryError sym p1 mop UnreadableRegion)
part_val'
data CacheEntry sym w =
CacheEntry !(StorageType) !(SymNat sym) !(SymBV sym w)
instance (TestEquality (SymExpr sym)) => Eq (CacheEntry sym w) where
(CacheEntry tp1 blk1 off1) == (CacheEntry tp2 blk2 off2) =
tp1 == tp2 && (blk1 == blk2) && (isJust $ testEquality off1 off2)
instance IsSymInterface sym => Ord (CacheEntry sym w) where
compare (CacheEntry tp1 blk1 off1) (CacheEntry tp2 blk2 off2) =
compare tp1 tp2
`mappend` compare blk1 blk2
`mappend` toOrdering (compareF off1 off2)
toCacheEntry :: StorageType -> LLVMPtr sym w -> CacheEntry sym w
toCacheEntry tp (llvmPointerView -> (blk, bv)) = CacheEntry tp blk bv
-- | Read a value from memory given a list of writes.
--
-- Note that the case where a read is entirely backed by an SMT array store is
-- handled in 'readMem'.
readMem' ::
forall w sym.
( 1 <= w, IsSymInterface sym, HasLLVMAnn sym
, ?memOpts :: MemOptions ) =>
sym ->
NatRepr w ->
EndianForm ->
Maybe String ->
LLVMPtr sym w {- ^ Address we are reading -} ->
Mem sym {- ^ The original memory state -} ->
StorageType {- ^ The type to read from memory -} ->
Alignment {- ^ Alignment of pointer to read from -} ->
MemWrites sym {- ^ List of writes -} ->
IO (PartLLVMVal sym)
readMem' sym w end gsym l0 origMem tp0 alignment (MemWrites ws) =
do runReadMem (go fallback0 l0 tp0 [] ws)
where
mop = MemLoadOp tp0 gsym l0 origMem
fallback0 ::
StorageType ->
LLVMPtr sym w ->
ReadMem sym (PartLLVMVal sym)
fallback0 tp _l =
liftIO $
if laxLoadsAndStores ?memOpts
&& indeterminateLoadBehavior ?memOpts == UnstableSymbolic
then Partial.totalLLVMVal sym <$> freshLLVMVal sym tp
else do -- We're playing a trick here. By making a fresh constant a proof obligation, we can be
-- sure it always fails. But, because it's a variable, it won't be constant-folded away
-- and we can be relatively sure the annotation will survive.
b <- if noSatisfyingWriteFreshConstant ?memOpts
then freshConstant sym (safeSymbol "noSatisfyingWrite") BaseBoolRepr
else return $ falsePred sym
Partial.Err <$>
Partial.annotateME sym mop (NoSatisfyingWrite tp) b
go :: (StorageType -> LLVMPtr sym w -> ReadMem sym (PartLLVMVal sym)) ->
LLVMPtr sym w ->
StorageType ->
[MemWrite sym] ->
[MemWritesChunk sym] ->
ReadMem sym (PartLLVMVal sym)
go fallback l tp [] [] = fallback tp l
go fallback l tp [] (head_chunk : tail_chunks) =
go fallback l tp (memWritesChunkAt l head_chunk) tail_chunks
go fallback l tp (h : r) rest_chunks =
do cache <- liftIO $ newIORef Map.empty
let readPrev ::
StorageType ->
LLVMPtr sym w ->
ReadMem sym (PartLLVMVal sym)
readPrev tp' l' = do
m <- liftIO $ readIORef cache
case Map.lookup (toCacheEntry tp' l') m of
Just x -> return x
Nothing -> do
x <- go fallback l' tp' r rest_chunks
liftIO $ writeIORef cache $ Map.insert (toCacheEntry tp' l') x m
return x
case h of
WriteMerge _ (MemWrites []) (MemWrites []) ->
go fallback l tp r rest_chunks
WriteMerge c (MemWrites xr) (MemWrites yr) ->
do x <- go readPrev l tp [] xr
y <- go readPrev l tp [] yr
liftIO $ Partial.muxLLVMVal sym c x y
MemWrite dst wsrc ->
case testEquality (ptrWidth dst) w of
Nothing -> readPrev tp l
Just Refl ->
do let LLVMPointer blk1 _ = l
let LLVMPointer blk2 d = dst
let readCurrent =
case wsrc of
MemCopy src sz -> readMemCopy sym w end mop l tp d src sz readPrev
MemSet v sz -> readMemSet sym w end mop l tp d v sz readPrev
MemStore v stp storeAlign -> readMemStore sym w end mop l tp d v stp alignment storeAlign readPrev
MemArrayStore arr sz -> readMemArrayStore sym w end mop l tp d arr sz readPrev
MemInvalidate msg sz -> readMemInvalidate sym w end mop l tp d msg sz readPrev
sameBlock <- liftIO $ natEq sym blk1 blk2
case asConstantPred sameBlock of
Just True -> do
result <- readCurrent
pure result
Just False -> readPrev tp l
Nothing ->
do x <- readCurrent
y <- readPrev tp l
liftIO $ Partial.muxLLVMVal sym sameBlock x y
--------------------------------------------------------------------------------
-- | Dummy newtype for now...
-- It may be useful later to add additional plumbing
-- to this monad.
newtype ReadMem sym a = ReadMem { runReadMem :: IO a }
deriving (Applicative, Functor, Monad, MonadIO)
--------------------------------------------------------------------------------
memWritesSize :: MemWrites sym -> Int
memWritesSize (MemWrites writes) = getSum $ foldMap
(\case
MemWritesChunkIndexed indexed_writes ->
foldMap (Sum . length) indexed_writes
MemWritesChunkFlat flat_writes -> Sum $ length flat_writes)
writes
muxChanges :: IsExpr (SymExpr sym) => Pred sym -> MemChanges sym -> MemChanges sym -> MemChanges sym
muxChanges c (left_allocs, lhs_writes) (rhs_allocs, rhs_writes) =
( muxMemAllocs c left_allocs rhs_allocs
, muxWrites c lhs_writes rhs_writes
)
muxWrites :: IsExpr (SymExpr sym) => Pred sym -> MemWrites sym -> MemWrites sym -> MemWrites sym
muxWrites _ (MemWrites []) (MemWrites []) = MemWrites []
muxWrites c lhs_writes rhs_writes
| Just b <- asConstantPred c = if b then lhs_writes else rhs_writes
muxWrites c lhs_writes rhs_writes
| Just lhs_indexed_writes <- asIndexedChunkMap lhs_writes
, Just rhs_indexed_writes <- asIndexedChunkMap rhs_writes =
MemWrites
[ MemWritesChunkIndexed $
mergeMemWritesChunkIndexed
(\lhs rhs ->
[ WriteMerge
c
(MemWrites [MemWritesChunkFlat lhs])
(MemWrites [MemWritesChunkFlat rhs])
])
lhs_indexed_writes
rhs_indexed_writes
]
| otherwise =
MemWrites [MemWritesChunkFlat [WriteMerge c lhs_writes rhs_writes]]
where asIndexedChunkMap :: MemWrites sym -> Maybe (IntMap [MemWrite sym])
asIndexedChunkMap (MemWrites [MemWritesChunkIndexed m]) = Just m
asIndexedChunkMap (MemWrites []) = Just IntMap.empty
asIndexedChunkMap _ = Nothing
mergeMemWritesChunkIndexed ::
([MemWrite sym] -> [MemWrite sym] -> [MemWrite sym]) ->
IntMap [MemWrite sym] ->
IntMap [MemWrite sym] ->
IntMap [MemWrite sym]
mergeMemWritesChunkIndexed merge_func = IntMap.mergeWithKey
(\_ lhs_alloc_writes rhs_alloc_writes -> Just $
merge_func lhs_alloc_writes rhs_alloc_writes)
(IntMap.map $ \lhs_alloc_writes -> merge_func lhs_alloc_writes [])
(IntMap.map $ \rhs_alloc_writes -> merge_func [] rhs_alloc_writes)
memChanges :: Monoid m => (MemChanges sym -> m) -> Mem sym -> m
memChanges f m = go (m^.memState)
where go (EmptyMem _ _ l) = f l
go (StackFrame _ _ _ l s) = f l <> go s
go (BranchFrame _ _ l s) = f l <> go s
memAllocs :: Mem sym -> MemAllocs sym
memAllocs = memChanges fst
memWrites :: Mem sym -> MemWrites sym
memWrites = memChanges snd
memWritesChunkAt ::
IsExprBuilder sym =>
LLVMPtr sym w ->
MemWritesChunk sym ->
[MemWrite sym]
memWritesChunkAt ptr = \case
MemWritesChunkIndexed indexed_writes
| Just blk <- asNat (llvmPointerBlock ptr) ->
IntMap.findWithDefault [] (fromIntegral blk) indexed_writes
| otherwise -> IntMap.foldr (++) [] indexed_writes
MemWritesChunkFlat flat_writes -> flat_writes
memWritesAtConstant :: Natural -> MemWrites sym -> [MemWrite sym]
memWritesAtConstant blk (MemWrites writes) = foldMap
(\case
MemWritesChunkIndexed indexed_writes ->
IntMap.findWithDefault [] (fromIntegral blk) indexed_writes
MemWritesChunkFlat flat_writes -> flat_writes)
writes
memStateAllocCount :: MemState sym -> Int
memStateAllocCount s = case s of
EmptyMem ac _ _ -> ac
StackFrame ac _ _ _ _ -> ac
BranchFrame ac _ _ _ -> ac
memStateWriteCount :: MemState sym -> Int
memStateWriteCount s = case s of
EmptyMem _ wc _ -> wc
StackFrame _ wc _ _ _ -> wc
BranchFrame _ wc _ _ -> wc
memAllocCount :: Mem sym -> Int
memAllocCount m = memStateAllocCount (m ^. memState)
memWriteCount :: Mem sym -> Int
memWriteCount m = memStateWriteCount (m ^. memState)
memAddAlloc :: (MemAllocs sym -> MemAllocs sym) -> Mem sym -> Mem sym
memAddAlloc f = memState %~ \case
EmptyMem ac wc (a, w) -> EmptyMem (ac+1) wc (f a, w)
StackFrame ac wc nm (a, w) s -> StackFrame (ac+1) wc nm (f a, w) s
BranchFrame ac wc (a, w) s -> BranchFrame (ac+1) wc (f a, w) s
memAddWrite ::
(IsExprBuilder sym, 1 <= w) =>
LLVMPtr sym w ->
WriteSource sym w ->
Mem sym ->
Mem sym
memAddWrite ptr src = do
let single_write = memWritesSingleton ptr src
memState %~ \case
EmptyMem ac wc (a, w) ->
EmptyMem ac (wc+1) (a, single_write <> w)
StackFrame ac wc nm (a, w) s ->
StackFrame ac (wc+1) nm (a, single_write <> w) s
BranchFrame ac wc (a, w) s ->
BranchFrame ac (wc+1) (a, single_write <> w) s
memStateAddChanges :: MemChanges sym -> MemState sym -> MemState sym
memStateAddChanges (a, w) = \case
EmptyMem ac wc (a0, w0) ->
EmptyMem (sizeMemAllocs a + ac) (memWritesSize w + wc) (a <> a0, w <> w0)
StackFrame ac wc nm (a0, w0) s ->
StackFrame (sizeMemAllocs a + ac) (memWritesSize w + wc) nm (a <> a0, w <> w0) s
BranchFrame ac wc (a0, w0) s ->
BranchFrame (sizeMemAllocs a + ac) (memWritesSize w + wc) (a <> a0, w <> w0) s