package typeface import ( "bytes" "encoding/binary" "errors" "fmt" "testing" ) // An sfnt whose directory points several tables at the same bytes passes // a per-table bounds check, yet a reader that copies each table (an // app renaming the font for its PDF, say) copies those bytes once per // table: a 10 MiB file became 4.8 GB to copy (final review, C1). Tables // may not overlap, nor sum past the file. // pointedAt is data with the directory entries of the given tags set to // the offset and length of the table at. func pointedAt(t *testing.T, data []byte, at string, tags ...string) []byte { t.Helper() out := bytes.Clone(data) n := int(binary.BigEndian.Uint16(out[4:])) var off, length uint32 found := false for i := 0; i < n; i++ { rec := out[12+16*i:] if string(rec[:4]) == at { off, length, found = binary.BigEndian.Uint32(rec[8:]), binary.BigEndian.Uint32(rec[12:]), true } } if !found { t.Fatalf("no %q table", at) } for i := 0; i < n; i++ { rec := out[12+16*i:] for _, tag := range tags { if string(rec[:4]) == tag { binary.BigEndian.PutUint32(rec[8:], off) binary.BigEndian.PutUint32(rec[12:], length) } } } return out } // withFillers is Liberation plus n small tables named z000, z001, ... func withFillers(t *testing.T, n int) ([]byte, []string) { t.Helper() v, ts := tablesOf(t, liberation(t)) var tags []string for i := 0; i < n; i++ { tag := fmt.Sprintf("z%03d", i) tags = append(tags, tag) ts = append(ts, table{tag, []byte{0, 0, 0, 0}}) } return buildSFNT(v, ts), tags } func TestInspectRefusesTablesThatShareBytes(t *testing.T) { // One table over another: the sum still fits the file. two := pointedAt(t, liberation(t), "hhea", "gasp") // A hundred tables over glyf, the amplification itself. many, tags := withFillers(t, 100) many = pointedAt(t, many, "glyf", tags...) // A table inside the table directory. inDir := bytes.Clone(liberation(t)) binary.BigEndian.PutUint32(inDir[12+8:], 0) // the first table at offset 0 // WOFF: two identical tables whose compressed bytes are one range. v, ts := tablesOf(t, liberation(t)) same := bytes.Repeat([]byte("same"), 64) woff := buildWOFF(t, buildSFNT(v, append(ts, table{"zzz1", same}, table{"zzz2", same}))) { n := int(binary.BigEndian.Uint16(woff[12:])) var off []byte for i := 0; i < n; i++ { rec := woff[44+20*i:] switch string(rec[:4]) { case "zzz1": off = bytes.Clone(rec[4:8]) case "zzz2": copy(rec[4:8], off) } } } for _, c := range []struct { name string data []byte }{ {"two tables over one range", two}, {"a hundred tables over glyf", many}, {"a table over the directory", inDir}, {"a WOFF with two tables over one range", woff}, } { t.Run(c.name, func(t *testing.T) { f, err := Inspect(c.data) if !errors.Is(err, ErrMalformed) { t.Fatalf("Inspect = %+v, %v; want ErrMalformed", f, err) } t.Log(err) }) } // Tables that only touch, and empty ones, are fine. touching, _ := withFillers(t, 3) mustInspect(t, touching) mustInspect(t, buildSFNT(v, append(ts, table{"zero", nil}))) }