-- | Parse and look up entries in the @.debug_str_offsets@ section. -- -- Each compilation unit may contribute a table: initial_length, version (2), -- padding (2), then an array of offsets (4 or 8 bytes each depending on -- DWARF format). The CU root DIE's @DW_AT_str_offsets_base@ points past the -- header to the first entry. @ValStrIndex@ indexes into this array; the -- resulting value is an offset into @.debug_str@. module Data.Dwarf.Read.StrOffsets ( StrOffsetsHeader(..) , parseStrOffsetsHeader , lookupStrOffset ) where import Data.Word (Word64) import Data.Dwarf.Encoding (Format(..), formatWordSize, formatInitialLengthSize) import Data.Dwarf.Reader ( Reader(..), Parse(..), runParse, parseError , getInitialLength, getOffset ) import Data.Dwarf.Section (DebugStrOffsets(..)) import Data.Dwarf.Types (DwarfError(..)) -- | Parsed header of a @.debug_str_offsets@ contribution. data StrOffsetsHeader = StrOffsetsHeader { strOffFormat :: !Format , strOffCount :: !Word64 -- ^ Number of offset entries in the table. , strOffBaseOff :: !Word64 -- ^ Byte offset of the first entry relative to the start of this -- contribution in the section. } deriving stock (Eq, Show) -- | Parse one @.debug_str_offsets@ header from the start of a contribution. parseStrOffsetsHeader :: Reader r => Parse r StrOffsetsHeader parseStrOffsetsHeader = do -- initial_length → format + content length (fmt, contentLen) <- getInitialLength -- version (must be 5) version <- fromIntegral <$> Parse getU16 if version /= 5 then parseError (UnsupportedVersion version) else pure () -- padding (2 bytes, reserved) _ <- Parse getU16 -- Header bytes within the content: version(2) + padding(2) = 4 let headerBytes = 4 :: Word64 entrySize = fromIntegral (formatWordSize fmt) :: Word64 entryBytes = contentLen - headerBytes count = entryBytes `div` entrySize -- Byte offset of the first entry from the start of this contribution: -- initial_length field + version + padding let baseOff = fromIntegral (formatInitialLengthSize fmt) + headerBytes pure StrOffsetsHeader { strOffFormat = fmt , strOffCount = count , strOffBaseOff = baseOff } -- | Look up an offset into @.debug_str@ by index. -- -- @base@ is the @DW_AT_str_offsets_base@ value (absolute byte offset of the -- first entry in the section). @index@ is the @ValStrIndex@ value. lookupStrOffset :: Reader r => DebugStrOffsets r -> Format -> Word64 -> Word64 -> Either DwarfError Word64 lookupStrOffset (DebugStrOffsets r) fmt base index = do let entrySize = fromIntegral (formatWordSize fmt) :: Word64 byteOff = base + index * entrySize r' <- skip (fromIntegral byteOff) r (off, _) <- runParse (getOffset fmt) r' Right off