qute

A software analysis framework built around the QBE intermediate language

git clone https://git.8pit.net/qute.git

  1-- SPDX-FileCopyrightText: 2025-2026 Sören Tempel <soeren+git@soeren-tempel.net>
  2--
  3-- SPDX-License-Identifier: GPL-3.0-only
  4
  5module Language.QBE.Simulator.Concolic.State
  6  ( Env (..),
  7    SimFunc,
  8    mkEnv,
  9    run,
 10    runPath,
 11    makeConcolic,
 12    ErrorState (..),
 13    ErrorPath (..),
 14    SimState (..),
 15  )
 16where
 17
 18import Control.Applicative ((<|>))
 19import Control.Exception (Exception, throwIO, try)
 20import Control.Monad.Error.Class (MonadError, catchError, throwError)
 21import Control.Monad.IO.Class (MonadIO, liftIO)
 22import Control.Monad.State.Strict
 23  ( MonadState,
 24    StateT (StateT),
 25    evalStateT,
 26    get,
 27    gets,
 28    modify,
 29    runStateT,
 30  )
 31import Data.Map (Map)
 32import Data.Map qualified as Map
 33import Data.Word (Word8)
 34import Language.QBE (Program)
 35import Language.QBE.Backend.Store qualified as ST
 36import Language.QBE.Backend.Tracer qualified as T
 37import Language.QBE.Simulator.ABI.C (readString)
 38import Language.QBE.Simulator.Concolic.Expression qualified as CE
 39import Language.QBE.Simulator.Default.Expression qualified as DE
 40import Language.QBE.Simulator.Default.Funcs (simFuncs)
 41import Language.QBE.Simulator.Default.State qualified as DS
 42import Language.QBE.Simulator.Error (EvalError (FuncArgsMismatch, TerminatePath, TypingError))
 43import Language.QBE.Simulator.Expression qualified as E
 44import Language.QBE.Simulator.Memory qualified as MEM
 45import Language.QBE.Simulator.State
 46import Language.QBE.Simulator.Symbolic.Expression qualified as SE
 47import Language.QBE.Types qualified as QBE
 48import System.Random (initStdGen, mkStdGen)
 49
 50-- | Type alias for representing /simulated functions/ that are intercepted during execution.
 51type SimFunc = [CE.Concolic DE.RegVal] -> SimState (Maybe (CE.Concolic DE.RegVal))
 52
 53data Env
 54  = Env
 55  { envBase :: DS.Env (CE.Concolic DE.RegVal) (CE.Concolic Word8),
 56    envTracer :: T.ExecTrace,
 57    envStore :: ST.Store,
 58    envSFuncs :: Map QBE.GlobalIdent SimFunc
 59  }
 60
 61mkEnv ::
 62  Program ->
 63  MEM.Address ->
 64  MEM.Size ->
 65  Bool ->
 66  Maybe Int ->
 67  IO Env
 68mkEnv prog memStart memSize initMem maySeed = do
 69  initEnv <- DS.mkEnv prog memStart memSize initMem
 70  randGen <-
 71    case maySeed of
 72      Just sd -> pure $ mkStdGen sd
 73      Nothing -> initStdGen
 74  pure $ Env initEnv T.newExecTrace (ST.empty randGen) defFuncs
 75  where
 76    defFuncs :: Map QBE.GlobalIdent SimFunc
 77    defFuncs =
 78      let mkFunc ident func = (ident, func ident)
 79       in Map.fromList
 80            [ mkFunc (QBE.GlobalIdent "qute_exit") exit,
 81              mkFunc (QBE.GlobalIdent "qute_make_symbolic") makeSymbolicArray
 82            ]
 83
 84liftState ::
 85  (DS.SimState (CE.Concolic DE.RegVal) (CE.Concolic Word8)) a ->
 86  SimState a
 87liftState (DS.SimState toLift) = do
 88  defEnv <- gets envBase
 89
 90  -- XXX: Since 'toLift' is run in the DS.SimState monad, it would
 91  -- use its 'throwError' implementation here. We want to use the
 92  -- implementation of our t'SimState' though, hence we need to handle
 93  -- IO exceptions here.
 94  result <- liftIO $ try (runStateT toLift defEnv)
 95  case result of
 96    Left (e :: EvalError) -> throwError e
 97    Right (a, s) -> do
 98      modify (\ps -> ps {envBase = s})
 99      pure a
100
101makeConcolic :: String -> QBE.ExtType -> SimState (CE.Concolic DE.RegVal)
102makeConcolic name ty = do
103  st <- gets envStore
104  let (ns, cv) = ST.getConcolic st name ty
105  modify (\e -> e {envStore = ns})
106  pure cv
107
108modifyTracer :: (MonadState Env m) => (T.ExecTrace -> T.ExecTrace) -> m ()
109modifyTracer f =
110  modify (\s@Env {envTracer = t} -> s {envTracer = f t})
111
112------------------------------------------------------------------------
113
114makeSymbolicArray ::
115  QBE.GlobalIdent ->
116  [CE.Concolic DE.RegVal] ->
117  SimState (Maybe (CE.Concolic DE.RegVal))
118makeSymbolicArray _ [arrayPtr, numElem, elemSize, namePtr] = do
119  name <- E.toString <$> (toAddress namePtr >>= readString)
120  vlty <- case E.toWord64 elemSize of
121    1 -> pure QBE.Byte
122    2 -> pure QBE.HalfWord
123    4 -> pure (QBE.Base QBE.Word)
124    8 -> pure (QBE.Base QBE.Long)
125    _ -> throwError TypingError
126
127  values <-
128    mapM
129      (\n -> makeConcolic (name ++ "_e" ++ show n) vlty)
130      [1 .. E.toWord64 numElem]
131
132  arrayAddr <- toAddress arrayPtr
133  liftState (DS.SimState $ DS.storeValues arrayAddr values) >> pure Nothing
134makeSymbolicArray ident _ = throwError $ FuncArgsMismatch ident
135
136exit ::
137  QBE.GlobalIdent ->
138  [CE.Concolic DE.RegVal] ->
139  SimState (Maybe (CE.Concolic DE.RegVal))
140exit _ [_code] = throwError TerminatePath
141exit ident _ = throwError $ FuncArgsMismatch ident
142
143findSimFunc :: QBE.GlobalIdent -> SimState (Maybe SimFunc)
144findSimFunc ident = do
145  funcs <- gets envSFuncs
146  pure (Map.lookup ident funcs <|> Map.lookup ident simFuncs)
147
148------------------------------------------------------------------------
149
150-- | State of the concolic executor with which an error was triggered
151-- in the application code, which can be reproduced using this state.
152data ErrorState
153  = ErrorState
154  { errTracer :: T.ExecTrace,
155    errStore :: ST.Store
156  }
157
158-- | Exception thrown upon encountered an t'ErrorState'.
159data ErrorPath
160  = ErrorPath
161  { pathInput :: ErrorState,
162    pathError :: EvalError
163  }
164
165instance Exception ErrorPath
166
167instance Show ErrorPath where
168  show (ErrorPath _ err) = show err
169
170------------------------------------------------------------------------
171
172newtype SimState a = SimState {unSimState :: StateT Env IO a}
173  deriving (Functor, Applicative, Monad, MonadIO)
174
175deriving instance MonadState Env SimState
176
177-- Implements 'MonadError' in t'SimState' via 'IOException's. On throw,
178-- it also returns the relevant executor state by encapsulting it in
179-- an 'ErrorPath'.
180--
181-- See also: The instance for 'DS.SimState'.
182instance MonadError EvalError SimState where
183  throwError err = do
184    Env {envTracer = t, envStore = s} <- get
185    liftIO $ throwIO (ErrorPath (ErrorState t s) err)
186
187  catchError (SimState st) handler =
188    SimState $ DS.unliftCatch st (unSimState . handler)
189
190------------------------------------------------------------------------
191
192instance Simulator SimState (CE.Concolic DE.RegVal) where
193  isTrue value = do
194    let condResult = E.toWord64 (CE.concrete value) /= 0
195    case CE.symbolic value of
196      Nothing -> pure condResult
197      Just sexpr -> do
198        -- Track the taken branch in the tracer.
199        let branch = T.newBranch sexpr
200        modifyTracer (\t -> T.appendBranch t condResult branch)
201
202        pure condResult
203
204  -- Implements address concretization as a memory model.
205  toAddress CE.Concolic {CE.concrete = cv, CE.symbolic = svMaybe} =
206    case svMaybe of
207      Just sv ->
208        case sv `E.eq` SE.fromReg cv of
209          Just c -> do
210            modifyTracer (`T.appendCons` c)
211            pure $ E.toWord64 cv
212          Nothing -> throwError TypingError
213      Nothing -> pure $ E.toWord64 cv
214
215  registerFunc name func =
216    modify (\e@(Env {envSFuncs = f}) -> e {envSFuncs = Map.insert name func f})
217  findFunc ident = do
218    funcs <- gets (DS.envFuncs . envBase)
219    case Map.lookup ident funcs of
220      Just x -> pure (Just $ SFuncDef x)
221      Nothing -> do
222        f <- findSimFunc ident
223        pure (SSimFunc <$> f)
224  findFuncByAddr addr = do
225    fptrs <- gets (DS.envFuncAddrs . envBase)
226    case Map.lookup addr fptrs of
227      Just fn -> findFunc fn
228      Nothing -> pure Nothing
229
230  lookupSymbol = liftState . lookupSymbol
231  activeFrame = liftState activeFrame
232  pushStackFrame = liftState . pushStackFrame
233  popStackFrame = liftState popStackFrame
234  getSP = liftState getSP
235  setSP = liftState . setSP
236
237  writeMemory a t v = liftState (writeMemory a t v)
238  readMemory t a = liftState (readMemory t a)
239
240------------------------------------------------------------------------
241
242runPath :: SimState a -> SimState (T.ExecTrace, ST.Store)
243runPath state = do
244  _ <- state
245  t <- gets envTracer
246  s <- gets envStore
247  pure (t, s)
248
249run :: Env -> SimState a -> IO (T.ExecTrace, ST.Store)
250run env state = evalStateT (unSimState $ runPath state) env