Wolfgang Jeltsch pushed to branch wip/jeltsch/portable-bco-byte-array-serialization at Glasgow Haskell Compiler / GHC Commits: 6685e2ac by Wolfgang Jeltsch at 2026-11-30T18:11:16+02:00 Make the `BCOByteArray` serialization format platform-independent - - - - - 1 changed file: - libraries/ghci/GHCi/ResolvedBCO.hs Changes: ===================================== libraries/ghci/GHCi/ResolvedBCO.hs ===================================== @@ -4,7 +4,7 @@ {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MagicHash #-} {-# LANGUAGE RecordWildCards #-} -{-# LANGUAGE ScopedTypeVariables #-} +{-# LANGUAGE TypeAbstractions #-} module GHCi.ResolvedBCO ( ResolvedBCO(..) @@ -16,33 +16,39 @@ module GHCi.ResolvedBCO #include "MachDeps.h" +#if SIZEOF_HSWORD != 4 && SIZEOF_HSWORD != 8 +#error Bytecode serialization works only on 32- and 64-bit platforms. +#endif + +#if !defined(WORDS_BIGENDIAN) && SIZEOF_HSWORD == 8 +#define LITTLE_ENDIAN_64_BITS +#endif + import Prelude -- See note [Why do we import Prelude here?] -import GHC.Data.SmallArray + import GHCi.RemoteTypes import GHCi.BreakArray -#if SIZEOF_HSWORD == 4 -import Control.Monad -import Data.Array.Base (foldrArray, listArray) -import Data.ByteString.Builder.Extra -import Foreign.Storable -#endif +import GHC.Exts (Int (I#), ByteArray#, sizeofByteArray#) +import qualified GHC.Exts.Heap as Heap -import Data.Binary (Binary(..)) -import Data.Binary.Get +import Data.Word (Word16) +import Data.ByteString.Short (ShortByteString (SBS), toShort) +import Data.Array.Base +import Data.Binary.Builder (fromShortByteString) import Data.Binary.Put -import Data.ByteString.Short (ShortByteString(..)) -import Data.Word -import GHC.Generics - -import GHC.Exts -import Data.Array.Base (UArray(..)) -import qualified GHC.Exts.Heap as Heap +import Data.Binary.Get +import Data.Binary (Binary (put, get)) +import Foreign.Storable (Storable, sizeOf) +import GHC.Data.SmallArray (SmallArray) +import GHC.Generics (Generic) -#include "MachDeps.h" +#ifndef LITTLE_ENDIAN_64_BITS +import Control.Monad (replicateM) +#endif isLittleEndian :: Bool -#if defined(WORDS_BIGENDIAN) +#ifdef WORDS_BIGENDIAN isLittleEndian = False #else isLittleEndian = True @@ -96,27 +102,19 @@ data BCOByteArray a getBCOByteArray :: !ByteArray# } -#if SIZEOF_HSWORD == 4 -fromBCOByteArray :: forall a . Storable a => BCOByteArray a -> UArray Int a -fromBCOByteArray (BCOByteArray ba#) = UArray 0 (n - 1) n ba# +#ifndef LITTLE_ENDIAN_64_BITS + +fromBCOByteArray :: Storable a => BCOByteArray a -> UArray Int a +fromBCOByteArray @a (BCOByteArray ba#) = UArray 0 (n - 1) n ba# where len# = sizeofByteArray# ba# n = (I# len#) `div` sizeOf (undefined :: a) + #endif mkBCOByteArray :: UArray Int a -> BCOByteArray a mkBCOByteArray (UArray _ _ _ arr) = BCOByteArray arr --- | Directly serialize 'BCOByteArray' payload without iterating over --- individual elements, assuming 'BCOByteArray' element type is a --- fixed-width type like 'Word16' that doesn't depend on host word --- size. See Note [BCOByteArray serialization] for more explanation. -unsafePutFixedWidthBCOByteArray :: BCOByteArray a -> Put -unsafePutFixedWidthBCOByteArray (BCOByteArray ba#) = put $ SBS ba# - -unsafeGetFixedWidthBCOByteArray :: Get (BCOByteArray a) -unsafeGetFixedWidthBCOByteArray = (\(SBS ba#) -> BCOByteArray ba#) <$> get - instance Show (BCOByteArray Word16) where showsPrec _ _ = showString "BCOByteArray Word16" @@ -152,48 +150,109 @@ instance Binary ResolvedBCO where 1 -> ResolvedStaticCon <$> get <*> get <*> get <*> get <*> get <*> get _ -> error "Binary ResolvedBCO: invalid byte" --- See Note [BCOByteArray serialization] +#ifndef LITTLE_ENDIAN_64_BITS + +-- | Serialize a 'BCOByteArray', not writing the payload verbatim but +-- serializing the individual elements. This can be used with any host +-- platform and element type. +putBCOByteArrayPortably :: (Storable a, IArray UArray a) + => (a -> Put) + -- ^ The serializer to use for each element + -> (BCOByteArray a -> Put) + -- ^ The 'BCOByteArray' serializer +putBCOByteArrayPortably @a putElement bcoByteArray + = putWord64le (fromIntegral size) <> foldMap putElement (elems uArray) + where + + uArray :: UArray Int a + uArray = fromBCOByteArray bcoByteArray + + size :: Int + size = numElements array + +-- | Deserialize a 'BCOByteArray', not reading the payload verbatim but +-- deserializing the individual elements. This can be used with any host +-- platform and element type. +getBCOByteArrayPortably :: IArray UArray a + => Get a + -- ^ The deserializer to use for each element + -> Get (BCOByteArray a) + -- ^ The 'BCOByteArray' deserializer +getBCOByteArrayPortably getElement = do + size <- fromIntegral <$> getWord64le :: Get Int + elements <- replicateM size getElement + return (mkBCOByteArray (listArray (0, pred size) elements)) + +#endif + +#ifndef WORDS_BIGENDIAN + +-- | Serialize a 'BCOByteArray', writing the payload verbatim instead of +-- serializing the individual elements. This must only be used when the host +-- platform uses little endian and the bitsize of the element type of the +-- array is the one that is used for the serialized form of elements. +putBCOByteArrayDirectly :: Storable a => BCOByteArray a -> Put +putBCOByteArrayDirectly @a (BCOByteArray byteArray#) + = putWord64le (fromIntegral size) <> + putBuilder (fromShortByteString (SBS byteArray#)) + where + + size :: Int + size = I# (sizeofByteArray# byteArray#) `div` sizeOf (undefined :: a) + +-- | Deserialize a 'BCOByteArray', reading the payload verbatim instead of +-- deserializing the individual elements. This must only be used when the host +-- platform uses little endian and the bitsize of the element type of the +-- array is the one that is used for the serialized form of elements. +getBCOByteArrayDirectly :: Storable a => Get (BCOByteArray a) +getBCOByteArrayDirectly @a = do + size <- fromIntegral <$> getWord64le :: Get Int + SBS byteArray# <- toShort <$> getByteString (size * sizeOf (undefined :: a)) + -- Beware that there is no overflow check for the byte count computation. + return (BCOByteArray byteArray#) + +#endif + +-- See Note [BCOByteArray serialization]. instance Binary (BCOByteArray Word16) where - put = unsafePutFixedWidthBCOByteArray - get = unsafeGetFixedWidthBCOByteArray --- Word size depends on host, which is tricky when host/target word --- sizes differ. We always serialize `BCOByteArray Word` as --- `BCOByteArray Word64`. -instance Binary (BCOByteArray Word) where -#if SIZEOF_HSWORD == 8 - -- 64-bit fast path. `BCOByteArray` is directly serialized via the - -- `Binary ShortByteString` instance, which serializes the `Int` - -- bytelength first (via `Int64` transparently), then copies the - -- buffer. - put = unsafePutFixedWidthBCOByteArray - - get = unsafeGetFixedWidthBCOByteArray +#ifdef WORDS_BIGENDIAN + put = putBCOByteArrayPortably putWord16le + get = getBCOByteArrayPortably getWord16le #else - -- 32-bit slow path. Pretend it's a `BCOByteArray Word64` and handle - -- the bytelength & buffer elements directly. - -- - -- Regarding endianness: the bytelength is serialized via the - -- `Binary Int` instance, which is serialized as `Int64` via - -- big-endian. The payload follows host-endianness. This doesn't - -- work when host/target has different endianness, but we don't - -- support that setup yet anyway. - put ba32@(BCOByteArray ba32#) = - put len64 *> - putBuilder - (foldrArray (\w32 acc -> word64Host (fromIntegral w32) <> acc) mempty arr32) - where - len32# = sizeofByteArray# ba32# - len64 = I# len32# * 2 - arr32 = fromBCOByteArray ba32 + put = putBCOByteArrayDirectly + get = getBCOByteArrayDirectly +#endif - get = do - len64 <- get - let len = len64 `div` 8 - w32s <- replicateM len (fromIntegral <$> getWord64host) - pure $ mkBCOByteArray $ listArray (0, len - 1) w32s +-- See Note [BCOByteArray serialization]. +instance Binary (BCOByteArray Word) where + +#ifdef LITTLE_ENDIAN_64_BITS + put = putBCOByteArrayDirectly + get = getBCOByteArrayDirectly +#else + put = putBCOByteArrayPortably (putWord64le . fromIntegral) + get = getBCOByteArrayPortably (fromIntegral <$> getWord64le) #endif +-- Note [BCOByteArray serialization] +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +-- +-- In its serialized form, a 'BCOByteArray' value is represented by the number +-- of its elements followed by the individual elements. The serialization format +-- is platform-independent, thanks to the following specifics: +-- +-- * All natural numbers are encoded using little endian, independently of the +-- host’s endianness. +-- * Array sizes are encoded using 64 bits, independently of the host’s native +-- bit size. +-- * 'Word' values are encoded using 64 bits, independently of the host’s +-- native bit size. +-- +-- Whenever the encoding of the payload matches its representation in main +-- memory, the whole payload is transferred verbatim. Otherwise, the elements +-- are serialized or deserialized individually. + data ResolvedBCOPtr = ResolvedBCORef {-# UNPACK #-} !Int -- ^ reference to the Nth BCO in the current set of BCOs and @@ -215,35 +274,3 @@ data ResolvedBCOPtr deriving (Generic, Show) instance Binary ResolvedBCOPtr - --- Note [BCOByteArray serialization] --- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ --- --- !12142 changed some BCO blob types from UArray to --- BCOByteArray(ByteArray#) to save a little space. Unfortunately, a --- nasty serialization bug has surfaced since then. It happens when we --- need to pass BCOByteArray between host/target with mismatching word --- sizes. When 32-bit iserv receives a `BCOByteArray Word` from 64-bit --- host GHC, it would parse the buffer assuming each Word=Word32, even --- if host GHC assumes each Word=Word64, and of course it's horribly --- wrong! --- --- The root issue here is the usage of platform sized integer types in --- BCO (and any messages we pass between ghc/iserv really), we should --- do what we already do for RemotePtr: always use Word64 instead of --- Word. --- --- When we serialize `BCOByteArray Word16`, element is fixed width on --- 32/64-bit host, so we can directly serialize the buffer per se. For --- `BCOByteArray Word`, we must always serialize it as `BCOByteArray --- Word64`, and hence it has fast-path/slow-path decided at --- compile-time, see comments of `instance Binary (BCOByteArray Word)` --- for explanation. These are the only two `Binary` instances we ever --- use, so to avoid unnecessary complexity, we're fine with flexible --- instances here, instead of generalizing to any element type that --- may be fixed-width or not. --- --- Since we erase the metadata in UArray, we need to find a way to --- calculate the item count by dividing the ByteArray# length with --- element size. The element size comes from Storable's sizeOf method, --- thus the addition of Storable constraint. View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/6685e2ac570a50028f98fc2a7762b031... -- View it on GitLab: https://gitlab.haskell.org/ghc/ghc/-/commit/6685e2ac570a50028f98fc2a7762b031... You're receiving this email because of your account on gitlab.haskell.org. Manage all notifications: https://gitlab.haskell.org/-/profile/notifications | Help: https://gitlab.haskell.org/help
participants (1)
-
Wolfgang Jeltsch (@jeltsch)