-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathMemModel.hs
1827 lines (1604 loc) · 64.8 KB
/
MemModel.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
-- Description : Core definitions of the symbolic C memory model
-- Copyright : (c) Galois, Inc 2015-2016
-- License : BSD3
-- Maintainer : Rob Dockins <[email protected]>
-- Stability : provisional
------------------------------------------------------------------------
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleInstances, FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Lang.Crucible.LLVM.MemModel
( -- * Memories
Mem
, memRepr
, mkMemVar
, MemImpl(..)
, SomePointer(..)
, GlobalMap
, emptyMem
, memEndian
, memAllocCount
, memWriteCount
, G.ppMem
, doDumpMem
, BlockSource(..)
, nextBlock
, MemOptions(..)
, IndeterminateLoadBehavior(..)
, defaultMemOptions
, laxPointerMemOptions
-- * Pointers
, LLVMPointerType
, pattern LLVMPointerRepr
, pattern PtrRepr
, pattern SizeT
, LLVMPtr
, pattern LLVMPointer
, llvmPointerView
, ptrWidth
, G.ppPtr
, G.ppTermExpr
, llvmPointer_bv
, Partial.projectLLVM_bv
-- * Memory operations
, doMalloc
, doMallocUnbounded
, G.AllocType(..)
, G.Mutability(..)
, doMallocHandle
, ME.FuncLookupError(..)
, ME.ppFuncLookupError
, doLookupHandle
, doInstallHandle
, doMemcpy
, doMemset
, doInvalidate
, doCalloc
, doFree
, doAlloca
, doLoad
, doStore
, doArrayStore
, doArrayStoreUnbounded
, doArrayConstStore
, loadString
, loadMaybeString
, strLen
, uncheckedMemcpy
, bindLLVMFunPtr
-- * \"Raw\" operations with LLVMVal
, LLVMVal(..)
, ppLLVMValWithGlobals
, FloatSize(..)
, unpackMemValue
, packMemValue
, loadRaw
, storeRaw
, condStoreRaw
, storeConstRaw
, mallocRaw
, mallocConstRaw
, constToLLVMVal
, constToLLVMValP
, ptrMessage
, Partial.PartLLVMVal(..)
, Partial.assertSafe
, explodeStringValue
-- Re-exports from MemModel.Value
, isZero
, testEqual
, llvmValStorableType
-- * Storage types
, StorageType
, storageTypeF
, StorageTypeF(..)
, Field
, storageTypeSize
, fieldVal
, fieldPad
, fieldOffset
, bitvectorType
, arrayType
, mkStructType
, floatType
, doubleType
, x86_fp80Type
, toStorableType
-- * Pointer operations
, ptrToPtrVal
, mkNullPointer
, ptrIsNull
, ptrEq
, ptrAdd
, ptrSub
, ptrDiff
, doPtrAddOffset
, doPtrSubtract
, isValidPointer
, isAllocatedAlignedPointer
, muxLLVMPtr
, G.isAligned
-- * Disjointness
, assertDisjointRegions
, buildDisjointRegionsAssertion
, buildDisjointRegionsAssertionWithSub
-- * Globals
, GlobalSymbol(..)
, doResolveGlobal
, registerGlobal
, allocGlobals
, allocGlobal
, isGlobalPointer
-- * Misc
, llvmStatementExec
, G.pushStackFrameMem
, G.popStackFrameMem
, G.asMemAllocationArrayStore
, SomeFnHandle(..)
, G.SomeAlloc(..)
, G.possibleAllocs
, G.ppSomeAlloc
, doConditionalWriteOperation
, mergeWriteOperations
, Partial.HasLLVMAnn
, Partial.LLVMAnnMap
, Partial.CexExplanation(..)
, Partial.explainCex
-- * PtrWidth (re-exports)
, HasPtrWidth
, pattern PtrWidth
, withPtrWidth
-- * Concretization
, ML.concPtr
, ML.concLLVMVal
, ML.concMem
, concMemImpl
) where
import Prelude hiding (seq)
import Control.Lens hiding (Empty, (:>))
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Trans (lift)
import Control.Monad.Trans.State
import Data.Dynamic
import Data.IORef
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Text (Text)
import Data.Word
import qualified GHC.Stack as GHC
import Numeric.Natural (Natural)
import System.IO (Handle, hPutStrLn)
import qualified Data.BitVector.Sized as BV
import Data.Parameterized.Classes
import qualified Data.Parameterized.Context as Ctx
import Data.Parameterized.NatRepr
import Data.Parameterized.Some
import qualified Data.Vector as V
import qualified Text.LLVM.AST as L
import What4.Interface
import What4.Expr( GroundValue )
import What4.InterpretedFloatingPoint
import What4.ProgramLoc
import Lang.Crucible.Backend
import Lang.Crucible.CFG.Common
import Lang.Crucible.FunctionHandle
import Lang.Crucible.Types
import Lang.Crucible.Simulator.ExecutionTree
import Lang.Crucible.Simulator.GlobalState
import Lang.Crucible.Simulator.Intrinsics
import Lang.Crucible.Simulator.RegMap
import Lang.Crucible.Simulator.SimError
import Lang.Crucible.LLVM.DataLayout
import Lang.Crucible.LLVM.Extension
import Lang.Crucible.LLVM.Bytes
import Lang.Crucible.LLVM.Errors.MemoryError
(MemErrContext, MemoryErrorReason(..), MemoryOp(..), ppMemoryErrorReason)
import qualified Lang.Crucible.LLVM.Errors.MemoryError as ME
import qualified Lang.Crucible.LLVM.Errors.UndefinedBehavior as UB
import Lang.Crucible.LLVM.MemType
import Lang.Crucible.LLVM.MemModel.CallStack (CallStack, getCallStack)
import qualified Lang.Crucible.LLVM.MemModel.MemLog as ML
import Lang.Crucible.LLVM.MemModel.Type
import qualified Lang.Crucible.LLVM.MemModel.Partial as Partial
import qualified Lang.Crucible.LLVM.MemModel.Generic as G
import Lang.Crucible.LLVM.MemModel.Pointer
import Lang.Crucible.LLVM.MemModel.Options
import Lang.Crucible.LLVM.MemModel.Value
import Lang.Crucible.LLVM.Translation.Constant
import Lang.Crucible.LLVM.Types
import Lang.Crucible.LLVM.Utils
import Lang.Crucible.Panic (panic)
import GHC.Stack (HasCallStack)
----------------------------------------------------------------------
-- The MemImpl type
newtype BlockSource = BlockSource (IORef Natural)
type GlobalMap sym = Map L.Symbol (SomePointer sym)
nextBlock :: BlockSource -> IO Natural
nextBlock (BlockSource ref) =
atomicModifyIORef' ref (\n -> (n+1, n))
-- | The implementation of an LLVM memory, containing an
-- allocation-block source, global map, handle map, and heap.
data MemImpl sym =
MemImpl
{ memImplBlockSource :: BlockSource
, memImplGlobalMap :: GlobalMap sym
, memImplSymbolMap :: Map Natural L.Symbol -- inverse mapping to 'memImplGlobalMap'
, memImplHandleMap :: Map Natural Dynamic
, memImplHeap :: G.Mem sym
}
memEndian :: MemImpl sym -> EndianForm
memEndian = G.memEndian . memImplHeap
memAllocCount :: MemImpl sym -> Int
memAllocCount = G.memAllocCount . memImplHeap
memWriteCount :: MemImpl sym -> Int
memWriteCount = G.memWriteCount . memImplHeap
-- | Produce a fresh empty memory.
-- NB, we start counting allocation blocks at '1'.
-- Block number 0 is reserved for representing raw bitvectors.
emptyMem :: EndianForm -> IO (MemImpl sym)
emptyMem endianness = do
blkRef <- newIORef 1
return $ MemImpl (BlockSource blkRef) Map.empty Map.empty Map.empty (G.emptyMem endianness)
-- | Pretty print a memory state to the given handle.
doDumpMem :: IsExprBuilder sym => Handle -> MemImpl sym -> IO ()
doDumpMem h mem = do
hPutStrLn h (show (G.ppMem (memImplHeap mem)))
----------------------------------------------------------------------
-- Memory operations
--
-- | Assert that some undefined behavior doesn't occur when performing memory
-- model operations
assertUndefined ::
(IsSymBackend sym bak, Partial.HasLLVMAnn sym) =>
bak ->
CallStack ->
Pred sym ->
(UB.UndefinedBehavior (RegValue' sym)) {- ^ The undesirable behavior -} ->
IO ()
assertUndefined bak callStack p ub =
do let sym = backendGetSym bak
p' <- Partial.annotateUB sym callStack ub p
assert bak p' $ AssertFailureSimError "Undefined behavior encountered" (show (UB.explain ub))
assertStoreError ::
(IsSymBackend sym bak, Partial.HasLLVMAnn sym, 1 <= wptr) =>
bak ->
MemErrContext sym wptr ->
MemoryErrorReason ->
Pred sym ->
IO ()
assertStoreError bak errCtx rsn p =
do let sym = backendGetSym bak
p' <- Partial.annotateME sym errCtx rsn p
assert bak p' $ AssertFailureSimError "Memory store failed" (show (ppMemoryErrorReason rsn))
instance IsSymInterface sym => IntrinsicClass sym "LLVM_memory" where
type Intrinsic sym "LLVM_memory" ctx = MemImpl sym
-- NB: Here we are assuming the global maps of both memories are identical.
-- This should be the case as memories are only supposed to allocate globals at
-- startup, not during program execution. We could check that the maps match,
-- but that would be expensive...
muxIntrinsic _sym _iTypes _nm _ p mem1 mem2 =
do let MemImpl blockSource gMap1 sMap1 hMap1 m1 = mem1
let MemImpl _blockSource _gMap2 _sMap2 hMap2 m2 = mem2
--putStrLn "MEM MERGE"
return $ MemImpl blockSource gMap1 sMap1
(Map.union hMap1 hMap2)
(G.mergeMem p m1 m2)
pushBranchIntrinsic _sym _iTypes _nm _ctx mem =
do let MemImpl nxt gMap sMap hMap m = mem
--putStrLn "MEM PUSH BRANCH"
return $ MemImpl nxt gMap sMap hMap $ G.branchMem m
abortBranchIntrinsic _sym _iTypes _nm _ctx mem =
do let MemImpl nxt gMap sMap hMap m = mem
--putStrLn "MEM ABORT BRANCH"
return $ MemImpl nxt gMap sMap hMap $ G.branchAbortMem m
-- | Top-level evaluation function for LLVM extension statements.
-- LLVM extension statements are used to implement the memory model operations.
llvmStatementExec ::
(Partial.HasLLVMAnn sym, ?memOpts :: MemOptions) =>
EvalStmtFunc p sym LLVM
llvmStatementExec stmt cst =
let simCtx = cst^.stateContext
in withBackend simCtx $ \bak ->
runStateT (evalStmt bak stmt) cst
type EvalM p sym ext rtp blocks ret args a =
StateT (CrucibleState p sym ext rtp blocks ret args) IO a
-- | Actual workhorse function for evaluating LLVM extension statements.
-- The semantics are explicitly organized as a state transformer monad
-- that modifies the global state of the simulator; this captures the
-- memory accessing effects of these statements.
evalStmt :: forall p sym bak ext rtp blocks ret args tp.
(IsSymBackend sym bak, Partial.HasLLVMAnn sym, GHC.HasCallStack, ?memOpts :: MemOptions) =>
bak ->
LLVMStmt (RegEntry sym) tp ->
EvalM p sym ext rtp blocks ret args (RegValue sym tp)
evalStmt bak = eval
where
sym = backendGetSym bak
getMem :: GlobalVar Mem ->
EvalM p sym ext rtp blocks ret args (MemImpl sym)
getMem mvar =
do gs <- use (stateTree.actFrame.gpGlobals)
case lookupGlobal mvar gs of
Just mem -> return mem
Nothing ->
panic "MemModel.evalStmt.getMem"
[ "Global heap value not initialized."
, "*** Global heap variable: " ++ show mvar
]
setMem :: GlobalVar Mem ->
MemImpl sym ->
EvalM p sym ext rtp blocks ret args ()
setMem mvar mem = stateTree.actFrame.gpGlobals %= insertGlobal mvar mem
failedAssert :: String -> String -> EvalM p sym ext rtp blocks ret args a
failedAssert msg details =
lift $ addFailedAssertion bak $ AssertFailureSimError msg details
eval :: LLVMStmt (RegEntry sym) tp ->
EvalM p sym ext rtp blocks ret args (RegValue sym tp)
eval (LLVM_PushFrame nm mvar) =
do mem <- getMem mvar
let heap' = G.pushStackFrameMem nm (memImplHeap mem)
setMem mvar mem{ memImplHeap = heap' }
eval (LLVM_PopFrame mvar) =
do mem <- getMem mvar
let heap' = G.popStackFrameMem (memImplHeap mem)
setMem mvar mem{ memImplHeap = heap' }
eval (LLVM_Alloca _w mvar (regValue -> sz) alignment loc) =
do mem <- getMem mvar
(ptr, mem') <- liftIO $ doAlloca bak mem sz alignment loc
setMem mvar mem'
return ptr
eval (LLVM_Load mvar (regValue -> ptr) tpr valType alignment) =
do mem <- getMem mvar
liftIO $ doLoad bak mem ptr valType tpr alignment
eval (LLVM_MemClear mvar (regValue -> ptr) bytes) =
do mem <- getMem mvar
z <- liftIO $ bvLit sym knownNat (BV.zero knownNat)
len <- liftIO $ bvLit sym PtrWidth (bytesToBV PtrWidth bytes)
mem' <- liftIO $ doMemset bak PtrWidth mem ptr z len
setMem mvar mem'
eval (LLVM_Store mvar (regValue -> ptr) tpr valType alignment (regValue -> val)) =
do mem <- getMem mvar
mem' <- liftIO $ doStore bak mem ptr tpr valType alignment val
setMem mvar mem'
eval (LLVM_LoadHandle mvar ltp (regValue -> ptr) args ret) =
do mem <- getMem mvar
let gsym = unsymbol <$> isGlobalPointer (memImplSymbolMap mem) ptr
mhandle <- liftIO $ doLookupHandle sym mem ptr
let mop = MemLoadHandleOp ltp gsym ptr (memImplHeap mem)
let expectedTp = FunctionHandleRepr args ret
case mhandle of
Left lookupErr -> lift $
do p <- Partial.annotateME sym mop (BadFunctionPointer lookupErr) (falsePred sym)
loc <- getCurrentProgramLoc sym
let err = SimError loc (AssertFailureSimError "Failed to load function handle" (show (ME.ppFuncLookupError lookupErr)))
addProofObligation bak (LabeledPred p err)
abortExecBecause (AssertionFailure err)
Right (VarargsFnHandle h) ->
let err = failedAssert "Failed to load function handle"
(unlines
["Expected function handle of type " <> show expectedTp
,"for call to function " <> show (handleName h)
,"but found varargs handle of non-matching type " ++ show (handleType h)
]) in
case handleArgTypes h of
prefix Ctx.:> VectorRepr AnyRepr
| Just Refl <- testEquality ret (handleReturnType h)
-> Ctx.dropPrefix args prefix err (return . VarargsFnVal h)
_ -> err
Right (SomeFnHandle h)
| Just Refl <- testEquality (handleType h) expectedTp -> return (HandleFnVal h)
| otherwise -> failedAssert
"Failed to load function handle"
(unlines ["Expected function handle of type " <> show expectedTp
, "for call to function " <> show (handleName h)
, "but found calling handle of type " ++ show (handleType h)])
eval (LLVM_ResolveGlobal _w mvar (GlobalSymbol symbol)) =
do mem <- getMem mvar
liftIO $ doResolveGlobal bak mem symbol
eval (LLVM_PtrEq mvar (regValue -> x) (regValue -> y)) = do
mem <- getMem mvar
liftIO $ do
v1 <- isValidPointer sym x mem
v2 <- isValidPointer sym y mem
v3 <- G.notAliasable sym x y (memImplHeap mem)
let callStack = getCallStack (mem ^. to memImplHeap . ML.memState)
assertUndefined bak callStack v1 $
UB.CompareInvalidPointer UB.Eq (RV x) (RV y)
assertUndefined bak callStack v2 $
UB.CompareInvalidPointer UB.Eq (RV x) (RV y)
unless (laxConstantEquality ?memOpts) $
do let allocs_doc = G.ppAllocs (G.memAllocs (memImplHeap mem))
let x_doc = G.ppPtr x
let y_doc = G.ppPtr y
-- TODO: Is this undefined behavior? If so, add to the UB module
assert bak v3 $
AssertFailureSimError
"Const pointers compared for equality"
(unlines [ show x_doc
, show y_doc
, show allocs_doc
])
ptrEq sym PtrWidth x y
eval (LLVM_PtrLe mvar (regValue -> x) (regValue -> y)) = do
mem <- getMem mvar
liftIO $ do
v1 <- isValidPointer sym x mem
v2 <- isValidPointer sym y mem
let callStack = getCallStack (mem ^. to memImplHeap . ML.memState)
assertUndefined bak callStack v1
(UB.CompareInvalidPointer UB.Leq (RV x) (RV y))
assertUndefined bak callStack v2
(UB.CompareInvalidPointer UB.Leq (RV x) (RV y))
(le, valid) <- ptrLe sym PtrWidth x y
assertUndefined bak callStack valid
(UB.CompareDifferentAllocs (RV x) (RV y))
pure le
eval (LLVM_PtrAddOffset _w mvar (regValue -> x) (regValue -> y)) =
do mem <- getMem mvar
liftIO $ doPtrAddOffset bak mem x y
eval (LLVM_PtrSubtract _w mvar (regValue -> x) (regValue -> y)) =
do mem <- getMem mvar
liftIO $ doPtrSubtract bak mem x y
eval LLVM_Debug{} = pure ()
mkMemVar :: Text
-> HandleAllocator
-> IO (GlobalVar Mem)
mkMemVar memName halloc = freshGlobalVar halloc memName knownRepr
-- | For now, the core message should be on the first line, with details
-- on further lines. Later we should make it more structured.
ptrMessage ::
(IsSymInterface sym) =>
String ->
LLVMPtr sym wptr {- ^ pointer involved in message -} ->
StorageType {- ^ type of value pointed to -} ->
String
ptrMessage msg ptr ty =
unlines [ msg
, " address " ++ show (G.ppPtr ptr)
, " at type " ++ show (G.ppType ty)
]
-- | Allocate memory on the stack frame of the currently executing function.
doAlloca ::
( IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym
, ?memOpts :: MemOptions ) =>
bak ->
MemImpl sym ->
SymBV sym wptr {- ^ allocation size -} ->
Alignment {- ^ pointer alignment -} ->
String {- ^ source location for use in error messages -} ->
IO (LLVMPtr sym wptr, MemImpl sym)
doAlloca bak mem sz alignment loc = do
let sym = backendGetSym bak
blkNum <- liftIO $ nextBlock (memImplBlockSource mem)
blk <- liftIO $ natLit sym blkNum
z <- liftIO $ bvLit sym PtrWidth (BV.zero PtrWidth)
let heap' = G.allocMem G.StackAlloc blkNum (Just sz) alignment G.Mutable loc (memImplHeap mem)
let ptr = LLVMPointer blk z
let mem' = mem{ memImplHeap = heap' }
mem'' <- if laxLoadsAndStores ?memOpts
&& indeterminateLoadBehavior ?memOpts == StableSymbolic
then doStoreStableSymbolic bak mem' ptr (Just sz) alignment
else pure mem'
pure (ptr, mem'')
-- | Load a 'RegValue' from memory. Both the 'StorageType' and 'TypeRepr'
-- arguments should be computed from a single 'MemType' using
-- 'toStorableType' and 'Lang.Crucible.LLVM.Translation.Types.llvmTypeAsRepr'
-- respectively.
--
-- Precondition: the pointer is valid and aligned, and the loaded value is defined.
doLoad ::
( IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym
, ?memOpts :: MemOptions ) =>
bak ->
MemImpl sym ->
LLVMPtr sym wptr {- ^ pointer to load from -} ->
StorageType {- ^ type of value to load -} ->
TypeRepr tp {- ^ crucible type of the result -} ->
Alignment {- ^ assumed pointer alignment -} ->
IO (RegValue sym tp)
doLoad bak mem ptr valType tpr alignment = do
let sym = backendGetSym bak
unpackMemValue sym tpr =<<
Partial.assertSafe bak =<<
loadRaw sym mem ptr valType alignment
-- | Store a 'RegValue' in memory. Both the 'StorageType' and 'TypeRepr'
-- arguments should be computed from a single 'MemType' using
-- 'toStorableType' and 'Lang.Crucible.LLVM.Translation.Types.llvmTypeAsRepr'
-- respectively.
--
-- Precondition: the pointer is valid and points to a mutable memory region.
doStore ::
(IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym) =>
bak ->
MemImpl sym ->
LLVMPtr sym wptr {- ^ pointer to store into -} ->
TypeRepr tp ->
StorageType {- ^ type of value to store -} ->
Alignment ->
RegValue sym tp {- ^ value to store -} ->
IO (MemImpl sym)
doStore bak mem ptr tpr valType alignment val = do
--putStrLn "MEM STORE"
let sym = backendGetSym bak
val' <- packMemValue sym valType tpr val
storeRaw bak mem ptr valType alignment val'
data SomeFnHandle where
SomeFnHandle :: FnHandle args ret -> SomeFnHandle
VarargsFnHandle :: FnHandle (args ::> VectorType AnyType) ret -> SomeFnHandle
sextendBVTo :: (1 <= w, 1 <= w', IsSymInterface sym)
=> sym
-> NatRepr w
-> NatRepr w'
-> SymExpr sym (BaseBVType w)
-> IO (SymExpr sym (BaseBVType w'))
sextendBVTo sym w w' x
| Just Refl <- testEquality w w' = return x
| Just LeqProof <- testLeq (incNat w) w' = bvSext sym w' x
| Just LeqProof <- testLeq (incNat w') w = bvTrunc sym w' x
| otherwise = panic "sextendBVTo"
[ "Impossible widths!"
, show w
, show w'
]
-- | Allocate and zero a memory region with /size * number/ bytes.
--
-- Precondition: the multiplication /size * number/ does not overflow.
doCalloc ::
( IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym
, ?memOpts :: MemOptions ) =>
bak ->
MemImpl sym ->
SymBV sym wptr {- ^ size -} ->
SymBV sym wptr {- ^ number -} ->
Alignment {- ^ Minimum alignment of the resulting allocation -} ->
IO (LLVMPtr sym wptr, MemImpl sym)
doCalloc bak mem sz num alignment = do
let sym = backendGetSym bak
(ov, sz') <- unsignedWideMultiplyBV sym sz num
ov_iszero <- notPred sym =<< bvIsNonzero sym ov
-- TODO, this probably shouldn't be UB
assert bak ov_iszero
(AssertFailureSimError "Multiplication overflow in calloc()" "")
loc <- plSourceLoc <$> getCurrentProgramLoc sym
let displayString = "<calloc> " ++ show loc
z <- bvLit sym knownNat (BV.zero knownNat)
(ptr, mem') <- doMalloc bak G.HeapAlloc G.Mutable displayString mem sz' alignment
mem'' <- doMemset bak PtrWidth mem' ptr z sz'
return (ptr, mem'')
-- | Allocate a memory region.
doMalloc
:: ( IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym
, ?memOpts :: MemOptions )
=> bak
-> G.AllocType {- ^ stack, heap, or global -}
-> G.Mutability {- ^ whether region is read-only -}
-> String {- ^ source location for use in error messages -}
-> MemImpl sym
-> SymBV sym wptr {- ^ allocation size -}
-> Alignment
-> IO (LLVMPtr sym wptr, MemImpl sym)
doMalloc bak allocType mut loc mem sz alignment = doMallocSize (Just sz) bak allocType mut loc mem alignment
-- | Allocate a memory region of unbounded size.
doMallocUnbounded
:: ( IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym
, ?memOpts :: MemOptions )
=> bak
-> G.AllocType {- ^ stack, heap, or global -}
-> G.Mutability {- ^ whether region is read-only -}
-> String {- ^ source location for use in error messages -}
-> MemImpl sym
-> Alignment
-> IO (LLVMPtr sym wptr, MemImpl sym)
doMallocUnbounded = doMallocSize Nothing
doMallocSize
:: ( IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym
, ?memOpts :: MemOptions )
=> Maybe (SymBV sym wptr) {- ^ allocation size -}
-> bak
-> G.AllocType {- ^ stack, heap, or global -}
-> G.Mutability {- ^ whether region is read-only -}
-> String {- ^ source location for use in error messages -}
-> MemImpl sym
-> Alignment
-> IO (LLVMPtr sym wptr, MemImpl sym)
doMallocSize sz bak allocType mut loc mem alignment = do
let sym = backendGetSym bak
blkNum <- nextBlock (memImplBlockSource mem)
blk <- natLit sym blkNum
z <- bvLit sym PtrWidth (BV.zero PtrWidth)
let heap' = G.allocMem allocType blkNum sz alignment mut loc (memImplHeap mem)
let ptr = LLVMPointer blk z
let mem' = mem{ memImplHeap = heap' }
mem'' <- if laxLoadsAndStores ?memOpts
&& mut == G.Mutable
&& allocType == G.HeapAlloc
&& indeterminateLoadBehavior ?memOpts == StableSymbolic
then doStoreStableSymbolic bak mem' ptr sz alignment
else pure mem'
return (ptr, mem'')
bindLLVMFunPtr ::
(IsSymBackend sym bak, HasPtrWidth wptr) =>
bak ->
L.Declare ->
FnHandle args ret ->
MemImpl sym ->
IO (MemImpl sym)
bindLLVMFunPtr bak dec h mem
| L.decVarArgs dec
, (_ Ctx.:> VectorRepr AnyRepr) <- handleArgTypes h
= do ptr <- doResolveGlobal bak mem (L.decName dec)
doInstallHandle bak ptr (VarargsFnHandle h) mem
| otherwise
= do ptr <- doResolveGlobal bak mem (L.decName dec)
doInstallHandle bak ptr (SomeFnHandle h) mem
doInstallHandle
:: (Typeable a, IsSymBackend sym bak)
=> bak
-> LLVMPtr sym wptr
-> a {- ^ handle -}
-> MemImpl sym
-> IO (MemImpl sym)
doInstallHandle _bak ptr x mem =
case asNat (llvmPointerBlock ptr) of
Just blkNum ->
do let hMap' = Map.insert blkNum (toDyn x) (memImplHandleMap mem)
return mem{ memImplHandleMap = hMap' }
Nothing ->
panic "MemModel.doInstallHandle"
[ "Attempted to install handle for symbolic pointer"
, " " ++ show (ppPtr ptr)
]
-- | Allocate a memory region for the given handle.
doMallocHandle
:: (Typeable a, IsSymInterface sym, HasPtrWidth wptr)
=> sym
-> G.AllocType {- ^ stack, heap, or global -}
-> String {- ^ source location for use in error messages -}
-> MemImpl sym
-> a {- ^ handle -}
-> IO (LLVMPtr sym wptr, MemImpl sym)
doMallocHandle sym allocType loc mem x = do
blkNum <- nextBlock (memImplBlockSource mem)
blk <- natLit sym blkNum
z <- bvLit sym PtrWidth (BV.zero PtrWidth)
let heap' = G.allocMem allocType blkNum (Just z) noAlignment G.Immutable loc (memImplHeap mem)
let hMap' = Map.insert blkNum (toDyn x) (memImplHandleMap mem)
let ptr = LLVMPointer blk z
return (ptr, mem{ memImplHeap = heap', memImplHandleMap = hMap' })
-- | Look up the handle associated with the given pointer, if any.
doLookupHandle
:: (Typeable a, IsSymInterface sym)
=> sym
-> MemImpl sym
-> LLVMPtr sym wptr
-> IO (Either ME.FuncLookupError a)
doLookupHandle _sym mem ptr = do
let LLVMPointer blk _ = ptr
case asNat blk of
Nothing -> return (Left ME.SymbolicPointer)
Just i
| i == 0 -> return (Left ME.RawBitvector)
| otherwise ->
case Map.lookup i (memImplHandleMap mem) of
Nothing -> return (Left ME.NoOverride)
Just x ->
case fromDynamic x of
Nothing -> return (Left (ME.Uncallable (dynTypeRep x)))
Just a -> return (Right a)
-- | Free the memory region pointed to by the given pointer.
--
-- Precondition: the pointer either points to the beginning of an allocated
-- region, or is null. Freeing a null pointer has no effect.
doFree
:: (IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym)
=> bak
-> MemImpl sym
-> LLVMPtr sym wptr
-> IO (MemImpl sym)
doFree bak mem ptr = do
let sym = backendGetSym bak
let LLVMPointer blk _off = ptr
loc <- show . plSourceLoc <$> getCurrentProgramLoc sym
(heap', p1, p2, notFreed) <- G.freeMem sym PtrWidth ptr (memImplHeap mem) loc
-- If this pointer is a handle pointer, remove the associated data
let hMap' =
case asNat blk of
Just i -> Map.delete i (memImplHandleMap mem)
Nothing -> memImplHandleMap mem
-- NB: free is defined and has no effect if passed a null pointer
isNull <- ptrIsNull sym PtrWidth ptr
p1' <- orPred sym p1 isNull
p2' <- orPred sym p2 isNull
notFreed' <- orPred sym notFreed isNull
let callStack = getCallStack (mem ^. to memImplHeap . ML.memState)
assertUndefined bak callStack p1' (UB.FreeBadOffset (RV ptr))
assertUndefined bak callStack p2' (UB.FreeUnallocated (RV ptr))
assertUndefined bak callStack notFreed' (UB.DoubleFree (RV ptr))
return mem{ memImplHeap = heap', memImplHandleMap = hMap' }
-- | Fill a memory range with copies of the specified byte.
--
-- Precondition: the memory range falls within a valid allocated region.
doMemset ::
(1 <= w, IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym) =>
bak ->
NatRepr w ->
MemImpl sym ->
LLVMPtr sym wptr {- ^ destination -} ->
SymBV sym 8 {- ^ fill byte -} ->
SymBV sym w {- ^ length -} ->
IO (MemImpl sym)
doMemset bak w mem dest val len = do
let sym = backendGetSym bak
len' <- sextendBVTo sym w PtrWidth len
(heap', p) <- G.setMem sym PtrWidth dest val len' (memImplHeap mem)
let callStack = getCallStack (mem ^. to memImplHeap . ML.memState)
assertUndefined bak callStack p $
UB.MemsetInvalidRegion (RV dest) (RV val) (RV len)
return mem{ memImplHeap = heap' }
doInvalidate ::
( 1 <= w, IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym
, ?memOpts :: MemOptions ) =>
bak ->
NatRepr w ->
MemImpl sym ->
LLVMPtr sym wptr {- ^ destination -} ->
Text {- ^ message -} ->
SymBV sym w {- ^ length -} ->
IO (MemImpl sym)
doInvalidate bak w mem dest msg len = do
let sym = backendGetSym bak
len' <- sextendBVTo sym w PtrWidth len
(heap', p) <- if laxLoadsAndStores ?memOpts &&
indeterminateLoadBehavior ?memOpts == StableSymbolic
then do p <- G.isAllocatedMutable sym PtrWidth noAlignment dest (Just len') (memImplHeap mem)
mem' <- doStoreStableSymbolic bak mem dest (Just len') noAlignment
pure (memImplHeap mem', p)
else G.invalidateMem sym PtrWidth dest msg len' (memImplHeap mem)
let gsym = unsymbol <$> isGlobalPointer (memImplSymbolMap mem) dest
let mop = MemInvalidateOp msg gsym dest len (memImplHeap mem)
p' <- Partial.annotateME sym mop UnwritableRegion p
assert bak p' $ AssertFailureSimError "Invalidation of unallocated or readonly region" ""
return mem{ memImplHeap = heap' }
-- | Store an array in memory.
--
-- Precondition: the pointer is valid and points to a mutable memory region.
doArrayStore
:: (IsSymBackend sym bak, HasPtrWidth w, Partial.HasLLVMAnn sym)
=> bak
-> MemImpl sym
-> LLVMPtr sym w {- ^ destination -}
-> Alignment
-> SymArray sym (SingleCtx (BaseBVType w)) (BaseBVType 8) {- ^ array value -}
-> SymBV sym w {- ^ array length -}
-> IO (MemImpl sym)
doArrayStore bak mem ptr alignment arr len = doArrayStoreSize (Just len) bak mem ptr alignment arr
-- | Store an array of unbounded length in memory.
--
-- Precondition: the pointer is valid and points to a mutable memory region.
doArrayStoreUnbounded
:: (IsSymBackend sym bak, HasPtrWidth w, Partial.HasLLVMAnn sym)
=> bak
-> MemImpl sym
-> LLVMPtr sym w {- ^ destination -}
-> Alignment
-> SymArray sym (SingleCtx (BaseBVType w)) (BaseBVType 8) {- ^ array value -}
-> IO (MemImpl sym)
doArrayStoreUnbounded = doArrayStoreSize Nothing
doArrayStoreSize
:: (IsSymBackend sym bak, HasPtrWidth w, Partial.HasLLVMAnn sym)
=> Maybe (SymBV sym w) {- ^ possibly-unbounded array length -}
-> bak
-> MemImpl sym
-> LLVMPtr sym w {- ^ destination -}
-> Alignment
-> SymArray sym (SingleCtx (BaseBVType w)) (BaseBVType 8) {- ^ array value -}
-> IO (MemImpl sym)
doArrayStoreSize len bak mem ptr alignment arr = do
let sym = backendGetSym bak
(heap', p1, p2) <-
G.writeArrayMem sym PtrWidth ptr alignment arr len (memImplHeap mem)
let gsym = unsymbol <$> isGlobalPointer (memImplSymbolMap mem) ptr
let mop = MemStoreBytesOp gsym ptr len (memImplHeap mem)
assertStoreError bak mop UnwritableRegion p1
let callStack = getCallStack (mem ^. to memImplHeap . ML.memState)
assertUndefined bak callStack p2 (UB.WriteBadAlignment (RV ptr) alignment)
return mem { memImplHeap = heap' }
-- | Store an array in memory.
--
-- Precondition: the pointer is valid and points to a mutable or immutable memory region.
-- Therefore it can be used to initialize read-only memory regions.
doArrayConstStore
:: (IsSymBackend sym bak, HasPtrWidth w, Partial.HasLLVMAnn sym)
=> bak
-> MemImpl sym
-> LLVMPtr sym w {- ^ destination -}
-> Alignment
-> SymArray sym (SingleCtx (BaseBVType w)) (BaseBVType 8) {- ^ array value -}
-> SymBV sym w {- ^ array length -}
-> IO (MemImpl sym)
doArrayConstStore bak mem ptr alignment arr len = do
let sym = backendGetSym bak
(heap', p1, p2) <-
G.writeArrayConstMem sym PtrWidth ptr alignment arr (Just len) (memImplHeap mem)
let gsym = unsymbol <$> isGlobalPointer (memImplSymbolMap mem) ptr
let mop = MemStoreBytesOp gsym ptr (Just len) (memImplHeap mem)
assertStoreError bak mop UnwritableRegion p1
let callStack = getCallStack (mem ^. to memImplHeap . ML.memState)
assertUndefined bak callStack p2 (UB.WriteBadAlignment (RV ptr) alignment)
return mem { memImplHeap = heap' }
-- | Copy memory from source to destination.
--
-- Precondition: the source and destination pointers fall within valid allocated
-- regions.
doMemcpy ::
( 1 <= w, IsSymBackend sym bak, HasPtrWidth wptr, Partial.HasLLVMAnn sym
, ?memOpts :: MemOptions ) =>
bak ->
NatRepr w ->
MemImpl sym ->
Bool {- ^ if true, require disjoint memory regions -} ->
LLVMPtr sym wptr {- ^ destination -} ->
LLVMPtr sym wptr {- ^ source -} ->
SymBV sym w {- ^ length -} ->
IO (MemImpl sym)
doMemcpy bak w mem mustBeDisjoint dest src len = do
let sym = backendGetSym bak
len' <- sextendBVTo sym w PtrWidth len
(heap', p1, p2) <- G.copyMem sym PtrWidth dest src len' (memImplHeap mem)
let gsym_dest = unsymbol <$> isGlobalPointer (memImplSymbolMap mem) dest
let gsym_src = unsymbol <$> isGlobalPointer (memImplSymbolMap mem) src
let mop = MemCopyOp (gsym_dest, dest) (gsym_src, src) len (memImplHeap mem)
p1' <- applyUnless (laxLoadsAndStores ?memOpts)
(Partial.annotateME sym mop UnreadableRegion) p1
p2' <- Partial.annotateME sym mop UnwritableRegion p2
assert bak p1' $ AssertFailureSimError "Mem copy failed" "Invalid copy source"
assert bak p2' $ AssertFailureSimError "Mem copy failed" "Invalid copy destination"
when mustBeDisjoint (assertDisjointRegions bak mop (bvWidth len) dest len src len)
return mem{ memImplHeap = heap' }
unsymbol :: L.Symbol -> String
unsymbol (L.Symbol s) = s