Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448-- | Serialise DWARF line number programs to @.debug_line@ section bytes.-- This is the inverse of "Data.Dwarf.Read.Line".module Data.Dwarf.Write.Line ( writeLineProgramHeader , encodeLineRows , writeLineProgram , writeDebugLine , poolLinePaths ) where
import Data.ByteString (ByteString)import Data.ByteString.Builder (Builder)import Data.Int (Int64)import Data.Word (Word8, Word64)
import qualified Data.ByteString as BSimport qualified Data.Vector as Vector
import Data.Dwarf.Constants ( DwLnct(..), DwLne(..), DwLns(..), DwForm(..) )import Data.Dwarf.Encoding (Endianness, Encoding(..), Format(..))import Data.Dwarf.Read.Attr (AttrVal(..))import Data.Dwarf.Read.Line ( DirEntry(..), FileEntry(..) , LineProgramHeader(..), LineRow(..) )import Data.Dwarf.Write.Str (StringTable, addString)import Data.Dwarf.Write.Writer
-------------------------------------------------------------------------- Header------------------------------------------------------------------------
-- | Serialise a line program header (without the program body).writeLineProgramHeader :: Endianness -> LineProgramHeader ByteString -> BuilderwriteLineProgramHeader e hdr = let ver = encodingVersion (lphEncoding hdr) in if ver >= 5 then writeV5Header e hdr else writeV2_4Header e hdr
writeV5Header :: Endianness -> LineProgramHeader ByteString -> BuilderwriteV5Header e hdr = let enc = lphEncoding hdr fmt = encodingFormat enc ver = encodingVersion enc as = encodingAddressSize enc
-- Build header body (after header_length) headerBody = writeV5HeaderBody e hdr
headerBodyBS = toStrict headerBody
-- Build program body progBodyBS = toStrict (putBytes (lphProgram hdr))
-- Content after initial_length: version(2) + addr_size(1) + seg_sel_size(1) + -- header_length(format) + headerBody + program contentLen = 2 + 1 + 1 + fromIntegral (formatOffsetSize fmt) + fromIntegral (BS.length headerBodyBS) + fromIntegral (BS.length progBodyBS) :: Word64
in putInitialLength e fmt contentLen <> putU16 e (fromIntegral ver) <> putU8 as <> putU8 (lphSegmentSelectorSize hdr) <> putOffset e fmt (fromIntegral (BS.length headerBodyBS)) <> putBytes headerBodyBS <> putBytes progBodyBS
writeV5HeaderBody :: Endianness -> LineProgramHeader ByteString -> BuilderwriteV5HeaderBody e hdr = let enc = lphEncoding hdr in putU8 (lphMinInsnLength hdr) <> putU8 (lphMaxOpsPerInsn hdr) <> putU8 (if lphDefaultIsStmt hdr then 1 else 0) <> putI8 (lphLineBase hdr) <> putU8 (lphLineRange hdr) <> putU8 (lphOpcodeBase hdr) <> Vector.foldl' (\acc w -> acc <> putU8 w) mempty (lphStdOpcodeLengths hdr) -- Directory entry format <> writeDirFormat hdr -- Directory entries <> putULEB128 (fromIntegral (Vector.length (lphDirectories hdr))) <> Vector.foldl' (\acc d -> acc <> writeDirEntryV5 e enc d) mempty (lphDirectories hdr) -- File name entry format <> writeFileFormat hdr -- File name entries <> putULEB128 (fromIntegral (Vector.length (lphFileNames hdr))) <> Vector.foldl' (\acc f -> acc <> writeFileEntryV5 e enc f) mempty (lphFileNames hdr)
writeDirFormat :: LineProgramHeader r -> BuilderwriteDirFormat hdr = -- 1 format pair: DW_LNCT_path + form let form = dirPathForm hdr in putU8 1 <> putULEB128 (fromIntegral (let DwLnct w = DW_LNCT_path in w)) <> putULEB128 (fromIntegral (let DwForm w = form in w))
writeDirEntryV5 :: Endianness -> Encoding -> DirEntry -> BuilderwriteDirEntryV5 _e _enc (DirEntry (ValString bs)) = putNullTerminated bswriteDirEntryV5 e enc (DirEntry (ValLineStrOffset off)) = putOffset e (encodingFormat enc) offwriteDirEntryV5 _e _enc (DirEntry _) = putNullTerminated BS.empty
writeFileFormat :: LineProgramHeader r -> BuilderwriteFileFormat hdr = -- 2 format pairs: DW_LNCT_path + form, DW_LNCT_directory_index + form let form = filePathForm hdr in putU8 2 <> putULEB128 (fromIntegral (let DwLnct w = DW_LNCT_path in w)) <> putULEB128 (fromIntegral (let DwForm w = form in w)) <> putULEB128 (fromIntegral (let DwLnct w = DW_LNCT_directory_index in w)) <> putULEB128 (fromIntegral (let DwForm w = DW_FORM_udata in w))
writeFileEntryV5 :: Endianness -> Encoding -> FileEntry -> BuilderwriteFileEntryV5 e enc fe = (case filePath fe of ValString bs -> putNullTerminated bs ValLineStrOffset off -> putOffset e (encodingFormat enc) off _ -> putNullTerminated BS.empty) <> putULEB128 (fileDirIndex fe)
writeV2_4Header :: Endianness -> LineProgramHeader ByteString -> BuilderwriteV2_4Header e hdr = let enc = lphEncoding hdr fmt = encodingFormat enc ver = encodingVersion enc
-- Build header body (after header_length) headerBody = writeV2_4HeaderBody e hdr headerBodyBS = toStrict headerBody
-- Build program body progBodyBS = toStrict (putBytes (lphProgram hdr))
-- Content after initial_length: version(2) + header_length(format) + headerBody + program contentLen = 2 + fromIntegral (formatOffsetSize fmt) + fromIntegral (BS.length headerBodyBS) + fromIntegral (BS.length progBodyBS) :: Word64
in putInitialLength e fmt contentLen <> putU16 e (fromIntegral ver) <> putOffset e fmt (fromIntegral (BS.length headerBodyBS)) <> putBytes headerBodyBS <> putBytes progBodyBS
writeV2_4HeaderBody :: Endianness -> LineProgramHeader ByteString -> BuilderwriteV2_4HeaderBody _e hdr = let ver = encodingVersion (lphEncoding hdr) in putU8 (lphMinInsnLength hdr) <> (if ver >= 4 then putU8 (lphMaxOpsPerInsn hdr) else mempty) <> putU8 (if lphDefaultIsStmt hdr then 1 else 0) <> putI8 (lphLineBase hdr) <> putU8 (lphLineRange hdr) <> putU8 (lphOpcodeBase hdr) <> Vector.foldl' (\acc w -> acc <> putU8 w) mempty (lphStdOpcodeLengths hdr) -- Directories: null-terminated strings, empty string terminator <> Vector.foldl' (\acc d -> acc <> writeDirEntryV2_4 d) mempty (lphDirectories hdr) <> putU8 0 -- terminator -- Files: name + dir_index + mtime + size, empty name terminator <> Vector.foldl' (\acc f -> acc <> writeFileEntryV2_4 f) mempty (lphFileNames hdr) <> putU8 0 -- terminator
writeDirEntryV2_4 :: DirEntry -> BuilderwriteDirEntryV2_4 (DirEntry (ValString bs)) = putNullTerminated bswriteDirEntryV2_4 (DirEntry _) = putNullTerminated BS.empty
writeFileEntryV2_4 :: FileEntry -> BuilderwriteFileEntryV2_4 fe = (case filePath fe of ValString bs -> putNullTerminated bs _ -> putNullTerminated BS.empty) <> putULEB128 (fileDirIndex fe) <> putULEB128 (maybe 0 id (fileTimestamp fe)) <> putULEB128 (maybe 0 id (fileSize fe))
-------------------------------------------------------------------------- Row encoding------------------------------------------------------------------------
-- | Encode line rows into a line program byte sequence.-- Uses special opcodes where possible for compact encoding.encodeLineRows :: Endianness -> LineProgramHeader r -> [LineRow] -> BuilderencodeLineRows e hdr rows = encodeSequences e hdr (splitSequences rows)
-- | Split rows into sequences at DW_LNE_end_sequence boundaries.splitSequences :: [LineRow] -> [[LineRow]]splitSequences [] = []splitSequences rows = let (seq_, rest) = span (not . lrEndSequence) rows in case rest of [] -> [seq_] (r:rs) -> (seq_ ++ [r]) : splitSequences rs
encodeSequences :: Endianness -> LineProgramHeader r -> [[LineRow]] -> BuilderencodeSequences e hdr = foldMap (encodeSequence e hdr)
encodeSequence :: Endianness -> LineProgramHeader r -> [LineRow] -> BuilderencodeSequence _e _hdr [] = memptyencodeSequence e hdr (first:rest) = let as = encodingAddressSize (lphEncoding hdr) -- Set initial address setAddr = extendedOp (DwLne 0x02) (putAddress e as (lrAddress first)) -- Set initial state changes from defaults and emit first row initSt = initialState (lphDefaultIsStmt hdr) (initOps, _) = encodeStateChanges hdr initSt first -- Also emit line advance from initial state (line=1) to first row lineDelta = fromIntegral (lrLine first) - lsLine initSt :: Int64 lineOp = if lineDelta /= 0 then stdOp DW_LNS_advance_line <> putSLEB128 lineDelta else mempty firstRow = if lrEndSequence first then setAddr <> initOps <> lineOp <> extendedOp DW_LNE_end_sequence mempty else setAddr <> initOps <> lineOp <> emitCopy -- Update first as "previous" for transitions firstSt = first -- Encode transitions for remaining rows (transOps, _) = foldl (\(acc, prev) cur -> let (ops, _) = encodeTransition hdr prev cur in (acc <> ops, cur) ) (mempty, firstSt) rest in firstRow <> transOps
-- | Initial state machine registers.data LineState = LineState { lsAddr :: !Word64 , lsOpIdx :: !Word64 , lsFile :: !Word64 , lsLine :: !Int64 , lsColumn :: !Word64 , lsIsStmt :: !Bool , lsBasicBlock :: !Bool , lsPrologueEnd :: !Bool , lsEpilogueBegin :: !Bool , lsIsa :: !Word64 , lsDiscriminator :: !Word64 }
initialState :: Bool -> LineStateinitialState defaultIsStmt = LineState { lsAddr = 0 , lsOpIdx = 0 , lsFile = 1 , lsLine = 1 , lsColumn = 0 , lsIsStmt = defaultIsStmt , lsBasicBlock = False , lsPrologueEnd = False , lsEpilogueBegin = False , lsIsa = 0 , lsDiscriminator = 0 }
rowToState :: LineRow -> LineStaterowToState r = LineState { lsAddr = lrAddress r , lsOpIdx = lrOpIndex r , lsFile = lrFile r , lsLine = fromIntegral (lrLine r) , lsColumn = lrColumn r , lsIsStmt = lrIsStmt r , lsBasicBlock = lrBasicBlock r , lsPrologueEnd = lrPrologueEnd r , lsEpilogueBegin = lrEpilogueBegin r , lsIsa = lrIsa r , lsDiscriminator = lrDiscriminator r }
-- | Encode state changes from prev to target row (flag changes only, no address/line).encodeStateChanges :: LineProgramHeader r -> LineState -> LineRow -> (Builder, LineState)encodeStateChanges _hdr prev row = let ops = mconcat [ if lrFile row /= lsFile prev then stdOp DW_LNS_set_file <> putULEB128 (lrFile row) else mempty , if lrColumn row /= lsColumn prev then stdOp DW_LNS_set_column <> putULEB128 (lrColumn row) else mempty , if lrIsStmt row /= lsIsStmt prev then stdOp DW_LNS_negate_stmt else mempty , if lrBasicBlock row && not (lsBasicBlock prev) then stdOp DW_LNS_set_basic_block else mempty , if lrPrologueEnd row && not (lsPrologueEnd prev) then stdOp DW_LNS_set_prologue_end else mempty , if lrEpilogueBegin row && not (lsEpilogueBegin prev) then stdOp DW_LNS_set_epilogue_begin else mempty , if lrIsa row /= lsIsa prev then stdOp DW_LNS_set_isa <> putULEB128 (lrIsa row) else mempty , if lrDiscriminator row /= lsDiscriminator prev && lrDiscriminator row /= 0 then extendedOp (DwLne 0x04) (putULEB128 (lrDiscriminator row)) else mempty ] st = rowToState row in (ops, st)
-- | Encode a transition from one row to the next.encodeTransition :: LineProgramHeader r -> LineRow -> LineRow -> (Builder, LineState)encodeTransition hdr prev cur | lrEndSequence cur = -- Advance address to end sequence location, then emit end_sequence let addrDelta = lrAddress cur - lrAddress prev advOps = if addrDelta > 0 then stdOp DW_LNS_advance_pc <> putULEB128 (computeOpAdvance hdr addrDelta) else mempty ops = advOps <> extendedOp DW_LNE_end_sequence mempty in (ops, initialState (lphDefaultIsStmt hdr)) | otherwise = let prevSt = rowToState prev -- State changes (file, column, flags) (stateOps, _) = encodeStateChanges hdr prevSt cur -- Address and line advance addrDelta = lrAddress cur - lrAddress prev lineDelta = fromIntegral (lrLine cur) - fromIntegral (lrLine prev) :: Int64 -- Try special opcode result = trySpecialOpcode hdr addrDelta lineDelta in case result of Just specialByte -> (stateOps <> putU8 specialByte, rowToState cur) Nothing -> -- Use standard opcodes let advOps = (if addrDelta > 0 then stdOp DW_LNS_advance_pc <> putULEB128 (computeOpAdvance hdr addrDelta) else mempty) <> (if lineDelta /= 0 then stdOp DW_LNS_advance_line <> putSLEB128 lineDelta else mempty) <> emitCopy in (stateOps <> advOps, rowToState cur)
-- | Try to encode address and line advance as a special opcode.trySpecialOpcode :: LineProgramHeader r -> Word64 -> Int64 -> Maybe Word8trySpecialOpcode hdr addrDelta lineDelta = let opcBase = fromIntegral (lphOpcodeBase hdr) :: Int64 lineBase_ = fromIntegral (lphLineBase hdr) :: Int64 lineRange = fromIntegral (lphLineRange hdr) :: Int64 minLen = fromIntegral (lphMinInsnLength hdr) :: Word64 maxOps = fromIntegral (lphMaxOpsPerInsn hdr) :: Word64 in if lineRange == 0 || minLen == 0 then Nothing else let opAdvance = if maxOps <= 1 then addrDelta `div` minLen else addrDelta `div` minLen -- simplified lineDeltaAdj = lineDelta - lineBase_ opcode = lineDeltaAdj + lineRange * fromIntegral opAdvance + opcBase in if lineDeltaAdj >= 0 && lineDeltaAdj < lineRange && opcode >= opcBase && opcode <= 255 && opAdvance * minLen == addrDelta -- exact address match then Just (fromIntegral opcode) else Nothing
-- | Compute the op_advance value for an address delta.computeOpAdvance :: LineProgramHeader r -> Word64 -> Word64computeOpAdvance hdr addrDelta = let minLen = fromIntegral (lphMinInsnLength hdr) :: Word64 in if minLen == 0 then addrDelta else addrDelta `div` minLen
-------------------------------------------------------------------------- Opcode helpers------------------------------------------------------------------------
-- | Emit a standard opcode byte.stdOp :: DwLns -> BuilderstdOp (DwLns w) = putU8 w
-- | Emit DW_LNS_copy.emitCopy :: BuilderemitCopy = stdOp DW_LNS_copy
-- | Emit an extended opcode: 0x00 + ULEB128(1+payloadLen) + opcode + payload.extendedOp :: DwLne -> Builder -> BuilderextendedOp (DwLne op) payload = let payloadBS = toStrict payload totalLen = 1 + fromIntegral (BS.length payloadBS) :: Word64 in putU8 0 <> putULEB128 totalLen <> putU8 op <> putBytes payloadBS
-- | Size of offset fields (not initial length).formatOffsetSize :: Format -> IntformatOffsetSize Dwarf32 = 4formatOffsetSize Dwarf64 = 8
-------------------------------------------------------------------------- Path pooling into .debug_line_str------------------------------------------------------------------------
-- | Pool directory and file path strings from a line program header into-- a 'StringTable', replacing 'ValString' paths with 'ValLineStrOffset'.-- The resulting offsets reference a @.debug_line_str@ section built by-- 'Data.Dwarf.Write.Str.buildDebugLineStr'.---- DWARF 2–4 headers are returned unchanged (no @.debug_line_str@ support).poolLinePaths :: LineProgramHeader r -> StringTable -> (LineProgramHeader r, StringTable)poolLinePaths hdr st0 | encodingVersion (lphEncoding hdr) < 5 = (hdr, st0) | otherwise = let (dirs', st1) = Vector.foldl' poolDir ([], st0) (lphDirectories hdr) (files', st2) = Vector.foldl' poolFile ([], st1) (lphFileNames hdr) in (hdr { lphDirectories = Vector.fromList (reverse dirs') , lphFileNames = Vector.fromList (reverse files') }, st2) where poolDir (!acc, !st) (DirEntry (ValString bs)) = let (off, st') = addString bs st in (DirEntry (ValLineStrOffset off) : acc, st') poolDir (!acc, !st) d = (d : acc, st)
poolFile (!acc, !st) fe = case filePath fe of ValString bs -> let (off, st') = addString bs st in (fe { filePath = ValLineStrOffset off } : acc, st') _ -> (fe : acc, st)
-------------------------------------------------------------------------- Internal: form detection------------------------------------------------------------------------
-- | Determine the DW_FORM for directory path entries by inspecting the-- first entry's AttrVal variant.dirPathForm :: LineProgramHeader r -> DwFormdirPathForm hdr | Vector.null (lphDirectories hdr) = DW_FORM_string | otherwise = case dirPath (lphDirectories hdr Vector.! 0) of ValLineStrOffset _ -> DW_FORM_line_strp _ -> DW_FORM_string
-- | Determine the DW_FORM for file path entries by inspecting the-- first entry's AttrVal variant.filePathForm :: LineProgramHeader r -> DwFormfilePathForm hdr | Vector.null (lphFileNames hdr) = DW_FORM_string | otherwise = case filePath (lphFileNames hdr Vector.! 0) of ValLineStrOffset _ -> DW_FORM_line_strp _ -> DW_FORM_string
-------------------------------------------------------------------------- High-level------------------------------------------------------------------------
-- | Serialize a complete line program (header + rows) to bytes.writeLineProgram :: Endianness -> LineProgramHeader ByteString -> [LineRow] -> ByteStringwriteLineProgram e hdr rows = let progBytes = toStrict (encodeLineRows e hdr rows) hdr' = hdr { lphProgram = progBytes } in toStrict (writeLineProgramHeader e hdr')
-- | Serialize multiple line programs into a single @.debug_line@ section.writeDebugLine :: Endianness -> [(LineProgramHeader ByteString, [LineRow])] -> ByteStringwriteDebugLine e progs = BS.concat (map (uncurry (writeLineProgram e)) progs)