-- | Proof for language L8 (Jorvik, plan T28, ledger D96), over the BIR the tasking front end -- makes (D95): tasks are the procedures @Verada_Task_T@ and the main subprogram is one more; -- protected actions are the @Verada_Action@ subprograms nested in protected objects' packages. -- -- Data-race freedom (B3019): a variable that two tasks may touch, one of them writing it, is -- a protected object's component, or the predefined library's synchronised state; flow -- analysis's inferred effects (through every call) say what each task touches. -- -- No potentially blocking operation in a protected action (B3020): a protected action never -- reaches, through its calls, a delay or an entry (whose wait is the run-time's `Wait`). module Verada.Flow.Tasking ( taskingDiagnostics ) where import Verada.BIR.Expr import Verada.BIR.Stmt import Verada.BIR.Traverse (statementExpressions, universeExpressions, universeStatements) import Verada.BIR.Types import Verada.Diagnostics (Diagnostic (..), Label (..), Note (..), Phase (..), diagnostic, label) import Verada.Diagnostics.Codes (DiagCode (..)) import Verada.Flow.Globals (Effects (..), Evidence (..), attachedHandlers, noEffects) import Verada.TAST.Ids (DeclId) import Data.IntMap.Strict qualified as IntMap import Data.IntSet qualified as IntSet import Data.List (find, nub) import Data.Map.Strict (Map) import Data.Map.Strict qualified as Map import Data.Maybe (isJust, mapMaybe, maybeToList) import Data.Set qualified as Set import Data.Text (Text) import Data.Text qualified as Text taskingDiagnostics :: BProgram -> Map DeclId Effects -> [Diagnostic] taskingDiagnostics p effects = races p effects <> blocking p <> ceilingDiagnostics p effects <> volatileFunctions p effects <> suspensionWaiters p <> queueLengths p -- | The last part of a full name. simple :: Text -> Text simple = last . (\xs -> if null xs then [""] else xs) . Text.splitOn "." -- | The task a task procedure runs: its package (a task's, or the instance of a task type). taskOf :: Text -> Text taskOf n = case reverse (Text.splitOn "." n) of _ : owner : _ -> owner _ -> n -- * Data races races :: BProgram -> Map DeclId Effects -> [Diagnostic] races p effects | length actors < 2 = [] | otherwise = mapMaybe race (IntMap.toList shared) where tasks = [s | s <- p.subprograms, "Verada_Task_" `Text.isPrefixOf` simple s.name, not ("'Access" `Text.isSuffixOf` s.name)] environment = [s | Just d <- [p.main], s <- p.subprograms, s.decl == d] -- (an interrupt handler runs at the same time as the tasks, on a thread of its own, G8) handlers = [s | d <- attachedHandlers p, s <- p.subprograms, s.decl == d] actors = tasks <> environment <> handlers protected = Set.fromList [key v | v <- p.protectedState] globals = IntMap.fromList [(key g.var.varId, g) | g <- p.globals, not g.var.constant, not g.var.ghost] -- (Ada.Text_IO's files are shared state too, as in SPARK: the run-time writes a line at a -- time, but what two tasks print interleaves as they run) -- (nor an atomic object, a synchronized one tasks may share, each read and write of it -- indivisible, SPARK RM 9(9), D199) candidates = IntMap.filterWithKey (\k g -> not (Set.member k protected) && not g.var.atomic) globals touches a = let e = Map.findWithDefault emptyEffects a.decl effects in (IntSet.union e.entryReads e.writes, e) shared = IntMap.mapWithKey (\k _ -> [(a, e) | a <- actors, let (t, e) = touches a, IntSet.member k t]) candidates race (k, users) = case users of (a, ea) : (b, eb) : _ | IntSet.member k ea.writes || IntSet.member k eb.writes -> let g = IntMap.lookup k globals name = maybe "?" (.var.name) g at e = maybe Nothing (.span) (IntMap.lookup k e.writtenAt `orElse` IntMap.lookup k e.readAt) in Just (diagnostic DataRace Flow ("`" <> name <> "` is shared by " <> actorName a <> " and " <> actorName b <> " outside a protected object")) { primary = (\s -> label s ("used by " <> actorName a)) <$> at ea , secondary = [Label {span = s, text = Just ("used by " <> actorName b)} | Just s <- [at eb]] <> [Label {span = s, text = Just "declared here"} | Just s <- [g >>= (.var.span)]] , notes = [Note {text = "tasks run at the same time: a variable more than one of them uses, one writing it, belongs in a protected object, whose actions hold its lock", span = Nothing}] , advice = Just ("make `" <> name <> "` a component of a protected object, and use it through that object\x27s operations") } _ -> Nothing actorName a | "Verada_Task_" `Text.isPrefixOf` simple a.name = "task `" <> taskOf a.name <> "`" | a.decl `elem` map (.decl) handlers = "the interrupt handler `" <> a.name <> "`" | otherwise = "the main subprogram" orElse x y = maybe y Just x emptyEffects = noEffects key (VarId n) = n -- * Suspension objects -- | At most one task waits on a suspension object (RM D.10(10), Ravenscar and Jorvik: a second -- would raise Program_Error; G8): for each library-level suspension object, the tasks (and the -- main subprogram) that may call Suspend_Until_True on it, directly or through subprograms -- given it as a parameter. suspensionWaiters :: BProgram -> [Diagnostic] suspensionWaiters p = mapMaybe report (Map.toList waiters) where byDecl = Map.fromList [(s.decl, s) | s <- p.subprograms] tasks = [s | s <- p.subprograms, "Verada_Task_" `Text.isPrefixOf` simple s.name, not ("'Access" `Text.isSuffixOf` s.name)] actors = tasks <> [s | Just d <- [p.main], s <- p.subprograms, s.decl == d] globals = Set.fromList [g.var.varId | g <- p.globals] -- (which parameters, by position, each subprogram may suspend on: a fixpoint from -- Suspend_Until_True's own) base = Map.fromList [(s.decl, Set.singleton (0 :: Int)) | s <- p.subprograms, s.name == "Ada.Synchronous_Task_Control.Suspend_Until_True"] step known = Map.unionWith Set.union known (Map.fromList [(s.decl, own) | s <- p.subprograms, s.name /= "Ada.Synchronous_Task_Control.Suspend_Until_True", let own = suspendedParams known s, not (Set.null own)]) suspendedParams known s = Set.fromList [j | (callee, args) <- callStatements s, Just ps <- [Map.lookup callee known], i <- Set.toList ps, ByReference v : _ <- [drop i args], Just j <- [lookup v (zip s.parameters [0 ..])]] fixpoint known = let next = step known in if next == known then known else fixpoint next suspending = fixpoint base callStatements s = [(d, c.arguments) | Just body <- [s.body], st <- universeStatements body, BCallStmt c <- [st.node], Direct d <- [c.callee]] reachable s = go Set.empty [s.decl] where go seen = \case [] -> seen d : ds | Set.member d seen -> go seen ds d : ds -> go (Set.insert d seen) (maybe [] (\x -> maybe [] calls x.body) (Map.lookup d byDecl) <> ds) waiters = Map.fromListWith (<>) [(v, [(a, sp)]) | a <- actors, d <- Set.toList (reachable a), Just s <- [Map.lookup d byDecl], Just body <- [s.body], st <- universeStatements body, BCallStmt c <- [st.node], Direct callee <- [c.callee], Just ps <- [Map.lookup callee suspending], i <- Set.toList ps, ByReference v : _ <- [drop i c.arguments], Set.member v globals, let sp = st.span] report (v, users) = case nub [a.decl | (a, _) <- users] of _ : _ : _ -> let name = maybe "?" (.var.name) (find (\g -> g.var.varId == v) p.globals) spans = [(a, sp) | (a, Just sp) <- users] in Just (diagnostic SuspensionWaiters Flow ("more than one task may wait on the suspension object `" <> name <> "`")) { primary = (\(a, sp) -> label sp ("waited on by " <> actorName a)) <$> listToMaybe' spans , secondary = [Label {span = sp, text = Just ("waited on by " <> actorName a)} | (a, sp) <- drop 1 spans] , notes = [Note {text = "a suspension object has one waiting task at most (RM D.10(10)): a second Suspend_Until_True on it raises Program_Error", span = Nothing}] , advice = Just "give each waiting task a suspension object of its own" } _ -> Nothing actorName a = if "Verada_Task_" `Text.isPrefixOf` simple a.name then "task `" <> taskOf a.name <> "`" else "the main subprogram" listToMaybe' = \case x : _ -> Just x [] -> Nothing -- * Entry queues -- | An entry with `Max_Queue_Length => N` has at most N callers waiting (RM D.4(19), a call -- beyond them raises Program_Error): the tasks (and the main subprogram) that may call it, -- through any subprogram, are at most N (B3030). queueLengths :: BProgram -> [Diagnostic] queueLengths p = mapMaybe check p.queueLengths where byDecl = Map.fromList [(s.decl, s) | s <- p.subprograms] tasks = [s | s <- p.subprograms, "Verada_Task_" `Text.isPrefixOf` simple s.name, not ("'Access" `Text.isSuffixOf` s.name)] actors = tasks <> [s | Just d <- [p.main], s <- p.subprograms, s.decl == d] callsIn s = [(d, st.span) | Just body <- [s.body], st <- universeStatements body, BCallStmt c <- [st.node], Direct d <- [c.callee]] reachable s = go Set.empty [s.decl] where go seen = \case [] -> seen d : ds | Set.member d seen -> go seen ds d : ds -> go (Set.insert d seen) (maybe [] (map fst . callsIn) (Map.lookup d byDecl) <> ds) check (entry, bound) = let callers = [(a, sp) | a <- actors, d <- Set.toList (reachable a), Just s <- [Map.lookup d byDecl], (callee, sp) <- callsIn s, callee == entry] distinct = nub [a.decl | (a, _) <- callers] name = maybe "?" (\s -> simple s.name) (Map.lookup entry byDecl) spans = [(a, sp) | (a, Just sp) <- callers] in if toInteger (length distinct) <= bound then Nothing else Just (diagnostic QueueLengthExceeded Flow ("entry `" <> name <> "` may be called by " <> Text.pack (show (length distinct)) <> " tasks, and its `Max_Queue_Length` is " <> Text.pack (show bound))) { primary = (\(a, sp) -> label sp ("called by " <> actorName a)) <$> listToMaybe' spans , secondary = [Label {span = sp, text = Just ("called by " <> actorName a)} | (a, sp) <- drop 1 spans] , notes = [Note {text = "a call that finds the entry's queue full raises Program_Error (RM D.4(19)): every task that may call the entry may be waiting at once", span = Nothing}] , advice = Just ("raise `Max_Queue_Length` to " <> Text.pack (show (length distinct)) <> ", or give the callers entries of their own") } actorName a = if "Verada_Task_" `Text.isPrefixOf` simple a.name then "task `" <> taskOf a.name <> "`" else "the main subprogram" listToMaybe' = \case x : _ -> Just x [] -> Nothing -- * Potentially blocking operations blocking :: BProgram -> [Diagnostic] blocking p = concatMap check actions where actions = [s | s <- p.subprograms, simple s.name == "Verada_Action"] byDecl = Map.fromList [(s.decl, s) | s <- p.subprograms] blockers = ["Verada.Tasking.Delay_Until", "Verada.Tasking.Delay_For", "Verada.Tasking.Wait", "Ada.Synchronous_Task_Control.Suspend_Until_True"] -- the subprograms each one calls callsOf s = nub (maybe [] calls s.body) reaches seen d | Set.member d seen = Nothing | otherwise = case Map.lookup d byDecl of Just s | s.name `elem` blockers -> Just [s.name] | otherwise -> (s.name :) <$> listToMaybe' (mapMaybe (reaches (Set.insert d seen)) (callsOf s)) Nothing -> Nothing listToMaybe' = \case x : _ -> Just x [] -> Nothing check s = do (callee, path) <- maybeToList (find (\(_, r) -> True `seq` not (null r)) [(c, r) | c <- callsOf s, Just r <- [reaches (Set.singleton s.decl) c]]) let what = case last path of "Ada.Synchronous_Task_Control.Suspend_Until_True" -> "`Suspend_Until_True`, which may wait" "Verada.Tasking.Wait" -> "an entry call, which may wait" _ -> "a `delay`" through = maybe "" (\c -> c.name) (Map.lookup callee byDecl) pure (diagnostic PotentiallyBlocking Flow ("a protected action reaches " <> what)) { primary = (\sp -> label sp "this protected action") <$> Just s.span , notes = [Note {text = (if length path <= 1 then "directly" else "through " <> Text.intercalate ", then " (map userName (through : drop 1 (init path)))) <> " (RM 9.5.1(18)): a protected action holds its object's lock, so it must never wait", span = Nothing}] , advice = Just "move the delay or the entry call out of the protected object, into the task that calls it" } userName n = case Text.splitOn ".Verada_Action" n of prefix : _ | ".Verada_Action" `Text.isInfixOf` n -> prefix _ -> n -- | The subprograms a body calls (directly): procedure calls, and function calls in its -- expressions. calls :: [BStmt] -> [DeclId] calls body = [d | BStmt {node = BCallStmt CallStmt {callee = Direct d}} <- universeStatements body] <> [c.callee | s <- universeStatements body, e <- statementExpressions s, BExpr {node = BCall c} <- universeExpressions e] -- * Ceilings -- | A protected action runs at its object's ceiling priority (Jorvik's Ceiling_Locking, RM -- D.3): a task (at its priority, the main subprogram at the default) that uses a protected -- object whose ceiling is lower, or a protected action that uses another object with a lower -- ceiling, breaks it (B3021). ceilingDiagnostics :: BProgram -> Map DeclId Effects -> [Diagnostic] ceilingDiagnostics p effects = concatMap fromTask actors <> concatMap fromAction actions where actors = [(s, priorityOf s) | s <- p.subprograms, "Verada_Task_" `Text.isPrefixOf` simple s.name, not ("'Access" `Text.isSuffixOf` s.name)] <> [(s, 48) | Just d <- [p.main], s <- p.subprograms, s.decl == d] priorityOf s = maybe 48 id (lookup (taskOf s.name) p.priorities) actions = [s | s <- p.subprograms, simple s.name == "Verada_Action"] uses s = let e = Map.findWithDefault noEffects s.decl effects in IntSet.union e.entryReads e.writes usedObjects s = [(o, c) | (o, c, vs) <- p.ceilings, any (\v -> IntSet.member (key v) (uses s)) vs] fromTask (s, prio) = [ (diagnostic CeilingViolation Flow ("the ceiling of `" <> o <> "` (" <> tshow c <> ") is below the priority of " <> actor s <> " (" <> tshow prio <> "), which uses it")) { primary = (\sp -> label sp "uses it") <$> Just s.span , notes = [Note {text = "a protected action runs at its object\x27s ceiling: a caller of a higher priority breaks Ceiling_Locking (RM D.3), which Program_Error would report at run time", span = Nothing}] , advice = Just ("give `" <> o <> "` a ceiling of at least " <> tshow prio <> " (`with Priority => " <> tshow prio <> "`), or the caller a lower priority") } | (o, c) <- usedObjects s , prio > c ] fromAction s = [ (diagnostic CeilingViolation Flow ("the ceiling of `" <> o <> "` (" <> tshow c <> ") is below that of `" <> own <> "` (" <> tshow ownCeiling <> "), whose action uses it")) { primary = (\sp -> label sp "this protected action") <$> Just s.span , advice = Just ("give `" <> o <> "` a ceiling of at least " <> tshow ownCeiling) } | (own, ownCeiling, _) <- take 1 [x | x@(n, _, _) <- p.ceilings, ("." <> n <> ".") `Text.isInfixOf` s.name] , (o, c) <- usedObjects s , o /= own , ownCeiling > c ] actor s = if "Verada_Task_" `Text.isPrefixOf` simple s.name then "task `" <> taskOf s.name <> "`" else "the main subprogram" tshow = Text.pack . show key (VarId n) = n -- * Volatile inputs of functions -- | A function is a function of its inputs (SPARK RM 7.1.3(8)): it may not read, through any -- call, an object something else may write (`Async_Writers`) or whose reads are effects -- (`Effective_Reads`), for two calls with the same arguments would not give the same value -- (B3022). volatileFunctions :: BProgram -> Map DeclId Effects -> [Diagnostic] volatileFunctions p effects = [ (diagnostic VolatileFunctionInput Flow ("function `" <> simple s.name <> "` reads `" <> name <> "`, which may change between two reads")) { primary = (\sp -> label sp "this function") <$> Just s.span , secondary = [Label {span = sp, text = Just "declared here"} | Just sp <- [g >>= (.var.span)]] , notes = [Note {text = "`" <> name <> "` has `Async_Writers` or `Effective_Reads` (or is `Volatile`): a function reading it would not be a function of its inputs", span = Nothing}] , advice = Just "read it in a procedure, and pass the value to the function" } | s <- p.subprograms , isJust s.result , not s.ghost , s.decl `notElem` p.volatileFunctions , let e = Map.findWithDefault noEffects s.decl effects , v <- p.volatileInputs , IntSet.member (key v) (IntSet.union e.entryReads e.writes) , let g = find (\x -> x.var.varId == v) p.globals name = maybe "?" (.var.name) g ] where key (VarId n) = n