-
Notifications
You must be signed in to change notification settings - Fork 62
/
Copy pathX86Spec.hs
1358 lines (1131 loc) · 45.1 KB
/
X86Spec.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
{-# Language GADTs, KindSignatures, DataKinds, ImplicitParams #-}
{-# Language PatternSynonyms, TypeFamilies, TypeSynonymInstances #-}
{-# Language TypeApplications #-}
{-# Language TypeOperators #-}
{-# Language OverloadedStrings #-}
{-# Language ExistentialQuantification #-}
{-# Language Rank2Types #-}
{-# Language FlexibleContexts #-}
{-# Language ScopedTypeVariables #-}
{-# Language ConstraintKinds #-}
{-# Language PartialTypeSignatures #-}
{-# Language CPP #-}
#if __GLASGOW_HASKELL__ >= 806
{-# Language NoStarIsType #-}
#endif
module SAWScript.X86Spec
( Specification(..)
, SpecType, Pre, Post
, FunSpec(..)
, verifyMode
, overrideMode
, State(..)
, Loc(..)
, V(..)
, Prop(..)
, Alloc(..)
, Area(..)
, Mode(..)
, Unit(..)
, (*.)
, inMem
, (===)
, Opts(..)
, optsSym
, KnownType
, intLit
, litByte
, litWord
, litDWord
, litQWord
, litV128
, litV256
, area
, LLVMPointerType
, Overrides
, debugPPReg
, Sym
, freshRegister
-- * Cryptol
, CryArg(..)
, cryPre
, cryCur
, cryTerm
, cryConst
, mkGlobalMap
) where
import GHC.TypeLits(KnownNat)
import GHC.Natural(Natural)
import Data.Kind(Type)
import Control.Applicative ( (<|>) )
import Control.Lens (view, (^.), over)
import qualified Data.BitVector.Sized as BV
import Data.List(sortBy)
import Data.Maybe(catMaybes)
import Data.Map (Map)
import Data.Proxy(Proxy(..))
import qualified Data.Map as Map
import Data.IORef(newIORef,atomicModifyIORef')
import Data.String
import Control.Monad (MonadPlus(..), foldM, join, zipWithM)
import Control.Monad.IO.Class (MonadIO(..))
import Data.Parameterized.NatRepr
import Data.Parameterized.Classes
import qualified Data.Parameterized.Context as Ctx
import qualified Data.Parameterized.Map as MapF
import Data.Parameterized.Pair
import Data.Foldable(foldlM, toList)
import What4.Interface
(bvLit,isEq, Pred, notPred, orPred, natEq, freshNat
, bvUle, truePred, natLit, asNat, andPred, userSymbol, freshConstant )
import What4.ProgramLoc
import Lang.Crucible.FunctionHandle
import SAWScript.Crucible.LLVM.CrucibleLLVM
( EndianForm(LittleEndian)
, MemImpl, doLoad, doPtrAddOffset, emptyMem
, AllocType(HeapAlloc, GlobalAlloc), Mutability(..), Mem
, pattern LLVMPointerRepr, doMalloc, storeConstRaw, packMemValue
, LLVMPointerType, LLVMVal(LLVMValInt)
, ptrEq, LLVMPtr, ppPtr, llvmPointerView, projectLLVM_bv, llvmPointer_bv
, muxLLVMPtr
, bitvectorType
, Bytes, bytesToInteger, toBytes
, StorageType
, noAlignment
, pattern LLVMPointer
)
import qualified Lang.Crucible.LLVM.MemModel as Crucible
import Lang.Crucible.Simulator.SimError(SimErrorReason(AssertFailureSimError))
import Lang.Crucible.Backend
( addAssumption, getProofObligations, goalsToList
, assert, CrucibleAssumption(..)
, ProofGoal(..), labeledPredMsg
, HasSymInterface(backendGetSym)
, SomeBackend(..), IsSymBackend
)
import Lang.Crucible.Simulator.ExecutionTree
import Lang.Crucible.Simulator.OverrideSim
import Lang.Crucible.CFG.Common
import Lang.Crucible.Simulator.RegMap
--import Lang.Crucible.Backend.SAWCore
-- (bindSAWTerm,sawBackendSharedContext,toSC,SAWCoreBackend)
import Lang.Crucible.Types
(TypeRepr(..),BaseTypeRepr(..),BaseToType,CrucibleType)
import Verifier.SAW.SharedTerm
(Term,scApplyAll,scVector,scBitvector,scAt,scNat)
import Data.Macaw.Memory(RegionIndex)
import Data.Macaw.Symbolic
( GlobalMap(..), ToCrucibleType, LookupFunctionHandle(..)
, MacawCrucibleRegTypes, MacawSimulatorState
)
import Data.Macaw.Symbolic.Backend ( crucArchRegTypes )
import Data.Macaw.X86.X86Reg
import Data.Macaw.X86.Symbolic
(x86_64MacawSymbolicFns,lookupX86Reg,updateX86Reg)
import Data.Macaw.X86.ArchTypes(X86_64)
import qualified Data.Macaw.Types as M
import Verifier.SAW.CryptolEnv(CryptolEnv(..), lookupIn, getAllIfaceDecls)
import Verifier.SAW.Simulator.What4.ReturnTrip
import Cryptol.ModuleSystem.Name(Name)
import Cryptol.ModuleSystem.Interface(ifTySyns)
import Cryptol.TypeCheck.AST(TySyn(tsDef))
import Cryptol.TypeCheck.TypePat(aNat)
import Cryptol.Utils.PP(pp)
import Cryptol.Utils.Patterns(matchMaybe)
import SAWScript.Crucible.Common (Sym, sawCoreState)
data Specification = Specification
{ specAllocs :: ![Alloc]
, specPres :: ![(String, Prop Pre)]
, specPosts :: ![(String, Prop Post)]
, specGlobsRO :: ![ (String, Integer, Unit, [ Integer ]) ]
-- ^ Read only globals.
, specCalls :: ![ (String, Integer, Int -> Specification) ]
-- ^ Specifications for the functions we call.
-- The integer is the absolute address of the function.
-- The "Int" counts how many times we called this function so far.
}
data Unit = Bytes | Words | DWords | QWords | V128s | V256s deriving Show
{- | A specifiction for a function.
The outer, "Pre", computiation sets up the initial state of the
computation (i.e., the pre-condition for the function).
As a result, we return the inital register assignemtn,
and the post-condition for the function). -}
data FunSpec =
NewStyle (CryptolEnv -> IO Specification)
(State -> IO ())
-- Debug: Run this to print some stuff at interesting times.
-- | Is this a pre- or post-condition specificiation.
data {- kind -} SpecType = Pre | Post
-- | We are specifying a pre-condition.
type Pre = 'Pre
-- | We are specifying a post-condition.
type Post = 'Post
data Opts = Opts
{ optsBackend :: SomeBackend Sym
, optsMvar :: GlobalVar Mem
, optsCry :: CryptolEnv
}
optsWithBackend :: Opts -> (forall bak. IsSymBackend Sym bak => bak -> a) -> a
optsWithBackend opts k = case optsBackend opts of SomeBackend bak -> k bak
optsSym :: Opts -> Sym
optsSym opts = optsWithBackend opts backendGetSym
(*.) :: Integer -> Unit -> Bytes
n *. u = toBytes (fromInteger n * bs)
where bs = unitByteSize u natValue :: Natural
unitBitSize :: Unit -> (forall w. (1 <= w) => NatRepr w -> a) -> a
unitBitSize u k = unitByteSize u $ \bits ->
case leqMulPos (knownNat @8) bits of
LeqProof -> k (natMultiply (knownNat @8) bits)
unitByteSize :: Unit -> (forall w. (1 <= w) => NatRepr w -> a) -> a
unitByteSize u k =
case u of
Bytes -> k (knownNat @1)
Words -> k (knownNat @2)
DWords -> k (knownNat @4)
QWords -> k (knownNat @8)
V128s -> k (knownNat @16)
V256s -> k (knownNat @32)
data Mode = RO -- ^ Starts initialized; cannot write to it
| RW -- ^ Starts initialized; can write to it
| WO -- ^ Starts uninitialized; can write to it
deriving (Eq,Show)
data Area = Area
{ areaName :: String
, areaMode :: Mode
, areaSize :: (Integer,Unit)
, areaHasPointers :: Bool
-- ^ Could this area contain pointers
, areaPtr :: Bytes
{- ^ The canonical pointer to this area is this many bytes from
-- the start of the actual object.
-- When we initialize such an area, we allocate it, then advnace
-- the pointer by this much, and return *that* as the value of
-- initialization.
-- When we match such an area, we get the value as it,
-- but then we have to check that there are this many bytes *before*
-- the value we got.
-}
}
area :: String -> Mode -> Integer -> Unit -> Area
area n m u s = Area { areaName = n
, areaMode = m
, areaSize = (u,s)
, areaHasPointers = False
, areaPtr = 0 *. Bytes
}
data Loc :: CrucibleType -> Type where
InMem :: (1 <= w) =>
NatRepr w {- Read this much (in bytes) -} ->
Loc (LLVMPointerType 64) {- Read from this pointer -} ->
Integer {- Starting at this offset in bytes -} ->
Loc (LLVMPointerType (8*w))
InReg :: X86Reg tp -> Loc (ToCrucibleType tp)
instance Show (Loc t) where
show x =
case x of
InReg r -> show r
InMem w l o ->
"[" ++ show l ++ off ++ " |" ++ show (8 * natValue w) ++ "]"
where off | o < 0 = " - " ++ show (negate o)
| o == 0 = ""
| otherwise = " + " ++ show o
inMem ::
(1 <= w, KnownNat w) =>
Loc (LLVMPointerType 64) ->
Integer ->
Unit ->
Loc (LLVMPointerType (8 * w))
inMem l n u = InMem knownNat l (bytesToInteger (n *. u))
instance TestEquality Loc where
testEquality x y = case compareF x y of
EQF -> Just Refl
_ -> Nothing
-- | Allocation order. Also used when resolving equalities,
-- the smallest number is the representative.
instance OrdF Loc where
compareF x y =
case (x,y) of
(InReg a, InReg b) -> case compareF a b of
EQF -> EQF
LTF -> LTF
GTF -> GTF
(InReg {}, InMem {}) -> LTF
(InMem {}, InReg {}) -> GTF
(InMem s a i, InMem t b j) ->
case compareF a b of
EQF -> case compare i j of
LT -> LTF
GT -> GTF
EQ -> case compareF s t of
LTF -> LTF -- XXX: shouldn't allow?
GTF -> GTF -- XXX: shouldn't allow?
EQF -> EQF
LTF -> LTF
GTF -> GTF
data Alloc = Loc (LLVMPointerType 64) := Area
allocArea :: Alloc -> Area
allocArea (_ := a) = a
cmpAlloc :: Alloc -> Alloc -> Ordering
cmpAlloc (l1 := _) (l2 := _) = case compareF l1 l2 of
LTF -> LT
EQF -> EQ
GTF -> GT
data V :: SpecType -> CrucibleType -> Type where
CryFun ::
(1 <= w) => NatRepr w -> String -> [CryArg p] -> V p (LLVMPointerType w)
-- An opaque Cryptol term term; WARNING: type is unchecked
IntLit :: (1 <= w) => NatRepr w -> Integer -> V p (LLVMPointerType w)
-- A literal value
-- The whole location thing needs to be fixed...
Loc :: Loc t -> V p t
-- Read the value at the location in the *current* state:
-- pre or post depending on `p`
PreLoc :: Loc t -> V Post t
-- Read the location from the pre-condition state.
PreAddPtr ::
Loc (LLVMPointerType 64) -> Integer -> Unit -> V Post (LLVMPointerType 64)
-- Add a constant to a pointer from a location in the pre-condition.
instance Show (V p t) where
show val =
case val of
CryFun w f xs -> pars (f ++ " " ++ unwords (map show xs) ++ sh w)
IntLit w x -> pars (show x ++ sh w)
Loc l -> show l
PreLoc l -> pars ("pre " ++ show l)
PreAddPtr l i u ->
pars ("pre &" ++ show l ++ " + " ++ show i ++ " " ++ show u)
where
pars x = "(" ++ x ++ ")"
sh w = " : [" ++ show (natValue w) ++ "]"
litByte :: Integer -> V p (LLVMPointerType 8)
litByte = intLit
litWord :: Integer -> V p (LLVMPointerType 16)
litWord = intLit
litDWord :: Integer -> V p (LLVMPointerType 32)
litDWord = intLit
litQWord :: Integer -> V p (LLVMPointerType 64)
litQWord = intLit
litV128 :: Integer -> V p (LLVMPointerType 128)
litV128 = intLit
litV256 :: Integer -> V p (LLVMPointerType 256)
litV256 = intLit
intLit :: (1 <= w, KnownNat w) => Integer -> V p (LLVMPointerType w)
intLit = IntLit knownNat
data CryArg :: SpecType -> Type where
CryNat :: Integer -> CryArg p
Cry :: V p (LLVMPointerType w) -> CryArg p
CryArrCur :: V p (LLVMPointerType 64) -> Integer -> Unit -> CryArg p
CryArrPre :: V Post (LLVMPointerType 64) -> Integer -> Unit -> CryArg Post
instance Show (CryArg p) where
show x =
case x of
Cry v -> show v
CryNat n -> show n
CryArrCur p n u -> "[" ++ show p ++ "|" ++ show n ++ " " ++ show u ++ "]"
CryArrPre p n u ->
"[pre " ++ show p ++ "|" ++ show n ++ " " ++ show u ++ "]"
cryPre :: Loc (LLVMPointerType w) -> CryArg Post
cryPre l = Cry (PreLoc l)
cryCur :: Loc (LLVMPointerType w) -> CryArg p
cryCur l = Cry (Loc l)
data Prop :: SpecType -> Type where
Same :: TypeRepr t -> V p t -> V p t -> Prop p
CryProp :: String -> [ CryArg p ] -> Prop p
CryPostMem ::
V Post (LLVMPointerType 64) {- starting here -} ->
Integer {- this many elemnts -} ->
Unit {- of this size -} ->
String {- are defined by this Cry. func. -} ->
[CryArg Post] {- applied to these argumnets -} ->
Prop Post
type KnownType = KnownRepr TypeRepr
(===) :: KnownType t => V p t -> V p t -> Prop p
x === y = Same knownRepr x y
locRepr :: Loc t -> TypeRepr t
locRepr l =
case l of
InMem w _ _ -> ptrTy w
InReg r ->
case M.typeRepr r of
M.BVTypeRepr w -> LLVMPointerRepr w
M.BoolTypeRepr -> BoolRepr
M.TupleTypeRepr {} -> error $ "[locRepr] Unexpected tuple register"
M.FloatTypeRepr {} -> error $ "[locRepr] Unexpected float register"
M.VecTypeRepr {} -> error $ "[locRepr] Unexpected vector register"
--------------------------------------------------------------------------------
data State = State
{ stateMem :: MemImpl Sym
, stateRegs :: Ctx.Assignment (RegValue' Sym) (MacawCrucibleRegTypes X86_64)
}
freshState :: Sym -> IO State
freshState sym =
do regs <- Ctx.traverseWithIndex (freshRegister sym) knownRepr
mem <- emptyMem LittleEndian
return State { stateMem = mem, stateRegs = regs }
freshRegister :: Sym -> Ctx.Index ctx tp -> TypeRepr tp -> IO (RegValue' Sym tp)
freshRegister sym idx repr = RV <$> freshVal sym repr True ("reg" ++ show idx)
freshVal ::
Sym -> TypeRepr t -> Bool {- ptrOK ?-}-> String -> IO (RegValue Sym t)
freshVal sym t ptrOk nm =
case t of
BoolRepr -> do
sn <- symName nm
freshConstant sym sn BaseBoolRepr
LLVMPointerRepr w
| ptrOk, Just Refl <- testEquality w (knownNat @64) -> do
sn_base <- symName (nm ++ "_base")
sn_off <- symName (nm ++ "_off")
base <- freshNat sym sn_base
off <- freshConstant sym sn_off (BaseBVRepr w)
return (LLVMPointer base off)
| otherwise -> do
sn <- symName nm
base <- natLit sym 0
off <- freshConstant sym sn (BaseBVRepr w)
return (LLVMPointer base off)
it -> fail ("[freshVal] Unexpected type repr: " ++ show it)
where
symName s =
case userSymbol ("macaw_" ++ s) of
Left err -> error ("Invalid symbol name " ++ show s ++ ": " ++ show err)
Right a -> return a
getLoc :: (?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Loc t -> Opts -> State -> IO (RegValue Sym t)
getLoc l =
case l of
InReg r ->
\_ s -> case lookupX86Reg r (stateRegs s) of
Just (RV v) -> return v
_ -> fail ("[getLoc] Invalid register: " ++ show r)
InMem w lm n ->
\opts s -> optsWithBackend opts $ \bak ->
do obj <- getLoc lm opts s
let mem = stateMem s
let ?ptrWidth = knownNat
loc <- adjustPtr bak mem obj n
doLoad bak mem loc (llvmBytes w) (locRepr l) noAlignment
ptrTy :: (1 <= w) => NatRepr w -> TypeRepr (LLVMPointerType (8 * w))
ptrTy wb
| LeqProof <- leqMulPos (knownNat @8) wb =
LLVMPointerRepr (natMultiply (knownNat @8) wb)
llvmBytes :: NatRepr w -> StorageType
llvmBytes w = bitvectorType (toBytes (natValue w))
setLoc :: (?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Loc t -> Opts -> RegValue Sym t -> State -> IO State
setLoc l =
case l of
InReg r ->
\_ v s ->
case updateX86Reg r (const (RV v)) (stateRegs s) of
Just rs -> return s { stateRegs = rs }
Nothing -> fail ("[setLoc] Invalid register: " ++ show r)
InMem w lm n ->
\opts v s ->
optsWithBackend opts $ \bak ->
do let sym = backendGetSym bak
obj <- getLoc lm opts s
let mem = stateMem s
let ?ptrWidth = knownNat
loc <- adjustPtr bak mem obj n
let lty = llvmBytes w
ty = locRepr l
val <- packMemValue sym lty ty v
let alignment = noAlignment -- default to byte-aligned (FIXME, see #338)
mem1 <- storeConstRaw bak mem loc lty alignment val
return s { stateMem = mem1 }
class Eval p where
type S p
eval ::
(?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
V p t -> Opts -> S p -> IO (RegValue Sym t)
curState :: f p -> S p -> State
setCurState :: f p -> State -> S p -> S p
evIntLit :: (1 <= w) => Sym -> NatRepr w -> Integer -> IO (LLVMPtr Sym w)
evIntLit sym w n = llvmPointer_bv sym =<< bvLit sym w (BV.mkBV w n)
instance Eval Pre where
type S Pre = State
eval val =
case val of
CryFun w f xs -> \opts s -> evalCryFun opts s w f xs
IntLit w n -> \opts _ -> evIntLit (optsSym opts) w n
Loc l -> \opts s -> getLoc l opts s
curState _ s = s
setCurState _ s _ = s
instance Eval Post where
type S Post = (State,State)
eval val =
case val of
CryFun w f xs -> \opts s -> evalCryFun opts s w f xs
IntLit w n -> \opts _ -> evIntLit (optsSym opts) w n
Loc l -> \opts (_,post) -> getLoc l opts post
PreLoc l -> \opts (pre,_) -> getLoc l opts pre
PreAddPtr l i u -> \opts (pre,_) ->
do ptr <- getLoc l opts pre
optsWithBackend opts $ \bak ->
adjustPtr bak (stateMem pre) ptr (bytesToInteger (i *. u))
curState _ (_,s) = s
setCurState _ s (s1,_) = (s1,s)
evalCry ::
forall p.
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> CryArg p -> S p -> IO Term
evalCry opts cry s =
optsWithBackend opts $ \bak ->
do let sym = backendGetSym bak
st <- sawCoreState sym
let sc = saw_ctx st
case cry of
CryNat n -> scNat sc (fromInteger n)
Cry v -> toSC sym st =<< projectLLVM_bv bak =<< eval v opts s
CryArrCur ptr n u ->
unitByteSize u $ \byteW ->
do vs <- readArr opts ptr n byteW s (curState (Proxy @p) s)
terms <- mapM (\x -> toSC sym st =<< projectLLVM_bv bak x) vs
ty <- scBitvector sc (fromIntegral (8 * natValue byteW))
scVector sc ty terms
CryArrPre ptr n u ->
unitByteSize u $ \byteW ->
do vs <- readArr opts ptr n byteW s (fst s)
terms <- mapM (\x -> toSC sym st =<< projectLLVM_bv bak x) vs
ty <- scBitvector sc (fromIntegral (8 * natValue byteW))
scVector sc ty terms
evalCryFunGen ::
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts ->
S p ->
BaseTypeRepr t ->
String ->
[CryArg p] ->
IO (RegValue Sym (BaseToType t))
evalCryFunGen opts s ty f xs =
do let sym = optsSym opts
st <- sawCoreState sym
ts <- mapM (\x -> evalCry opts x s) xs
bindSAWTerm sym st ty =<< cryTerm opts f ts
-- | Cryptol function that returns a list of bit-vectors.
evalCryFunArr ::
(1 <= w, Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts ->
S p ->
Integer ->
NatRepr w ->
String ->
[CryArg p] ->
IO [ LLVMPtr Sym w ]
evalCryFunArr opts s n w f xs =
do term <- cryTerm opts f =<< mapM (\x -> evalCry opts x s) xs
let sym = optsSym opts
st <- sawCoreState sym
let sc = saw_ctx st
len <- scNat sc (fromInteger n)
ty <- scBitvector sc (natValue w)
let atIx i = do ind <- scNat sc (fromInteger i)
term_i <- scAt sc len ty term ind
bv <- bindSAWTerm sym st (BaseBVRepr w) term_i
llvmPointer_bv sym bv
mapM atIx [ 0 .. n - 1 ]
-- | Cryptol function that returns a bitvector of the given len
evalCryFun ::
(1 <= w, Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts ->
S p ->
NatRepr w ->
String ->
[CryArg p] ->
IO (LLVMPtr Sym w)
evalCryFun opts s w f xs =
llvmPointer_bv (optsSym opts) =<< evalCryFunGen opts s (BaseBVRepr w) f xs
evalProp ::
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> Prop p -> S p -> IO (Pred Sym)
evalProp opts p s =
case p of
Same t x y ->
do v1 <- eval x opts s
v2 <- eval y opts s
evalSame sym t v1 v2
CryProp f xs -> evalCryFunGen opts s BaseBoolRepr f xs
CryPostMem ptr n u f xs ->
-- unitBitSize u $ \wBits ->
unitByteSize u $ \wBytes ->
do LeqProof <- return (leqMulPos (Proxy @8) wBytes)
let wBits = natMultiply (knownNat @8) wBytes
need <- evalCryFunArr opts s n wBits f xs -- expected values
have <- readArr opts ptr n wBytes s (snd s)
checks <- zipWithM (ptrEq sym wBits) need have
foldM (andPred sym) (truePred sym) checks
where
sym = optsSym opts
readArr :: forall w p.
(1 <= w, Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts ->
V p (LLVMPointerType 64) ->
Integer ->
NatRepr w ->
S p ->
State ->
IO [ LLVMPtr Sym (8 * w) ]
readArr opts ptr n wBytes s sMem =
optsWithBackend opts $ \bak ->
do ptrV <- eval ptr opts s
LeqProof <- return (leqMulPos (Proxy @8) (Proxy @w))
let mem = stateMem sMem
wBits = natMultiply (knownNat @8) wBytes
cruT = LLVMPointerRepr wBits
llT = llvmBytes wBytes
getAt i =
do let ?ptrWidth = knownNat
loc <- adjustPtr bak mem ptrV (i * toInteger (natValue wBytes))
doLoad bak mem loc llT cruT noAlignment
mapM getAt [ 0 .. n - 1 ]
evalSame ::
Sym -> TypeRepr t -> RegValue Sym t -> RegValue Sym t -> IO (Pred Sym)
evalSame sym t v1 v2 =
case t of
BoolRepr -> isEq sym v1 v2
LLVMPointerRepr w -> ptrEq sym w v1 v2
it -> fail ("[evalProp] Unexpected value repr: " ++ show it)
-- | Add an assertion to the post-condition.
doAssert ::
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> S p -> (String, Prop p) -> IO ()
doAssert opts s (msg,p) =
do pr <- evalProp opts p s
optsWithBackend opts $ \bak ->
assert bak pr (AssertFailureSimError msg "")
--------------------------------------------------------------------------------
data Rep t = Rep (TypeRepr t) Int
instance Eq (Rep t) where
Rep _ x == Rep _ y = x == y
instance TestEquality Rep where
testEquality x y = case compareF x y of
EQF -> Just Refl
_ -> Nothing
instance OrdF Rep where
compareF (Rep s x) (Rep t y) =
case compareF s t of
LTF -> LTF
GTF -> GTF
EQF -> case compare x y of
LT -> LTF
GT -> GTF
EQ -> EQF
data RepMap p = RepMap
{ repFor :: MapF.MapF Loc Rep
-- ^ Keeps track of the representative for a value
, repBy :: MapF.MapF Rep (Equiv p)
-- ^ Inverse of the above: keeps track of which locs have this rep.
, nextRep :: !Int
}
emptyRepMap :: RepMap p
emptyRepMap = RepMap { repFor = MapF.empty
, repBy = MapF.empty
, nextRep = 0
}
data Equiv p t = Equiv [ Loc t ] [ V p t ] deriving Show
jnEquiv :: Equiv p t -> Equiv p t -> Equiv p t
jnEquiv (Equiv xs ys) (Equiv as bs) = Equiv (xs ++ as) (ys ++ bs)
-- | Add a fresh representative for something that had no rep before.
newRep :: TypeRepr t -> Equiv p t -> RepMap p -> (Rep t, RepMap p)
newRep t xs mp =
let n = nextRep mp
r = Rep t n
in (r, mp { nextRep = n + 1
, repBy = MapF.insert r xs (repBy mp)
})
getRep :: TypeRepr t -> RepMap p -> Loc t -> (Rep t, RepMap p)
getRep t mp x =
case MapF.lookup x (repFor mp) of
Nothing -> let (r,mp1) = newRep t (Equiv [x] []) mp
in (r, mp1 { repFor = MapF.insert x r (repFor mp1) })
Just y -> (y, mp)
addEqLocVal :: TypeRepr t -> Loc t -> V p t -> RepMap p -> RepMap p
addEqLocVal t loc lit mp =
let (x1,mp1) = getRep t mp loc
(x2,mp2) = newRep t (Equiv [] [lit]) mp1
in joinReps x1 x2 mp2
addEqLocLoc :: TypeRepr t -> Loc t -> Loc t -> RepMap p -> RepMap p
addEqLocLoc t x y mp =
let (x1,mp1) = getRep t mp x
(y1,mp2) = getRep t mp1 y
in joinReps x1 y1 mp2
joinReps :: Rep t -> Rep t -> RepMap p -> RepMap p
joinReps x y mp
| x == y = mp
| otherwise =
-- x is the new rep
case MapF.lookup y (repBy mp) of
Nothing -> error "[joinReps] Empty equivalance class"
Just new@(Equiv ls _) ->
let setRep z = MapF.insert z x
in mp { repBy = MapF.insertWith jnEquiv x new
$ MapF.delete y (repBy mp)
, repFor = foldr setRep (repFor mp) ls
}
getEq :: (String,Prop p) -> RepMap p -> RepMap p
getEq (_,p) mp =
case p of
Same t (Loc x) (Loc y) -> addEqLocLoc t x y mp
Same t (Loc x) v -> addEqLocVal t x v mp
Same t v (Loc x) -> addEqLocVal t x v mp
_ -> mp
makeEquiv ::
forall p.
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> S p -> Pair Rep (Equiv p) -> IO (S p)
makeEquiv opts s (Pair (Rep t _) (Equiv xs ys)) =
optsWithBackend opts $ \bak ->
do -- Note that (at least currently) the `ys` do not
-- depend on the current state: they are all either `Lit`
-- or SAW terms, or `PreLoc`. This is why we can evaluate
-- them now, without worrying about dependencies. I think. (Yav)
-- XXX: With the introduction of `CryFun` one could depend on the
-- current state. For now, we are simply careful not to,
-- in particular, `CryFun` is used only in pre-conditions and all
-- its argumnets are `LocPre` (i.e., the values before execution).
-- Note 2: Sometimes it is useful for CryFun to depend on the current
-- state. For example, consider a function which computes two things
-- f : x -> (a,b)
-- Now we may have specs like this:
-- a = spec1 x
-- b = spec2 x a
-- Of course, we could replcae `b` by:
-- b = spec2 x (spec1 x)
-- but that's ugly and duplicates stuff.
vs <- mapM (\v -> eval v opts s) ys
let sym = backendGetSym bak
let pName = Proxy :: Proxy p
let cur = curState pName s
(v,rest) <- case vs of
v : us -> return (v,us)
[] -> case xs of
[] -> error "[makeEquiv] Empty equivalence class"
l : _ -> do v <- getLoc l opts cur
return (v,[])
s1 <- foldM (\s' y -> setLoc y opts v s') cur xs
let same a =
do p <- evalSame sym t v a
let loc = mkProgramLoc "<makeEquiv>" InternalPos
addAssumption bak
$ GenericAssumption loc "equivalance class assumption" p
mapM_ same rest
return (setCurState pName s1 s)
makeEquivs ::
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> RepMap p -> S p -> IO (S p)
makeEquivs opts mp s = foldM (makeEquiv opts) s (MapF.toList (repBy mp))
addAsmp ::
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> S p -> (String,Prop p) -> IO ()
addAsmp opts s (msg,p) =
case p of
Same _ (Loc _) _ -> return ()
Same _ _ (Loc _) -> return ()
CryPostMem {} -> return ()
_ -> optsWithBackend opts $ \bak ->
do p' <- evalProp opts p s
let loc = mkProgramLoc "<addAssmp>" InternalPos -- FIXME
addAssumption bak (GenericAssumption loc msg p')
setCryPost ::
forall p.
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> S p -> (String,Prop p) -> IO (S p)
setCryPost opts s (_nm,p) =
optsWithBackend opts $ \bak ->
case p of
(CryPostMem ptr n u f xs) ->
unitBitSize u $ \bitW ->
unitByteSize u $ \byteW ->
do vs <- evalCryFunArr opts s n bitW f xs
ptrV <- eval ptr opts s
let llT = llvmBytes byteW
cruT = LLVMPointerRepr bitW
sym = backendGetSym bak
let doSet mem (i,v) =
do let ?ptrWidth = knownNat
loc <- adjustPtr bak mem ptrV (bytesToInteger (i *. u))
val <- packMemValue sym llT cruT v
let alignment = noAlignment -- default to byte-aligned (FIXME, see #338)
storeConstRaw bak mem loc llT alignment val
let cur = Proxy @p
curSt = curState cur s :: State
mem1 <- foldM doSet (stateMem curSt) (zip [ 0 .. ] vs)
return (setCurState cur curSt { stateMem = mem1 } s)
_ -> return s
addAssumptions ::
forall p.
(Eval p, ?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> S p -> [(String, Prop p)] -> IO State
addAssumptions opts s0 ps =
do let mp = foldr getEq emptyRepMap ps
s1 <- makeEquivs opts mp s0
s2 <- foldM (setCryPost opts) s1 ps
mapM_ (addAsmp opts s2) ps
return (curState (Proxy :: Proxy p) s2)
--------------------------------------------------------------------------------
-- | Allocate a memory region.
allocate ::
(?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts -> Area -> State -> IO (LLVMPtr Sym 64, State)
allocate opts ar s =
case areaMode ar of
RO -> do (base,p,m1) <- alloc Immutable
m2 <- fillFresh opts withPtrs base uni names m1
return (p, s { stateMem = m2 })
RW -> do (base,p,m1) <- alloc Mutable
m2 <- fillFresh opts withPtrs base uni names m1
return (p, s { stateMem = m2 })
WO -> do (_,p,m1) <- alloc Mutable
return (p, s { stateMem = m1 })
where
withPtrs = areaHasPointers ar
alloc mut =
optsWithBackend opts $ \bak ->
do let sym = backendGetSym bak
let ?ptrWidth = knownNat @64
let szInt = bytesToInteger (uncurry (*.) (areaSize ar))
sz <- bvLit sym knownNat (BV.mkBV knownNat szInt)
let alignment = noAlignment -- default to byte-aligned (FIXME, see #338)
(base,mem) <- doMalloc bak HeapAlloc mut (areaName ar) (stateMem s) sz alignment
ptr <- adjustPtr bak mem base (bytesToInteger (areaPtr ar))
return (base,ptr,mem)
(num,uni) = areaSize ar
names :: [String]
names = [ areaName ar ++ "_" ++ show uni ++ "_" ++ show i
| i <- take (fromInteger num) [ 0 :: Int .. ] ]
fillFresh ::
(?memOpts::Crucible.MemOptions, Crucible.HasLLVMAnn Sym) =>
Opts ->
Bool ->
LLVMPtr Sym 64 ->
Unit ->
[String] ->
MemImpl Sym ->
IO (MemImpl Sym)
fillFresh opts ptrOk p u todo mem =
unitByteSize u $ \w ->
optsWithBackend opts $ \bak ->
case todo of
[] -> return mem
nm : more ->
do let sym = backendGetSym bak
let ?ptrWidth = knownNat
let ty = ptrTy w
let elS = toInteger (natValue w)
let lty = bitvectorType (toBytes elS)
val <- packMemValue sym lty ty =<< freshVal sym ty ptrOk nm
-- Here we use the write that ignore mutability.
-- This is because we are writinging initialization code.
let alignment = noAlignment -- default to byte-aligned (FIXME, see #338)
mem1 <- storeConstRaw bak mem p lty alignment val
p1 <- adjustPtr bak mem1 p elS
fillFresh opts ptrOk p1 u more mem1
-- | Make an allocation. Used when verifying.
doAlloc ::