diff --git a/src/EPPlus.Fonts.OpenType.Tests/FontScanning/DefaultFontFileReaderTests.cs b/src/EPPlus.Fonts.OpenType.Tests/FontScanning/DefaultFontFileReaderTests.cs
new file mode 100644
index 0000000000..2637e1292c
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/FontScanning/DefaultFontFileReaderTests.cs
@@ -0,0 +1,162 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 11/30/2026 EPPlus Software AB Tests for TTC extraction bounds checks
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Scanner;
+using EPPlus.Fonts.OpenType.Tests.Helpers;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.IO;
+
+namespace EPPlus.Fonts.OpenType.Tests.FontScanning
+{
+ ///
+ /// Tests that DefaultFontFileReader validates a TTC face's table directory against the
+ /// file size before extracting it. TTC bytes are written to a temporary file because
+ /// ReadFontBytes reads from disk.
+ ///
+ [TestClass]
+ public class DefaultFontFileReaderTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private const int TtcHeaderSize = 16;
+
+ private static uint ReadUInt32(byte[] b, int pos)
+ {
+ return (uint)(b[pos] << 24 | b[pos + 1] << 16 | b[pos + 2] << 8 | b[pos + 3]);
+ }
+
+ private static void WriteUInt32(byte[] b, int pos, uint v)
+ {
+ b[pos] = (byte)(v >> 24);
+ b[pos + 1] = (byte)(v >> 16);
+ b[pos + 2] = (byte)(v >> 8);
+ b[pos + 3] = (byte)v;
+ }
+
+ private static void WriteUInt16(byte[] b, int pos, ushort v)
+ {
+ b[pos] = (byte)(v >> 8);
+ b[pos + 1] = (byte)v;
+ }
+
+ private static void WriteTtcHeader(byte[] b, uint numFonts, uint firstOffset)
+ {
+ WriteUInt32(b, 0, 0x74746366); // 'ttcf'
+ WriteUInt32(b, 4, 0x00010000); // version 1.0
+ WriteUInt32(b, 8, numFonts);
+ WriteUInt32(b, 12, firstOffset);
+ }
+
+ ///
+ /// Wraps Roboto-Regular.ttf in a single-face TTC: a 16 byte TTC header followed by the
+ /// font, with every table offset in the font's directory moved forward 16 bytes.
+ ///
+ private static byte[] BuildRobotoTtc(out byte[] originalFont)
+ {
+ originalFont = File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"));
+ var ttc = new byte[TtcHeaderSize + originalFont.Length];
+ WriteTtcHeader(ttc, 1, TtcHeaderSize);
+ Buffer.BlockCopy(originalFont, 0, ttc, TtcHeaderSize, originalFont.Length);
+
+ int numTables = (originalFont[4] << 8) | originalFont[5];
+ for (int i = 0; i < numTables; i++)
+ {
+ int offsetPos = TtcHeaderSize + 12 + i * 16 + 8;
+ WriteUInt32(ttc, offsetPos, ReadUInt32(ttc, offsetPos) + TtcHeaderSize);
+ }
+ return ttc;
+ }
+
+ private static byte[] ReadFromTempFile(byte[] fileBytes, long offsetInFile)
+ {
+ string path = Path.GetTempFileName();
+ try
+ {
+ File.WriteAllBytes(path, fileBytes);
+ var face = new FontFaceInfo { FilePath = path, OffsetInFile = offsetInFile };
+ return new DefaultFontFileReader().ReadFontBytes(face);
+ }
+ finally
+ {
+ File.Delete(path);
+ }
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void ReadFontBytes_ValidTtc_ExtractsLoadableFont()
+ {
+ var ttc = BuildRobotoTtc(out var originalBytes);
+
+ var extracted = ReadFromTempFile(ttc, TtcHeaderSize);
+
+ var original = new OpenTypeFont(originalBytes);
+ var font = new OpenTypeFont(extracted);
+ Assert.AreEqual(original.FullName, font.FullName);
+ Assert.AreEqual(original.MaxpTable.numGlyphs, font.MaxpTable.numGlyphs);
+
+ var originalA = original.GlyfTable.GetGlyph(37); // 'A'
+ var extractedA = font.GlyfTable.GetGlyph(37);
+ Assert.IsNotNull(extractedA);
+ CollectionAssert.AreEqual(originalA.SimpleData.XBytes, extractedA.SimpleData.XBytes);
+ CollectionAssert.AreEqual(originalA.SimpleData.YBytes, extractedA.SimpleData.YBytes);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void ReadFontBytes_TableLengthBeyondFile_Throws()
+ {
+ var ttc = BuildRobotoTtc(out _);
+ int firstLengthPos = TtcHeaderSize + 12 + 12; // first table record, length field
+ WriteUInt32(ttc, firstLengthPos, 0xFFFFFFF0);
+
+ Assert.ThrowsExactly(() => ReadFromTempFile(ttc, TtcHeaderSize));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void ReadFontBytes_OverlappingTables_Throws()
+ {
+ // A small TTC where 1000 table records all point to the whole file.
+ const ushort numTables = 1000;
+ int fileLength = TtcHeaderSize + 12 + numTables * 16;
+ var ttc = new byte[fileLength];
+ WriteTtcHeader(ttc, 1, TtcHeaderSize);
+ WriteUInt32(ttc, TtcHeaderSize, 0x00010000); // sfntVersion
+ WriteUInt16(ttc, TtcHeaderSize + 4, numTables);
+
+ for (int i = 0; i < numTables; i++)
+ {
+ int record = TtcHeaderSize + 12 + i * 16;
+ WriteUInt32(ttc, record, 0x74737431 + (uint)i); // unique tag
+ WriteUInt32(ttc, record + 8, 0); // offset
+ WriteUInt32(ttc, record + 12, (uint)fileLength); // length = whole file
+ }
+
+ Assert.ThrowsExactly(() => ReadFromTempFile(ttc, TtcHeaderSize));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void ReadFontBytes_DirectoryBeyondFile_Throws()
+ {
+ // The SFNT header claims 10 tables, but the file ends right after the header.
+ var ttc = new byte[TtcHeaderSize + 12];
+ WriteTtcHeader(ttc, 1, TtcHeaderSize);
+ WriteUInt32(ttc, TtcHeaderSize, 0x00010000);
+ WriteUInt16(ttc, TtcHeaderSize + 4, 10);
+
+ Assert.ThrowsExactly(() => ReadFromTempFile(ttc, TtcHeaderSize));
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Helpers/GsubTestFontBuilder.cs b/src/EPPlus.Fonts.OpenType.Tests/Helpers/GsubTestFontBuilder.cs
new file mode 100644
index 0000000000..5cee0c09ec
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Helpers/GsubTestFontBuilder.cs
@@ -0,0 +1,97 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Helper that gives a test font a crafted GSUB table
+ *************************************************************************************************/
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.Text;
+
+namespace EPPlus.Fonts.OpenType.Tests
+{
+ ///
+ /// Builds test fonts whose GSUB table is replaced by a crafted one, appended to the end of the
+ /// font file so it can be as large as needed.
+ ///
+ internal static class GsubTestFontBuilder
+ {
+ private static void WriteUInt16(byte[] b, int pos, int v)
+ {
+ b[pos] = (byte)(v >> 8);
+ b[pos + 1] = (byte)v;
+ }
+
+ private static void WriteUInt32(byte[] b, int pos, uint v)
+ {
+ b[pos] = (byte)(v >> 24);
+ b[pos + 1] = (byte)(v >> 16);
+ b[pos + 2] = (byte)(v >> 8);
+ b[pos + 3] = (byte)v;
+ }
+
+ /// Returns the position of the table record with the given tag in the table directory.
+ internal static int RecordPosition(byte[] font, string tag)
+ {
+ int numTables = (font[4] << 8) | font[5];
+ for (int i = 0; i < numTables; i++)
+ {
+ int record = 12 + i * 16;
+ if (Encoding.ASCII.GetString(font, record, 4) == tag)
+ return record;
+ }
+ throw new AssertFailedException("Table " + tag + " not found");
+ }
+
+ ///
+ /// Returns a copy of whose GSUB is one Multiple Substitution lookup that
+ /// replaces the glyph for with . The new
+ /// GSUB has no ScriptList or FeatureList and is appended to the end of the file.
+ ///
+ internal static byte[] AppendMultipleSubst(byte[] font, char trigger, ushort[] sequence)
+ {
+ Assert.IsTrue(new OpenTypeFont(font).CmapTable.TryGetGlyphId(trigger, out ushort triggerGlyph));
+
+ int gsub = (font.Length + 3) & ~3;
+ int length = 36 + 2 + 2 * sequence.Length;
+ var bytes = new byte[gsub + length];
+ Array.Copy(font, bytes, font.Length);
+
+ int record = RecordPosition(bytes, "GSUB");
+ WriteUInt32(bytes, record + 8, (uint)gsub);
+ WriteUInt32(bytes, record + 12, (uint)length);
+
+ // GSUB header: version 1.0, no ScriptList or FeatureList, LookupList at 10
+ WriteUInt16(bytes, gsub, 1);
+ WriteUInt16(bytes, gsub + 8, 10);
+ // LookupList (10): one lookup at +4
+ WriteUInt16(bytes, gsub + 10, 1);
+ WriteUInt16(bytes, gsub + 12, 4);
+ // Lookup (14): type 2 (Multiple Substitution), one subtable at +8
+ WriteUInt16(bytes, gsub + 14, 2);
+ WriteUInt16(bytes, gsub + 18, 1);
+ WriteUInt16(bytes, gsub + 20, 8);
+ // MultipleSubst format 1 (22): coverage at +8, one sequence at +14
+ WriteUInt16(bytes, gsub + 22, 1);
+ WriteUInt16(bytes, gsub + 24, 8);
+ WriteUInt16(bytes, gsub + 26, 1);
+ WriteUInt16(bytes, gsub + 28, 14);
+ // Coverage format 1 (30): the trigger glyph
+ WriteUInt16(bytes, gsub + 30, 1);
+ WriteUInt16(bytes, gsub + 32, 1);
+ WriteUInt16(bytes, gsub + 34, triggerGlyph);
+ // Sequence (36)
+ WriteUInt16(bytes, gsub + 36, sequence.Length);
+ for (int i = 0; i < sequence.Length; i++)
+ WriteUInt16(bytes, gsub + 38 + 2 * i, sequence[i]);
+
+ return bytes;
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Serialization/LayoutLookupOverflowTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Serialization/LayoutLookupOverflowTests.cs
new file mode 100644
index 0000000000..eb5f64c5b5
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Serialization/LayoutLookupOverflowTests.cs
@@ -0,0 +1,170 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for GSUB/GPOS lookup lists over 64 KB
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables;
+using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage;
+using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups;
+using EPPlus.Fonts.OpenType.Tables.Gpos;
+using EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups.LookupType2;
+using EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace EPPlus.Fonts.OpenType.Tests.Serialization
+{
+ ///
+ /// Tests that a GSUB or GPOS lookup list too large for 16-bit offsets is written with Extension
+ /// lookups (32-bit offsets), and that lists that fit are written as before, without them.
+ ///
+ [TestClass]
+ public class LayoutLookupOverflowTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private static OpenTypeFont LoadTestFont(string fileName)
+ {
+ return new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, fileName)));
+ }
+
+ /// XAdvance adjustments for the pair: for every lookup, the first matching subtable applies.
+ private static (int first, int second) Kerning(GposTable gpos, ushort a, ushort b)
+ {
+ int first = 0, second = 0;
+ foreach (var lookup in gpos.LookupList.Lookups)
+ {
+ foreach (var subtable in lookup.SubTables)
+ {
+ if (subtable is PairPosSubTable pairPos && pairPos.TryGetPairAdjustment(a, b, out var value1, out var value2))
+ {
+ first += value1?.XAdvance ?? 0;
+ second += value2?.XAdvance ?? 0;
+ break;
+ }
+ }
+ }
+ return (first, second);
+ }
+
+ private static string CharRange(params (int first, int last)[] ranges)
+ {
+ var sb = new StringBuilder();
+ foreach (var (first, last) in ranges)
+ for (int c = first; c <= last; c++)
+ sb.Append((char)c);
+ return sb.ToString();
+ }
+
+ private static int ReadUInt16(byte[] b, int pos) => (b[pos] << 8) | b[pos + 1];
+
+ private static long ReadUInt32(byte[] b, int pos) =>
+ ((long)b[pos] << 24) | ((long)b[pos + 1] << 16) | ((long)b[pos + 2] << 8) | b[pos + 3];
+
+ [TestMethod]
+ [Timeout(60000)]
+ public void Subset_LargeGpos_RoundTripsWithSameKerning()
+ {
+ // The GPOS of this subset is about 85 KB. Oi itself uses an Extension lookup for that.
+ var font = LoadTestFont("Oi-Regular.ttf");
+ string text = CharRange((0x20, 0x7E), (0xA0, 0x17F), (0x391, 0x3C9), (0x410, 0x44F));
+
+ var subset = font.CreateSubset(text.ToCharArray());
+ var reparsed = new OpenTypeFont(subset.Serialize());
+
+ Assert.IsTrue(reparsed.GposTable.LookupList.Lookups.Any(l => l.LookupType == 9),
+ "A GPOS lookup list over 64 KB must be written with Extension lookups.");
+ var map = subset.SubsetGlyphMapping;
+ foreach (var a in map.Keys)
+ {
+ foreach (var b in map.Keys)
+ {
+ var expected = Kerning(font.GposTable, a, b);
+ var actual = Kerning(reparsed.GposTable, map[a], map[b]);
+ if (expected != actual)
+ Assert.Fail($"Pair {a}-{b}: expected {expected}, got {actual}.");
+ }
+ }
+ }
+
+ [TestMethod]
+ [Timeout(10000)]
+ public void Subset_SmallLayoutTables_WrittenWithoutExtensionLookups()
+ {
+ var font = LoadTestFont("Roboto-Regular.ttf");
+
+ var subset = font.CreateSubset("Hello".ToCharArray());
+ var reparsed = new OpenTypeFont(subset.Serialize());
+
+ Assert.IsTrue(reparsed.GposTable.LookupList.Lookups.Count > 0);
+ Assert.IsFalse(reparsed.GposTable.LookupList.Lookups.Any(l => l.LookupType == 9));
+ Assert.IsFalse(reparsed.GsubTable.LookupList.Lookups.Any(l => l.LookupType == 7));
+ }
+
+ [TestMethod]
+ [Timeout(10000)]
+ public void LookupList_OverflowingGsub_WrittenAsExtensionLookups()
+ {
+ // Three lookups of about 60 KB each: the third lookup starts beyond 64 KB.
+ const int glyphCount = 30000;
+ var list = new LookupListTable { ExtensionLookupType = 7 };
+ for (int i = 0; i < 3; i++)
+ {
+ int start = 1000 * (i + 1);
+ var glyphs = Enumerable.Range(start, glyphCount).Select(g => (ushort)g).ToList();
+ list.Lookups.Add(new LookupTable
+ {
+ LookupType = 1,
+ SubTables = new List
+ {
+ new SingleSubstSubTableFormat2
+ {
+ SubtableFormat = 2,
+ Coverage = CoverageTableFormat2.CreateCoverageFormat2(glyphs),
+ GlyphCount = glyphCount,
+ SubstituteGlyphIDs = glyphs.Select(g => (ushort)(g + 1)).ToArray()
+ }
+ }
+ });
+ }
+
+ byte[] bytes;
+ using (var stream = new MemoryStream())
+ using (var writer = new FontsBinaryWriter(stream))
+ {
+ list.Serialize(writer);
+ writer.Flush();
+ bytes = stream.ToArray();
+ }
+
+ Assert.AreEqual(3, ReadUInt16(bytes, 0));
+ for (int i = 0; i < 3; i++)
+ {
+ int lookup = ReadUInt16(bytes, 2 + 2 * i);
+ Assert.AreEqual(7, ReadUInt16(bytes, lookup), "Lookup type must be Extension Substitution.");
+ Assert.AreEqual(1, ReadUInt16(bytes, lookup + 4), "One subtable.");
+ int extension = lookup + ReadUInt16(bytes, lookup + 6);
+ Assert.AreEqual(1, ReadUInt16(bytes, extension), "Extension format.");
+ Assert.AreEqual(1, ReadUInt16(bytes, extension + 2), "Inner lookup type: single substitution.");
+ int subTable = (int)(extension + ReadUInt32(bytes, extension + 4));
+ Assert.AreEqual(2, ReadUInt16(bytes, subTable), "Single substitution format 2.");
+ Assert.AreEqual(glyphCount, ReadUInt16(bytes, subTable + 4));
+ int start = 1000 * (i + 1);
+ Assert.AreEqual(start + 1, ReadUInt16(bytes, subTable + 6), "First substitute glyph.");
+ int coverage = subTable + ReadUInt16(bytes, subTable + 2);
+ Assert.AreEqual(2, ReadUInt16(bytes, coverage), "Coverage format 2.");
+ Assert.AreEqual(start, ReadUInt16(bytes, coverage + 4), "First covered glyph.");
+ }
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GsubSubsetRecursionTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GsubSubsetRecursionTests.cs
new file mode 100644
index 0000000000..01d8c31d69
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/GsubSubsetRecursionTests.cs
@@ -0,0 +1,148 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for GSUB discovery with chaining lookups
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tests.Helpers;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.IO;
+using System.Linq;
+
+namespace EPPlus.Fonts.OpenType.Tests.Subsetting
+{
+ ///
+ /// Tests GSUB glyph discovery during subsetting with chaining contextual lookups (type 6).
+ /// The fonts are Roboto-Regular.ttf with the GSUB table contents replaced by hand-built lookups.
+ ///
+ [TestClass]
+ public class GsubSubsetRecursionTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private static void WriteUInt16(byte[] b, int pos, int v)
+ {
+ b[pos] = (byte)(v >> 8);
+ b[pos + 1] = (byte)v;
+ }
+
+ private static ushort GlyphOf(OpenTypeFont font, char c)
+ {
+ Assert.IsTrue(font.CmapTable.TryGetGlyphId(c, out ushort gid), "No glyph for '" + c + "'");
+ return gid;
+ }
+
+ ///
+ /// Clears Roboto's GSUB table and writes the header (version 1.0, no ScriptList or FeatureList,
+ /// LookupList at offset 10). Returns the font bytes and the absolute GSUB offset.
+ ///
+ private static byte[] PrepareGsub(out int gsub, out OpenTypeFont original)
+ {
+ var bytes = File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"));
+ original = new OpenTypeFont((byte[])bytes.Clone());
+ FontTestHelper.FindTableInDirectory(bytes, "GSUB", out gsub, out int gsubLength);
+ Array.Clear(bytes, gsub, gsubLength);
+
+ WriteUInt16(bytes, gsub + 0, 1); // MajorVersion
+ WriteUInt16(bytes, gsub + 2, 0); // MinorVersion
+ WriteUInt16(bytes, gsub + 8, 10); // LookupList offset
+ return bytes;
+ }
+
+ ///
+ /// Writes a ChainingContextSubstFormat3 subtable with one input coverage (format 1) and one
+ /// SubstLookupRecord. Returns the number of bytes written.
+ ///
+ private static int WriteChainingSubtable(byte[] b, int pos, ushort[] coverageGlyphs, int referencedLookup)
+ {
+ WriteUInt16(b, pos + 0, 3); // SubstFormat
+ WriteUInt16(b, pos + 2, 0); // BacktrackGlyphCount
+ WriteUInt16(b, pos + 4, 1); // InputGlyphCount
+ WriteUInt16(b, pos + 6, 16); // InputCoverage offset
+ WriteUInt16(b, pos + 8, 0); // LookaheadGlyphCount
+ WriteUInt16(b, pos + 10, 1); // SubstCount
+ WriteUInt16(b, pos + 12, 0); // SequenceIndex
+ WriteUInt16(b, pos + 14, referencedLookup);
+ WriteUInt16(b, pos + 16, 1); // Coverage format 1
+ WriteUInt16(b, pos + 18, coverageGlyphs.Length);
+ for (int i = 0; i < coverageGlyphs.Length; i++)
+ WriteUInt16(b, pos + 20 + 2 * i, coverageGlyphs[i]);
+ return 20 + 2 * coverageGlyphs.Length;
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void CreateSubset_SelfReferencingChainingLookup_Completes()
+ {
+ var bytes = PrepareGsub(out int gsub, out var original);
+ ushort space = GlyphOf(original, ' ');
+ ushort a = GlyphOf(original, 'a');
+
+ // LookupList at 10: one lookup at offset 4 -> absolute 14
+ WriteUInt16(bytes, gsub + 10, 1);
+ WriteUInt16(bytes, gsub + 12, 4);
+ // Lookup 0 at 14: type 6, one subtable at offset 8 -> absolute 22, which references lookup 0
+ WriteUInt16(bytes, gsub + 14, 6);
+ WriteUInt16(bytes, gsub + 18, 1);
+ WriteUInt16(bytes, gsub + 20, 8);
+ WriteChainingSubtable(bytes, gsub + 22, new[] { space, a }.OrderBy(g => g).ToArray(), 0);
+
+ var font = new OpenTypeFont(bytes);
+ var subset = font.CreateSubset("a");
+
+ Assert.IsNotNull(subset);
+ Assert.IsTrue(subset.CmapTable.TryGetGlyphId('a', out _));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void CreateSubset_ChainingLookupReferencingSingleSubst_IncludesSubstitute()
+ {
+ var bytes = PrepareGsub(out int gsub, out var original);
+ ushort a = GlyphOf(original, 'a');
+ ushort b = GlyphOf(original, 'b');
+
+ // LookupList at 10: two lookups, at offsets 6 (absolute 16) and 36 (absolute 46)
+ WriteUInt16(bytes, gsub + 10, 2);
+ WriteUInt16(bytes, gsub + 12, 6);
+ WriteUInt16(bytes, gsub + 14, 36);
+
+ // Lookup 0 at 16: type 6, one subtable at offset 8 -> absolute 24, which references lookup 1
+ WriteUInt16(bytes, gsub + 16, 6);
+ WriteUInt16(bytes, gsub + 20, 1);
+ WriteUInt16(bytes, gsub + 22, 8);
+ int written = WriteChainingSubtable(bytes, gsub + 24, new[] { a }, 1);
+ Assert.AreEqual(22, written); // ends at 46, where lookup 1 starts
+
+ // Lookup 1 at 46: type 1, one subtable at offset 8 -> absolute 54
+ WriteUInt16(bytes, gsub + 46, 1);
+ WriteUInt16(bytes, gsub + 50, 1);
+ WriteUInt16(bytes, gsub + 52, 8);
+ // SingleSubst format 2 at 54: 'a' -> 'b', coverage at offset 8 -> absolute 62
+ WriteUInt16(bytes, gsub + 54, 2);
+ WriteUInt16(bytes, gsub + 56, 8);
+ WriteUInt16(bytes, gsub + 58, 1);
+ WriteUInt16(bytes, gsub + 60, b);
+ WriteUInt16(bytes, gsub + 62, 1);
+ WriteUInt16(bytes, gsub + 64, 1);
+ WriteUInt16(bytes, gsub + 66, a);
+
+ var font = new OpenTypeFont(bytes);
+ var subset = font.CreateSubset("a");
+
+ // The subset has no cmap entry for 'b' (it is not in the text), so look for its outline.
+ var originalB = original.GlyfTable.GetGlyph(b).SimpleData;
+ bool hasB = subset.GlyfTable.Glyphs.Any(g => g?.SimpleData != null &&
+ g.SimpleData.XBytes.SequenceEqual(originalB.XBytes) &&
+ g.SimpleData.YBytes.SequenceEqual(originalB.YBytes));
+ Assert.IsTrue(hasB, "The glyph reached through the chaining lookup must be in the subset.");
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PairPosFormat2SubsettingTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PairPosFormat2SubsettingTests.cs
new file mode 100644
index 0000000000..095c31c30f
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/PairPosFormat2SubsettingTests.cs
@@ -0,0 +1,248 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for subsetting class-based pair kerning
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Gpos;
+using EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups.LookupType2;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.IO;
+using System.Linq;
+using System.Text;
+
+namespace EPPlus.Fonts.OpenType.Tests.Subsetting
+{
+ ///
+ /// Tests that class-based pair kerning (GPOS PairPos format 2) is kept as format 2 when a font
+ /// is subset: only the classes used by the subset remain, every glyph pair keeps the adjustment
+ /// it has in the original font (also pairs of the same glyph), the result survives serialization
+ /// and the work does not grow with the subset size squared.
+ ///
+ [TestClass]
+ public class PairPosFormat2SubsettingTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private static OpenTypeFont LoadTestFont(string fileName)
+ {
+ return new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, fileName)));
+ }
+
+ ///
+ /// The XAdvance adjustments a shaper gets for the pair: for every pair positioning lookup,
+ /// the first subtable that matches applies.
+ ///
+ private static (int first, int second) Kerning(GposTable gpos, ushort a, ushort b)
+ {
+ int first = 0, second = 0;
+ foreach (var lookup in gpos.LookupList.Lookups)
+ {
+ foreach (var subtable in lookup.SubTables)
+ {
+ if (subtable is PairPosSubTable pairPos && pairPos.TryGetPairAdjustment(a, b, out var value1, out var value2))
+ {
+ first += value1?.XAdvance ?? 0;
+ second += value2?.XAdvance ?? 0;
+ break;
+ }
+ }
+ }
+ return (first, second);
+ }
+
+ /// Asserts that every glyph pair of the subset has the same kerning as in the original.
+ private static void AssertSameKerning(OpenTypeFont original, OpenTypeFont subset, GposTable subsetGpos)
+ {
+ var map = subset.SubsetGlyphMapping;
+ int compared = 0;
+ foreach (var a in map.Keys)
+ {
+ foreach (var b in map.Keys)
+ {
+ var expected = Kerning(original.GposTable, a, b);
+ var actual = Kerning(subsetGpos, map[a], map[b]);
+ if (expected != actual)
+ Assert.Fail($"Pair {a}-{b}: expected {expected}, got {actual}.");
+ compared++;
+ }
+ }
+ Assert.IsTrue(compared > 0);
+ }
+
+ private static string CharRange(params (int first, int last)[] ranges)
+ {
+ var sb = new StringBuilder();
+ foreach (var (first, last) in ranges)
+ for (int c = first; c <= last; c++)
+ sb.Append((char)c);
+ return sb.ToString();
+ }
+
+ [TestMethod]
+ [Timeout(10000)]
+ public void Subset_ClassKerning_KeptAsFormat2WithSameAdjustments()
+ {
+ var font = LoadTestFont("Roboto-Regular.ttf");
+
+ var subset = font.CreateSubset("Hello World AVATAR Toyota WAVE".ToCharArray());
+
+ Assert.IsTrue(subset.GposTable.LookupList.Lookups.SelectMany(l => l.SubTables).Any(s => s is PairPosSubTableFormat2),
+ "Class-based kerning must stay format 2 in the subset.");
+ AssertSameKerning(font, subset, subset.GposTable);
+ }
+
+ [TestMethod]
+ [Timeout(10000)]
+ public void Subset_ClassKerning_UnusedClassesRemoved()
+ {
+ var font = LoadTestFont("Roboto-Regular.ttf");
+ var original = font.GposTable.LookupList.Lookups.SelectMany(l => l.SubTables).OfType().First();
+
+ var subset = font.CreateSubset("To".ToCharArray());
+ var subsetTables = subset.GposTable.LookupList.Lookups.SelectMany(l => l.SubTables).OfType().ToList();
+
+ Assert.AreEqual(1, subsetTables.Count);
+ var table = subsetTables[0];
+ // Every glyph has one class, and class 0 is always kept, so the subset cannot use more
+ // classes than it has glyphs plus one.
+ int glyphCount = subset.SubsetGlyphMapping.Count;
+ Assert.IsTrue(table.Class1Count <= glyphCount + 1 && table.Class1Count < original.Class1Count,
+ $"Class1Count {table.Class1Count} (original {original.Class1Count}, glyphs {glyphCount})");
+ Assert.IsTrue(table.Class2Count <= glyphCount + 1 && table.Class2Count < original.Class2Count,
+ $"Class2Count {table.Class2Count} (original {original.Class2Count}, glyphs {glyphCount})");
+ Assert.AreEqual(table.Class1Count, table.ClassMatrix.GetLength(0));
+ Assert.AreEqual(table.Class2Count, table.ClassMatrix.GetLength(1));
+ AssertSameKerning(font, subset, subset.GposTable);
+ }
+
+ [TestMethod]
+ [Timeout(10000)]
+ public void Subset_ClassKerning_SameGlyphPairKept()
+ {
+ var font = LoadTestFont("Roboto-Regular.ttf");
+ Assert.IsTrue(font.CmapTable.TryGetGlyphId('T', out ushort t));
+ var expected = Kerning(font.GposTable, t, t);
+ Assert.AreNotEqual((0, 0), expected, "Roboto is expected to kern T followed by T.");
+
+ var subset = font.CreateSubset("TT".ToCharArray());
+ ushort newT = subset.SubsetGlyphMapping[t];
+
+ Assert.AreEqual(expected, Kerning(subset.GposTable, newT, newT));
+ }
+
+ [TestMethod]
+ [Timeout(60000)]
+ public void Subset_ClassKerningWithManyGlyphs_RoundTripsWithSameAdjustments()
+ {
+ // Expanded to glyph pairs, this subset of Oi's class kerning no longer fit the 16-bit offsets
+ // of a PairPos subtable and was corrupted when serialized. Kept as format 2 it fits.
+ var font = LoadTestFont("Oi-Regular.ttf");
+ string text = CharRange((0x20, 0x7E), (0xA0, 0x17F));
+
+ var subset = font.CreateSubset(text.ToCharArray());
+ var reparsed = new OpenTypeFont(subset.Serialize());
+
+ AssertSameKerning(font, subset, reparsed.GposTable);
+ }
+
+ private static void WriteUInt16(byte[] b, int pos, int v)
+ {
+ b[pos] = (byte)(v >> 8);
+ b[pos + 1] = (byte)v;
+ }
+
+ private static void WriteUInt32(byte[] b, int pos, uint v)
+ {
+ b[pos] = (byte)(v >> 24);
+ b[pos + 1] = (byte)(v >> 16);
+ b[pos + 2] = (byte)(v >> 8);
+ b[pos + 3] = (byte)v;
+ }
+
+
+ ///
+ /// Returns a copy of whose GPOS is one PairPos format 2 subtable that
+ /// covers glyphs 0-65534 with a single class pair (XAdvance -10), appended to the end of the file.
+ ///
+ private static byte[] AppendClassKerningForEveryGlyph(byte[] font)
+ {
+ int gpos = (font.Length + 3) & ~3;
+ const int length = 72;
+ var bytes = new byte[gpos + length];
+ Array.Copy(font, bytes, font.Length);
+
+ int record = GsubTestFontBuilder.RecordPosition(bytes, "GPOS");
+ WriteUInt32(bytes, record + 8, (uint)gpos);
+ WriteUInt32(bytes, record + 12, length);
+
+ // GPOS header: version 1.0, no ScriptList, FeatureList at 10, LookupList at 24
+ WriteUInt16(bytes, gpos, 1);
+ WriteUInt16(bytes, gpos + 6, 10);
+ WriteUInt16(bytes, gpos + 8, 24);
+ // FeatureList (10): one "kern" feature at +8 that uses lookup 0
+ WriteUInt16(bytes, gpos + 10, 1);
+ Encoding.ASCII.GetBytes("kern").CopyTo(bytes, gpos + 12);
+ WriteUInt16(bytes, gpos + 16, 8);
+ WriteUInt16(bytes, gpos + 20, 1); // Feature (18): no params, one lookup index (0)
+ // LookupList (24): one lookup at +4
+ WriteUInt16(bytes, gpos + 24, 1);
+ WriteUInt16(bytes, gpos + 26, 4);
+ // Lookup (28): type 2 (PairPos), one subtable at +8
+ WriteUInt16(bytes, gpos + 28, 2);
+ WriteUInt16(bytes, gpos + 32, 1);
+ WriteUInt16(bytes, gpos + 34, 8);
+ // PairPos format 2 (36): coverage +18, ValueFormat1 XAdvance, ClassDef1 +28, ClassDef2 +32, 1x1 classes
+ int s = gpos + 36;
+ WriteUInt16(bytes, s, 2);
+ WriteUInt16(bytes, s + 2, 18);
+ WriteUInt16(bytes, s + 4, 0x0004);
+ WriteUInt16(bytes, s + 6, 0);
+ WriteUInt16(bytes, s + 8, 28);
+ WriteUInt16(bytes, s + 10, 32);
+ WriteUInt16(bytes, s + 12, 1);
+ WriteUInt16(bytes, s + 14, 1);
+ WriteUInt16(bytes, s + 16, -10); // matrix [0,0]: XAdvance -10
+ // Coverage format 2 (s+18): one range 0-65534
+ WriteUInt16(bytes, s + 18, 2);
+ WriteUInt16(bytes, s + 20, 1);
+ WriteUInt16(bytes, s + 22, 0);
+ WriteUInt16(bytes, s + 24, 65534);
+ WriteUInt16(bytes, s + 26, 0);
+ // ClassDef1 and ClassDef2 (s+28, s+32): format 2 without ranges, so every glyph is class 0
+ WriteUInt16(bytes, s + 28, 2);
+ WriteUInt16(bytes, s + 32, 2);
+ return bytes;
+ }
+
+ [TestMethod]
+ [Timeout(30000)]
+ public void Subset_ClassKerningCoveringEveryGlyph_CompletesQuickly()
+ {
+ // A GSUB substitution pulls all 5130 glyphs of the font into the subset and one class
+ // kerning rule covers every glyph. Expanded to glyph pairs that is about 26 million pairs
+ // (and grows with the square of the glyph count, up to 65535); kept as format 2 it is a
+ // 1x1 class matrix.
+ var bytes = File.ReadAllBytes(Path.Combine(FontFolder, "NotoSansMath-Regular.ttf"));
+ int numGlyphs = new OpenTypeFont(bytes).MaxpTable.numGlyphs;
+ var sequence = Enumerable.Range(1, numGlyphs - 1).Select(g => (ushort)g).ToArray();
+ bytes = GsubTestFontBuilder.AppendMultipleSubst(bytes, 'a', sequence);
+ var font = new OpenTypeFont(AppendClassKerningForEveryGlyph(bytes));
+
+ var subset = font.CreateSubset("a".ToCharArray());
+
+ Assert.AreEqual(numGlyphs, subset.SubsetGlyphMapping.Count);
+ var table = subset.GposTable.LookupList.Lookups.SelectMany(l => l.SubTables).OfType().Single();
+ Assert.AreEqual(1, table.Class1Count);
+ Assert.AreEqual(1, table.Class2Count);
+ Assert.AreEqual((-10, 0), Kerning(subset.GposTable, 1, 2));
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetGlyphRangeTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetGlyphRangeTests.cs
new file mode 100644
index 0000000000..3a2cd12264
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Subsetting/SubsetGlyphRangeTests.cs
@@ -0,0 +1,73 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for glyph IDs outside the font in subsetting
+ *************************************************************************************************/
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.IO;
+using System.Linq;
+
+namespace EPPlus.Fonts.OpenType.Tests.Subsetting
+{
+ ///
+ /// Tests that glyph IDs which a GSUB table references but which do not exist in the font are
+ /// left out of the subset. Before, a substitution to every glyph ID (0-65535) made the glyph
+ /// mapping loop wrap around its ushort counter and never finish.
+ /// The font is Roboto-Regular.ttf with a crafted GSUB table appended to the end of the file.
+ ///
+ [TestClass]
+ public class SubsetGlyphRangeTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ ///
+ /// Roboto whose GSUB is replaced by one Multiple Substitution lookup that replaces the glyph
+ /// for 'a' with .
+ ///
+ private static byte[] BuildFontWithMultipleSubst(ushort[] sequence)
+ {
+ var roboto = File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"));
+ return GsubTestFontBuilder.AppendMultipleSubst(roboto, 'a', sequence);
+ }
+
+ [TestMethod]
+ [Timeout(10000)]
+ public void CreateSubset_SubstitutionToEveryGlyphId_Completes()
+ {
+ // Glyphs 1..65535; together with .notdef that is every possible glyph ID.
+ var sequence = Enumerable.Range(1, 65535).Select(g => (ushort)g).ToArray();
+ var font = new OpenTypeFont(BuildFontWithMultipleSubst(sequence));
+ int numGlyphs = font.MaxpTable.numGlyphs;
+
+ var subset = font.CreateSubset("a".ToCharArray());
+
+ Assert.IsTrue(subset.SubsetGlyphMapping.Keys.All(g => g < numGlyphs),
+ "Only glyphs that exist in the font may be in the subset.");
+ Assert.IsTrue(subset.MaxpTable.numGlyphs > 0 && subset.MaxpTable.numGlyphs <= numGlyphs);
+ Assert.AreEqual(subset.SubsetGlyphMapping.Count, subset.MaxpTable.numGlyphs);
+ Assert.IsTrue(subset.Serialize().Length > 0);
+ }
+
+ [TestMethod]
+ [Timeout(10000)]
+ public void CreateSubset_SubstitutionToMissingGlyphs_OnlyExistingGlyphsIncluded()
+ {
+ var font = new OpenTypeFont(BuildFontWithMultipleSubst(new ushort[] { 5, 60000, 60001 }));
+ Assert.IsTrue(font.MaxpTable.numGlyphs < 60000);
+
+ var subset = font.CreateSubset("a".ToCharArray());
+
+ Assert.IsTrue(subset.SubsetGlyphMapping.ContainsKey(5));
+ Assert.IsFalse(subset.SubsetGlyphMapping.ContainsKey(60000));
+ Assert.IsFalse(subset.SubsetGlyphMapping.ContainsKey(60001));
+ Assert.IsTrue(subset.Serialize().Length > 0);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/BasicTableReadBudgetTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/BasicTableReadBudgetTests.cs
new file mode 100644
index 0000000000..76acbcb6c8
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/BasicTableReadBudgetTests.cs
@@ -0,0 +1,259 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for the read budget of cmap, kern and name
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Scanner;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.IO;
+using System.Text;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables
+{
+ ///
+ /// Tests that cmap, kern and name tables whose offsets make the parser read the same data over
+ /// and over are stopped by the read budget. kern is optional and is ignored with a warning;
+ /// a font cannot be used without cmap or name, so the font is rejected with InvalidDataException.
+ /// The malformed fonts are Roboto-Regular.ttf with one table replaced.
+ ///
+ [TestClass]
+ public class BasicTableReadBudgetTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private static byte[] LoadRoboto()
+ {
+ return File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"));
+ }
+
+ private static void WriteUInt16(byte[] b, int pos, int v)
+ {
+ b[pos] = (byte)(v >> 8);
+ b[pos + 1] = (byte)v;
+ }
+
+ private static void WriteUInt32(byte[] b, int pos, uint v)
+ {
+ b[pos] = (byte)(v >> 24);
+ b[pos + 1] = (byte)(v >> 16);
+ b[pos + 2] = (byte)(v >> 8);
+ b[pos + 3] = (byte)v;
+ }
+
+ private static uint ReadUInt32(byte[] b, int pos)
+ {
+ return (uint)((b[pos] << 24) | (b[pos + 1] << 16) | (b[pos + 2] << 8) | b[pos + 3]);
+ }
+
+ /// Returns the position of the table record with the given tag in the table directory.
+ private static int RecordPosition(byte[] font, string tag)
+ {
+ int numTables = (font[4] << 8) | font[5];
+ for (int i = 0; i < numTables; i++)
+ {
+ int record = 12 + i * 16;
+ if (Encoding.ASCII.GetString(font, record, 4) == tag)
+ return record;
+ }
+ throw new AssertFailedException("Table " + tag + " not found");
+ }
+
+ ///
+ /// Points the table record at the glyf table's data (about 125 KB),
+ /// clears that data and returns its offset, so a large crafted table can be written there.
+ ///
+ private static int RedirectToGlyfArea(byte[] font, string tag, out int length)
+ {
+ int glyfRecord = RecordPosition(font, "glyf");
+ int offset = (int)ReadUInt32(font, glyfRecord + 8);
+ length = (int)ReadUInt32(font, glyfRecord + 12);
+ int record = RecordPosition(font, tag);
+ WriteUInt32(font, record + 8, (uint)offset);
+ WriteUInt32(font, record + 12, (uint)length);
+ Array.Clear(font, offset, length);
+ return offset;
+ }
+
+ ///
+ /// Roboto has no kern table, so the hdmx record (1304 bytes) is renamed to kern and filled with:
+ /// 65535 subtables whose length is 0, so every one of them re-reads the same first subtable
+ /// (214 pairs). Without a budget that is about 85 MB of reads and 14 million pairs.
+ ///
+ private static byte[] BuildFontWithAmplifyingKern()
+ {
+ var bytes = LoadRoboto();
+ int record = RecordPosition(bytes, "hdmx");
+ Encoding.ASCII.GetBytes("kern").CopyTo(bytes, record);
+ int kern = (int)ReadUInt32(bytes, record + 8);
+ int length = (int)ReadUInt32(bytes, record + 12);
+ Array.Clear(bytes, kern, length);
+
+ int pairCount = (length - 4 - 6 - 8) / 6;
+ WriteUInt16(bytes, kern, 0); // version
+ WriteUInt16(bytes, kern + 2, 65535); // nTables
+ WriteUInt16(bytes, kern + 4, 0); // subtable version
+ WriteUInt16(bytes, kern + 6, 0); // subtable length 0: the position never advances
+ WriteUInt16(bytes, kern + 8, 0x0001); // coverage: horizontal, format 0
+ WriteUInt16(bytes, kern + 10, pairCount); // nPairs (search fields left 0)
+ for (int i = 0; i < pairCount; i++)
+ {
+ int pair = kern + 18 + 6 * i;
+ WriteUInt16(bytes, pair, 1); // left
+ WriteUInt16(bytes, pair + 2, i + 2); // right
+ WriteUInt16(bytes, pair + 4, -10); // value
+ }
+ return bytes;
+ }
+
+ ///
+ /// cmap with one format 14 subtable: 200 variation selectors whose default UVS offsets all
+ /// point to the same table of 17000 ranges. Without a budget that is about 13.6 MB of reads
+ /// from a 125 KB table.
+ ///
+ private static byte[] BuildFontWithAmplifyingCmap()
+ {
+ const int selectorCount = 200;
+ const int rangeCount = 17000;
+
+ var bytes = LoadRoboto();
+ int cmap = RedirectToGlyfArea(bytes, "cmap", out int length);
+
+ int subtable = 12;
+ int defaultUvs = 10 + 11 * selectorCount; // relative to the subtable
+ Assert.IsTrue(subtable + defaultUvs + 4 + 4 * rangeCount <= length, "The crafted cmap must fit.");
+
+ WriteUInt16(bytes, cmap, 0); // version
+ WriteUInt16(bytes, cmap + 2, 1); // numTables
+ WriteUInt16(bytes, cmap + 4, 0); // platform: Unicode
+ WriteUInt16(bytes, cmap + 6, 5); // encoding: variation sequences
+ WriteUInt32(bytes, cmap + 8, (uint)subtable);
+
+ int s = cmap + subtable;
+ WriteUInt16(bytes, s, 14); // format
+ WriteUInt32(bytes, s + 2, (uint)(defaultUvs + 4 + 4 * rangeCount)); // length
+ WriteUInt32(bytes, s + 6, selectorCount);
+ for (int i = 0; i < selectorCount; i++)
+ {
+ int rec = s + 10 + 11 * i;
+ int selector = 0xFE00 + i; // varSelector (uint24)
+ bytes[rec] = (byte)(selector >> 16);
+ bytes[rec + 1] = (byte)(selector >> 8);
+ bytes[rec + 2] = (byte)selector;
+ WriteUInt32(bytes, rec + 3, (uint)defaultUvs); // same table every time
+ WriteUInt32(bytes, rec + 7, 0); // no non-default UVS
+ }
+ WriteUInt32(bytes, s + defaultUvs, rangeCount);
+ for (int i = 0; i < rangeCount; i++)
+ {
+ int range = s + defaultUvs + 4 + 4 * i;
+ int start = 0x4E00 + i;
+ bytes[range] = (byte)(start >> 16);
+ bytes[range + 1] = (byte)(start >> 8);
+ bytes[range + 2] = (byte)start;
+ }
+ return bytes;
+ }
+
+ ///
+ /// name table with 100 records that all point to the same 60000-byte string. Without a
+ /// budget that is 6 MB of reads (and decoded strings) from a 125 KB table.
+ ///
+ private static byte[] BuildFontWithAmplifyingName()
+ {
+ const int recordCount = 100;
+ const int stringLength = 60000;
+
+ var bytes = LoadRoboto();
+ int name = RedirectToGlyfArea(bytes, "name", out int length);
+
+ int stringOffset = 6 + 12 * recordCount;
+ Assert.IsTrue(stringOffset + stringLength <= length, "The crafted name table must fit.");
+
+ WriteUInt16(bytes, name, 0); // format
+ WriteUInt16(bytes, name + 2, recordCount);
+ WriteUInt16(bytes, name + 4, stringOffset);
+ for (int i = 0; i < recordCount; i++)
+ {
+ int rec = name + 6 + 12 * i;
+ WriteUInt16(bytes, rec, 3); // platform: Windows
+ WriteUInt16(bytes, rec + 2, 1); // encoding: Unicode BMP
+ WriteUInt16(bytes, rec + 4, 0x0409); // language: en-US
+ WriteUInt16(bytes, rec + 6, i); // nameID
+ WriteUInt16(bytes, rec + 8, stringLength);
+ WriteUInt16(bytes, rec + 10, 0); // same string every time
+ }
+ for (int i = 0; i < stringLength; i += 2)
+ WriteUInt16(bytes, name + stringOffset + i, 'A');
+ return bytes;
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_AmplifyingKern_TableIgnoredWithWarning()
+ {
+ var font = new OpenTypeFont(BuildFontWithAmplifyingKern());
+
+ Assert.IsNull(font.KernTable);
+ Assert.IsNotNull(font.CmapTable, "cmap is not affected and must still load.");
+ Assert.IsNotNull(font.NameTable, "name is not affected and must still load.");
+
+ var warnings = font.LoadWarnings;
+ Assert.AreEqual(1, warnings.Length);
+ StringAssert.Contains(warnings[0], "kern");
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_AmplifyingCmap_ThrowsInvalidDataException()
+ {
+ var bytes = BuildFontWithAmplifyingCmap();
+
+ var ex = Assert.ThrowsExactly(() =>
+ {
+ var font = new OpenTypeFont(bytes);
+ _ = font.CmapTable;
+ });
+ StringAssert.Contains(ex.Message, "cmap");
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_AmplifyingName_ThrowsInvalidDataException()
+ {
+ var bytes = BuildFontWithAmplifyingName();
+
+ var ex = Assert.ThrowsExactly(() =>
+ {
+ var font = new OpenTypeFont(bytes);
+ _ = font.NameTable;
+ });
+ StringAssert.Contains(ex.Message, "name");
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void ScanSingleFace_AmplifyingName_ThrowsInvalidDataException()
+ {
+ string path = Path.Combine(Path.GetTempPath(), "epplus-budgettest-" + Guid.NewGuid().ToString("N") + ".ttf");
+ try
+ {
+ File.WriteAllBytes(path, BuildFontWithAmplifyingName());
+
+ var ex = Assert.ThrowsExactly(() => FontScannerV2Core.ScanSingleFace(path, 0));
+ StringAssert.Contains(ex.Message, "name");
+ }
+ finally
+ {
+ File.Delete(path);
+ }
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable12Tests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable12Tests.cs
new file mode 100644
index 0000000000..4e75ecba2d
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable12Tests.cs
@@ -0,0 +1,107 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 11/30/2026 EPPlus Software AB Tests for malformed format 12 groups
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Cmap;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Linq;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables.Cmap
+{
+ ///
+ /// Tests that CmapSubtable12.GetGlyphMappings() stays bounded for malformed groups
+ /// (endCharCode = 0xFFFFFFFF, end before start, overlapping groups).
+ /// The subtables are built by hand so no font file is needed.
+ ///
+ [TestClass]
+ public class CmapSubtable12Tests
+ {
+ private static CmapSubtable12 CreateSubtable(params (uint start, uint end, uint glyph)[] groups)
+ {
+ var subtable = new CmapSubtable12();
+ foreach (var g in groups)
+ {
+ subtable.Groups.Add(new SequencialMapGroup
+ {
+ StartCharCode = g.start,
+ EndCharCode = g.end,
+ StartGlyphId = g.glyph
+ });
+ }
+ subtable.NumGroups = (uint)groups.Length;
+ return subtable;
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetGlyphMappings_EndCharCodeMaxUInt_TerminatesAndClampsToUnicodeMax()
+ {
+ var subtable = CreateSubtable((0x10FFF0u, 0xFFFFFFFFu, 1u));
+
+ var mappings = subtable.GetGlyphMappings();
+
+ Assert.AreEqual(16, mappings.CharCodeToGlyphIndex.Count);
+ Assert.AreEqual(0x10FFFFu, mappings.CharCodeToGlyphIndex.Keys.Max());
+ Assert.AreEqual((ushort)16, mappings.CharCodeToGlyphIndex[0x10FFFF]);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetGlyphMappings_EndBeforeStart_GroupIsIgnored()
+ {
+ var subtable = CreateSubtable((0x50u, 0x40u, 1u));
+
+ var mappings = subtable.GetGlyphMappings();
+
+ Assert.AreEqual(0, mappings.CharCodeToGlyphIndex.Count);
+ Assert.AreEqual(0, mappings.GlyphIndexToCharCodes.Count);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetGlyphMappings_OverlappingGroups_FirstGroupWinsAndNoDuplicates()
+ {
+ // Both groups cover A-Z, with different glyph ids.
+ var subtable = CreateSubtable(
+ ((uint)'A', (uint)'Z', 10u),
+ ((uint)'A', (uint)'Z', 100u));
+
+ var mappings = subtable.GetGlyphMappings();
+
+ Assert.AreEqual(26, mappings.CharCodeToGlyphIndex.Count);
+ Assert.AreEqual((ushort)10, mappings.CharCodeToGlyphIndex['A']);
+ Assert.AreEqual((ushort)35, mappings.CharCodeToGlyphIndex['Z']);
+
+ // Each code point must occur exactly once in the reverse mapping.
+ var allCharCodes = mappings.GlyphIndexToCharCodes.Values.SelectMany(l => l).ToList();
+ Assert.AreEqual(26, allCharCodes.Count);
+ Assert.AreEqual(26, allCharCodes.Distinct().Count());
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetGlyphMappings_ValidGroups_MappedAsBefore()
+ {
+ var subtable = CreateSubtable(
+ (0x41u, 0x43u, 5u), // A, B, C -> 5, 6, 7
+ (0x1F600u, 0x1F601u, 20u)); // two emoji -> 20, 21
+
+ var mappings = subtable.GetGlyphMappings();
+
+ Assert.AreEqual(5, mappings.CharCodeToGlyphIndex.Count);
+ Assert.AreEqual((ushort)5, mappings.CharCodeToGlyphIndex[0x41]);
+ Assert.AreEqual((ushort)6, mappings.CharCodeToGlyphIndex[0x42]);
+ Assert.AreEqual((ushort)7, mappings.CharCodeToGlyphIndex[0x43]);
+ Assert.AreEqual((ushort)20, mappings.CharCodeToGlyphIndex[0x1F600]);
+ Assert.AreEqual((ushort)21, mappings.CharCodeToGlyphIndex[0x1F601]);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable4Tests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable4Tests.cs
new file mode 100644
index 0000000000..74bb9af183
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Cmap/CmapSubtable4Tests.cs
@@ -0,0 +1,128 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 11/30/2026 EPPlus Software AB Tests for malformed format 4 segments
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Cmap;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Linq;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables.Cmap
+{
+ ///
+ /// Tests that CmapSubtable4.GetGlyphMappings() stays bounded for overlapping or invalid
+ /// segments, and agrees with MapCodePointToGlyph. The subtables are built by hand.
+ ///
+ [TestClass]
+ public class CmapSubtable4Tests
+ {
+ private static CmapSubtable4 CreateSubtable(
+ ushort[] startCode, ushort[] endCode, short[] idDelta, ushort[] idRangeOffset,
+ ushort[]? glyphIdArray = null)
+ {
+ return new CmapSubtable4
+ {
+ StartCode = startCode,
+ EndCode = endCode,
+ IdDelta = idDelta,
+ IdRangeOffset = idRangeOffset,
+ GlyphIdArray = glyphIdArray ?? new ushort[0],
+ SegCountX2 = (ushort)(endCode.Length * 2)
+ };
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetGlyphMappings_ManyOverlappingFullRangeSegments_NoDuplicates()
+ {
+ // 1000 segments covering 0x0000-0xFFFE, followed by the required 0xFFFF segment.
+ const int overlapping = 1000;
+ int segCount = overlapping + 1;
+ var start = new ushort[segCount];
+ var end = new ushort[segCount];
+ var delta = new short[segCount];
+ var rangeOffset = new ushort[segCount];
+ for (int i = 0; i < overlapping; i++)
+ {
+ start[i] = 0x0000;
+ end[i] = 0xFFFE;
+ delta[i] = 1;
+ }
+ start[overlapping] = 0xFFFF;
+ end[overlapping] = 0xFFFF;
+ delta[overlapping] = 1; // maps to glyph 0, i.e. not mapped
+
+ var mappings = CreateSubtable(start, end, delta, rangeOffset).GetGlyphMappings();
+
+ Assert.AreEqual(65535, mappings.CharCodeToGlyphIndex.Count);
+ int reverseEntries = mappings.GlyphIndexToCharCodes.Values.Sum(l => l.Count);
+ Assert.AreEqual(65535, reverseEntries);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetGlyphMappings_OverlappingSegments_MatchesMapCodePointToGlyph()
+ {
+ // Two segments both covering A-Z with different deltas.
+ var subtable = CreateSubtable(
+ new ushort[] { 'A', 'A', 0xFFFF },
+ new ushort[] { 'Z', 'Z', 0xFFFF },
+ new short[] { 1, 100, 1 },
+ new ushort[] { 0, 0, 0 });
+
+ var mappings = subtable.GetGlyphMappings();
+
+ Assert.AreEqual(26, mappings.CharCodeToGlyphIndex.Count);
+ for (uint c = 'A'; c <= 'Z'; c++)
+ {
+ Assert.AreEqual((ushort)(c + 1), mappings.CharCodeToGlyphIndex[c], $"U+{c:X4}");
+ Assert.AreEqual(subtable.MapCodePointToGlyph((int)c), mappings.CharCodeToGlyphIndex[c], $"U+{c:X4}");
+ }
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetGlyphMappings_EndBeforeStart_SegmentIsIgnored()
+ {
+ var subtable = CreateSubtable(
+ new ushort[] { 0x50, 0xFFFF },
+ new ushort[] { 0x40, 0xFFFF },
+ new short[] { 0, 1 },
+ new ushort[] { 0, 0 });
+
+ var mappings = subtable.GetGlyphMappings();
+
+ Assert.AreEqual(0, mappings.CharCodeToGlyphIndex.Count);
+ Assert.AreEqual(0, mappings.GlyphIndexToCharCodes.Count);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetGlyphMappings_ValidSegmentsWithGlyphIdArray_MappedAsBefore()
+ {
+ // Segment 0: A-C via GlyphIdArray. idRangeOffset 4 -> index = 4/2 + (c - start) - (2 - 0) = c - start.
+ var subtable = CreateSubtable(
+ new ushort[] { 'A', 0xFFFF },
+ new ushort[] { 'C', 0xFFFF },
+ new short[] { 0, 1 },
+ new ushort[] { 4, 0 },
+ new ushort[] { 10, 11, 12 });
+
+ var mappings = subtable.GetGlyphMappings();
+
+ Assert.AreEqual(3, mappings.CharCodeToGlyphIndex.Count);
+ Assert.AreEqual((ushort)10, mappings.CharCodeToGlyphIndex['A']);
+ Assert.AreEqual((ushort)11, mappings.CharCodeToGlyphIndex['B']);
+ Assert.AreEqual((ushort)12, mappings.CharCodeToGlyphIndex['C']);
+ for (uint c = 'A'; c <= 'C'; c++)
+ Assert.AreEqual(subtable.MapCodePointToGlyph((int)c), mappings.CharCodeToGlyphIndex[c]);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/GlyfBoundsTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/GlyfBoundsTests.cs
new file mode 100644
index 0000000000..972c66ee4c
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Glyph/GlyfBoundsTests.cs
@@ -0,0 +1,186 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 11/30/2026 EPPlus Software AB Tests for glyf data bounded by loca ranges
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Glyph.Serialization;
+using EPPlus.Fonts.OpenType.Tables.Head;
+using EPPlus.Fonts.OpenType.Tests.Helpers;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables
+{
+ ///
+ /// Tests that glyph data is only read within the glyph's own loca range, and that
+ /// malformed loca entries are treated as empty glyphs instead of being parsed.
+ ///
+ [TestClass]
+ public class GlyfBoundsTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private static void WriteUInt16(List bytes, int v)
+ {
+ bytes.Add((byte)(v >> 8));
+ bytes.Add((byte)v);
+ }
+
+ private static void WriteGlyphHeader(List bytes, short numberOfContours)
+ {
+ WriteUInt16(bytes, (ushort)numberOfContours);
+ for (int i = 0; i < 4; i++) WriteUInt16(bytes, 0); // xMin, yMin, xMax, yMax
+ }
+
+ // ---------------------------------------------------------------------------------
+ // Unit tests - glyph bytes built by hand
+ // ---------------------------------------------------------------------------------
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_SimpleGlyphFlagsBeyondGlyphEnd_Throws()
+ {
+ var bytes = new List();
+ WriteGlyphHeader(bytes, 1);
+ WriteUInt16(bytes, 65535); // endPtsOfContours[0] -> 65536 points
+ WriteUInt16(bytes, 0); // instructionLength
+ for (int i = 0; i < 300; i++)
+ {
+ bytes.Add(0x39); // onCurve | repeat | xSame | ySame (no coordinate bytes)
+ bytes.Add(255); // repeat count
+ }
+
+ long glyphEnd = 14 + 4; // header + endPts + instrLen + two flag runs
+ using var reader = new FontsBinaryReader(new MemoryStream(bytes.ToArray()));
+
+ Assert.ThrowsExactly(() => GlyphDeserializer.Deserialize(reader, glyphEnd));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_CompositeComponentsBeyondGlyphEnd_Throws()
+ {
+ const int MoreComponents = 0x0020;
+ var bytes = new List();
+ WriteGlyphHeader(bytes, -1);
+ for (int i = 0; i < 100; i++)
+ {
+ WriteUInt16(bytes, MoreComponents); // flags (byte arguments)
+ WriteUInt16(bytes, 1); // glyphIndex
+ bytes.Add(0); // arg1
+ bytes.Add(0); // arg2
+ }
+
+ long glyphEnd = 10 + 12; // header + two components
+ using var reader = new FontsBinaryReader(new MemoryStream(bytes.ToArray()));
+
+ Assert.ThrowsExactly(() => GlyphDeserializer.Deserialize(reader, glyphEnd));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ValidSimpleGlyph_ReadsWithinRange()
+ {
+ var bytes = new List();
+ WriteGlyphHeader(bytes, 1);
+ WriteUInt16(bytes, 2); // endPtsOfContours[0] -> 3 points
+ WriteUInt16(bytes, 0); // instructionLength
+ for (int i = 0; i < 3; i++)
+ bytes.Add(0x37); // onCurve | xShort | yShort | xPositive | yPositive
+ bytes.AddRange(new byte[] { 0, 10, 0 }); // x deltas
+ bytes.AddRange(new byte[] { 0, 0, 10 }); // y deltas
+
+ long glyphEnd = bytes.Count;
+ using var reader = new FontsBinaryReader(new MemoryStream(bytes.ToArray()));
+
+ var glyph = GlyphDeserializer.Deserialize(reader, glyphEnd);
+
+ Assert.IsNotNull(glyph.SimpleData);
+ Assert.AreEqual((ushort)2, glyph.SimpleData.EndPtsOfContours[0]);
+ Assert.AreEqual(3, glyph.SimpleData.Flags.Count);
+ Assert.AreEqual(glyphEnd, reader.BaseStream.Position);
+ }
+
+ // ---------------------------------------------------------------------------------
+ // Integration tests - Roboto-Regular.ttf with a patched loca table
+ // ---------------------------------------------------------------------------------
+
+ private static byte[] LoadRobotoBytes(out int locaOffset, out int numGlyphs)
+ {
+ var bytes = File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"));
+ var original = new OpenTypeFont(bytes);
+ Assert.AreEqual(HeadTable.IndexToLocFormats.Offset16, original.HeadTable.IndexToLocFormat,
+ "These tests patch a short (Offset16) loca table.");
+
+ numGlyphs = original.MaxpTable.numGlyphs;
+ FontTestHelper.FindTableInDirectory(bytes, "loca", out locaOffset, out _);
+ return bytes;
+ }
+
+ private static int ReadLoca16(byte[] bytes, int locaOffset, int index)
+ {
+ int pos = locaOffset + index * 2;
+ return (bytes[pos] << 8) | bytes[pos + 1];
+ }
+
+ private static void WriteLoca16(byte[] bytes, int locaOffset, int index, int value)
+ {
+ int pos = locaOffset + index * 2;
+ bytes[pos] = (byte)(value >> 8);
+ bytes[pos + 1] = (byte)value;
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_LocaOffsetsNotAscending_GlyphIsNullOthersLoad()
+ {
+ var bytes = LoadRobotoBytes(out int locaOffset, out int numGlyphs);
+ var original = new OpenTypeFont((byte[])bytes.Clone());
+ var originalA = original.GlyfTable.GetGlyph(37); // 'A'
+
+ // Make the last glyph's end lower than its start.
+ int lastStart = ReadLoca16(bytes, locaOffset, numGlyphs - 1);
+ WriteLoca16(bytes, locaOffset, numGlyphs, lastStart - 1);
+
+ var font = new OpenTypeFont(bytes);
+ var glyf = font.GlyfTable;
+
+ Assert.IsNotNull(original.GlyfTable.GetGlyph((ushort)(numGlyphs - 1)));
+ Assert.IsNull(glyf.GetGlyph((ushort)(numGlyphs - 1)));
+
+ var patchedA = glyf.GetGlyph(37);
+ Assert.IsNotNull(patchedA);
+ CollectionAssert.AreEqual(originalA.SimpleData.XBytes, patchedA.SimpleData.XBytes);
+ CollectionAssert.AreEqual(originalA.SimpleData.YBytes, patchedA.SimpleData.YBytes);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_LocaWithTinyOverlappingRegions_CompletesQuickly()
+ {
+ var bytes = LoadRobotoBytes(out int locaOffset, out int numGlyphs);
+ var original = new OpenTypeFont((byte[])bytes.Clone());
+ int originalNonEmpty = original.GlyfTable.Glyphs.Count(g => g != null);
+
+ // Ascending entries 16 bytes apart: each glyph gets a range too small for its
+ // real data, so parsing must stop at the range end instead of expanding further.
+ for (int i = 0; i <= numGlyphs; i++)
+ WriteLoca16(bytes, locaOffset, i, i * 8); // short loca stores offset / 2
+
+ var font = new OpenTypeFont(bytes);
+ var glyf = font.GlyfTable;
+
+ Assert.IsNotNull(glyf);
+ Assert.IsTrue(glyf.Glyphs.Count(g => g != null) < originalNonEmpty);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/MarkToBaseSubTableFormat1DeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/MarkToBaseSubTableFormat1DeserializerTests.cs
new file mode 100644
index 0000000000..f68f0dd910
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/MarkToBaseSubTableFormat1DeserializerTests.cs
@@ -0,0 +1,96 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for MarkToBase subtables without mark classes
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups.LookupType4;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections.Generic;
+using System.IO;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables.Gpos
+{
+ ///
+ /// Tests that MarkToBaseSubTableFormat1Deserializer skips a subtable with MarkClassCount 0
+ /// (which can never attach a mark) instead of allocating BaseCount empty records, and that
+ /// valid subtables are read as before. The subtable bytes are built by hand.
+ ///
+ [TestClass]
+ public class MarkToBaseSubTableFormat1DeserializerTests
+ {
+ private static MarkToBaseSubTableFormat1 Deserialize(byte[] bytes)
+ {
+ using var reader = new FontsBinaryReader(new MemoryStream(bytes));
+ return new MarkToBaseSubTableFormat1Deserializer(reader).Deserialize(0);
+ }
+
+ private static void Write(List bytes, ushort v)
+ {
+ bytes.Add((byte)(v >> 8));
+ bytes.Add((byte)v);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ZeroMarkClassCount_ReturnsNull()
+ {
+ var bytes = new List();
+ Write(bytes, 1); // PosFormat
+ Write(bytes, 0); // MarkCoverage offset
+ Write(bytes, 0); // BaseCoverage offset
+ Write(bytes, 0); // MarkClassCount
+ Write(bytes, 0); // MarkArray offset
+ Write(bytes, 12); // BaseArray offset
+ Write(bytes, 65535); // BaseArray.BaseCount (no data needed per record when there are no classes)
+
+ Assert.IsNull(Deserialize(bytes.ToArray()));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ValidSubtable_ReadAsBefore()
+ {
+ var bytes = new List();
+ // Header (0-11)
+ Write(bytes, 1); // PosFormat
+ Write(bytes, 12); // MarkCoverage offset
+ Write(bytes, 18); // BaseCoverage offset
+ Write(bytes, 1); // MarkClassCount
+ Write(bytes, 24); // MarkArray offset
+ Write(bytes, 36); // BaseArray offset
+ // Mark coverage, format 1, glyph 10 (12-17)
+ Write(bytes, 1); Write(bytes, 1); Write(bytes, 10);
+ // Base coverage, format 1, glyph 5 (18-23)
+ Write(bytes, 1); Write(bytes, 1); Write(bytes, 5);
+ // MarkArray (24-29): one record, class 0, anchor at +6
+ Write(bytes, 1); Write(bytes, 0); Write(bytes, 6);
+ // Mark anchor, format 1 (30-35)
+ Write(bytes, 1); Write(bytes, 100); Write(bytes, 200);
+ // BaseArray (36-39): one record with one anchor offset (+4)
+ Write(bytes, 1); Write(bytes, 4);
+ // Base anchor, format 1 (40-45)
+ Write(bytes, 1); Write(bytes, 300); Write(bytes, 400);
+
+ var subtable = Deserialize(bytes.ToArray());
+
+ Assert.IsNotNull(subtable);
+ Assert.AreEqual(1, subtable.MarkClassCount);
+ CollectionAssert.AreEqual(new ushort[] { 10 }, subtable.MarkCoverage.GetCoveredGlyphs());
+ CollectionAssert.AreEqual(new ushort[] { 5 }, subtable.BaseCoverage.GetCoveredGlyphs());
+ Assert.AreEqual(1, subtable.MarkArray.MarkCount);
+ Assert.AreEqual(0, subtable.MarkArray.Records[0].MarkClass);
+ Assert.AreEqual(100, subtable.MarkArray.Records[0].MarkAnchor.XCoordinate);
+ Assert.AreEqual(200, subtable.MarkArray.Records[0].MarkAnchor.YCoordinate);
+ Assert.AreEqual(1, subtable.BaseArray.BaseCount);
+ Assert.AreEqual(300, subtable.BaseArray.Records[0].BaseAnchors[0].XCoordinate);
+ Assert.AreEqual(400, subtable.BaseArray.Records[0].BaseAnchors[0].YCoordinate);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs
new file mode 100644
index 0000000000..c904f21360
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/PairPosSubTableFormat2DeserializerTests.cs
@@ -0,0 +1,94 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 11/30/2026 EPPlus Software AB Tests for malformed PairPos format 2 class matrices
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups.LookupType2;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections.Generic;
+using System.IO;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables.Gpos
+{
+ ///
+ /// Tests that PairPosSubTableFormat2Deserializer validates the class matrix size before
+ /// allocating it. The subtable bytes are built by hand so no font file is needed.
+ ///
+ [TestClass]
+ public class PairPosSubTableFormat2DeserializerTests
+ {
+ private const ushort ValueFormatXAdvance = 0x0004;
+
+ ///
+ /// Builds a PairPos format 2 header (16 bytes) followed by the given matrix values.
+ /// Coverage and ClassDef offsets are 0, so only the header and the matrix are read.
+ ///
+ private static byte[] BuildSubtable(ushort valueFormat1, ushort valueFormat2,
+ ushort class1Count, ushort class2Count, params short[] matrixValues)
+ {
+ var bytes = new List();
+ void Write(ushort v) { bytes.Add((byte)(v >> 8)); bytes.Add((byte)v); }
+
+ Write(2); // PosFormat
+ Write(0); // Coverage offset
+ Write(valueFormat1);
+ Write(valueFormat2);
+ Write(0); // ClassDef1 offset
+ Write(0); // ClassDef2 offset
+ Write(class1Count);
+ Write(class2Count);
+ foreach (var v in matrixValues) Write((ushort)v);
+
+ return bytes.ToArray();
+ }
+
+ private static PairPosSubTableFormat2 Deserialize(byte[] bytes)
+ {
+ using var reader = new FontsBinaryReader(new MemoryStream(bytes));
+ return new PairPosSubTableFormat2Deserializer(reader).Deserialize(0);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_EmptyValueFormatsWithHugeClassCounts_ReturnsNull()
+ {
+ var bytes = BuildSubtable(0, 0, 65535, 65535);
+
+ Assert.AreEqual(16, bytes.Length);
+ Assert.IsNull(Deserialize(bytes));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ClassCountsExceedingAvailableData_ReturnsNull()
+ {
+ var bytes = BuildSubtable(ValueFormatXAdvance, 0, 65535, 65535);
+
+ Assert.IsNull(Deserialize(bytes));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ValidSmallMatrix_ReadsValues()
+ {
+ var bytes = BuildSubtable(ValueFormatXAdvance, 0, 2, 2, 10, 20, 30, 40);
+
+ var table = Deserialize(bytes);
+
+ Assert.IsNotNull(table);
+ Assert.AreEqual((ushort)2, table.Class1Count);
+ Assert.AreEqual((ushort)2, table.Class2Count);
+ Assert.AreEqual((short)10, table.ClassMatrix[0, 0].Value1.XAdvance);
+ Assert.AreEqual((short)20, table.ClassMatrix[0, 1].Value1.XAdvance);
+ Assert.AreEqual((short)30, table.ClassMatrix[1, 0].Value1.XAdvance);
+ Assert.AreEqual((short)40, table.ClassMatrix[1, 1].Value1.XAdvance);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/SinglePosSubTableFormat2DeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/SinglePosSubTableFormat2DeserializerTests.cs
new file mode 100644
index 0000000000..0e3d5d4428
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gpos/SinglePosSubTableFormat2DeserializerTests.cs
@@ -0,0 +1,120 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for SinglePos format 2 value record bounds
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups.LookupType1;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections.Generic;
+using System.IO;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables.Gpos
+{
+ ///
+ /// Tests that SinglePosSubTableFormat2Deserializer does not allocate one object per empty
+ /// ValueRecord (ValueFormat 0), validates the record array against the available data, and
+ /// that covered glyphs still get an (empty) adjustment. The subtable bytes are built by hand.
+ ///
+ [TestClass]
+ public class SinglePosSubTableFormat2DeserializerTests
+ {
+ private const ushort ValueFormatXAdvance = 0x0004;
+ private const int HeaderSize = 8;
+
+ private static void Write(List bytes, ushort v)
+ {
+ bytes.Add((byte)(v >> 8));
+ bytes.Add((byte)v);
+ }
+
+ ///
+ /// Builds a SinglePos format 2 subtable: header, the given record values (one ushort each),
+ /// and optionally a format 1 coverage table with the given glyphs.
+ ///
+ private static byte[] BuildSubtable(ushort valueFormat, ushort valueCount, short[] values, ushort[]? coverageGlyphs)
+ {
+ var bytes = new List();
+ ushort coverageOffset = coverageGlyphs == null ? (ushort)0 : (ushort)(HeaderSize + values.Length * 2);
+
+ Write(bytes, 2); // PosFormat
+ Write(bytes, coverageOffset);
+ Write(bytes, valueFormat);
+ Write(bytes, valueCount);
+ foreach (var v in values) Write(bytes, (ushort)v);
+
+ if (coverageGlyphs != null)
+ {
+ Write(bytes, 1); // Coverage format 1
+ Write(bytes, (ushort)coverageGlyphs.Length);
+ foreach (var g in coverageGlyphs) Write(bytes, g);
+ }
+
+ return bytes.ToArray();
+ }
+
+ private static SinglePosSubTableFormat2 Deserialize(byte[] bytes)
+ {
+ using var reader = new FontsBinaryReader(new MemoryStream(bytes));
+ return new SinglePosSubTableFormat2Deserializer(reader).Deserialize(0);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ZeroValueFormatWithHugeValueCount_DoesNotAllocateRecords()
+ {
+ var subtable = Deserialize(BuildSubtable(0, 65535, new short[0], null));
+
+ Assert.IsNotNull(subtable);
+ Assert.AreEqual((ushort)65535, subtable.ValueCount);
+ Assert.AreEqual(0, subtable.Values.Length);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void TryGetAdjustment_ZeroValueFormat_CoveredGlyphReturnsEmptyAdjustment()
+ {
+ var subtable = Deserialize(BuildSubtable(0, 2, new short[0], new ushort[] { 5, 7 }));
+
+ Assert.IsTrue(subtable.TryGetAdjustment(5, out var value));
+ Assert.IsNotNull(value);
+ Assert.AreEqual((short)0, value.XPlacement);
+ Assert.AreEqual((short)0, value.YPlacement);
+ Assert.AreEqual((short)0, value.XAdvance);
+ Assert.AreEqual((short)0, value.YAdvance);
+
+ Assert.IsTrue(subtable.TryGetAdjustment(7, out _));
+ Assert.IsFalse(subtable.TryGetAdjustment(6, out _));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ValueCountExceedingAvailableData_ReturnsNull()
+ {
+ var subtable = Deserialize(BuildSubtable(ValueFormatXAdvance, 65535, new short[0], null));
+
+ Assert.IsNull(subtable);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ValidRecords_ReadAsBefore()
+ {
+ var subtable = Deserialize(BuildSubtable(ValueFormatXAdvance, 2, new short[] { 10, 20 }, new ushort[] { 5, 7 }));
+
+ Assert.IsNotNull(subtable);
+ Assert.AreEqual(2, subtable.Values.Length);
+ Assert.IsTrue(subtable.TryGetAdjustment(5, out var first));
+ Assert.AreEqual((short)10, first.XAdvance);
+ Assert.IsTrue(subtable.TryGetAdjustment(7, out var second));
+ Assert.AreEqual((short)20, second.XAdvance);
+ Assert.IsFalse(subtable.TryGetAdjustment(6, out _));
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/Gsub/LigatureSubstSubTableDeserializerTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gsub/LigatureSubstSubTableDeserializerTests.cs
new file mode 100644
index 0000000000..996b842fcc
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/Gsub/LigatureSubstSubTableDeserializerTests.cs
@@ -0,0 +1,134 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for malformed ligature substitution coverage
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups;
+using EPPlus.Fonts.OpenType.Tables.Gsub.IO;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System.Collections.Generic;
+using System.IO;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables.Gsub
+{
+ ///
+ /// Tests that LigatureSubstSubTableDeserializer only expands as many coverage glyphs as there
+ /// are ligature sets (so overlapping format 2 ranges cannot blow up memory), tolerates a glyph
+ /// listed twice in the coverage, and maps valid subtables as before. Bytes are built by hand.
+ ///
+ [TestClass]
+ public class LigatureSubstSubTableDeserializerTests
+ {
+ private static void Write(List bytes, ushort v)
+ {
+ bytes.Add((byte)(v >> 8));
+ bytes.Add((byte)v);
+ }
+
+ ///
+ /// Builds a ligature substitution subtable with one ligature set per entry in
+ /// . Each set holds one two-component ligature
+ /// (second component glyph 7) producing the given glyph. The coverage table is placed last.
+ ///
+ private static byte[] BuildSubtable(byte[] coverage, params ushort[] ligatureGlyphs)
+ {
+ int setCount = ligatureGlyphs.Length;
+ int headerSize = 6 + 2 * setCount;
+ const int setSize = 10; // LigatureCount, offset, LigatureGlyph, ComponentCount, one component
+ int coverageOffset = headerSize + setCount * setSize;
+
+ var bytes = new List();
+ Write(bytes, 1); // SubstFormat
+ Write(bytes, (ushort)coverageOffset); // Coverage offset
+ Write(bytes, (ushort)setCount); // LigSetCount
+ for (int i = 0; i < setCount; i++)
+ Write(bytes, (ushort)(headerSize + i * setSize));
+ foreach (var ligatureGlyph in ligatureGlyphs)
+ {
+ Write(bytes, 1); // LigatureCount
+ Write(bytes, 4); // Ligature offset (from set start)
+ Write(bytes, ligatureGlyph); // LigatureGlyph
+ Write(bytes, 2); // ComponentCount
+ Write(bytes, 7); // Second component
+ }
+ bytes.AddRange(coverage);
+ return bytes.ToArray();
+ }
+
+ private static byte[] CoverageFormat1(params ushort[] glyphs)
+ {
+ var bytes = new List();
+ Write(bytes, 1);
+ Write(bytes, (ushort)glyphs.Length);
+ foreach (var g in glyphs) Write(bytes, g);
+ return bytes.ToArray();
+ }
+
+ private static byte[] CoverageFormat2(params (ushort start, ushort end, ushort startIndex)[] ranges)
+ {
+ var bytes = new List();
+ Write(bytes, 2);
+ Write(bytes, (ushort)ranges.Length);
+ foreach (var r in ranges)
+ {
+ Write(bytes, r.start);
+ Write(bytes, r.end);
+ Write(bytes, r.startIndex);
+ }
+ return bytes.ToArray();
+ }
+
+ private static LigatureSubstSubTable Deserialize(byte[] bytes)
+ {
+ using var reader = new FontsBinaryReader(new MemoryStream(bytes));
+ return new LigatureSubstSubTableDeserializer(reader).Deserialize(0);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_OverlappingCoverageRanges_ExpandsOnlyLigatureSetCount()
+ {
+ // 65535 ranges each covering every glyph: fully expanded that is over 4 billion glyphs.
+ var ranges = new (ushort, ushort, ushort)[65535];
+ for (int i = 0; i < ranges.Length; i++)
+ ranges[i] = (0, 65535, 0);
+
+ var subTable = Deserialize(BuildSubtable(CoverageFormat2(ranges), 99));
+
+ Assert.AreEqual(1, subTable.LigatureSets.Count);
+ Assert.AreEqual(99, subTable.LigatureSets[0].Ligatures[0].LigatureGlyph);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_DuplicateGlyphInCoverage_KeepsFirstSet()
+ {
+ var subTable = Deserialize(BuildSubtable(CoverageFormat1(5, 5), 100, 200));
+
+ Assert.AreEqual(1, subTable.LigatureSets.Count);
+ Assert.AreEqual(100, subTable.LigatureSets[5].Ligatures[0].LigatureGlyph);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Deserialize_ValidSubtable_MapsLigatureSetsAsBefore()
+ {
+ var subTable = Deserialize(BuildSubtable(CoverageFormat2((5, 6, 0)), 100, 200));
+
+ Assert.AreEqual(2, subTable.LigatureSets.Count);
+ var first = subTable.LigatureSets[5].Ligatures[0];
+ var second = subTable.LigatureSets[6].Ligatures[0];
+ Assert.AreEqual(100, first.LigatureGlyph);
+ CollectionAssert.AreEqual(new ushort[] { 7 }, first.Components);
+ Assert.AreEqual(200, second.LigatureGlyph);
+ CollectionAssert.AreEqual(new ushort[] { 7 }, second.Components);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadAmountTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadAmountTests.cs
new file mode 100644
index 0000000000..8c9827bd63
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadAmountTests.cs
@@ -0,0 +1,89 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Read amount measurement for GSUB/GPOS parsing
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.IO;
+using System.Linq;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables
+{
+ ///
+ /// Reports how many bytes the GSUB and GPOS parsers read relative to the table length.
+ /// Shared offsets (coverage tables, class definitions) make real fonts read some parts
+ /// more than once, so the ratio is above 1. This is the basis for a read budget.
+ ///
+ [TestClass]
+ public class LayoutTableReadAmountTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ [TestMethod]
+ public void GsubGpos_ReadAmount_ReportedForTestFonts()
+ {
+ var files = Directory.GetFiles(FontFolder)
+ .Where(f => f.EndsWith(".ttf", StringComparison.OrdinalIgnoreCase) ||
+ f.EndsWith(".otf", StringComparison.OrdinalIgnoreCase))
+ .OrderBy(f => f)
+ .ToList();
+
+ Assert.IsTrue(files.Count > 0, "No test fonts found in " + FontFolder);
+ Console.WriteLine($"{"Font",-45} {"Table",-5} {"Length",10} {"Read",12} {"Ratio",8}");
+
+ int measured = 0;
+ foreach (var file in files)
+ {
+ var font = new OpenTypeFont(File.ReadAllBytes(file));
+ var name = Path.GetFileName(file);
+
+ if (font.TableRecords.ContainsKey(TableNames.Gsub))
+ {
+ _ = font.GsubTable;
+ var loader = TableLoaders.GetGsubTableLoader(font._tblSettings);
+ Report(name, "GSUB", loader.TableLength, loader.LastLoadBytesRead);
+ Assert.IsTrue(loader.LastLoadBytesRead > 0, $"{name}: GSUB read no bytes");
+ AssertWithinBudget(name, "GSUB", loader.TableLength, loader.LastLoadBytesRead);
+ measured++;
+ }
+
+ if (font.TableRecords.ContainsKey(TableNames.Gpos))
+ {
+ _ = font.GposTable;
+ var loader = TableLoaders.GetGposTableLoader(font._tblSettings);
+ Report(name, "GPOS", loader.TableLength, loader.LastLoadBytesRead);
+ Assert.IsTrue(loader.LastLoadBytesRead > 0, $"{name}: GPOS read no bytes");
+ AssertWithinBudget(name, "GPOS", loader.TableLength, loader.LastLoadBytesRead);
+ measured++;
+ }
+ }
+
+ Assert.IsTrue(measured > 0, "No test font has a GSUB or GPOS table");
+ }
+
+ ///
+ /// Real fonts must stay within the layout read budget, otherwise their GSUB/GPOS would be ignored.
+ ///
+ private static void AssertWithinBudget(string font, string table, uint length, long read)
+ {
+ long budget = Math.Max(TableLoader.LayoutReadBudgetMinimum,
+ TableLoader.LayoutReadBudgetFactor * (long)length);
+ Assert.IsTrue(read <= budget, $"{font}: {table} read {read} bytes, over the budget of {budget}.");
+ }
+
+ private static void Report(string font, string table, uint length, long read)
+ {
+ double ratio = length == 0 ? 0 : (double)read / length;
+ Console.WriteLine($"{font,-45} {table,-5} {length,10} {read,12} {ratio,8:F2}");
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadBudgetTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadBudgetTests.cs
new file mode 100644
index 0000000000..f2fba32a94
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/LayoutTableReadBudgetTests.cs
@@ -0,0 +1,148 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for the GSUB/GPOS read budget
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tests.Helpers;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using OfficeOpenXml.Interfaces.Fonts;
+using System;
+using System.IO;
+using System.Linq;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables
+{
+ ///
+ /// Tests that a GPOS table whose offsets make the parser read the same data over and over
+ /// is stopped by the read budget, ignored, and reported as a warning via IFontLogger.
+ /// The malformed font is Roboto-Regular.ttf with its GPOS table contents replaced.
+ ///
+ [TestClass]
+ public class LayoutTableReadBudgetTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private const int SubtableCount = 2000;
+ private const int CoverageGlyphCount = 4000;
+
+ private static void WriteUInt16(byte[] b, int pos, int v)
+ {
+ b[pos] = (byte)(v >> 8);
+ b[pos + 1] = (byte)v;
+ }
+
+ private static byte[] LoadRoboto()
+ {
+ return File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"));
+ }
+
+ ///
+ /// Replaces the GPOS table contents with: one SinglePos lookup with 2000 subtable offsets
+ /// that all point to the same subtable, whose coverage table lists 4000 glyphs. About 12 KB
+ /// of data that the parser would read 2000 times (about 16 MB).
+ ///
+ private static byte[] BuildFontWithAmplifyingGpos()
+ {
+ var bytes = LoadRoboto();
+ FontTestHelper.FindTableInDirectory(bytes, "GPOS", out int gpos, out int gposLength);
+
+ int lookupList = 10;
+ int lookup = lookupList + 4;
+ int subtable = lookup + 6 + 2 * SubtableCount;
+ int coverage = subtable + 8;
+ int end = coverage + 4 + 2 * CoverageGlyphCount;
+ Assert.IsTrue(end <= gposLength, "The crafted GPOS must fit in Roboto's GPOS table.");
+
+ Array.Clear(bytes, gpos, gposLength);
+
+ // GPOS header: version 1.0, no ScriptList or FeatureList, LookupList at 10
+ WriteUInt16(bytes, gpos + 0, 1);
+ WriteUInt16(bytes, gpos + 2, 0);
+ WriteUInt16(bytes, gpos + 8, lookupList);
+
+ // LookupList: one lookup
+ WriteUInt16(bytes, gpos + lookupList, 1);
+ WriteUInt16(bytes, gpos + lookupList + 2, lookup - lookupList);
+
+ // Lookup: type 1 (SinglePos), every subtable offset points to the same subtable
+ WriteUInt16(bytes, gpos + lookup, 1);
+ WriteUInt16(bytes, gpos + lookup + 4, SubtableCount);
+ for (int i = 0; i < SubtableCount; i++)
+ WriteUInt16(bytes, gpos + lookup + 6 + 2 * i, subtable - lookup);
+
+ // SinglePos format 1: coverage at +8, ValueFormat XAdvance, value 10
+ WriteUInt16(bytes, gpos + subtable, 1);
+ WriteUInt16(bytes, gpos + subtable + 2, coverage - subtable);
+ WriteUInt16(bytes, gpos + subtable + 4, 0x0004);
+ WriteUInt16(bytes, gpos + subtable + 6, 10);
+
+ // Coverage format 1 with glyphs 0..3999
+ WriteUInt16(bytes, gpos + coverage, 1);
+ WriteUInt16(bytes, gpos + coverage + 2, CoverageGlyphCount);
+ for (int g = 0; g < CoverageGlyphCount; g++)
+ WriteUInt16(bytes, gpos + coverage + 4 + 2 * g, g);
+
+ return bytes;
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_AmplifyingGpos_TableIgnoredWithWarning()
+ {
+ var font = new OpenTypeFont(BuildFontWithAmplifyingGpos());
+
+ Assert.IsNull(font.GposTable);
+ Assert.IsNotNull(font.GsubTable, "GSUB is not affected and must still load.");
+
+ var warnings = font.LoadWarnings;
+ Assert.AreEqual(1, warnings.Length);
+ StringAssert.Contains(warnings[0], "GPOS");
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetFromBytes_AmplifyingGpos_LogsFontTableIgnoredWarning()
+ {
+ var log = new CollectingFontLogger();
+ var engine = new OpenTypeFontEngine(c =>
+ {
+ c.SearchSystemDirectories = false;
+ c.Logger = log;
+ });
+
+ var font = engine.GetFromBytes(BuildFontWithAmplifyingGpos());
+
+ Assert.IsNull(font.GposTable);
+ var events = log.GetEvents(FontLogEventType.FontTableIgnored);
+ Assert.AreEqual(1, events.Count);
+ Assert.AreEqual(FontLogSeverity.Warning, events[0].Severity);
+ StringAssert.Contains(events[0].Message, "GPOS");
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetFromBytes_ValidFont_NoWarningsAndTablesLoaded()
+ {
+ var log = new CollectingFontLogger();
+ var engine = new OpenTypeFontEngine(c =>
+ {
+ c.SearchSystemDirectories = false;
+ c.Logger = log;
+ });
+
+ var font = engine.GetFromBytes(LoadRoboto());
+
+ Assert.IsNotNull(font.GsubTable);
+ Assert.IsNotNull(font.GposTable);
+ Assert.AreEqual(0, font.LoadWarnings.Length);
+ Assert.AreEqual(0, log.GetEvents(FontLogEventType.FontTableIgnored).Count);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/TableDirectoryValidationTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/TableDirectoryValidationTests.cs
new file mode 100644
index 0000000000..34282aa5db
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/TableDirectoryValidationTests.cs
@@ -0,0 +1,151 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for table directory validation
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Scanner;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.IO;
+using System.Text;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables
+{
+ ///
+ /// Tests that table records pointing outside the font data, a table directory that does not
+ /// fit, and duplicate table tags are rejected with InvalidDataException, both when a font is
+ /// loaded and when a font file is scanned.
+ ///
+ [TestClass]
+ public class TableDirectoryValidationTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private static byte[] LoadRoboto()
+ {
+ return File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"));
+ }
+
+ private static void WriteUInt32(byte[] b, int pos, uint v)
+ {
+ b[pos] = (byte)(v >> 24);
+ b[pos + 1] = (byte)(v >> 16);
+ b[pos + 2] = (byte)(v >> 8);
+ b[pos + 3] = (byte)v;
+ }
+
+ /// Returns the position of the table record with the given tag in the table directory.
+ private static int RecordPosition(byte[] font, string tag)
+ {
+ int numTables = (font[4] << 8) | font[5];
+ for (int i = 0; i < numTables; i++)
+ {
+ int record = 12 + i * 16;
+ if (Encoding.ASCII.GetString(font, record, 4) == tag)
+ return record;
+ }
+ throw new AssertFailedException("Table " + tag + " not found");
+ }
+
+ /// Roboto with the name table's length set to almost 2 GB.
+ private static byte[] RobotoWithHugeNameLength()
+ {
+ var bytes = LoadRoboto();
+ WriteUInt32(bytes, RecordPosition(bytes, "name") + 12, 0x7FFFFF78);
+ return bytes;
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Constructor_TableLengthBeyondData_Throws()
+ {
+ var bytes = RobotoWithHugeNameLength();
+
+ var ex = Assert.ThrowsExactly(() => new OpenTypeFont(bytes));
+ StringAssert.Contains(ex.Message, "name");
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Constructor_TableOffsetBeyondData_Throws()
+ {
+ var bytes = LoadRoboto();
+ WriteUInt32(bytes, RecordPosition(bytes, "post") + 8, (uint)bytes.Length);
+
+ var ex = Assert.ThrowsExactly(() => new OpenTypeFont(bytes));
+ StringAssert.Contains(ex.Message, "post");
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Constructor_DirectoryBeyondData_Throws()
+ {
+ // A 20-byte font whose header claims 10 tables (160 bytes of directory).
+ var bytes = new byte[20];
+ WriteUInt32(bytes, 0, 0x00010000);
+ bytes[4] = 0;
+ bytes[5] = 10;
+
+ Assert.ThrowsExactly(() => new OpenTypeFont(bytes));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Constructor_DuplicateTag_Throws()
+ {
+ var bytes = LoadRoboto();
+ int post = RecordPosition(bytes, "post");
+ Encoding.ASCII.GetBytes("name").CopyTo(bytes, post);
+
+ var ex = Assert.ThrowsExactly(() => new OpenTypeFont(bytes));
+ StringAssert.Contains(ex.Message, "more than once");
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void ScanSingleFace_TableLengthBeyondFile_Throws()
+ {
+ string path = Path.Combine(Path.GetTempPath(), "epplus-dirtest-" + Guid.NewGuid().ToString("N") + ".ttf");
+ try
+ {
+ File.WriteAllBytes(path, RobotoWithHugeNameLength());
+
+ Assert.ThrowsExactly(() => FontScannerV2Core.ScanSingleFace(path, 0));
+ }
+ finally
+ {
+ File.Delete(path);
+ }
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void GetAllScannedFontsInPath_CorruptFont_IsSkipped()
+ {
+ string dir = Path.Combine(Path.GetTempPath(), "epplus-dirtest-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(dir);
+ try
+ {
+ File.WriteAllBytes(Path.Combine(dir, "corrupt.ttf"), RobotoWithHugeNameLength());
+ File.WriteAllBytes(Path.Combine(dir, "valid.ttf"), LoadRoboto());
+
+ var faces = FontScannerV2.GetAllScannedFontsInPath(dir);
+
+ Assert.AreEqual(1, faces.Count);
+ Assert.AreEqual("valid.ttf", Path.GetFileName(faces[0].FilePath));
+ Assert.AreEqual("Roboto", faces[0].FamilyName);
+ }
+ finally
+ {
+ Directory.Delete(dir, true);
+ }
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/Tables/TableLoaderFailureTests.cs b/src/EPPlus.Fonts.OpenType.Tests/Tables/TableLoaderFailureTests.cs
new file mode 100644
index 0000000000..ebacc23794
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/Tables/TableLoaderFailureTests.cs
@@ -0,0 +1,133 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for TableLoader after a failed load
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables;
+using EPPlus.Fonts.OpenType.Tables.Name;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.IO;
+using System.Threading;
+
+namespace EPPlus.Fonts.OpenType.Tests.Tables
+{
+ ///
+ /// Tests that a TableLoader whose LoadInternal throws does not leave later callers waiting
+ /// forever, and that successful loads are still cached.
+ ///
+ [TestClass]
+ public class TableLoaderFailureTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ ///
+ /// Loader whose LoadInternal behaviour is set by the test. Uses a made-up table name so it
+ /// does not interfere with the font's real tables.
+ ///
+ private sealed class TestTableLoader : TableLoader
+ {
+ private int _calls;
+
+ public TestTableLoader(TableLoaderSettings settings) : base(settings, "TST1") { }
+
+ /// Called with the 1-based call number; returns the table or throws.
+ public Func Behaviour { get; set; } = _ => new NameTable();
+
+ public int Calls => _calls;
+
+ protected override NameTable LoadInternal()
+ {
+ int call = Interlocked.Increment(ref _calls);
+ return Behaviour(call);
+ }
+ }
+
+ private static TestTableLoader CreateLoader()
+ {
+ var font = new OpenTypeFont(File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf")));
+ return new TestTableLoader(font._tblSettings);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_AfterFailedLoad_NextCallDoesNotHang()
+ {
+ var loader = CreateLoader();
+ var table = new NameTable();
+ loader.Behaviour = call =>
+ {
+ if (call == 1) throw new InvalidDataException("Simulated malformed table");
+ return table;
+ };
+
+ Assert.ThrowsExactly(() => loader.Load());
+
+ var result = loader.Load();
+
+ Assert.AreSame(table, result);
+ Assert.AreEqual(2, loader.Calls);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_FailedLoad_ReleasesWaitingThread()
+ {
+ var loader = CreateLoader();
+ var table = new NameTable();
+ using var entered = new ManualResetEvent(false);
+ using var release = new ManualResetEvent(false);
+
+ loader.Behaviour = call =>
+ {
+ if (call == 1)
+ {
+ entered.Set();
+ release.WaitOne();
+ throw new InvalidDataException("Simulated malformed table");
+ }
+ return table;
+ };
+
+ Exception? firstError = null;
+ var first = new Thread(() =>
+ {
+ try { loader.Load(); } catch (Exception ex) { firstError = ex; }
+ });
+ first.Start();
+ Assert.IsTrue(entered.WaitOne(2000), "The first load never started.");
+
+ NameTable? secondResult = null;
+ var second = new Thread(() => secondResult = loader.Load());
+ second.Start();
+ Thread.Sleep(200); // let the second thread reach Monitor.Wait
+ release.Set(); // the first load now throws
+
+ Assert.IsTrue(first.Join(2000), "The first load did not finish.");
+ Assert.IsInstanceOfType(firstError, typeof(InvalidDataException));
+ Assert.IsTrue(second.Join(2000), "The waiting thread was not released after the failed load.");
+ Assert.AreSame(table, secondResult);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Load_Success_IsCachedAsBefore()
+ {
+ var loader = CreateLoader();
+
+ var first = loader.Load();
+ var second = loader.Load();
+
+ Assert.IsNotNull(first);
+ Assert.AreSame(first, second);
+ Assert.AreEqual(1, loader.Calls);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MultipleSubstitutionLimitTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MultipleSubstitutionLimitTests.cs
new file mode 100644
index 0000000000..e7aa79a5bd
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/MultipleSubstitutionLimitTests.cs
@@ -0,0 +1,97 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for the Multiple Substitution sequence limit
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables;
+using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage;
+using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups;
+using EPPlus.Fonts.OpenType.Tables.Common.Layout.Scripts;
+using EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups;
+using EPPlus.Fonts.OpenType.TextShaping;
+using EPPlus.Fonts.OpenType.TextShaping.Substitutions;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using OfficeOpenXml.Interfaces.Fonts;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace EPPlus.Fonts.OpenType.Tests.TextShaping
+{
+ ///
+ /// Tests that shaping ignores Multiple Substitution sequences longer than
+ /// MultipleSubstitutionProcessor.MaxSequenceLength, so one character cannot expand into up to
+ /// 65535 glyphs. The substitution ('X' to a sequence of 'A' glyphs) is injected into Roboto's
+ /// latn-reachable "liga" feature, the same way as in MultipleSubstitutionShapingTests.
+ ///
+ [TestClass]
+ public class MultipleSubstitutionLimitTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ private OpenTypeFont LoadFontWithSequence(int sequenceLength, out ushort glyphIdX, out ushort glyphIdA)
+ {
+ var font = TestFolderEngine.LoadFont("Roboto", FontSubFamily.Regular, true);
+ Assert.IsTrue(font.CmapTable.TryGetGlyphId('X', out glyphIdX));
+ Assert.IsTrue(font.CmapTable.TryGetGlyphId('A', out glyphIdA));
+
+ var multiSubst = new MultipleSubstSubTable
+ {
+ SubtableFormat = 1,
+ Coverage = CoverageTableFormat2.CreateCoverageFormat2(new List { glyphIdX }),
+ Sequences = new List { Enumerable.Repeat(glyphIdA, sequenceLength).ToArray() }
+ };
+ int lookupIndex = font.GsubTable.LookupList.Lookups.Count;
+ font.GsubTable.LookupList.Lookups.Add(new LookupTable
+ {
+ LookupType = 2,
+ SubTables = new List { multiSubst }
+ });
+
+ var activeIndices = ScriptFeatureResolver.GetActiveFeatureIndices(font.GsubTable.ScriptList, "latn", null);
+ Assert.IsNotNull(activeIndices);
+ var records = font.GsubTable.FeatureList.FeatureRecords;
+ int ligaIndex = Enumerable.Range(0, records.Count)
+ .First(i => records[i].FeatureTag.Value == "liga" && activeIndices.Contains(i));
+ var featureTable = records[ligaIndex].FeatureTable;
+ featureTable.LookupListIndices = (featureTable.LookupListIndices ?? new ushort[0])
+ .Concat(new[] { (ushort)lookupIndex }).ToArray();
+ featureTable.LookupCount = (ushort)featureTable.LookupListIndices.Length;
+
+ return font;
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Shape_SequenceLongerThanLimit_GlyphNotExpanded()
+ {
+ var font = LoadFontWithSequence(65535, out ushort glyphIdX, out _);
+ var shaper = new TextShaper(TestFolderEngine, font);
+
+ var shaped = shaper.Shape(new string('X', 100));
+
+ Assert.AreEqual(100, shaped.Glyphs.Length, "A sequence over the limit must not be applied.");
+ Assert.IsTrue(shaped.Glyphs.All(g => g.GlyphId == glyphIdX));
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void Shape_SequenceAtLimit_IsExpanded()
+ {
+ int limit = MultipleSubstitutionProcessor.MaxSequenceLength;
+ var font = LoadFontWithSequence(limit, out _, out ushort glyphIdA);
+ var shaper = new TextShaper(TestFolderEngine, font);
+
+ var shaped = shaper.Shape("X");
+
+ Assert.AreEqual(limit, shaped.Glyphs.Length, "A sequence at the limit must still be applied.");
+ Assert.IsTrue(shaped.Glyphs.All(g => g.GlyphId == glyphIdA));
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ShapingLookupReferenceLimitTests.cs b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ShapingLookupReferenceLimitTests.cs
new file mode 100644
index 0000000000..1fb8d2f87b
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType.Tests/TextShaping/ShapingLookupReferenceLimitTests.cs
@@ -0,0 +1,144 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Tests for the shaping subtable reference limit
+ *************************************************************************************************/
+using EPPlus.Fonts.OpenType.TextShaping;
+using Microsoft.VisualStudio.TestTools.UnitTesting;
+using System;
+using System.IO;
+using System.Text;
+
+namespace EPPlus.Fonts.OpenType.Tests.TextShaping
+{
+ ///
+ /// Tests that a font whose feature lists the same lookup many times, with a lookup that has many
+ /// offsets to the same subtable, cannot make building and using a TextShaper grow with the square
+ /// of the table size (ShapingLimits.MaxSubtableReferences).
+ /// The fonts are Roboto-Regular.ttf with a crafted GPOS or GSUB table appended to the end of the file.
+ ///
+ [TestClass]
+ public class ShapingLookupReferenceLimitTests : FontTestBase
+ {
+ public override TestContext? TestContext { get; set; }
+
+ // 30000 lookup references x 30000 subtable offsets = 900 million subtable references.
+ private const int RepeatCount = 30000;
+
+ private static void WriteUInt16(byte[] b, int pos, int v)
+ {
+ b[pos] = (byte)(v >> 8);
+ b[pos + 1] = (byte)v;
+ }
+
+ private static void WriteUInt32(byte[] b, int pos, uint v)
+ {
+ b[pos] = (byte)(v >> 24);
+ b[pos + 1] = (byte)(v >> 16);
+ b[pos + 2] = (byte)(v >> 8);
+ b[pos + 3] = (byte)v;
+ }
+
+ ///
+ /// Returns Roboto whose table is replaced by one feature
+ /// that lists lookup 0 times, where lookup 0
+ /// (of ) has offsets to the same subtable.
+ /// is the subtable. If is true,
+ /// its coverage offset (bytes 2-3) is filled in and points to an empty coverage table after it.
+ ///
+ private static byte[] BuildFont(string tableTag, string featureTag, int lookupType, int[] subtableHeader, bool hasCoverage, int n)
+ {
+ var font = File.ReadAllBytes(Path.Combine(FontFolder, "Roboto-Regular.ttf"));
+ int table = (font.Length + 3) & ~3;
+ const int featureList = 10;
+ int feature = featureList + 8;
+ int lookupList = feature + 4 + 2 * n;
+ int lookup = lookupList + 4;
+ int subtable = lookup + 6 + 2 * n;
+ int coverage = subtable + 2 * subtableHeader.Length;
+ int length = hasCoverage ? coverage + 4 : coverage;
+ Assert.IsTrue(lookupList <= ushort.MaxValue && subtable - lookup <= ushort.MaxValue);
+
+ var bytes = new byte[table + length];
+ Array.Copy(font, bytes, font.Length);
+ int record = GsubTestFontBuilder.RecordPosition(bytes, tableTag);
+ WriteUInt32(bytes, record + 8, (uint)table);
+ WriteUInt32(bytes, record + 12, (uint)length);
+
+ // Header: version 1.0, no ScriptList, FeatureList and LookupList
+ WriteUInt16(bytes, table, 1);
+ WriteUInt16(bytes, table + 6, featureList);
+ WriteUInt16(bytes, table + 8, lookupList);
+ // FeatureList: one feature record
+ WriteUInt16(bytes, table + featureList, 1);
+ Encoding.ASCII.GetBytes(featureTag).CopyTo(bytes, table + featureList + 2);
+ WriteUInt16(bytes, table + featureList + 6, feature - featureList);
+ // Feature: n lookup indices, all 0
+ WriteUInt16(bytes, table + feature + 2, n);
+ // LookupList: one lookup
+ WriteUInt16(bytes, table + lookupList, 1);
+ WriteUInt16(bytes, table + lookupList + 2, lookup - lookupList);
+ // Lookup: n offsets to the same subtable
+ WriteUInt16(bytes, table + lookup, lookupType);
+ WriteUInt16(bytes, table + lookup + 4, n);
+ for (int i = 0; i < n; i++)
+ WriteUInt16(bytes, table + lookup + 6 + 2 * i, subtable - lookup);
+ // Subtable, optionally with its coverage offset pointing to an empty format 1 coverage
+ for (int i = 0; i < subtableHeader.Length; i++)
+ WriteUInt16(bytes, table + subtable + 2 * i, subtableHeader[i]);
+ if (hasCoverage)
+ {
+ WriteUInt16(bytes, table + subtable + 2, coverage - subtable);
+ WriteUInt16(bytes, table + coverage, 1);
+ }
+ return bytes;
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void TextShaper_RepeatedGposLookupReferences_BuildsAndShapesQuickly()
+ {
+ // PairPos format 1: format, coverage offset, ValueFormat1 (XAdvance), ValueFormat2, PairSetCount 0
+ var font = new OpenTypeFont(BuildFont("GPOS", "kern", 2, new[] { 1, 0, 4, 0, 0 }, true, RepeatCount));
+
+ var shaper = new TextShaper(TestFolderEngine, font);
+ var shaped = shaper.Shape("AVAV");
+
+ Assert.AreEqual(4, shaped.Glyphs.Length);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void TextShaper_RepeatedGsubLookupReferences_BuildsAndShapesQuickly()
+ {
+ // LigatureSubst format 1: format, coverage offset, LigatureSetCount 0
+ var font = new OpenTypeFont(BuildFont("GSUB", "liga", 4, new[] { 1, 0, 0 }, true, RepeatCount));
+
+ var shaper = new TextShaper(TestFolderEngine, font);
+ var shaped = shaper.Shape("office");
+
+ Assert.AreEqual(6, shaped.Glyphs.Length);
+ }
+
+ [TestMethod]
+ [Timeout(5000)]
+ public void TextShaper_RepeatedGsubContextualLookupReferences_ShapesQuickly()
+ {
+ // ChainContextSubst format 3 with no glyph sequences: format, backtrack count 0, input count 0,
+ // lookahead count 0, substitution count 0. ChainingContextualProcessor collects these lookups
+ // on every call, so shape several times.
+ var font = new OpenTypeFont(BuildFont("GSUB", "calt", 6, new[] { 3, 0, 0, 0, 0 }, false, RepeatCount));
+
+ var shaper = new TextShaper(TestFolderEngine, font);
+ for (int i = 0; i < 5; i++)
+ Assert.AreEqual(4, shaper.Shape("text").Glyphs.Length);
+ }
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType/FontStore.cs b/src/EPPlus.Fonts.OpenType/FontStore.cs
index 45dd195f59..1946a4d92a 100644
--- a/src/EPPlus.Fonts.OpenType/FontStore.cs
+++ b/src/EPPlus.Fonts.OpenType/FontStore.cs
@@ -117,6 +117,7 @@ internal OpenTypeFont LoadFont(string fontName, FontSubFamily subFamily, bool ig
}
font.EnsureFullyLoaded();
+ FontLog.WriteLoadWarnings(Logger, font, fontName);
font.IsReadOnly = true;
_fontCache.AddToCache(font, lockKey);
return font;
diff --git a/src/EPPlus.Fonts.OpenType/FontsBinaryReader.cs b/src/EPPlus.Fonts.OpenType/FontsBinaryReader.cs
index 1f07244a06..970438b046 100644
--- a/src/EPPlus.Fonts.OpenType/FontsBinaryReader.cs
+++ b/src/EPPlus.Fonts.OpenType/FontsBinaryReader.cs
@@ -21,15 +21,50 @@ public FontsBinaryReader(Stream input) : base(input)
{
}
+ private long _totalBytesRead;
+ private long _readLimit = long.MaxValue;
+ private long _readBudget;
+
+ /// Total number of bytes read through this reader since it was created.
+ internal long TotalBytesRead => _totalBytesRead;
+
+ ///
+ /// Limits how many more bytes may be read until is called.
+ /// Reading past the limit throws .
+ /// Protects parsers where shared or overlapping offsets would otherwise let a small
+ /// malformed table be read over and over.
+ ///
+ internal void SetReadBudget(long budget)
+ {
+ _readBudget = budget;
+ _readLimit = _totalBytesRead + budget;
+ }
- private string _context;
- private int _numberOfReadBytes = 0;
+ internal void ClearReadBudget()
+ {
+ _readLimit = long.MaxValue;
+ }
+ public override byte[] ReadBytes(int count)
+ {
+ CheckReadBudget(count);
+ var bytes = base.ReadBytes(count);
+ _totalBytesRead += bytes.Length;
+ return bytes;
+ }
- internal void SetContext(string name)
+ public override byte ReadByte()
{
- _context = name;
- _numberOfReadBytes = 0;
+ CheckReadBudget(1);
+ var b = base.ReadByte();
+ _totalBytesRead++;
+ return b;
+ }
+
+ private void CheckReadBudget(int count)
+ {
+ if (_totalBytesRead + count > _readLimit)
+ throw new FontReadBudgetExceededException(_readBudget);
}
internal ushort ReadUInt16BigEndian()
@@ -90,4 +125,18 @@ internal short[] ReadInt16ArrayBigEndian(int count)
}
}
+
+ ///
+ /// Thrown by when a parser reads more than its read budget.
+ ///
+ internal sealed class FontReadBudgetExceededException : IOException
+ {
+ internal FontReadBudgetExceededException(long budget)
+ : base("Parsing exceeded the read budget of " + budget + " bytes.")
+ {
+ Budget = budget;
+ }
+
+ internal long Budget { get; }
+ }
}
diff --git a/src/EPPlus.Fonts.OpenType/Logging/FontLog.cs b/src/EPPlus.Fonts.OpenType/Logging/FontLog.cs
index fd73c81d84..95cdc0d060 100644
--- a/src/EPPlus.Fonts.OpenType/Logging/FontLog.cs
+++ b/src/EPPlus.Fonts.OpenType/Logging/FontLog.cs
@@ -67,6 +67,28 @@ internal static void Write(
});
}
+ ///
+ /// Writes the font's load warnings (e.g. an ignored GSUB/GPOS table) as Warning events.
+ /// Call after the font is fully loaded, since tables are loaded lazily.
+ ///
+ internal static void WriteLoadWarnings(IFontLogger logger, OpenTypeFont font, string requestedFont)
+ {
+ if (font == null || !IsEnabled(logger, FontLogSeverity.Warning))
+ return;
+
+ var warnings = font.LoadWarnings;
+ if (warnings.Length == 0)
+ return;
+
+ string resolvedFont = FamilyOf(font);
+ string fontDescription = Describe(font);
+ foreach (var warning in warnings)
+ {
+ Write(logger, FontLogSeverity.Warning, FontLogEventType.FontTableIgnored,
+ "Font '" + fontDescription + "': " + warning, requestedFont, resolvedFont);
+ }
+ }
+
/// Family and subfamily of a font, for messages.
internal static string Describe(OpenTypeFont font)
{
diff --git a/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs b/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs
index 84b835f76f..60a7bdc137 100644
--- a/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs
+++ b/src/EPPlus.Fonts.OpenType/OpenTypeFont.cs
@@ -34,6 +34,7 @@ Date Author Change
using System;
using System.Collections.Generic;
using System.Diagnostics;
+using System.IO;
using System.Linq;
namespace EPPlus.Fonts.OpenType
@@ -73,7 +74,13 @@ internal OpenTypeFont(byte[] fontBytes, long startOffset)
if (fontBytes == null || fontBytes.Length < 4)
throw new ArgumentException("Invalid font data: too short to contain a valid SFNT header.", nameof(fontBytes));
- Format = DetectFormat(fontBytes, startOffset > -1 ? startOffset : 0);
+ // The SFNT header (12 bytes) must fit in the data
+ long headerStart = startOffset > -1 ? startOffset : 0;
+ if (headerStart < 0 || headerStart + 12 > fontBytes.Length)
+ throw new InvalidDataException("Invalid font data: the SFNT header at offset " + headerStart +
+ " does not fit in the font data (length " + fontBytes.Length + ").");
+
+ Format = DetectFormat(fontBytes, headerStart);
_fontBytes = fontBytes;
var tableReaderFactory = new FontTableReaderFactory(fontBytes);
@@ -232,6 +239,15 @@ internal FontSerializationContext GetSerializationContext()
return new FontSerializationContext(this);
}
+ ///
+ /// Problems found while loading tables, e.g. a GSUB/GPOS table that was ignored because
+ /// parsing it exceeded its read budget. Empty for fonts built in memory.
+ ///
+ internal string[] LoadWarnings
+ {
+ get { return _tblSettings != null ? _tblSettings.GetLoadWarnings() : new string[0]; }
+ }
+
public FontValidationReport ValidateFont(FontValidationSeverity severity)
{
var validator = new FontValidator();
@@ -515,6 +531,13 @@ private void Initialize(FontsBinaryReader reader)
private void ReadTableRecords(FontsBinaryReader reader)
{
+ long dataLength = reader.BaseStream.Length;
+
+ // The whole table directory (16 bytes per record) must fit in the data
+ if (reader.BaseStream.Position + 16L * NumTables > dataLength)
+ throw new InvalidDataException("Invalid font data: the table directory (" + NumTables +
+ " tables) extends beyond the end of the font data (length " + dataLength + ").");
+
_tableRecords = new Dictionary();
for (var x = 0; x < NumTables; x++)
{
@@ -525,6 +548,17 @@ private void ReadTableRecords(FontsBinaryReader reader)
Offset = reader.ReadUInt32BigEndian(),
Length = reader.ReadUInt32BigEndian()
};
+
+ // Every table must lie within the data. Table lengths are used to size buffers and
+ // readers, so an unchecked length lets a tiny file trigger a huge allocation.
+ if (!record.FitsWithin(dataLength))
+ throw new InvalidDataException("Invalid font data: table '" + record.Tag.Value + "' (offset " +
+ record.Offset + ", length " + record.Length + ") extends beyond the end of the font data (length " +
+ dataLength + ").");
+
+ if (_tableRecords.ContainsKey(record.Tag.Value))
+ throw new InvalidDataException("Invalid font data: table '" + record.Tag.Value + "' occurs more than once.");
+
_tableRecords.Add(record.Tag.Value, record);
}
}
diff --git a/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs b/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs
index f2537b2117..492d5c339a 100644
--- a/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs
+++ b/src/EPPlus.Fonts.OpenType/OpenTypeFontEngine.cs
@@ -288,6 +288,7 @@ public OpenTypeFont GetFromBytes(byte[] bytes)
var font = new OpenTypeFont(bytes);
font.EnsureFullyLoaded();
+ FontLog.WriteLoadWarnings(Logger, font, null);
return font;
}
diff --git a/src/EPPlus.Fonts.OpenType/Scanner/DefaultFontFileReader.cs b/src/EPPlus.Fonts.OpenType/Scanner/DefaultFontFileReader.cs
index c6c40c8e98..e31b37211b 100644
--- a/src/EPPlus.Fonts.OpenType/Scanner/DefaultFontFileReader.cs
+++ b/src/EPPlus.Fonts.OpenType/Scanner/DefaultFontFileReader.cs
@@ -41,6 +41,10 @@ public byte[] ReadFontBytes(FontFaceInfo face)
/// Standalone TTF bytes for the font at the given offset.
private static byte[] ExtractTtcFont(byte[] ttcBytes, long offset)
{
+ // The SFNT header (12 bytes) must fit in the file
+ if (offset < 0 || offset + 12 > ttcBytes.Length)
+ throw new InvalidDataException("TTC font offset is outside the file.");
+
using (var ms = new MemoryStream(ttcBytes))
using (var reader = new BinaryReader(ms))
{
@@ -50,6 +54,11 @@ private static byte[] ExtractTtcFont(byte[] ttcBytes, long offset)
ushort numTables = ReadUInt16BE(reader);
ms.Position += 6; // skip searchRange, entrySelector, rangeShift
+ // The whole table directory must fit in the file
+ long directorySize = 12 + 16L * numTables;
+ if (offset + directorySize > ttcBytes.Length)
+ throw new InvalidDataException("TTC table directory extends beyond the end of the file.");
+
// Read table records from the font's table directory
var tags = new string[numTables];
var checksums = new uint[numTables];
@@ -63,13 +72,21 @@ private static byte[] ExtractTtcFont(byte[] ttcBytes, long offset)
checksums[i] = ReadUInt32BE(reader);
srcOffsets[i] = ReadUInt32BE(reader);
lengths[i] = ReadUInt32BE(reader);
+
+ // Each table must fit in the file
+ if ((long)srcOffsets[i] + lengths[i] > ttcBytes.Length)
+ throw new InvalidDataException($"TTC table '{tags[i]}' extends beyond the end of the file.");
}
- // Calculate output size: SFNT header (12) + table directory (16 * n) + aligned table data
- int directorySize = 12 + numTables * 16;
- int totalSize = directorySize;
+ // Calculate output size: SFNT header (12) + table directory (16 * n) + aligned table data.
+ // Computed as long: the tables of one face never overlap in a valid file, so the total
+ // cannot exceed the file size plus the new directory and padding.
+ long totalSize = directorySize;
for (int i = 0; i < numTables; i++)
- totalSize += (int)((lengths[i] + 3u) & ~3u);
+ totalSize += (lengths[i] + 3L) & ~3L;
+
+ if (totalSize > ttcBytes.Length + directorySize + 3L * numTables)
+ throw new InvalidDataException("TTC tables overlap or exceed the file size.");
byte[] result = new byte[totalSize];
diff --git a/src/EPPlus.Fonts.OpenType/Scanner/FontScannerV2Core.cs b/src/EPPlus.Fonts.OpenType/Scanner/FontScannerV2Core.cs
index fe45739553..8ae0166789 100644
--- a/src/EPPlus.Fonts.OpenType/Scanner/FontScannerV2Core.cs
+++ b/src/EPPlus.Fonts.OpenType/Scanner/FontScannerV2Core.cs
@@ -79,6 +79,12 @@ internal static FontFaceInfo ScanSingleFace(string filePath, long offset)
reader.ReadUInt16BigEndian(); // entrySelector
reader.ReadUInt16BigEndian(); // rangeShift
+ // The whole table directory (16 bytes per record) must fit in the file
+ long fileLength = fs.Length;
+ if (fs.Position + 16L * numTables > fileLength)
+ throw new InvalidDataException(string.Format(
+ "The table directory ({0} tables) extends beyond the end of font file '{1}'.", numTables, filePath));
+
for (int i = 0; i < numTables; i++)
{
long tagPos = fs.Position;
@@ -89,6 +95,13 @@ internal static FontFaceInfo ScanSingleFace(string filePath, long offset)
Offset = reader.ReadUInt32BigEndian(),
Length = reader.ReadUInt32BigEndian()
};
+
+ // Every table must lie within the file; the name table length is used to size a buffer below.
+ if (!record.FitsWithin(fileLength))
+ throw new InvalidDataException(string.Format(
+ "Table '{0}' (offset {1}, length {2}) extends beyond the end of font file '{3}'.",
+ record.Tag.Value, record.Offset, record.Length, filePath));
+
info.TableRecords[record.Tag.Value] = record;
}
diff --git a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs
index 6dba1d5d73..2f197519b4 100644
--- a/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs
+++ b/src/EPPlus.Fonts.OpenType/Subsetting/SubsetFontBuilder.cs
@@ -92,13 +92,19 @@ public OpenTypeFont CreateSubset(OpenTypeFont originalFont, IEnumerable uni
// Creates a deterministic mapping between old and new Glyph IDs.
private void BuildGlyphMapping(FontSubsettingContext context)
{
+ // Glyph IDs referenced by GSUB, GPOS or composite glyphs that do not exist in the font
+ // cannot be part of the subset. Removing them also keeps the count at most 65535, so every
+ // new glyph ID fits in a ushort. Glyph 0 (.notdef) is always kept.
+ int numGlyphs = context.OriginalFont.MaxpTable.numGlyphs;
+ context.IncludedGlyphs.RemoveWhere(g => g != 0 && g >= numGlyphs);
+
var sortedGlyphs = new List(context.IncludedGlyphs);
sortedGlyphs.Sort();
- for (ushort newId = 0; newId < sortedGlyphs.Count; newId++)
+ for (int newId = 0; newId < sortedGlyphs.Count; newId++)
{
ushort oldId = sortedGlyphs[newId];
- context.OldToNewGlyphId[oldId] = newId;
+ context.OldToNewGlyphId[oldId] = (ushort)newId;
context.NewToOldGlyphId.Add(oldId);
}
}
diff --git a/src/EPPlus.Fonts.OpenType/TableRecord.cs b/src/EPPlus.Fonts.OpenType/TableRecord.cs
index 62df6567d0..684fc9daa3 100644
--- a/src/EPPlus.Fonts.OpenType/TableRecord.cs
+++ b/src/EPPlus.Fonts.OpenType/TableRecord.cs
@@ -21,5 +21,11 @@ public class TableRecord
public uint Offset { get; set; }
public uint Length { get; set; }
+
+ /// True if the table lies entirely within data of the given length.
+ internal bool FitsWithin(long dataLength)
+ {
+ return (long)Offset + Length <= dataLength;
+ }
}
}
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapSubtable12.cs b/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapSubtable12.cs
index 2a228ea978..e6fc7ab6b9 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapSubtable12.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapSubtable12.cs
@@ -33,21 +33,38 @@ internal class CmapSubtable12 : CmapSubtableBase
public List Groups { get; } = new List();
+ // Highest valid Unicode code point. Format 12 allows uint, but anything above this is invalid.
+ private const uint MaxUnicodeCodePoint = 0x10FFFF;
+
public override GlyphMappings GetGlyphMappings()
{
var mapping = new GlyphMappings();
+ // Spec: groups must be sorted and must not overlap. We enforce this by never mapping
+ // a code point already covered by a previous group. This caps the total number of
+ // iterations at 0x110000, regardless of what the font file contains.
+ long nextAllowed = 0;
+
foreach (var group in Groups)
{
uint startCharCode = group.StartCharCode;
uint endCharCode = group.EndCharCode;
uint startGlyphId = group.StartGlyphId;
- for (uint charCode = startCharCode; charCode <= endCharCode; charCode++)
+ if (endCharCode < startCharCode) continue; // invalid group
+ if (startCharCode > MaxUnicodeCodePoint) continue; // entirely outside Unicode
+
+ long from = Math.Max((long)startCharCode, nextAllowed);
+ long to = Math.Min((long)endCharCode, MaxUnicodeCodePoint);
+
+ // long loop variable so it cannot wrap around like a uint would
+ for (long charCode = from; charCode <= to; charCode++)
{
- ushort glyphIndex = (ushort)(startGlyphId + (charCode - startCharCode));
- mapping.AddMapping(charCode, glyphIndex);
+ ushort glyphIndex = (ushort)(startGlyphId + (uint)(charCode - startCharCode));
+ mapping.AddMapping((uint)charCode, glyphIndex);
}
+
+ if (to + 1 > nextAllowed) nextAllowed = to + 1;
}
return mapping;
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapSubtable4.cs b/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapSubtable4.cs
index d19ed73526..fda8227950 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapSubtable4.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapSubtable4.cs
@@ -50,6 +50,12 @@ public override GlyphMappings GetGlyphMappings()
int segCount = EndCode.Length;
+ // Spec: segments are sorted by endCode and must not overlap. MapCodePointToGlyph picks the
+ // first segment whose endCode >= code point; we mirror that by never mapping a code point
+ // that a previous segment has already passed. This caps the total iterations at 65536,
+ // regardless of what the font file contains.
+ uint nextAllowed = 0;
+
for (int i = 0; i < segCount; i++)
{
ushort startCode = StartCode[i];
@@ -57,7 +63,13 @@ public override GlyphMappings GetGlyphMappings()
short idDelta = IdDelta[i];
ushort idRangeOffset = IdRangeOffset[i];
- for (uint charCode = startCode; charCode <= endCode; charCode++)
+ uint from = Math.Max(startCode, nextAllowed);
+
+ // The segment owns everything up to its endCode, even code points it does not map
+ // (endCode < startCode, or glyph 0) - just as MapCodePointToGlyph treats them.
+ if ((uint)endCode + 1 > nextAllowed) nextAllowed = (uint)endCode + 1;
+
+ for (uint charCode = from; charCode <= endCode; charCode++)
{
ushort glyphIndex;
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapTableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapTableLoader.cs
index 2e10794821..55276f5ab0 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapTableLoader.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Cmap/CmapTableLoader.cs
@@ -21,9 +21,18 @@ internal class CmapTableLoader : TableLoader
{
public CmapTableLoader(TableLoaderSettings settings) : base(settings, TableNames.Cmap)
{
+ _settings = settings;
}
+ private readonly TableLoaderSettings _settings;
+
protected override CmapTable LoadInternal()
+ {
+ // A font cannot be used without cmap: if it exceeds the read budget the font is rejected.
+ return LoadWithReadBudget(LoadCmapTable, _settings, tableIsRequired: true);
+ }
+
+ private CmapTable LoadCmapTable()
{
_reader.BaseStream.Position = _offset;
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/LookupListTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/LookupListTable.cs
index 0b0e234347..5d4056a222 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/LookupListTable.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Common/Layout/Lookups/LookupListTable.cs
@@ -11,6 +11,7 @@ Date Author Change
10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0
*************************************************************************************************/
using System.Collections.Generic;
+using System.IO;
using EPPlus.Fonts.OpenType.Subsetting;
namespace EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups
@@ -25,7 +26,25 @@ public class LookupListTable : FontTableElement
///
public List Lookups { get; set; } = new List();
+ ///
+ /// Lookup type of an Extension lookup in the table this list belongs to: 7 in GSUB, 9 in GPOS.
+ /// Set by GsubTable and GposTable before serialization. 0 means unknown, and then the list is
+ /// always written with 16-bit offsets only.
+ ///
+ internal ushort ExtensionLookupType { get; set; }
+
internal override void Serialize(FontsBinaryWriter writer)
+ {
+ // Lookups and subtables are referenced with 16-bit offsets. When the list is too large for
+ // that (subsets of large fonts, whose original used Extension lookups for the same reason),
+ // every lookup is written as an Extension lookup with 32-bit offsets to its subtables.
+ if (ExtensionLookupType != 0 && TrySerializeAsExtensionLookups(writer))
+ return;
+
+ SerializeWith16BitOffsets(writer);
+ }
+
+ private void SerializeWith16BitOffsets(FontsBinaryWriter writer)
{
long startPos = writer.BaseStream.Position;
@@ -50,6 +69,149 @@ internal override void Serialize(FontsBinaryWriter writer)
}
}
+ private sealed class SerializedLookup
+ {
+ public LookupTable Lookup;
+ public ushort InnerLookupType;
+ public readonly List SubTables = new List();
+ public long SizeWith16BitOffsets;
+ public bool SubTablesFit = true;
+ }
+
+ ///
+ /// Writes the list as Extension lookups if it does not fit with 16-bit offsets. Returns false,
+ /// without writing anything, if it fits (the list is then written exactly as before) or if it
+ /// cannot be written as Extension lookups.
+ ///
+ private bool TrySerializeAsExtensionLookups(FontsBinaryWriter writer)
+ {
+ // Serialize every subtable on its own so all sizes are known before anything is written.
+ // Subtables use offsets relative to their own start, so their bytes can be moved as is.
+ var lookups = new List();
+ foreach (var lookup in Lookups)
+ {
+ var serialized = new SerializedLookup { Lookup = lookup, InnerLookupType = lookup.LookupType };
+ long size = LookupHeaderSize(lookup);
+ foreach (var subTable in lookup.SubTables)
+ {
+ FontTableElement inner = subTable;
+ if (subTable is ExtensionSubTableBase extension)
+ {
+ inner = extension.ExtendedSubTable;
+ serialized.InnerLookupType = extension.ExtensionLookupType;
+ }
+ if (inner == null)
+ return false;
+
+ byte[] bytes = SerializeElement(inner);
+ // The 16-bit offset points at the start of the subtable, so the start must fit.
+ if (size > ushort.MaxValue)
+ serialized.SubTablesFit = false;
+ size += subTable is ExtensionSubTableBase ? 8 + bytes.Length : bytes.Length;
+ serialized.SubTables.Add(bytes);
+ }
+ // A lookup of the Extension type whose subtables are not Extension subtables (GPOS
+ // lookups as loaded from a font file) has no known inner type.
+ if (serialized.InnerLookupType == ExtensionLookupType)
+ return false;
+
+ serialized.SizeWith16BitOffsets = size;
+ lookups.Add(serialized);
+ }
+
+ if (FitsWith16BitOffsets(lookups))
+ return false;
+
+ // Lookup headers and the 8-byte Extension subtables come first; they must fit 16-bit offsets.
+ long headersSize = 2 + 2L * lookups.Count;
+ foreach (var serialized in lookups)
+ headersSize += LookupHeaderSize(serialized.Lookup) + 8L * serialized.SubTables.Count;
+ if (headersSize > ushort.MaxValue)
+ return false;
+
+ long listStart = writer.BaseStream.Position;
+ writer.WriteUInt16BigEndian((ushort)lookups.Count);
+ long lookupOffsetsPos = writer.BaseStream.Position;
+ for (int i = 0; i < lookups.Count; i++)
+ writer.WriteUInt16BigEndian(0);
+
+ var pending = new List>(); // Extension subtable position, subtable bytes
+ for (int i = 0; i < lookups.Count; i++)
+ {
+ var serialized = lookups[i];
+ var lookup = serialized.Lookup;
+ long lookupStart = writer.BaseStream.Position;
+ WriteUInt16At(writer, lookupOffsetsPos + 2 * i, (ushort)(lookupStart - listStart));
+
+ writer.WriteUInt16BigEndian(ExtensionLookupType);
+ writer.WriteUInt16BigEndian(lookup.LookupFlag);
+ writer.WriteUInt16BigEndian((ushort)serialized.SubTables.Count);
+ long subTableOffsetsPos = writer.BaseStream.Position;
+ for (int k = 0; k < serialized.SubTables.Count; k++)
+ writer.WriteUInt16BigEndian(0);
+ if ((lookup.LookupFlag & 0x0010) != 0)
+ writer.WriteUInt16BigEndian(lookup.MarkFilteringSet);
+
+ for (int k = 0; k < serialized.SubTables.Count; k++)
+ {
+ long extensionStart = writer.BaseStream.Position;
+ WriteUInt16At(writer, subTableOffsetsPos + 2 * k, (ushort)(extensionStart - lookupStart));
+ writer.WriteUInt16BigEndian(1); // Extension format
+ writer.WriteUInt16BigEndian(serialized.InnerLookupType);
+ writer.WriteUInt32BigEndian(0); // 32-bit offset, written below
+ pending.Add(new KeyValuePair(extensionStart, serialized.SubTables[k]));
+ }
+ }
+
+ foreach (var item in pending)
+ {
+ long subTableStart = writer.BaseStream.Position;
+ writer.BaseStream.Seek(item.Key + 4, SeekOrigin.Begin);
+ writer.WriteUInt32BigEndian((uint)(subTableStart - item.Key));
+ writer.BaseStream.Seek(subTableStart, SeekOrigin.Begin);
+ writer.Write(item.Value);
+ }
+
+ return true;
+ }
+
+ /// True if every lookup and subtable offset of the 16-bit layout is at most 65535.
+ private static bool FitsWith16BitOffsets(List lookups)
+ {
+ long lookupStart = 2 + 2L * lookups.Count;
+ foreach (var serialized in lookups)
+ {
+ if (lookupStart > ushort.MaxValue || !serialized.SubTablesFit)
+ return false;
+ lookupStart += serialized.SizeWith16BitOffsets;
+ }
+ return true;
+ }
+
+ private static long LookupHeaderSize(LookupTable lookup)
+ {
+ return 6 + 2L * lookup.SubTables.Count + ((lookup.LookupFlag & 0x0010) != 0 ? 2 : 0);
+ }
+
+ private static byte[] SerializeElement(FontTableElement element)
+ {
+ using (var stream = new MemoryStream())
+ using (var elementWriter = new FontsBinaryWriter(stream))
+ {
+ element.Serialize(elementWriter);
+ elementWriter.Flush();
+ return stream.ToArray();
+ }
+ }
+
+ private static void WriteUInt16At(FontsBinaryWriter writer, long position, ushort value)
+ {
+ long current = writer.BaseStream.Position;
+ writer.BaseStream.Seek(position, SeekOrigin.Begin);
+ writer.WriteUInt16BigEndian(value);
+ writer.BaseStream.Seek(current, SeekOrigin.Begin);
+ }
+
///
/// Rewrites the lookup list. Note that in a full implementation,
/// removing lookups might require remapping indexes in Features.
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTableLoader.cs
index 3d3e1b9c2c..fc3dee0785 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTableLoader.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Glyph/GlyfTableLoader.cs
@@ -14,6 +14,7 @@ Date Author Change
using EPPlus.Fonts.OpenType.Tables.Glyph.Serialization;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
namespace EPPlus.Fonts.OpenType.Tables.Glyph
@@ -36,7 +37,6 @@ public GlyfTableLoader(TableLoaderSettings settings) : base(settings, TableNames
protected override GlyfTable LoadInternal()
{
var glyphs = new Glyph[_glyphOffsets.Length];
- _reader.SetContext("glyf");
for (int i = 0; i < _glyphOffsets.Length - 1; i++)
{
var start = _glyphOffsets[i];
@@ -47,10 +47,25 @@ protected override GlyfTable LoadInternal()
continue;
}
- _reader.BaseStream.Position = _offset + start;
- glyphs[i] = GlyphDeserializer.Deserialize(_reader);
+ // Spec: loca offsets must be ascending and point inside the glyf table.
+ // A malformed entry is treated as an empty glyph.
+ if (end < start || end > _length)
+ {
+ continue;
+ }
+
+ long glyphEnd = (long)_offset + end;
+ _reader.BaseStream.Position = (long)_offset + start;
+ try
+ {
+ glyphs[i] = GlyphDeserializer.Deserialize(_reader, glyphEnd);
+ }
+ catch (InvalidDataException)
+ {
+ // The glyph data does not fit within its loca range - treat as empty glyph.
+ glyphs[i] = null;
+ }
}
- _reader.SetContext(string.Empty);
return new GlyfTable(_settings) { Glyphs = new List(glyphs) };
}
}
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/CompositeGlyphDeserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/CompositeGlyphDeserializer.cs
index 7ac792a911..da813f6489 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/CompositeGlyphDeserializer.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/CompositeGlyphDeserializer.cs
@@ -10,19 +10,23 @@ Date Author Change
*************************************************************************************************
10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0
*************************************************************************************************/
+using System.IO;
using System.Linq;
namespace EPPlus.Fonts.OpenType.Tables.Glyph.Serialization
{
internal static class CompositeGlyphDeserializer
{
- public static CompositeGlyph Deserialize(FontsBinaryReader reader)
+ public static CompositeGlyph Deserialize(FontsBinaryReader reader, long glyphEnd)
{
var glyph = new CompositeGlyph();
bool moreComponents;
do
{
+ if (reader.BaseStream.Position >= glyphEnd)
+ throw new InvalidDataException("Composite glyph components extend beyond the glyph's loca range.");
+
var flags = (CompositeGlyphFlags)reader.ReadUInt16BigEndian();
var glyphIndex = reader.ReadUInt16BigEndian();
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/GlyphDeserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/GlyphDeserializer.cs
index ac73ccd3cd..182979b5f6 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/GlyphDeserializer.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/GlyphDeserializer.cs
@@ -10,11 +10,16 @@ Date Author Change
*************************************************************************************************
10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0
*************************************************************************************************/
+using System.IO;
+
namespace EPPlus.Fonts.OpenType.Tables.Glyph.Serialization
{
internal static class GlyphDeserializer
{
- public static Glyph Deserialize(FontsBinaryReader reader)
+ /// Reader positioned at the start of the glyph.
+ /// Absolute stream position where the glyph's loca range ends.
+ /// Reading past it throws .
+ public static Glyph Deserialize(FontsBinaryReader reader, long glyphEnd)
{
var numberOfContours = reader.ReadInt16BigEndian();
var xMin = reader.ReadInt16BigEndian();
@@ -34,16 +39,26 @@ public static Glyph Deserialize(FontsBinaryReader reader)
}
};
+ EnsureWithinGlyph(reader, glyphEnd);
+
if (numberOfContours > 0)
{
- glyph.SimpleData = SimpleGlyphDeserializer.Deserialize(reader, numberOfContours);
+ glyph.SimpleData = SimpleGlyphDeserializer.Deserialize(reader, numberOfContours, glyphEnd);
}
else if (numberOfContours < 0)
{
- glyph.CompositeData = CompositeGlyphDeserializer.Deserialize(reader);
+ glyph.CompositeData = CompositeGlyphDeserializer.Deserialize(reader, glyphEnd);
}
+ EnsureWithinGlyph(reader, glyphEnd);
+
return glyph;
}
+
+ private static void EnsureWithinGlyph(FontsBinaryReader reader, long glyphEnd)
+ {
+ if (reader.BaseStream.Position > glyphEnd)
+ throw new InvalidDataException("Glyph data extends beyond the glyph's loca range.");
+ }
}
}
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/SimpleGlyphDeserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/SimpleGlyphDeserializer.cs
index 1056df9c86..446808ea8b 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/SimpleGlyphDeserializer.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Glyph/Serialization/SimpleGlyphDeserializer.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.IO;
using System.Linq;
using System.Text;
@@ -7,7 +8,7 @@ namespace EPPlus.Fonts.OpenType.Tables.Glyph.Serialization
{
internal static class SimpleGlyphDeserializer
{
- public static SimpleGlyph Deserialize(FontsBinaryReader reader, int numberOfContours)
+ public static SimpleGlyph Deserialize(FontsBinaryReader reader, int numberOfContours, long glyphEnd)
{
var glyph = new SimpleGlyph();
@@ -31,6 +32,11 @@ public static SimpleGlyph Deserialize(FontsBinaryReader reader, int numberOfCont
while (expandedFlags.Count < pointCount)
{
+ // Checked inside the loop: repeat flags let a few bytes expand to many points,
+ // so the limit must stop the expansion, not just be verified afterwards.
+ if (reader.BaseStream.Position >= glyphEnd)
+ throw new InvalidDataException("Glyph flags extend beyond the glyph's loca range.");
+
byte flag = reader.ReadByte();
byte repeatCount = 0;
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType1/SinglePosSubTableFormat2 .cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType1/SinglePosSubTableFormat2 .cs
index 770cc6dd8e..fca6ed0d02 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType1/SinglePosSubTableFormat2 .cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType1/SinglePosSubTableFormat2 .cs
@@ -68,6 +68,13 @@ public bool TryGetAdjustment(ushort glyphId, out ValueRecord value)
value = Values[coverageIndex];
return true;
}
+
+ // ValueFormat 0: records are empty and not stored (see the deserializer).
+ if (ValueFormat == 0 && coverageIndex >= 0 && coverageIndex < ValueCount)
+ {
+ value = new ValueRecord();
+ return true;
+ }
}
value = null;
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType1/SinglePosSubTableFormat2Deserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType1/SinglePosSubTableFormat2Deserializer.cs
index 4711bf6f3d..d18a3b0bb7 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType1/SinglePosSubTableFormat2Deserializer.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType1/SinglePosSubTableFormat2Deserializer.cs
@@ -47,10 +47,26 @@ public SinglePosSubTableFormat2 Deserialize(long subtableStartOffset)
};
// Read array of ValueRecords
- subtable.Values = new ValueRecord[subtable.ValueCount];
- for (int i = 0; i < subtable.ValueCount; i++)
+ int recordSize = ValueRecord.GetSize(subtable.ValueFormat);
+ if (recordSize == 0)
{
- subtable.Values[i] = ReadValueRecord(subtable.ValueFormat);
+ // ValueFormat 0: every record is empty and occupies no bytes in the font. Don't allocate
+ // one object per record (ValueCount can be 65535 from an 8-byte header). TryGetAdjustment
+ // and the subset handler treat covered glyphs as having an empty adjustment.
+ subtable.Values = new ValueRecord[0];
+ }
+ else
+ {
+ // The records must fit in the remaining bytes of the font.
+ long remaining = _reader.BaseStream.Length - _reader.BaseStream.Position;
+ if ((long)subtable.ValueCount * recordSize > remaining)
+ return null;
+
+ subtable.Values = new ValueRecord[subtable.ValueCount];
+ for (int i = 0; i < subtable.ValueCount; i++)
+ {
+ subtable.Values[i] = ReadValueRecord(subtable.ValueFormat);
+ }
}
// Read Coverage table
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2.cs
index 95797b15be..01122b962f 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2.cs
@@ -104,21 +104,22 @@ internal override void Serialize(FontsBinaryWriter writer)
{
long subtableStart = writer.BaseStream.Position;
- // Header
+ // Header, in the order the OpenType specification (and PairPosSubTableFormat2Deserializer)
+ // defines: format, coverage offset, value formats, class definition offsets, class counts.
writer.WriteUInt16BigEndian(SubtableFormat); // 2
long coverageOffsetPos = writer.BaseStream.Position;
writer.WriteUInt16BigEndian(0); // Coverage offset placeholder
+ writer.WriteUInt16BigEndian(ValueFormat1);
+ writer.WriteUInt16BigEndian(ValueFormat2);
+
long classDef1OffsetPos = writer.BaseStream.Position;
writer.WriteUInt16BigEndian(0); // ClassDef1 offset placeholder
long classDef2OffsetPos = writer.BaseStream.Position;
writer.WriteUInt16BigEndian(0); // ClassDef2 offset placeholder
- writer.WriteUInt16BigEndian(ValueFormat1);
- writer.WriteUInt16BigEndian(ValueFormat2);
-
writer.WriteUInt16BigEndian(Class1Count);
writer.WriteUInt16BigEndian(Class2Count);
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2Deserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2Deserializer.cs
index 6a2d0689e4..09f1837239 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2Deserializer.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType2/PairPosSubTableFormat2Deserializer.cs
@@ -46,6 +46,23 @@ public PairPosSubTableFormat2 Deserialize(long subtableStart)
table.Class1Count = _reader.ReadUInt16BigEndian();
table.Class2Count = _reader.ReadUInt16BigEndian();
+ // Validate the matrix size before allocating it. A malformed font can otherwise
+ // make us allocate billions of records from a few bytes of input.
+ long recordCount = (long)table.Class1Count * table.Class2Count;
+ if (recordCount > 0)
+ {
+ int recordSize = ValueRecord.GetSize(table.ValueFormat1) + ValueRecord.GetSize(table.ValueFormat2);
+
+ // Both value formats empty: the matrix carries no adjustments at all.
+ if (recordSize == 0)
+ return null;
+
+ // The matrix data must fit in the remaining bytes of the font.
+ long remaining = _reader.BaseStream.Length - _reader.BaseStream.Position;
+ if (recordCount * recordSize > remaining)
+ return null;
+ }
+
// Read class matrix
table.ClassMatrix = new PairValueRecord[table.Class1Count, table.Class2Count];
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType4/MarkToBaseSubTableFormat1Deserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType4/MarkToBaseSubTableFormat1Deserializer.cs
index 2367fc68a1..6a43673c7a 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType4/MarkToBaseSubTableFormat1Deserializer.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/LookupType4/MarkToBaseSubTableFormat1Deserializer.cs
@@ -47,6 +47,11 @@ public MarkToBaseSubTableFormat1 Deserialize(long subtableStartOffset)
BaseArrayOffset = _reader.ReadUInt16BigEndian()
};
+ // A subtable without mark classes can never attach a mark (every mark's class must be
+ // below MarkClassCount). Skip it instead of allocating BaseCount empty records.
+ if (subtable.MarkClassCount == 0)
+ return null;
+
// Read MarkCoverage table
if (subtable.MarkCoverageOffset > 0)
{
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/ValueRecord.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/ValueRecord.cs
index c454be28be..d1130f0cc8 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/ValueRecord.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Data/Lookups/ValueRecord.cs
@@ -61,6 +61,20 @@ public class ValueRecord
///
public ushort YAdvanceDeviceOffset { get; set; }
+ ///
+ /// Number of bytes a ValueRecord with the given format occupies in the font.
+ /// Each of the eight defined flags (bits 0-7) adds one 16-bit field; reserved bits are ignored, as in Read().
+ ///
+ internal static int GetSize(ushort valueFormat)
+ {
+ int size = 0;
+ for (int bit = 0; bit < 8; bit++)
+ {
+ if ((valueFormat & (1 << bit)) != 0) size += 2;
+ }
+ return size;
+ }
+
///
/// Reads a ValueRecord from reader based on format flags
///
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTable.cs
index efca838409..08ef2b8688 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTable.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTable.cs
@@ -100,6 +100,7 @@ internal override void SerializeInternal(FontsBinaryWriter writer, FontSerializa
// 3. LookupList
if (this.LookupList != null)
{
+ this.LookupList.ExtensionLookupType = 9; // GPOS Extension Positioning, used if 16-bit offsets do not fit
LayoutTableSerializationHelper.UpdateOffsetAndSerialize(writer, tableStartOffset, lookupListOffPos, this.LookupList);
}
}
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTableLoader.cs
index 29cb6ad5f8..fb6c8e72ce 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTableLoader.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/GposTableLoader.cs
@@ -30,9 +30,17 @@ internal class GposTableLoader : TableLoader
public GposTableLoader(TableLoaderSettings settings)
: base(settings, TableNames.Gpos)
{
+ _settings = settings;
}
+ private readonly TableLoaderSettings _settings;
+
protected override GposTable LoadInternal()
+ {
+ return LoadWithReadBudget(LoadGposTable, _settings);
+ }
+
+ private GposTable LoadGposTable()
{
_reader.BaseStream.Position = _offset;
var table = new GposTable();
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/PairPosHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/PairPosHandler.cs
index ab25853d34..df1a63eff1 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/PairPosHandler.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/PairPosHandler.cs
@@ -12,6 +12,7 @@ Date Author Change
09/07/2026 EPPlus Software AB Sort expanded pair records by second glyph
*************************************************************************************************/
using EPPlus.Fonts.OpenType.Subsetting;
+using EPPlus.Fonts.OpenType.Tables.Common.Layout.ClassDef;
using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage;
using EPPlus.Fonts.OpenType.Tables.Common.Layout.Lookups;
using EPPlus.Fonts.OpenType.Tables.Gpos.Data.Lookups;
@@ -153,141 +154,127 @@ private PairPosSubTableFormat1 RewriteFormat1(FontSubsettingContext context, Pai
}
///
- /// Rewrites a PairPos Format 2 subtable by expanding class-based kerning to Format 1.
- /// This simplifies subsetting and ensures compatibility.
+ /// Rewrites a PairPos Format 2 subtable as Format 2. The coverage and both class definitions
+ /// are remapped to the subset's glyph IDs, and only the classes used by subset glyphs are kept
+ /// (renumbered in ascending order; class 0 stays 0). Every remaining glyph pair resolves to the
+ /// same value as in the original font. Work and output size grow with the subset size and the
+ /// number of used classes. Expanding every class pair to individual glyph pairs (Format 1), as
+ /// was done before, grew with the subset size squared and could overflow the 16-bit offsets of
+ /// a Format 1 subtable.
///
- private PairPosSubTableFormat1 RewriteFormat2(FontSubsettingContext context, PairPosSubTableFormat2 original)
+ private PairPosSubTableFormat2 RewriteFormat2(FontSubsettingContext context, PairPosSubTableFormat2 original)
{
- // Strategy: Expand class matrix to individual pairs (Format 1)
- // This is simpler than subsetting the class definitions and matrix
-
- // Build map of first glyphs that are both:
- // 1. In the original coverage
- // 2. In our subset
- var firstGlyphMappings = new List();
-
- for (ushort oldGlyphId = 0; oldGlyphId < 65535; oldGlyphId++)
- {
- // Must be in coverage
- int coverageIndex = original.Coverage.GetGlyphIndex(oldGlyphId);
- if (coverageIndex < 0)
- continue;
-
- // Must be in subset
- if (!context.OldToNewGlyphId.TryGetValue(oldGlyphId, out ushort newGlyphId))
- continue;
-
- firstGlyphMappings.Add(new GlyphMapping
- {
- OldGlyphId = oldGlyphId,
- NewGlyphId = newGlyphId,
- OldCoverageIndex = -1 // Not used for Format 2
- });
- }
-
- if (firstGlyphMappings.Count == 0)
+ if (original.Coverage == null || original.ClassMatrix == null)
return null;
- // Sort by NEW glyph ID for coverage
- firstGlyphMappings.Sort((a, b) => a.NewGlyphId.CompareTo(b.NewGlyphId));
-
- // Build PairSets by expanding class matrix
- var newPairSets = new List();
- var newCoverageGlyphs = new List();
+ var firstGlyphs = new List();
+ var firstGlyphClasses = new List>(); // new glyph ID, original class
+ var secondGlyphClasses = new List>(); // new glyph ID, original class
- foreach (var firstMapping in firstGlyphMappings)
+ // NewToOldGlyphId is in ascending order of both old and new glyph IDs, so the lists stay sorted.
+ foreach (ushort oldId in context.NewToOldGlyphId)
{
- // Get class for first glyph
- int class1 = original.ClassDef1.GetClass(firstMapping.OldGlyphId);
- if (class1 < 0 || class1 >= original.Class1Count)
- continue;
+ ushort newId = context.OldToNewGlyphId[oldId];
- // Collect all pairs for this first glyph
- var pairRecords = new List();
+ int class2 = original.ClassDef2?.GetClass(oldId) ?? 0;
+ if (class2 > 0 && class2 < original.Class2Count)
+ secondGlyphClasses.Add(new KeyValuePair(newId, class2));
- // Check all possible second glyphs in our subset
- foreach (var oldSecondGlyph in context.IncludedGlyphs)
- {
- // Skip if same glyph
- if (oldSecondGlyph == firstMapping.OldGlyphId)
- continue;
+ if (original.Coverage.GetGlyphIndex(oldId) < 0)
+ continue;
- // Get class for second glyph
- int class2 = original.ClassDef2.GetClass(oldSecondGlyph);
- if (class2 < 0 || class2 >= original.Class2Count)
- continue;
+ int class1 = original.ClassDef1?.GetClass(oldId) ?? 0;
+ if (class1 < 0 || class1 >= original.Class1Count)
+ continue; // Invalid class: leave the glyph out, as before.
- // Look up in class matrix
- var record = original.ClassMatrix[class1, class2];
- if (record == null)
- continue;
+ firstGlyphs.Add(newId);
+ if (class1 > 0)
+ firstGlyphClasses.Add(new KeyValuePair(newId, class1));
+ }
- // Skip if no actual adjustment
- bool hasValue1 = record.Value1 != null && record.Value1.XAdvance != 0;
- bool hasValue2 = record.Value2 != null && record.Value2.XAdvance != 0;
+ if (firstGlyphs.Count == 0)
+ return null;
- if (!hasValue1 && !hasValue2)
- continue;
+ Dictionary class1Map = BuildClassMap(firstGlyphClasses);
+ Dictionary class2Map = BuildClassMap(secondGlyphClasses);
- // Get remapped second glyph ID
- if (!context.OldToNewGlyphId.TryGetValue(oldSecondGlyph, out ushort newSecondGlyph))
- continue;
+ // Device tables are not carried over: their offsets point into the original subtable.
+ ushort valueFormat1 = (ushort)(original.ValueFormat1 & 0x000F);
+ ushort valueFormat2 = (ushort)(original.ValueFormat2 & 0x000F);
- // Add pair with remapped ID
- pairRecords.Add(new PairValueRecord
- {
- SecondGlyph = newSecondGlyph,
- Value1 = record.Value1,
- Value2 = record.Value2
- });
- }
+ // The matrix follows the 16-byte header and every offset in the subtable is 16-bit.
+ long matrixBytes = (long)class1Map.Count * class2Map.Count
+ * (ValueRecord.GetSize(valueFormat1) + ValueRecord.GetSize(valueFormat2));
+ if (16 + matrixBytes > ushort.MaxValue)
+ return null;
- // Only include if we found pairs
- if (pairRecords.Count > 0)
+ var matrix = new PairValueRecord[class1Map.Count, class2Map.Count];
+ foreach (var c1 in class1Map)
+ {
+ foreach (var c2 in class2Map)
{
- // PairValueRecords must be ordered by SecondGlyph. Both the OpenType
- // specification and PairPosSubTableFormat1.TryGetPairAdjustment, which
- // binary searches the list, rely on it. The records are collected by
- // iterating context.IncludedGlyphs, which is a HashSet with no defined
- // enumeration order, so the list has to be sorted explicitly here.
- pairRecords.Sort(CompareBySecondGlyph);
-
- newCoverageGlyphs.Add(firstMapping.NewGlyphId);
- newPairSets.Add(new PairSet
- {
- PairValueRecords = pairRecords
- });
+ matrix[c1.Value, c2.Value] = original.ClassMatrix[c1.Key, c2.Key];
}
}
- if (newPairSets.Count == 0)
- return null;
-
- // Create new coverage
- var newCoverage = new CoverageTableFormat1
+ return new PairPosSubTableFormat2
{
- CoverageFormat = 1,
- GlyphCount = (ushort)newCoverageGlyphs.Count,
- GlyphArray = newCoverageGlyphs.ToArray()
+ SubtableFormat = 2,
+ ValueFormat1 = valueFormat1,
+ ValueFormat2 = valueFormat2,
+ Coverage = CoverageTableFormat2.CreateCoverageFormat2(firstGlyphs),
+ ClassDef1 = CreateClassDef(firstGlyphClasses, class1Map),
+ ClassDef2 = CreateClassDef(secondGlyphClasses, class2Map),
+ Class1Count = (ushort)class1Map.Count,
+ Class2Count = (ushort)class2Map.Count,
+ ClassMatrix = matrix
};
+ }
- // Return as Format 1 (expanded from class-based)
- return new PairPosSubTableFormat1
- {
- SubtableFormat = 1,
- ValueFormat1 = original.ValueFormat1,
- ValueFormat2 = original.ValueFormat2,
- Coverage = newCoverage,
- PairSets = newPairSets
- };
+ ///
+ /// Maps each class used by the subset to a new class number: class 0 (glyphs not listed in the
+ /// class definition) stays 0, the other used classes get 1, 2, 3... in ascending order.
+ ///
+ private static Dictionary BuildClassMap(List> glyphClasses)
+ {
+ var used = new SortedSet { 0 };
+ foreach (var glyphClass in glyphClasses)
+ used.Add(glyphClass.Value);
+
+ var map = new Dictionary();
+ foreach (int oldClass in used)
+ map[oldClass] = (ushort)map.Count;
+ return map;
}
///
- /// Orders pair value records by second glyph id.
+ /// Builds a ClassDef format 2 from glyph/class pairs sorted by glyph ID, with classes renumbered
+ /// through . Consecutive glyphs with the same class share one range.
+ /// Glyphs that are not listed get class 0.
///
- private static int CompareBySecondGlyph(PairValueRecord a, PairValueRecord b)
+ private static ClassDefFormat2 CreateClassDef(List> glyphClasses, Dictionary classMap)
{
- return a.SecondGlyph.CompareTo(b.SecondGlyph);
+ var ranges = new List();
+ ClassRangeRecord current = null;
+ foreach (var glyphClass in glyphClasses)
+ {
+ ushort newClass = classMap[glyphClass.Value];
+ if (current != null && current.Class == newClass && current.EndGlyphID + 1 == glyphClass.Key)
+ {
+ current.EndGlyphID = glyphClass.Key;
+ }
+ else
+ {
+ current = new ClassRangeRecord
+ {
+ StartGlyphID = glyphClass.Key,
+ EndGlyphID = glyphClass.Key,
+ Class = newClass
+ };
+ ranges.Add(current);
+ }
+ }
+ return new ClassDefFormat2 { ClassRangeRecords = ranges };
}
///
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/SinglePosHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/SinglePosHandler.cs
index 289ab26903..971a239b3b 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/SinglePosHandler.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gpos/Handlers/SinglePosHandler.cs
@@ -103,16 +103,20 @@ private SinglePosSubTableFormat2 RewriteFormat2(FontSubsettingContext context, S
var includedGlyphs = new List();
var includedValues = new List();
+ // ValueFormat 0: records are empty and not stored by the deserializer.
+ bool isEmptyFormat = original.ValueFormat == 0;
+
for (ushort oldGlyphId = 0; oldGlyphId < 65535; oldGlyphId++)
{
int coverageIndex = original.Coverage.GetGlyphIndex(oldGlyphId);
- if (coverageIndex >= 0 && coverageIndex < original.Values.Length)
+ if (coverageIndex >= 0 && (isEmptyFormat ? coverageIndex < original.ValueCount
+ : coverageIndex < original.Values.Length))
{
// Check if this glyph is included in subset
if (context.OldToNewGlyphId.ContainsKey(oldGlyphId))
{
includedGlyphs.Add(context.OldToNewGlyphId[oldGlyphId]); // New ID
- includedValues.Add(original.Values[coverageIndex]);
+ includedValues.Add(isEmptyFormat ? new ValueRecord() : original.Values[coverageIndex]);
}
}
}
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/GsubTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/GsubTable.cs
index 9d2d655654..85db8ba6b0 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/GsubTable.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/GsubTable.cs
@@ -94,6 +94,7 @@ internal override void SerializeInternal(FontsBinaryWriter writer, FontSerializa
// 3. LookupList
if (this.LookupList != null)
{
+ this.LookupList.ExtensionLookupType = 7; // GSUB Extension Substitution, used if 16-bit offsets do not fit
LayoutTableSerializationHelper.UpdateOffsetAndSerialize(writer, tableStartOffset, lookupListOffPos, this.LookupList);
}
}
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/GsubTableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/GsubTableLoader.cs
index a8f76a9920..cf7aee0949 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/GsubTableLoader.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/GsubTableLoader.cs
@@ -35,6 +35,11 @@ public GsubTableLoader(TableLoaderSettings tblSettings) : base(tblSettings, Tabl
private readonly TableLoaderSettings _settings;
protected override GsubTable LoadInternal()
+ {
+ return LoadWithReadBudget(LoadGsubTable, _settings);
+ }
+
+ private GsubTable LoadGsubTable()
{
_reader.BaseStream.Position = _offset;
long tableStartOffset = _offset;
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/ChainingContextualHandler.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/ChainingContextualHandler.cs
index 3a420dd29c..b32dd0ba7a 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/ChainingContextualHandler.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/Handlers/ChainingContextualHandler.cs
@@ -15,43 +15,12 @@ internal class ChainingContextualHandler : IGsubLookupHandler
public void Discover(FontSubsettingContext context, LookupTable lookup, GsubSubsetProcessor processor)
{
- foreach (var subTable in lookup.SubTables.OfType())
- {
- // 1. Check if we have a match on the first character (e.g., 'f')
- // Using the name InputCoverage here as it's most common in format 3
- if (subTable.InputCoverages != null && subTable.InputCoverages.Count > 0)
- {
- var initialCoverage = subTable.InputCoverages[0];
-
- if (AnyGlyphInSubset(initialCoverage, context.IncludedGlyphs))
- {
- // 2. Loop through records to find linked lookups
- foreach (var record in subTable.SubstLookupRecords)
- {
- int lookupIndex = record.LookupListIndex;
-
- // 3. Get the actual LookupTable instance from the original font
- // We go through context.OriginalFont to find the correct table in the list
- if (lookupIndex >= 0 && lookupIndex < context.OriginalFont.GsubTable.LookupList.Lookups.Count)
- {
- var targetLookup = context.OriginalFont.GsubTable.LookupList.Lookups[lookupIndex];
-
- // 4. Now the argument matches! (context, LookupTable)
- processor.DiscoverLookup(context, targetLookup);
- }
- }
- }
- }
- }
- }
-
- private bool AnyGlyphInSubset(CoverageTable coverage, HashSet includedGlyphs)
- {
- if (coverage == null) return false;
- // Get all GIDs that this coverage table includes
- var coveredGids = coverage.GetCoveredGlyphs();
- // Check if any of these GIDs exist in our current subset
- return coveredGids.Any(gid => includedGlyphs.Contains(gid));
+ // Intentionally empty. A chaining contextual lookup substitutes nothing itself; it only
+ // invokes other lookups. GsubSubsetProcessor.Discover runs every lookup in the font in a
+ // fixpoint loop, so the referenced lookups are discovered there anyway. Discovering them
+ // recursively from here added nothing to the result, and with a lookup that references
+ // itself (directly or through an extension lookup) it recursed until the process crashed
+ // with a stack overflow.
}
public LookupTable Rewrite(FontSubsettingContext context, LookupTable oldLookup)
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Gsub/IO/LigatureSubstSubTableDeserializer.cs b/src/EPPlus.Fonts.OpenType/Tables/Gsub/IO/LigatureSubstSubTableDeserializer.cs
index 6615b0ff73..f257230831 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Gsub/IO/LigatureSubstSubTableDeserializer.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Gsub/IO/LigatureSubstSubTableDeserializer.cs
@@ -10,8 +10,10 @@ Date Author Change
*************************************************************************************************
10/07/2025 EPPlus Software AB EPPlus.Fonts.OpenType 1.0
*************************************************************************************************/
+using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage;
using EPPlus.Fonts.OpenType.Tables.Common.Layout.Coverage.IO;
using EPPlus.Fonts.OpenType.Tables.Gsub.Data.Lookups;
+using System.Collections.Generic;
using System.IO;
namespace EPPlus.Fonts.OpenType.Tables.Gsub.IO
@@ -72,7 +74,7 @@ public LigatureSubstSubTable Deserialize(long subTableStartOffset)
// 2. Deserialize LigatureSetTables
long currentPosition = _reader.BaseStream.Position;
- ushort[] coveredGlyphs = subTable.Coverage?.CoveredGlyphs ?? new ushort[0]; // Use new ushort[0] for .NET 3.5 safety
+ ushort[] coveredGlyphs = FirstCoveredGlyphs(subTable.Coverage, ligSetCount);
if (coveredGlyphs.Length != ligSetCount)
{
@@ -92,8 +94,9 @@ public LigatureSubstSubTable Deserialize(long subTableStartOffset)
if (coveredGlyphs.Length > i)
{
ushort baseGlyphID = coveredGlyphs[i];
- // This assumes LigatureSubstSubTable has a Dictionary property named LigatureSets
- subTable.LigatureSets.Add(baseGlyphID, ligSet);
+ // A glyph listed twice in the coverage is invalid; keep the first ligature set.
+ if (!subTable.LigatureSets.ContainsKey(baseGlyphID))
+ subTable.LigatureSets.Add(baseGlyphID, ligSet);
}
}
@@ -102,5 +105,29 @@ public LigatureSubstSubTable Deserialize(long subTableStartOffset)
return subTable;
}
+
+ ///
+ /// Returns the first covered glyphs, in coverage order. Only that many
+ /// are needed (one per ligature set), so overlapping or huge format 2 ranges are not expanded.
+ ///
+ private static ushort[] FirstCoveredGlyphs(CoverageTable coverage, int count)
+ {
+ var result = new List(count);
+ if (coverage is CoverageTableFormat1 f1 && f1.GlyphArray != null)
+ {
+ for (int i = 0; i < f1.GlyphArray.Length && result.Count < count; i++)
+ result.Add(f1.GlyphArray[i]);
+ }
+ else if (coverage is CoverageTableFormat2 f2 && f2.RangeRecords != null)
+ {
+ foreach (var range in f2.RangeRecords)
+ {
+ for (int g = range.StartGlyphID; g <= range.EndGlyphID && result.Count < count; g++)
+ result.Add((ushort)g);
+ if (result.Count == count) break;
+ }
+ }
+ return result.ToArray();
+ }
}
}
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Kern/KernTableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Kern/KernTableLoader.cs
index 17ad3eb53d..fb0fd2f433 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Kern/KernTableLoader.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Kern/KernTableLoader.cs
@@ -19,9 +19,18 @@ internal class KernTableLoader : TableLoader
{
public KernTableLoader(TableLoaderSettings settings) : base(settings, TableNames.Kern)
{
+ _settings = settings;
}
+ private readonly TableLoaderSettings _settings;
+
protected override KernTable LoadInternal()
+ {
+ // The legacy kern table is optional: if it exceeds the read budget it is ignored with a warning.
+ return LoadWithReadBudget(LoadKernTable, _settings);
+ }
+
+ private KernTable LoadKernTable()
{
var v = _reader.ReadUInt16BigEndian();
var nt = _reader.ReadUInt16BigEndian();
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Name/NameTable.cs b/src/EPPlus.Fonts.OpenType/Tables/Name/NameTable.cs
index 42dcf89b17..0b57cb3555 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Name/NameTable.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Name/NameTable.cs
@@ -245,55 +245,75 @@ public void LoadFromBytes(byte[] tableBytes)
using (var ms = new MemoryStream(tableBytes))
using (var reader = new FontsBinaryReader(ms))
{
- format = reader.ReadUInt16BigEndian();
- count = reader.ReadUInt16BigEndian();
- stringOffset = reader.ReadUInt16BigEndian();
-
- NameRecords = new NameRecord[count];
-
- // Step 1: Read all name record headers
- for (int i = 0; i < count; i++)
+ // Same read budget as NameTableLoader: many records pointing at the same long string
+ // must not make the scanner read (and decode) the same data over and over.
+ long budget = Math.Max(TableLoader.LayoutReadBudgetMinimum,
+ TableLoader.LayoutReadBudgetFactor * (long)tableBytes.Length);
+ reader.SetReadBudget(budget);
+ try
{
- var record = new NameRecord
- {
- platformId = reader.ReadUInt16BigEndian(),
- encodingId = reader.ReadUInt16BigEndian(),
- languageID = reader.ReadUInt16BigEndian(),
- nameId = reader.ReadUInt16BigEndian(),
- length = reader.ReadUInt16BigEndian(),
- offset = reader.ReadUInt16BigEndian()
- };
-
- record.RecordType = (NameRecordTypes)record.nameId;
-
- NameRecords[i] = record;
+ ReadRecords(tableBytes, ms, reader);
}
-
- // Step 2: Read all strings from string pool
- for (int i = 0; i < count; i++)
+ catch (FontReadBudgetExceededException ex)
{
- var record = NameRecords[i];
+ throw new InvalidDataException(string.Format(
+ "The font is malformed: parsing the name table exceeded the read budget of {0} bytes ({1} x table length {2}).",
+ budget, TableLoader.LayoutReadBudgetFactor, tableBytes.Length), ex);
+ }
+ }
+ }
+
+ /// Reads the header, the name records and their strings (the body of ).
+ private void ReadRecords(byte[] tableBytes, MemoryStream ms, FontsBinaryReader reader)
+ {
+ format = reader.ReadUInt16BigEndian();
+ count = reader.ReadUInt16BigEndian();
+ stringOffset = reader.ReadUInt16BigEndian();
+
+ NameRecords = new NameRecord[count];
- if (record.length == 0)
- {
- record.Name = string.Empty;
- continue;
- }
+ // Step 1: Read all name record headers
+ for (int i = 0; i < count; i++)
+ {
+ var record = new NameRecord
+ {
+ platformId = reader.ReadUInt16BigEndian(),
+ encodingId = reader.ReadUInt16BigEndian(),
+ languageID = reader.ReadUInt16BigEndian(),
+ nameId = reader.ReadUInt16BigEndian(),
+ length = reader.ReadUInt16BigEndian(),
+ offset = reader.ReadUInt16BigEndian()
+ };
- long stringPos = stringOffset + record.offset;
- if (stringPos + record.length > tableBytes.Length)
- continue; // corrupted
+ record.RecordType = (NameRecordTypes)record.nameId;
- ms.Position = stringPos;
- byte[] stringBytes = reader.ReadBytes(record.length);
+ NameRecords[i] = record;
+ }
- Encoding encoding = GetEncodingForRecord(record);
- record.Name = encoding.GetString(stringBytes);
+ // Step 2: Read all strings from string pool
+ for (int i = 0; i < count; i++)
+ {
+ var record = NameRecords[i];
- // Vi skippar LanguageMapping helt under scanning
- // Det är bara tungt och behövs inte för att få Family/Subfamily
- record.LanguageMapping = null;
+ if (record.length == 0)
+ {
+ record.Name = string.Empty;
+ continue;
}
+
+ long stringPos = stringOffset + record.offset;
+ if (stringPos + record.length > tableBytes.Length)
+ continue; // corrupted
+
+ ms.Position = stringPos;
+ byte[] stringBytes = reader.ReadBytes(record.length);
+
+ Encoding encoding = GetEncodingForRecord(record);
+ record.Name = encoding.GetString(stringBytes);
+
+ // Vi skippar LanguageMapping helt under scanning
+ // Det är bara tungt och behövs inte för att få Family/Subfamily
+ record.LanguageMapping = null;
}
}
diff --git a/src/EPPlus.Fonts.OpenType/Tables/Name/NameTableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/Name/NameTableLoader.cs
index e1b3d293ff..9aa6b952a3 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/Name/NameTableLoader.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/Name/NameTableLoader.cs
@@ -25,9 +25,18 @@ public NameTableLoader(TableLoaderSettings settings) : base(settings, TableNames
#if NET5_0_OR_GREATER
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //Add Support for codepage 1252
#endif
+ _settings = settings;
}
+ private readonly TableLoaderSettings _settings;
+
protected override NameTable LoadInternal()
+ {
+ // A font cannot be used without name: if it exceeds the read budget the font is rejected.
+ return LoadWithReadBudget(LoadNameTable, _settings, tableIsRequired: true);
+ }
+
+ private NameTable LoadNameTable()
{
ushort format = _reader.ReadUInt16BigEndian();
ushort count = _reader.ReadUInt16BigEndian();
diff --git a/src/EPPlus.Fonts.OpenType/Tables/TableLoader.cs b/src/EPPlus.Fonts.OpenType/Tables/TableLoader.cs
index aa7588178f..e9df51f9ce 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/TableLoader.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/TableLoader.cs
@@ -13,6 +13,7 @@ Date Author Change
*************************************************************************************************/
using System.Collections.Generic;
using System;
+using System.IO;
using System.Threading;
namespace EPPlus.Fonts.OpenType.Tables
@@ -44,6 +45,59 @@ public TableLoader(TableLoaderSettings tblSettings, string tableName)
protected abstract T LoadInternal();
+ /// Number of bytes the last call to LoadInternal read (for diagnostics and tests).
+ internal long LastLoadBytesRead { get; private set; }
+
+ /// Length of the table according to the table directory.
+ internal uint TableLength => _length;
+
+ ///
+ /// Read budget for tables parsed with (GSUB, GPOS, cmap, kern
+ /// and name): at most this many times the table length. Shared offsets make real fonts read
+ /// parts of these tables more than once; the highest ratios measured on real fonts were
+ /// 10.4 for GSUB/GPOS (785 tables), 1.03 for cmap, 1.97 for name (598 each) and 1.0 for kern (242).
+ ///
+ internal const int LayoutReadBudgetFactor = 16;
+
+ /// Lower bound of the layout read budget, so small tables are never limited.
+ internal const long LayoutReadBudgetMinimum = 256 * 1024;
+
+ ///
+ /// Runs with a read budget of
+ /// max(, × table length).
+ /// If the budget is exceeded the table is treated as missing (null) and a load warning is
+ /// recorded on the font, so a malformed table cannot make parsing read the same data over and over.
+ /// If is true the font cannot be used without the table, so
+ /// an is thrown instead.
+ ///
+ protected T LoadWithReadBudget(Func load, TableLoaderSettings settings, bool tableIsRequired = false)
+ {
+ long budget = Math.Max(LayoutReadBudgetMinimum, LayoutReadBudgetFactor * (long)_length);
+ _reader.SetReadBudget(budget);
+ try
+ {
+ return load();
+ }
+ catch (FontReadBudgetExceededException ex)
+ {
+ // A font cannot be used without this table (cmap, name): reject the font instead of ignoring the table.
+ if (tableIsRequired)
+ throw new InvalidDataException(string.Format(
+ "The font is malformed: parsing the {0} table exceeded the read budget of {1} bytes ({2} x table length {3}).",
+ _tableName, budget, LayoutReadBudgetFactor, _length), ex);
+
+ settings.AddLoadWarning(string.Format(
+ "The {0} table was ignored: parsing it exceeded the read budget of {1} bytes ({2} x table length {3}). " +
+ "The font may be malformed; it is used without {0}.",
+ _tableName, budget, LayoutReadBudgetFactor, _length));
+ return null;
+ }
+ finally
+ {
+ _reader.ClearReadBudget();
+ }
+ }
+
private readonly object _instanceLock = new object();
private bool _isLoading;
private bool _isLoaded;
@@ -92,7 +146,24 @@ public T Load(bool useCache = true)
// Now safe to read - no other thread can access this font's reader
_reader.BaseStream.Position = _offset;
- t = LoadInternal();
+ long bytesBefore = _reader.TotalBytesRead;
+ try
+ {
+ t = LoadInternal();
+ }
+ catch
+ {
+ // Loading failed. Clear the in-progress flag and wake waiting threads, otherwise every
+ // later Load() on this loader would wait in Monitor.Wait forever. They will retry the
+ // load (and get the same exception) instead.
+ lock (_instanceLock)
+ {
+ _isLoading = false;
+ Monitor.PulseAll(_instanceLock);
+ }
+ throw;
+ }
+ LastLoadBytesRead = _reader.TotalBytesRead - bytesBefore;
}
// Third: Update cache
diff --git a/src/EPPlus.Fonts.OpenType/Tables/TableLoaderSettings.cs b/src/EPPlus.Fonts.OpenType/Tables/TableLoaderSettings.cs
index 6376aa6e1d..97b1eae33e 100644
--- a/src/EPPlus.Fonts.OpenType/Tables/TableLoaderSettings.cs
+++ b/src/EPPlus.Fonts.OpenType/Tables/TableLoaderSettings.cs
@@ -34,5 +34,28 @@ internal TableLoaderSettings(
_tblCacheRef = tblCache;
_loaderCacheRef = loaderCache;
}
+
+ private readonly List _loadWarnings = new List();
+
+ ///
+ /// Records a problem found while loading a table, e.g. a table that was ignored.
+ /// The table loaders have no logger; FontStore and OpenTypeFontEngine write these
+ /// to the configured IFontLogger after the font is loaded.
+ ///
+ internal void AddLoadWarning(string message)
+ {
+ lock (_loadWarnings)
+ {
+ _loadWarnings.Add(message);
+ }
+ }
+
+ internal string[] GetLoadWarnings()
+ {
+ lock (_loadWarnings)
+ {
+ return _loadWarnings.ToArray();
+ }
+ }
}
}
\ No newline at end of file
diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs
index 542191e2bb..504e2ca153 100644
--- a/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs
+++ b/src/EPPlus.Fonts.OpenType/TextShaping/Contextual/ChainingContextualProcessor.cs
@@ -83,6 +83,7 @@ private List FindContextualLookupsForFeature(
var activeIndices = ScriptFeatureResolver.GetActiveFeatureIndices(gsub.ScriptList, script, language);
var featureRecords = gsub.FeatureList.FeatureRecords;
+ int references = 0;
for (int featureIndex = 0; featureIndex < featureRecords.Count; featureIndex++)
{
@@ -104,6 +105,15 @@ private List FindContextualLookupsForFeature(
{
var lookup = gsub.LookupList.Lookups[lookupIndex];
+ // The subtables of Type 6 and 7 lookups are examined here or when the
+ // lookup is applied, so count them.
+ if (lookup.LookupType == 6 || lookup.LookupType == 7)
+ {
+ references += System.Math.Max(1, lookup.SubTables?.Count ?? 0);
+ if (references > ShapingLimits.MaxSubtableReferences)
+ return lookups; // Malformed font: see ShapingLimits.
+ }
+
// Only Type 6 (Chaining Contextual) or Type 7 (Extension wrapping Type 6)
if (lookup.LookupType == 6)
{
diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs
index 3f0e4058be..4b8ba839b1 100644
--- a/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs
+++ b/src/EPPlus.Fonts.OpenType/TextShaping/Kerning/GposKerningProvider.cs
@@ -108,6 +108,7 @@ private List FindAllKerningSubtables(GposTable gpos)
return subtables;
var featureRecords = gpos.FeatureList.FeatureRecords;
+ int references = 0;
for (int featureIndex = 0; featureIndex < featureRecords.Count; featureIndex++)
{
@@ -132,6 +133,9 @@ private List FindAllKerningSubtables(GposTable gpos)
// test below is what actually identifies pair positioning data.
foreach (var subtable in lookup.SubTables)
{
+ if (++references > ShapingLimits.MaxSubtableReferences)
+ return subtables; // Malformed font: see ShapingLimits.
+
if (subtable is PairPosSubTable pairPos)
{
subtables.Add(new IndexedSubtable(featureIndex, pairPos));
diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs
index 43fce78cf6..b9ad77e2fe 100644
--- a/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs
+++ b/src/EPPlus.Fonts.OpenType/TextShaping/Ligatures/LigatureProcessor.cs
@@ -248,6 +248,7 @@ private static Dictionary> BuildLookupsByFeatureTag(
return map;
var featureRecords = gsub.FeatureList.FeatureRecords;
+ int references = 0;
for (int featureIndex = 0; featureIndex < featureRecords.Count; featureIndex++)
{
@@ -273,6 +274,11 @@ private static Dictionary> BuildLookupsByFeatureTag(
if (lookup.LookupType != 4 && lookup.LookupType != 7)
continue;
+ // Every collected lookup has all its subtables applied, so count those.
+ references += System.Math.Max(1, lookup.SubTables?.Count ?? 0);
+ if (references > ShapingLimits.MaxSubtableReferences)
+ return map; // Malformed font: see ShapingLimits.
+
if (!map.TryGetValue(tag, out var list))
{
list = new List();
diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/MarkToBaseProvider.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/MarkToBaseProvider.cs
index 1cbd2f3b43..a234c08acc 100644
--- a/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/MarkToBaseProvider.cs
+++ b/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/MarkToBaseProvider.cs
@@ -183,6 +183,7 @@ private List FindAllMarkToBaseSubtables(GposTable gpos)
return subtables;
var featureRecords = gpos.FeatureList.FeatureRecords;
+ int references = 0;
for (int featureIndex = 0; featureIndex < featureRecords.Count; featureIndex++)
{
@@ -204,6 +205,9 @@ private List FindAllMarkToBaseSubtables(GposTable gpos)
// (type 9) mark lookups are unwrapped by GposTableLoader but keep LookupType 9.
foreach (var subtable in lookup.SubTables)
{
+ if (++references > ShapingLimits.MaxSubtableReferences)
+ return subtables; // Malformed font: see ShapingLimits.
+
if (subtable is MarkToBaseSubTableFormat1 markToBase)
{
subtables.Add(new IndexedSubtable(featureIndex, markToBase));
diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/SingleAdjustmentProvider.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/SingleAdjustmentProvider.cs
index 1516d191cd..64a35bb4c5 100644
--- a/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/SingleAdjustmentProvider.cs
+++ b/src/EPPlus.Fonts.OpenType/TextShaping/Positioning/SingleAdjustmentProvider.cs
@@ -161,6 +161,7 @@ private void BuildFeatureMap(GposTable gpos)
return;
var featureRecords = gpos.FeatureList.FeatureRecords;
+ int references = 0;
for (int featureIndex = 0; featureIndex < featureRecords.Count; featureIndex++)
{
@@ -183,6 +184,9 @@ private void BuildFeatureMap(GposTable gpos)
{
foreach (var subtable in lookup.SubTables)
{
+ if (++references > ShapingLimits.MaxSubtableReferences)
+ return; // Malformed font: see ShapingLimits.
+
if (subtable is SinglePosSubTableFormat1 || subtable is SinglePosSubTableFormat2)
{
if (!_subtablesByFeature.TryGetValue(featureTag, out var list))
diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/ShapingLimits.cs b/src/EPPlus.Fonts.OpenType/TextShaping/ShapingLimits.cs
new file mode 100644
index 0000000000..1832280531
--- /dev/null
+++ b/src/EPPlus.Fonts.OpenType/TextShaping/ShapingLimits.cs
@@ -0,0 +1,30 @@
+/*************************************************************************************************
+ Required Notice: Copyright (C) EPPlus Software AB.
+ This software is licensed under PolyForm Noncommercial License 1.0.0
+ and may only be used for noncommercial purposes
+ https://polyformproject.org/licenses/noncommercial/1.0.0/
+
+ A commercial license to use this software can be purchased at https://epplussoftware.com
+ *************************************************************************************************
+ Date Author Change
+ *************************************************************************************************
+ 12/01/2026 EPPlus Software AB Limits for malformed fonts in text shaping
+ *************************************************************************************************/
+namespace EPPlus.Fonts.OpenType.TextShaping
+{
+ ///
+ /// Limits that keep text shaping proportional to the size of the font for malformed fonts.
+ ///
+ internal static class ShapingLimits
+ {
+ ///
+ /// Maximum number of subtable references (feature record x lookup index x subtable) a shaping
+ /// processor examines when it collects the lookups for the features it handles. A font can list
+ /// the same lookup many times in a feature and give that lookup many offsets to the same small
+ /// subtable, so the number of references can grow with the square of the table size. Real fonts
+ /// have at most 9938 (Gabriola GSUB, measured on 600 font faces). References beyond the limit
+ /// are ignored.
+ ///
+ internal const int MaxSubtableReferences = 65536;
+ }
+}
diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/MultipleSubstitutionProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/MultipleSubstitutionProcessor.cs
index 10f44c5f39..e7bf5e6256 100644
--- a/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/MultipleSubstitutionProcessor.cs
+++ b/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/MultipleSubstitutionProcessor.cs
@@ -38,6 +38,14 @@ public IndexedSubtable(int featureIndex, MultipleSubstSubTable subtable)
}
}
+ ///
+ /// Longest substitute sequence applied during shaping. Real fonts use at most 8 glyphs
+ /// (measured on 1345 Multiple Substitution subtables in 600 font faces). A longer sequence
+ /// would let one character expand into up to 65535 glyphs, so it is ignored and the glyph
+ /// is left unchanged.
+ ///
+ internal const int MaxSequenceLength = 32;
+
private readonly OpenTypeFont _font;
private readonly GsubTable _gsubTable;
@@ -108,7 +116,7 @@ public List ApplySubstitutions(List glyphs, List MaxSequenceLength)
continue;
ShapedGlyph original = glyphs[i];
@@ -214,6 +222,7 @@ private void BuildFeatureSubtableMap()
return;
var featureRecords = _gsubTable.FeatureList.FeatureRecords;
+ int references = 0;
for (int featureIndex = 0; featureIndex < featureRecords.Count; featureIndex++)
{
@@ -235,6 +244,9 @@ private void BuildFeatureSubtableMap()
{
foreach (var subtableObj in lookup.SubTables)
{
+ if (++references > ShapingLimits.MaxSubtableReferences)
+ return; // Malformed font: see ShapingLimits.
+
var multiSubst = UnwrapMultipleSubstSubtable(subtableObj);
if (multiSubst == null) continue;
diff --git a/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/SingleSubstitutionProcessor.cs b/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/SingleSubstitutionProcessor.cs
index 9bd3bcb7cf..c2c835603d 100644
--- a/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/SingleSubstitutionProcessor.cs
+++ b/src/EPPlus.Fonts.OpenType/TextShaping/Substitutions/SingleSubstitutionProcessor.cs
@@ -211,6 +211,7 @@ private void BuildFeatureSubtableMap()
return;
var featureRecords = _gsubTable.FeatureList.FeatureRecords;
+ int references = 0;
for (int featureIndex = 0; featureIndex < featureRecords.Count; featureIndex++)
{
@@ -235,6 +236,9 @@ private void BuildFeatureSubtableMap()
{
foreach (var subtableObj in lookup.SubTables)
{
+ if (++references > ShapingLimits.MaxSubtableReferences)
+ return; // Malformed font: see ShapingLimits.
+
var singleSubst = UnwrapSingleSubstSubtable(subtableObj);
if (singleSubst == null) continue;
diff --git a/src/EPPlus.Interfaces/Fonts/FontLogEventType.cs b/src/EPPlus.Interfaces/Fonts/FontLogEventType.cs
index cdbe834682..ce80c24c03 100644
--- a/src/EPPlus.Interfaces/Fonts/FontLogEventType.cs
+++ b/src/EPPlus.Interfaces/Fonts/FontLogEventType.cs
@@ -42,6 +42,8 @@ public enum FontLogEventType
/// A code point was routed to a fallback font (reported once per code point).
GlyphFallback,
/// No candidate font has a glyph for a code point (reported once per code point).
- GlyphMissing
+ GlyphMissing,
+ /// A font table could not be read safely and is ignored; the font is used without it.
+ FontTableIgnored
}
}
\ No newline at end of file