on master help sign in
Enable array bound check during deserialize
commit73533c028cb6547ec8427878f2590d1c6e773c7f authorHarendra Kumar <harendra@composewell.com> dateSat 19 Aug 2023, 15:49 (3 years ago) parent209e990
1 file changed+6−5
core/src/Streamly/Internal/Data/Serialize.hs+6−5
core/src/Streamly/Internal/Data/Serialize.hs+6−5
@@ -22,7 +22,6 @@ module Streamly.Internal.Data.Serialize
2222
2323#ifdef DEBUG
2424import Control.Exception (assert)
25−import Streamly.Internal.Data.Unbox (Unbox(..), sizeOfMutableByteArray)
2625#endif
2726
2827import Control.Monad (void)
@@ -32,6 +31,7 @@ import Streamly.Internal.Data.Unbox
3231 ( MutableByteArray(..)
3332 , PinnedState(..)
3433 , Unbox
34+ , sizeOfMutableByteArray
3535 )
3636import Streamly.Internal.Data.Array.Type (Array(..))
3737import Streamly.Internal.System.IO (unsafeInlineIO)
@@ -114,10 +114,12 @@ class Serialize a where
114114-- Instances
115115--------------------------------------------------------------------------------
116116
117+-- XXX We do not need to pass the end of data offset, we can just check the
118+-- mutable array end here to avoid a crash, and when we return from deserialize
119+-- we can check if the offset returned is beyond the bound or not.
117120{-# INLINE checkBounds #-}
118121checkBounds :: String -> Int -> MutableByteArray -> IO ()
119122checkBounds _label _off _arr = do
120−#ifdef DEBUG
121123 sz <- sizeOfMutableByteArray _arr
122124 if (_off > sz)
123125 then error
@@ -126,9 +128,6 @@ checkBounds _label _off _arr = do
126128 ++ show (_off - 1)
127129 ++ " max valid offset = " ++ show (sz - 1)
128130 else return ()
129−#else
130− return ()
131−#endif
132131
133132{-# INLINE deserializeUnsafe #-}
134133deserializeUnsafe :: forall a. Unbox a => Int -> MutableByteArray -> IO (Int, a)
@@ -143,7 +142,9 @@ serializeUnsafe :: forall a. Unbox a => Int -> MutableByteArray -> a -> IO Int
143142serializeUnsafe off arr val =
144143 let next = off + Unbox.sizeOf (Proxy :: Proxy a)
145144 in do
145+#ifdef DEBUG
146146 checkBounds "serialize" next arr
147+#endif
147148 Unbox.pokeByteIndex off arr val
148149 pure next
149150