-- | Serialise CIE and FDE records to @.eh_frame@ section bytes. -- Inverse of "Data.Dwarf.Read.EhFrame". -- -- @.eh_frame@ differs from @.debug_frame@ in CIE sentinel (0 vs 0xFFFFFFFF), -- CIE pointer representation (relative backward vs absolute), pointer -- encoding (@DW_EH_PE_*@), and structured augmentation data. The shared -- 'CfaInstr' type and 'writeCfaInstrs' are reused from "Data.Dwarf.Write.Frame". module Data.Dwarf.Write.EhFrame ( putEncodedValue , writeEhCie , writeEhFde , writeEhFrame , writeEhAugmentationData , hasZAug , stripZ ) where import Control.Monad (foldM) import Data.Bits ((.&.)) import Data.ByteString (ByteString) import Data.ByteString.Builder (Builder) import Data.Int (Int16, Int32, Int64) import Data.Word (Word8, Word64) import qualified Data.ByteString as BS import Data.Dwarf.Encoding (Endianness, Format(Dwarf32)) import Data.Dwarf.Read.EhFrame ( EhCie(..), EhFde(..), EhAugmentation(..), EhFrameRecord(..) ) import Data.Dwarf.Write.Frame (writeCfaInstrs) import Data.Dwarf.Write.Writer ------------------------------------------------------------------------ -- DW_EH_PE pointer encoding ------------------------------------------------------------------------ -- | Encode a value using a @DW_EH_PE_*@ encoding (inverse of -- 'Data.Dwarf.Read.EhFrame.getEncodedValue'). Only the value format -- (lower 4 bits) is handled; application bits (upper 4 bits like -- @DW_EH_PE_pcrel@) are the caller's responsibility. putEncodedValue :: Endianness -> Word8 -> Word8 -> Word64 -> Maybe Builder putEncodedValue e addrSize enc val = case enc .&. 0x0F of 0x00 -> case addrSize of -- DW_EH_PE_absptr 4 -> Just (putU32 e (fromIntegral val)) 8 -> Just (putU64 e val) _ -> Nothing 0x01 -> Just (putULEB128 val) -- DW_EH_PE_uleb128 0x02 -> Just (putU16 e (fromIntegral val)) -- DW_EH_PE_udata2 0x03 -> Just (putU32 e (fromIntegral val)) -- DW_EH_PE_udata4 0x04 -> Just (putU64 e val) -- DW_EH_PE_udata8 0x09 -> Just (putSLEB128 (fromIntegral val :: Int64)) -- DW_EH_PE_sleb128 0x0A -> Just (putI16 e (fromIntegral val :: Int16)) -- DW_EH_PE_sdata2 0x0B -> Just (putI32 e (fromIntegral val :: Int32)) -- DW_EH_PE_sdata4 0x0C -> Just (putI64 e (fromIntegral val :: Int64)) -- DW_EH_PE_sdata8 _ -> Nothing ------------------------------------------------------------------------ -- CIE serialisation ------------------------------------------------------------------------ -- | Serialise an @.eh_frame@ CIE record to bytes (including initial_length). -- The @Word8@ parameter is the target address size (4 or 8), needed because -- @.eh_frame@ CIEs do not carry it in the header. -- Returns 'Nothing' if augmentation encoding fails. writeEhCie :: Endianness -> Word8 -> EhCie -> Maybe ByteString writeEhCie e addrSize cie = do let ver = ehCieVersion cie augStr = ehCieAugmentationString cie -- Serialise augmentation data (if 'z' prefix present) augDataBuilder <- if hasZAug augStr then writeEhAugmentationData e addrSize (stripZ augStr) (ehCieAugmentation cie) else Just mempty let augDataBS = toStrict augDataBuilder content = putU8 ver <> putNullTerminated augStr <> putULEB128 (ehCieCodeAlignmentFactor cie) <> putSLEB128 (ehCieDataAlignmentFactor cie) <> (if ver == 1 then putU8 (fromIntegral (ehCieReturnAddressRegister cie)) else putULEB128 (ehCieReturnAddressRegister cie)) <> (if hasZAug augStr then putULEB128 (fromIntegral (BS.length augDataBS)) <> putBytes augDataBS else mempty) <> writeCfaInstrs e addrSize (ehCieInitialInstructions cie) contentBS = toStrict content -- CIE sentinel for .eh_frame is 0x00000000 (always 4 bytes) sentinelBS = toStrict (putU32 e 0x00000000) totalContent = BS.length sentinelBS + BS.length contentBS Just (toStrict (putInitialLength e Dwarf32 (fromIntegral totalContent) <> putBytes sentinelBS <> putBytes contentBS)) ------------------------------------------------------------------------ -- FDE serialisation ------------------------------------------------------------------------ -- | Serialise an @.eh_frame@ FDE record to bytes (including initial_length). -- -- @cieAbsOff@ is the absolute offset of the associated CIE within the -- section. @fdeAbsOff@ is the absolute offset where this FDE will be -- written (needed to compute the relative backward CIE pointer). writeEhFde :: Endianness -> Word8 -> EhCie -> Word64 -> Word64 -> EhFde -> Maybe ByteString writeEhFde e addrSize cie cieAbsOff fdeAbsOff fde = do let aug = ehCieAugmentation cie fdeEnc = ehAugFdeEnc aug hasZ = hasZAug (ehCieAugmentationString cie) -- CIE pointer: relative backward from the pointer field position. -- ptrFieldPos = fdeAbsOff + 4 (after 4-byte initial_length) ptrFieldPos = fdeAbsOff + 4 ciePtrVal = ptrFieldPos - cieAbsOff -- Encode initial_location (full encoding including application bits) initLocB <- putEncodedValue e addrSize fdeEnc (ehFdeInitialLocation fde) -- Encode address_range (format bits only, no application) addrRangeB <- putEncodedValue e addrSize (fdeEnc .&. 0x0F) (ehFdeAddressRange fde) -- FDE augmentation data augData <- if hasZ then if ehAugLsdaEnc aug /= 0xFF then do lsdaB <- putEncodedValue e addrSize (ehAugLsdaEnc aug) (ehFdeLsdaPointer fde) let lsdaBS = toStrict lsdaB Just (putULEB128 (fromIntegral (BS.length lsdaBS)) <> putBytes lsdaBS) else Just (putULEB128 0) else Just mempty let content = initLocB <> addrRangeB <> augData <> writeCfaInstrs e addrSize (ehFdeInstructions fde) contentBS = toStrict content -- CIE pointer is always 4 bytes in .eh_frame ciePtrBS = toStrict (putU32 e (fromIntegral ciePtrVal)) totalContent = BS.length ciePtrBS + BS.length contentBS Just (toStrict (putInitialLength e Dwarf32 (fromIntegral totalContent) <> putBytes ciePtrBS <> putBytes contentBS)) ------------------------------------------------------------------------ -- Full section ------------------------------------------------------------------------ -- | Serialise a list of @.eh_frame@ records into a section, appending -- the zero-length terminator. -- -- CIE offsets are tracked so FDEs can reference them. Returns 'Nothing' -- if an FDE references a CIE that has not been seen. writeEhFrame :: Endianness -> Word8 -> [EhFrameRecord] -> Maybe ByteString writeEhFrame e addrSize records = do (chunks, _, _) <- foldM go ([], [], 0 :: Word64) records let terminator = toStrict (putU32 e 0) Just (BS.concat (chunks ++ [terminator])) where go (!acc, !cies, !off) (EhFrameCie cie) = do bs <- writeEhCie e addrSize cie let len = fromIntegral (BS.length bs) :: Word64 Just (acc ++ [bs], (off, cie) : cies, off + len) go (!acc, !cies, !off) (EhFrameFde fde) = do let cieOff = ehFdeCieOffset fde cie <- case lookup cieOff (reverse cies) of Just c -> Just c Nothing -> case cies of ((_, c):_) -> Just c [] -> Nothing bs <- writeEhFde e addrSize cie cieOff off fde let len = fromIntegral (BS.length bs) :: Word64 Just (acc ++ [bs], cies, off + len) ------------------------------------------------------------------------ -- Internal helpers ------------------------------------------------------------------------ -- | Serialise augmentation data for a CIE, guided by the augmentation -- string characters (after @\'z\'@). writeEhAugmentationData :: Endianness -> Word8 -> ByteString -> EhAugmentation -> Maybe Builder writeEhAugmentationData e addrSize augChars aug = go 0 mempty where go idx acc | idx >= BS.length augChars = Just acc | otherwise = case BS.index augChars idx of 0x50 -> do -- 'P': personality encoding + pointer pBytes <- putEncodedValue e addrSize (ehAugPersonalityEnc aug) (ehAugPersonality aug) go (idx + 1) (acc <> putU8 (ehAugPersonalityEnc aug) <> pBytes) 0x4C -> -- 'L': LSDA encoding go (idx + 1) (acc <> putU8 (ehAugLsdaEnc aug)) 0x52 -> -- 'R': FDE pointer encoding go (idx + 1) (acc <> putU8 (ehAugFdeEnc aug)) 0x53 -> -- 'S': signal frame (no data) go (idx + 1) acc _ -> Nothing -- | Check if an augmentation string starts with @\'z\'@. hasZAug :: ByteString -> Bool hasZAug bs = not (BS.null bs) && BS.index bs 0 == 0x7A -- 'z' -- | Strip the leading @\'z\'@ from an augmentation string. stripZ :: ByteString -> ByteString stripZ bs | BS.null bs = bs | otherwise = BS.drop 1 bs