-- | 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 BS import 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 -> Builder writeLineProgramHeader e hdr = let ver = encodingVersion (lphEncoding hdr) in if ver >= 5 then writeV5Header e hdr else writeV2_4Header e hdr writeV5Header :: Endianness -> LineProgramHeader ByteString -> Builder writeV5Header 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 -> Builder writeV5HeaderBody 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 -> Builder writeDirFormat 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 -> Builder writeDirEntryV5 _e _enc (DirEntry (ValString bs)) = putNullTerminated bs writeDirEntryV5 e enc (DirEntry (ValLineStrOffset off)) = putOffset e (encodingFormat enc) off writeDirEntryV5 _e _enc (DirEntry _) = putNullTerminated BS.empty writeFileFormat :: LineProgramHeader r -> Builder writeFileFormat 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 -> Builder writeFileEntryV5 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 -> Builder writeV2_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 -> Builder writeV2_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 -> Builder writeDirEntryV2_4 (DirEntry (ValString bs)) = putNullTerminated bs writeDirEntryV2_4 (DirEntry _) = putNullTerminated BS.empty writeFileEntryV2_4 :: FileEntry -> Builder writeFileEntryV2_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] -> Builder encodeLineRows 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]] -> Builder encodeSequences e hdr = foldMap (encodeSequence e hdr) encodeSequence :: Endianness -> LineProgramHeader r -> [LineRow] -> Builder encodeSequence _e _hdr [] = mempty encodeSequence 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 -> LineState initialState 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 -> LineState rowToState 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 Word8 trySpecialOpcode 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 -> Word64 computeOpAdvance 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 -> Builder stdOp (DwLns w) = putU8 w -- | Emit DW_LNS_copy. emitCopy :: Builder emitCopy = stdOp DW_LNS_copy -- | Emit an extended opcode: 0x00 + ULEB128(1+payloadLen) + opcode + payload. extendedOp :: DwLne -> Builder -> Builder extendedOp (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 -> Int formatOffsetSize Dwarf32 = 4 formatOffsetSize 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 -> DwForm dirPathForm 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 -> DwForm filePathForm 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] -> ByteString writeLineProgram 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])] -> ByteString writeDebugLine e progs = BS.concat (map (uncurry (writeLineProgram e)) progs)