-- | Moves made explicit, and leak checks (L4a, language 6.3). Run after flow analysis (which -- checks ownership on the program as written), before proof and code generation: -- -- * A move empties its source: after an assignment moves an owning name, the access values -- in it become null. Ownership guarantees that nothing reads them until they are given -- new values, so this changes no result, and it makes "owns nothing" a plain fact about -- values (every access value in it is null) that the prover can check. -- * Leak checks (B6005, proof only): an owning object must own nothing where it is -- overwritten (an assignment, an `out` actual) and where it dies (the end of its scope, a -- return), and an object being freed must own nothing itself. -- -- These are the death points L4b turns into finalization (language 6.3, the design -- constraint): a reclaimed object's leak check becomes a call of its `Finalize` there. module Verada.BIR.Moves ( deallocationName , explicitMoves , isOwning , ownsNothing ) where import Verada.BIR.Expr import Verada.BIR.Stmt import Verada.BIR.Types import Verada.Source (Span) import Verada.TAST.Decl (ParamMode (..)) import Control.Applicative ((<|>)) import Control.Monad (forM) import Control.Monad.State.Strict (State, evalState, gets, modify') import Data.Functor ((<&>)) import Data.IntMap.Strict (IntMap) import Data.IntMap.Strict qualified as IntMap import Data.IntSet (IntSet) import Data.IntSet qualified as IntSet import Data.List (find, mapAccumL) import Data.Map.Strict qualified as Map import Data.Maybe (fromMaybe, mapMaybe) import Data.Text (Text) -- | Whether values of a type own heap objects: values of pool-specific access types, and -- composites that hold them. isOwning :: BType -> Bool isOwning = \case AccessOf a -> not a.toConstant && not a.borrower RecordOf r -> any (isOwning . (.typ)) r.fields ArrayOf a -> isOwning a.component ArrayValue d -> isOwning d.component ClassWide c -> any (isOwning . RecordOf . snd) c.alternatives Scalar _ -> False SubprogramAccessOf _ -> False -- (a formal private type's values are moved as the actual's would be, which need not own: -- the instances are checked) Abstract _ -> False -- | The C name of `Ada.Unchecked_Deallocation`'s body. deallocationName :: Text deallocationName = "verada_rt_deallocate" data MoveState = MoveState { vars :: IntMap Var , next :: Int , declared :: IntSet -- ^ locals whose declaration (first assignment) has been seen, in program order , live :: IntSet -- ^ of those, the ones whose scope has not ended } type Moving = State MoveState -- | The program with its moves explicit and its leak checks. explicitMoves :: BProgram -> BProgram explicitMoves p | not (any (isOwning . (.typ)) (concatMap (IntMap.elems . (.variables)) p.subprograms <> map (.var) p.globals)) = p | otherwise = p {subprograms = snd (mapAccumL (subprogramMoves p) firstFree p.subprograms)} where -- (variable ids are unique in the whole program, as lowering made them: a proof of one -- subprogram also reads expressions of others, such as a type's invariant or default -- condition, so a temporary numbered after its own subprogram's variables could name -- another's) firstFree = 1 + maximum (0 : map (key . (.var.varId)) p.globals <> concatMap (map fst . IntMap.toList . (.variables)) p.subprograms) -- | A subprogram's moves made explicit, its temporaries numbered from the given id; the next -- free id after them. subprogramMoves :: BProgram -> Int -> BSubprogram -> (Int, BSubprogram) subprogramMoves p free sub = case sub.body of Nothing -> (free, sub) Just body -> let start = MoveState {vars = sub.variables, next = free, declared = IntSet.empty, live = IntSet.empty} (body', final, after) = evalState ((,,) <$> program body <*> gets (.vars) <*> gets (.next)) start in (after,) BSubprogram {decl = sub.decl, name = sub.name, linkName = sub.linkName, span = sub.span, parameters = sub.parameters, result = sub.result, resultLow = sub.resultLow, resultHigh = sub.resultHigh, variables = final, pre = sub.pre, post = sub.post, snapshots = sub.snapshots, valueSnapshots = sub.valueSnapshots, body = Just body', expressionBody = sub.expressionBody, imported = sub.imported, ghost = sub.ghost, flow = sub.flow, variant = sub.variant, structural = sub.structural, borrowed = sub.borrowed, exceptional = sub.exceptional, terminates = sub.terminates, cConvention = sub.cConvention, programExit = sub.programExit, exitCases = sub.exitCases} where globalVars = IntMap.fromList [(key g.var.varId, g.var) | g <- p.globals] temporaries = IntMap.filter (\x -> x.role == Temporary) sub.variables program body = do -- `out` parameters start owning nothing (callers checked that their actuals do) let outs = [v | v <- sub.parameters, Just x <- [IntMap.lookup (key v) sub.variables], x.role == Parameter ModeOut, isOwning x.typ] emptied <- concat <$> forM outs \v -> nullify . var v <$> typeOf v rest <- stmts body pure (emptied <> rest) stmts = fmap concat . mapM stmt stmt :: BStmt -> Moving [BStmt] stmt s = case s.node of -- (a ghost copy, a loop's snapshot of what it changes, takes nothing: the value is still -- its owner's, ACATS C352001) BAssign a | Just x <- IntMap.lookup (key a.target) sub.variables, x.ghost, x.role == Temporary -> pure [s] BAssign a -> do target <- var a.target <$> typeOf a.target firstTime <- declaration a.target role <- roleOf a.target assignWith here a.value target (role /= Temporary && not firstTime && not (lent a.value)) \v -> BAssign Assign {target = a.target, value = v} BAssignPart a -> do whole <- var a.target <$> typeOf a.target role <- roleOf a.target assignWith here a.value (pathExpr p whole a.path) (role /= Temporary && not (lent a.value)) \v -> BAssignPart AssignPart {target = a.target, path = a.path, value = v} BCallStmt c -> do let callee = find (\x -> Direct x.decl == c.callee) p.subprograms formals = maybe [] (\x -> [IntMap.lookup (key v) x.variables | v <- x.parameters]) callee freeing = maybe False (\x -> x.imported && x.linkName == deallocationName) callee checks <- fmap concat . forM (zip c.arguments (map Just formals <> repeat Nothing)) $ \case -- an `out` actual is overwritten by the call (ByReference v, Just (Just formal)) | formal.role == Parameter ModeOut, isOwning formal.typ -> do leakCheck here "might still own an object, which the call would overwrite" . var v <$> typeOf v -- an object being freed must own nothing itself (ByReference v, _) | freeing -> do pointer <- var v <$> typeOf v pure case designatedOf pointer.typ >>= \dt -> ownsNothing BExpr {typ = dt, span = Nothing, node = BDeref pointer} of Just inside -> [check here "the object freed here might still own objects, which would leak" (orElse (isNull pointer) inside)] Nothing -> [] _ -> pure [] pure (checks <> [s]) BIf i -> do t <- scoped (stmts i.whenTrue) f <- scoped (stmts i.whenFalse) pure [BStmt {span = s.span, node = BIf If {condition = i.condition, whenTrue = t, whenFalse = f}}] BLoop l -> do body <- scoped (stmts l.body) pure [BStmt {span = s.span, node = BLoop Loop {loop = l.loop, parameter = l.parameter, body}}] BHandle h -> do body <- scoped (stmts h.body) handlers <- forM h.handlers \hd -> scoped (stmts hd.body) <&> \b -> Handler {exceptions = hd.exceptions, body = b} pure [BStmt {span = s.span, node = BHandle Handle {body, handlers}}] -- (a traversal function returns an observer or a borrower: nothing moves) BReturn (Just v) | maybe False isOwning sub.result, not (null (movedNames v)) -> do -- the value first, then its sources empty, then the dying objects own nothing (t, temp) <- temporary v dying <- dyingHere here pure ([t] <> concatMap nullify (movedNames v) <> dying <> [BStmt {span = s.span, node = BReturn (Just temp)}]) BReturn _ -> do dying <- dyingHere here pure (dying <> [s]) BScopeExit vs -> do owning <- concat <$> forM vs \v -> do x <- varInfo v pure case x of Just info | info.role == Local -> leakCheck (fromMaybe here info.span) ("`" <> info.name <> "` might still own an object when its scope ends") (var v info.typ) _ -> [] modify' \st -> st {live = IntSet.difference st.live (IntSet.fromList (map key vs))} pure (owning <> [s]) _ -> pure [s] where here = fromMaybe sub.span s.span -- an assignment: the value into a temporary when it moves names (they are emptied before -- the target changes), the leak check of the target's old value, then the assignment assignWith here value target checked build = do -- only an owner takes what it is given: an observer or a borrower leaves it where it is let moved = if isOwning target.typ then movedNames value else [] -- (a borrower given back to its owner is what the owner held: nothing leaks) givenBack = case value.typ of AccessOf a -> a.borrower _ -> False leak = if checked && isOwning target.typ && not givenBack then leakCheck here "might still own an object, which this assignment would overwrite" target else [] if null moved then pure (leak <> [BStmt {span = Just here, node = build value}]) else do (t, temp) <- temporary value pure ([t] <> concatMap nullify moved <> leak <> [BStmt {span = Just here, node = build temp}]) -- copying a temporary back (an actual lent to a call) gives back what was lent lent v = case v.node of BVar x -> IntMap.member (key x) temporaries _ -> False temporary v = do n <- gets (.next) let x = Var {varId = VarId n, name = "moved", typ = v.typ, low = Nothing, high = Nothing, role = Temporary, constant = False, span = Nothing, ghost = False, volatile = False, heapParts = False, atomic = False, alignment = Nothing} modify' \st -> st {vars = IntMap.insert n x st.vars, next = n + 1} pure (BStmt {span = v.span, node = BAssign Assign {target = VarId n, value = v}}, BExpr {typ = v.typ, span = v.span, node = BVar (VarId n)}) -- the first assignment of a local is its declaration; it is live from there declaration v = do role <- roleOf v seen <- gets (IntSet.member (key v) . (.declared)) if role == Local && not seen then True <$ modify' \st -> st {declared = IntSet.insert (key v) st.declared, live = IntSet.insert (key v) st.live} else pure False -- locals declared inside a branch or a loop body are gone after it (their scope exits -- are inside it) scoped run = do before <- gets (.live) r <- run modify' \st -> st {live = before} pure r dyingHere here = do vs <- gets (IntSet.toList . (.live)) concat <$> forM vs \k -> do x <- varInfo (VarId k) pure case x of Just info -> leakCheck here ("`" <> info.name <> "` might still own an object when `" <> sub.name <> "` returns") (var (VarId k) info.typ) Nothing -> [] varInfo v = gets \st -> IntMap.lookup (key v) st.vars <|> IntMap.lookup (key v) globalVars typeOf v = maybe (Scalar BooleanScalar) (.typ) <$> varInfo v roleOf v = maybe Global (.role) <$> varInfo v designatedOf = \case AccessOf a -> Map.lookup a.name p.designated _ -> Nothing -- | The access values in an object of an owning type become null. nullify :: BExpr -> [BStmt] nullify e = case e.typ of AccessOf a | not a.toConstant -> assignAt BExpr {typ = e.typ, span = Nothing, node = BNull} RecordOf r -> concat [nullify BExpr {typ = f.typ, span = Nothing, node = BField Field {record = e, field = k}} | (k, f) <- zip [0 ..] r.fields, isOwning f.typ] ArrayOf a | AccessOf _ <- a.component -> assignAt BExpr {typ = e.typ, span = Nothing, node = BArrayFill BExpr {typ = a.component, span = Nothing, node = BNull}} _ -> [] where assignAt value = case pathOf e of Just (v, []) -> [BStmt {span = e.span, node = BAssign Assign {target = v, value}}] Just (v, path) -> [BStmt {span = e.span, node = BAssignPart AssignPart {target = v, path, value}}] Nothing -> [] key :: VarId -> Int key (VarId n) = n var :: VarId -> BType -> BExpr var v t = BExpr {typ = t, span = Nothing, node = BVar v} componentOf :: BType -> BType componentOf = \case ArrayOf a -> a.component ArrayValue d -> d.component t -> t -- | The names an assigned value moves: the value itself when it names an owning part, and -- such names among the components of aggregates and allocators. movedNames :: BExpr -> [BExpr] movedNames e | isOwning e.typ, Just _ <- pathOf e = [e] | otherwise = case e.node of BRecordLit xs -> concatMap movedNames xs BArrayLit xs -> concatMap movedNames xs BAllocate x -> movedNames x BArrayWith w -> movedNames w.array <> movedNames w.value BCond c -> movedNames c.whenTrue <> movedNames c.whenFalse _ -> [] -- | A name as a variable and a component path. pathOf :: BExpr -> Maybe (VarId, [PathStep]) pathOf e = case e.node of BVar v -> Just (v, []) BField f -> (\(v, path) -> (v, path <> [StepField f.field])) <$> pathOf f.record BIndex ix -> (\(v, path) -> (v, path <> [StepIndex ix.index])) <$> pathOf ix.array BDeref x -> (\(v, path) -> (v, path <> [StepDeref])) <$> pathOf x _ -> Nothing -- | The part of a variable at the end of a path, as an expression. pathExpr :: BProgram -> BExpr -> [PathStep] -> BExpr pathExpr p = foldl step where step x = \case StepField k -> case x.typ of RecordOf r | f : _ <- drop k r.fields -> BExpr {typ = f.typ, span = Nothing, node = BField Field {record = x, field = k}} _ -> x StepIndex i -> BExpr {typ = componentOf x.typ, span = Nothing, node = BIndex Index {array = x, index = i}} StepDeref -> case x.typ of AccessOf a | Just dt <- Map.lookup a.name p.designated -> BExpr {typ = dt, span = Nothing, node = BDeref x} _ -> x StepAs r -> BExpr {typ = RecordOf r, span = Nothing, node = BConvert x} -- | That a value owns nothing: every access value in it (not through other access values) -- is null. Nothing when its type holds no access values (arrays with run-time bounds are not -- looked into). ownsNothing :: BExpr -> Maybe BExpr ownsNothing = ownsNothingAt 0 -- | 'ownsNothing' inside this many quantifiers over array components (each quantifier's -- variable is numbered by its depth, below the variables of any subprogram). ownsNothingAt :: Int -> BExpr -> Maybe BExpr ownsNothingAt depth e = case e.typ of -- (a general access value designates what is never freed: nothing to leak, G6) AccessOf a | not a.toConstant && not a.borrower && not a.general -> Just (isNull e) RecordOf r -> case mapMaybe (\(k, f) -> ownsNothingAt depth BExpr {typ = f.typ, span = Nothing, node = BField Field {record = e, field = k}}) (zip [0 ..] r.fields) of [] -> Nothing [x] -> Just x xs -> Just BExpr {typ = Scalar BooleanScalar, span = Nothing, node = BLogic Logic {logic = And, operands = xs}} -- every component of an array ArrayOf a -> let j = VarId (-1 - depth) index = BExpr {typ = Scalar a.index, span = Nothing, node = BVar j} lit n = BExpr {typ = Scalar a.index, span = Nothing, node = BLit n} in (\inner -> BExpr {typ = Scalar BooleanScalar, span = Nothing, node = BQuantified Quantified {universal = True, variable = j, low = lit a.first, high = lit a.last, body = inner, over = Nothing}}) <$> ownsNothingAt (depth + 1) BExpr {typ = a.component, span = Nothing, node = BIndex Index {array = e, index}} _ -> Nothing isNull :: BExpr -> BExpr isNull x = BExpr {typ = Scalar BooleanScalar, span = Nothing, node = BCompare Compare {cmp = Eq, left = x, right = BExpr {typ = x.typ, span = Nothing, node = BNull}}} orElse :: BExpr -> BExpr -> BExpr orElse a b = BExpr {typ = Scalar BooleanScalar, span = Nothing, node = BLogic Logic {logic = Or, operands = [a, b]}} leakCheck :: Span -> Text -> BExpr -> [BStmt] leakCheck at message x = maybe [] (\c -> [check at message c]) (ownsNothing x) check :: Span -> Text -> BExpr -> BStmt check at message condition = BStmt {span = Just at, node = BCheck Check {kind = LeakCheck, condition, span = at, message, reasons = []}}