Wolfgang Jeltsch pushed to branch wip/jeltsch/portable-bco-byte-array-serialization at Glasgow Haskell Compiler / GHC

Commits:

1 changed file:

Changes:

  • libraries/ghci/GHCi/ResolvedBCO.hs
    ... ... @@ -4,7 +4,7 @@
    4 4
     {-# LANGUAGE FlexibleInstances #-}
    
    5 5
     {-# LANGUAGE MagicHash #-}
    
    6 6
     {-# LANGUAGE RecordWildCards #-}
    
    7
    -{-# LANGUAGE ScopedTypeVariables #-}
    
    7
    +{-# LANGUAGE TypeAbstractions #-}
    
    8 8
     
    
    9 9
     module GHCi.ResolvedBCO
    
    10 10
       ( ResolvedBCO(..)
    
    ... ... @@ -16,33 +16,39 @@ module GHCi.ResolvedBCO
    16 16
     
    
    17 17
     #include "MachDeps.h"
    
    18 18
     
    
    19
    +#if SIZEOF_HSWORD != 4 && SIZEOF_HSWORD != 8
    
    20
    +#error Bytecode serialization works only on 32- and 64-bit platforms.
    
    21
    +#endif
    
    22
    +
    
    23
    +#if !defined(WORDS_BIGENDIAN) && SIZEOF_HSWORD == 8
    
    24
    +#define LITTLE_ENDIAN_64_BITS
    
    25
    +#endif
    
    26
    +
    
    19 27
     import Prelude -- See note [Why do we import Prelude here?]
    
    20
    -import GHC.Data.SmallArray
    
    28
    +
    
    21 29
     import GHCi.RemoteTypes
    
    22 30
     import GHCi.BreakArray
    
    23 31
     
    
    24
    -#if SIZEOF_HSWORD == 4
    
    25
    -import Control.Monad
    
    26
    -import Data.Array.Base (foldrArray, listArray)
    
    27
    -import Data.ByteString.Builder.Extra
    
    28
    -import Foreign.Storable
    
    29
    -#endif
    
    32
    +import GHC.Exts (Int (I#), ByteArray#, sizeofByteArray#)
    
    33
    +import qualified GHC.Exts.Heap as Heap
    
    30 34
     
    
    31
    -import Data.Binary (Binary(..))
    
    32
    -import Data.Binary.Get
    
    35
    +import Data.Word (Word16)
    
    36
    +import Data.ByteString.Short (ShortByteString (SBS), toShort)
    
    37
    +import Data.Array.Base
    
    38
    +import Data.Binary.Builder (fromShortByteString)
    
    33 39
     import Data.Binary.Put
    
    34
    -import Data.ByteString.Short (ShortByteString(..))
    
    35
    -import Data.Word
    
    36
    -import GHC.Generics
    
    37
    -
    
    38
    -import GHC.Exts
    
    39
    -import Data.Array.Base (UArray(..))
    
    40
    -import qualified GHC.Exts.Heap as Heap
    
    40
    +import Data.Binary.Get
    
    41
    +import Data.Binary (Binary (put, get))
    
    42
    +import Foreign.Storable (Storable, sizeOf)
    
    43
    +import GHC.Data.SmallArray (SmallArray)
    
    44
    +import GHC.Generics (Generic)
    
    41 45
     
    
    42
    -#include "MachDeps.h"
    
    46
    +#ifndef LITTLE_ENDIAN_64_BITS
    
    47
    +import Control.Monad (replicateM)
    
    48
    +#endif
    
    43 49
     
    
    44 50
     isLittleEndian :: Bool
    
    45
    -#if defined(WORDS_BIGENDIAN)
    
    51
    +#ifdef WORDS_BIGENDIAN
    
    46 52
     isLittleEndian = False
    
    47 53
     #else
    
    48 54
     isLittleEndian = True
    
    ... ... @@ -96,27 +102,19 @@ data BCOByteArray a
    96 102
             getBCOByteArray :: !ByteArray#
    
    97 103
       }
    
    98 104
     
    
    99
    -#if SIZEOF_HSWORD == 4
    
    100
    -fromBCOByteArray :: forall a . Storable a => BCOByteArray a -> UArray Int a
    
    101
    -fromBCOByteArray (BCOByteArray ba#) = UArray 0 (n - 1) n ba#
    
    105
    +#ifndef LITTLE_ENDIAN_64_BITS
    
    106
    +
    
    107
    +fromBCOByteArray :: Storable a => BCOByteArray a -> UArray Int a
    
    108
    +fromBCOByteArray @a (BCOByteArray ba#) = UArray 0 (n - 1) n ba#
    
    102 109
       where
    
    103 110
         len# = sizeofByteArray# ba#
    
    104 111
         n = (I# len#) `div` sizeOf (undefined :: a)
    
    112
    +
    
    105 113
     #endif
    
    106 114
     
    
    107 115
     mkBCOByteArray :: UArray Int a -> BCOByteArray a
    
    108 116
     mkBCOByteArray (UArray _ _ _ arr) = BCOByteArray arr
    
    109 117
     
    
    110
    --- | Directly serialize 'BCOByteArray' payload without iterating over
    
    111
    --- individual elements, assuming 'BCOByteArray' element type is a
    
    112
    --- fixed-width type like 'Word16' that doesn't depend on host word
    
    113
    --- size. See Note [BCOByteArray serialization] for more explanation.
    
    114
    -unsafePutFixedWidthBCOByteArray :: BCOByteArray a -> Put
    
    115
    -unsafePutFixedWidthBCOByteArray (BCOByteArray ba#) = put $ SBS ba#
    
    116
    -
    
    117
    -unsafeGetFixedWidthBCOByteArray :: Get (BCOByteArray a)
    
    118
    -unsafeGetFixedWidthBCOByteArray = (\(SBS ba#) -> BCOByteArray ba#) <$> get
    
    119
    -
    
    120 118
     instance Show (BCOByteArray Word16) where
    
    121 119
       showsPrec _ _ = showString "BCOByteArray Word16"
    
    122 120
     
    
    ... ... @@ -152,48 +150,109 @@ instance Binary ResolvedBCO where
    152 150
           1 -> ResolvedStaticCon <$> get <*> get <*> get <*> get <*> get <*> get
    
    153 151
           _ -> error "Binary ResolvedBCO: invalid byte"
    
    154 152
     
    
    155
    --- See Note [BCOByteArray serialization]
    
    153
    +#ifndef LITTLE_ENDIAN_64_BITS
    
    154
    +
    
    155
    +-- | Serialize a 'BCOByteArray', not writing the payload verbatim but
    
    156
    +--   serializing the individual elements. This can be used with any host
    
    157
    +--   platform and element type.
    
    158
    +putBCOByteArrayPortably :: (Storable a, IArray UArray a)
    
    159
    +                        => (a -> Put)
    
    160
    +                           -- ^ The serializer to use for each element
    
    161
    +                        -> (BCOByteArray a -> Put)
    
    162
    +                           -- ^ The 'BCOByteArray' serializer
    
    163
    +putBCOByteArrayPortably @a putElement bcoByteArray
    
    164
    +  = putWord64le (fromIntegral size) <> foldMap putElement (elems uArray)
    
    165
    +  where
    
    166
    +
    
    167
    +  uArray :: UArray Int a
    
    168
    +  uArray = fromBCOByteArray bcoByteArray
    
    169
    +
    
    170
    +  size :: Int
    
    171
    +  size = numElements array
    
    172
    +
    
    173
    +-- | Deserialize a 'BCOByteArray', not reading the payload verbatim but
    
    174
    +--   deserializing the individual elements. This can be used with any host
    
    175
    +--   platform and element type.
    
    176
    +getBCOByteArrayPortably :: IArray UArray a
    
    177
    +                        => Get a
    
    178
    +                           -- ^ The deserializer to use for each element
    
    179
    +                        -> Get (BCOByteArray a)
    
    180
    +                           -- ^ The 'BCOByteArray' deserializer
    
    181
    +getBCOByteArrayPortably getElement = do
    
    182
    +  size <- fromIntegral <$> getWord64le :: Get Int
    
    183
    +  elements <- replicateM size getElement
    
    184
    +  return (mkBCOByteArray (listArray (0, pred size) elements))
    
    185
    +
    
    186
    +#endif
    
    187
    +
    
    188
    +#ifndef WORDS_BIGENDIAN
    
    189
    +
    
    190
    +-- | Serialize a 'BCOByteArray', writing the payload verbatim instead of
    
    191
    +--   serializing the individual elements. This must only be used when the host
    
    192
    +--   platform uses little endian and the bitsize of the element type of the
    
    193
    +--   array is the one that is used for the serialized form of elements.
    
    194
    +putBCOByteArrayDirectly :: Storable a => BCOByteArray a -> Put
    
    195
    +putBCOByteArrayDirectly @a (BCOByteArray byteArray#)
    
    196
    +  = putWord64le (fromIntegral size) <>
    
    197
    +    putBuilder (fromShortByteString (SBS byteArray#))
    
    198
    +  where
    
    199
    +
    
    200
    +  size :: Int
    
    201
    +  size = I# (sizeofByteArray# byteArray#) `div` sizeOf (undefined :: a)
    
    202
    +
    
    203
    +-- | Deserialize a 'BCOByteArray', reading the payload verbatim instead of
    
    204
    +--   deserializing the individual elements. This must only be used when the host
    
    205
    +--   platform uses little endian and the bitsize of the element type of the
    
    206
    +--   array is the one that is used for the serialized form of elements.
    
    207
    +getBCOByteArrayDirectly :: Storable a => Get (BCOByteArray a)
    
    208
    +getBCOByteArrayDirectly @a = do
    
    209
    +  size <- fromIntegral <$> getWord64le :: Get Int
    
    210
    +  SBS byteArray# <- toShort <$> getByteString (size * sizeOf (undefined :: a))
    
    211
    +    -- Beware that there is no overflow check for the byte count computation.
    
    212
    +  return (BCOByteArray byteArray#)
    
    213
    +
    
    214
    +#endif
    
    215
    +
    
    216
    +-- See Note [BCOByteArray serialization].
    
    156 217
     instance Binary (BCOByteArray Word16) where
    
    157
    -  put = unsafePutFixedWidthBCOByteArray
    
    158
    -  get = unsafeGetFixedWidthBCOByteArray
    
    159 218
     
    
    160
    --- Word size depends on host, which is tricky when host/target word
    
    161
    --- sizes differ. We always serialize `BCOByteArray Word` as
    
    162
    --- `BCOByteArray Word64`.
    
    163
    -instance Binary (BCOByteArray Word) where
    
    164
    -#if SIZEOF_HSWORD == 8
    
    165
    -  -- 64-bit fast path. `BCOByteArray` is directly serialized via the
    
    166
    -  -- `Binary ShortByteString` instance, which serializes the `Int`
    
    167
    -  -- bytelength first (via `Int64` transparently), then copies the
    
    168
    -  -- buffer.
    
    169
    -  put = unsafePutFixedWidthBCOByteArray
    
    170
    -
    
    171
    -  get = unsafeGetFixedWidthBCOByteArray
    
    219
    +#ifdef WORDS_BIGENDIAN
    
    220
    +  put = putBCOByteArrayPortably putWord16le
    
    221
    +  get = getBCOByteArrayPortably getWord16le
    
    172 222
     #else
    
    173
    -  -- 32-bit slow path. Pretend it's a `BCOByteArray Word64` and handle
    
    174
    -  -- the bytelength & buffer elements directly.
    
    175
    -  --
    
    176
    -  -- Regarding endianness: the bytelength is serialized via the
    
    177
    -  -- `Binary Int` instance, which is serialized as `Int64` via
    
    178
    -  -- big-endian. The payload follows host-endianness. This doesn't
    
    179
    -  -- work when host/target has different endianness, but we don't
    
    180
    -  -- support that setup yet anyway.
    
    181
    -  put ba32@(BCOByteArray ba32#) =
    
    182
    -    put len64 *>
    
    183
    -    putBuilder
    
    184
    -      (foldrArray (\w32 acc -> word64Host (fromIntegral w32) <> acc) mempty arr32)
    
    185
    -    where
    
    186
    -      len32# = sizeofByteArray# ba32#
    
    187
    -      len64 = I# len32# * 2
    
    188
    -      arr32 = fromBCOByteArray ba32
    
    223
    +  put = putBCOByteArrayDirectly
    
    224
    +  get = getBCOByteArrayDirectly
    
    225
    +#endif
    
    189 226
     
    
    190
    -  get = do
    
    191
    -    len64 <- get
    
    192
    -    let len = len64 `div` 8
    
    193
    -    w32s <- replicateM len (fromIntegral <$> getWord64host)
    
    194
    -    pure $ mkBCOByteArray $ listArray (0, len - 1) w32s
    
    227
    +-- See Note [BCOByteArray serialization].
    
    228
    +instance Binary (BCOByteArray Word) where
    
    229
    +
    
    230
    +#ifdef LITTLE_ENDIAN_64_BITS
    
    231
    +  put = putBCOByteArrayDirectly
    
    232
    +  get = getBCOByteArrayDirectly
    
    233
    +#else
    
    234
    +  put = putBCOByteArrayPortably (putWord64le . fromIntegral)
    
    235
    +  get = getBCOByteArrayPortably (fromIntegral <$> getWord64le)
    
    195 236
     #endif
    
    196 237
     
    
    238
    +-- Note [BCOByteArray serialization]
    
    239
    +-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    240
    +--
    
    241
    +-- In its serialized form, a 'BCOByteArray' value is represented by the number
    
    242
    +-- of its elements followed by the individual elements. The serialization format
    
    243
    +-- is platform-independent, thanks to the following specifics:
    
    244
    +--
    
    245
    +--   * All natural numbers are encoded using little endian, independently of the
    
    246
    +--     host’s endianness.
    
    247
    +--   * Array sizes are encoded using 64 bits, independently of the host’s native
    
    248
    +--     bit size.
    
    249
    +--   * 'Word' values are encoded using 64 bits, independently of the host’s
    
    250
    +--     native bit size.
    
    251
    +--
    
    252
    +-- Whenever the encoding of the payload matches its representation in main
    
    253
    +-- memory, the whole payload is transferred verbatim. Otherwise, the elements
    
    254
    +-- are serialized or deserialized individually.
    
    255
    +
    
    197 256
     data ResolvedBCOPtr
    
    198 257
       = ResolvedBCORef {-# UNPACK #-} !Int
    
    199 258
           -- ^ reference to the Nth BCO in the current set of BCOs and
    
    ... ... @@ -215,35 +274,3 @@ data ResolvedBCOPtr
    215 274
       deriving (Generic, Show)
    
    216 275
     
    
    217 276
     instance Binary ResolvedBCOPtr
    218
    -
    
    219
    --- Note [BCOByteArray serialization]
    
    220
    --- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    
    221
    ---
    
    222
    --- !12142 changed some BCO blob types from UArray to
    
    223
    --- BCOByteArray(ByteArray#) to save a little space. Unfortunately, a
    
    224
    --- nasty serialization bug has surfaced since then. It happens when we
    
    225
    --- need to pass BCOByteArray between host/target with mismatching word
    
    226
    --- sizes. When 32-bit iserv receives a `BCOByteArray Word` from 64-bit
    
    227
    --- host GHC, it would parse the buffer assuming each Word=Word32, even
    
    228
    --- if host GHC assumes each Word=Word64, and of course it's horribly
    
    229
    --- wrong!
    
    230
    ---
    
    231
    --- The root issue here is the usage of platform sized integer types in
    
    232
    --- BCO (and any messages we pass between ghc/iserv really), we should
    
    233
    --- do what we already do for RemotePtr: always use Word64 instead of
    
    234
    --- Word.
    
    235
    ---
    
    236
    --- When we serialize `BCOByteArray Word16`, element is fixed width on
    
    237
    --- 32/64-bit host, so we can directly serialize the buffer per se. For
    
    238
    --- `BCOByteArray Word`, we must always serialize it as `BCOByteArray
    
    239
    --- Word64`, and hence it has fast-path/slow-path decided at
    
    240
    --- compile-time, see comments of `instance Binary (BCOByteArray Word)`
    
    241
    --- for explanation. These are the only two `Binary` instances we ever
    
    242
    --- use, so to avoid unnecessary complexity, we're fine with flexible
    
    243
    --- instances here, instead of generalizing to any element type that
    
    244
    --- may be fixed-width or not.
    
    245
    ---
    
    246
    --- Since we erase the metadata in UArray, we need to find a way to
    
    247
    --- calculate the item count by dividing the ByteArray# length with
    
    248
    --- element size. The element size comes from Storable's sizeOf method,
    
    249
    --- thus the addition of Storable constraint.