Commit f37ffef2 for tesseract
commit f37ffef28bfa4d2cb598391916ee98393ff0f6fc
Author: Stefan Weil <sw@weilnetz.de>
Date: Thu Nov 26 16:22:41 2026 +0100
Add fuzzer for raw images with layout analysis and thresholding
fuzzer-api always uses a 1 bpp image of a fixed size and the default
page segmentation mode PSM_SINGLE_BLOCK. The OSS-Fuzz coverage report
of 2026-11-26 therefore shows 0 % line coverage for the layout analysis
(colfind.cpp, tabfind.cpp, strokewidth.cpp, colpartition*.cpp,
imagefind.cpp, linefind.cpp, tablefind.cpp) and for otsuthr.cpp, and
23 % for thresholder.cpp. A corpus of the new fuzzer-raw-image reaches
all of these files.
Input format
The fuzz input is a text line of key=value pairs, for example
"psm=3 depth=8 width=448 height=144 resolution=300", followed by
uncompressed pixel data in the layout of the binary PBM, PGM and PPM
formats. The keys are the page segmentation mode (same numbers as
--psm), the image depth (1, 8 or 32 bpp), the thresholding method, the
image size and the resolution. All keys are optional and have defaults.
Missing pixels are white. No image file format is decoded, so the time
is spent in Tesseract and not in image decoders.
An input with an unknown key, a key which is used twice, a value which
is not allowed or an image which is too large or too flat is not run.
So no input which does something can depend on something that is not
accepted today, and new keys, new values (for example more page
segmentation modes) and higher limits can be added later without
changing the meaning of the corpus and of the test cases of bug
reports. The rules are written down in the source file.
LLVMFuzzerTestOneInput returns 0 for an input which is not accepted,
and not -1 as libFuzzer and AFL++ would allow, because honggfuzz ends
with an error for any other value than 0.
Mutations of single bytes nearly always give a header which is not
accepted. With such mutations only, 10867 runs found no image size,
resolution or set of keys which was not in the seeds. Therefore the
fuzzer has a custom mutator for libFuzzer which either sets one
parameter to another valid value or mutates the pixel data. AFL++ and
honggfuzz do not use it (both provide a stub for LLVMFuzzerMutate), so
a dictionary with the keys is added for them.
Limits
OSS-Fuzz stops a test case after 25 s. The times were measured with
ASan and -D_GLIBCXX_DEBUG.
- The image has at most 65536 pixels (256 x 256) and a side of at most
2048 pixels. A page full of 5 x 7 pixel characters needed up to 9 s
with that limit and up to 14 s with the 512 x 256 pixels of
fuzzer-api-512x256.
- The image is at most 64 times as wide as it is high. With
PSM_SINGLE_LINE and PSM_SINGLE_CHAR the whole image is one text line,
and the LSTM recognizer scales a text line to a fixed height. A blank
image of 2048 x 1 pixels needed 34 s, 2048 x 32 pixels 2 s.
- PSM_SINGLE_WORD, PSM_CIRCLE_WORD and PSM_RAW_LINE are not used. They
make a single word from all blobs of the image, and the run time of
Tesseract::split_and_recog_word grows much faster than the number of
blobs in a word. A checkerboard of 2 x 2 pixel squares needed 19 s
for 256 x 32 pixels with PSM_RAW_LINE and 58 s for 1024 x 32 pixels
with PSM_SINGLE_WORD.
- The modes with OSD are not used because the fuzzer build has no
osd.traineddata.
Like fuzzer-api, the fuzzer limits the number of classifications and
deletes the API on exit. In addition it resets the adaptive classifier
after each input, so the result for an input does not depend on the
inputs which were run before it: 254 inputs gave the same text in
reverse order with the reset, and 8 of them a different text without
it.
Seed corpus
The seed corpus is generated by a Python script with a built-in 5 x 7
pixel font, so no image files are added to the repository. It has 15
small pages with text lines, columns, a table, ruling lines and a photo
like region for all modes, depths and thresholding methods.
Results
Fuzzing on Linux aarch64 with clang 18 for 5 minutes executed 2313
inputs with one process (7 per second) and 9484 inputs with 16
processes without a crash, leak, timeout or input which needed 10 s.
In an earlier run of 7 minutes, the slowest of the 2594 inputs in the
resulting corpus needed 1.6 s, and the corpus had inputs with
recognized text for all 7 page segmentation modes and 382 different
image sizes. The fuzzer also builds and runs on x86-64 with clang 19,
and the CIFuzz job built and ran it in the OSS-Fuzz image. It was not
run with AFL++ or honggfuzz.
An earlier version found the memory leak which was fixed in commit
8fa86060 within a minute.
Assisted-by: Claude Fable 5.2 (Anthropic)
Signed-off-by: Stefan Weil <sw@weilnetz.de>
diff --git a/Makefile.am b/Makefile.am
index 066538d6..1f2be8d7 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -976,7 +976,7 @@ wordlist2dawg_CPPFLAGS = $(training_CPPFLAGS)
wordlist2dawg_SOURCES = src/training/wordlist2dawg.cpp
wordlist2dawg_LDADD = $(extralib)
-# fuzzer-api is used for fuzzing tests.
+# fuzzer-api and fuzzer-raw-image are used for fuzzing tests.
# They are run by OSS-Fuzz https://oss-fuzz.com/, but can also be run locally.
# Note: -fsanitize=fuzzer currently requires the clang++ compiler.
@@ -1020,7 +1020,30 @@ fuzzer-api-512x256: unittest/fuzzers/fuzzer-api.cpp
$(libcurl_LIBS) \
-o $@
+# fuzzer-raw-image gets the page segmentation mode and the size, depth and
+# resolution of the image from a text line at the start of the fuzz input.
+# Run it with -dict=$(top_srcdir)/unittest/fuzzers/fuzzer-raw-image.dict.
+fuzzer-raw-image: libtesseract.la
+fuzzer-raw-image: unittest/fuzzers/fuzzer-raw-image.cpp
+ $(CXX) $(DEFS) $(CXXFLAGS) -g $(LIB_FUZZING_ENGINE) \
+ -I $(top_srcdir)/include \
+ -I $(builddir)/include \
+ $(LEPTONICA_CFLAGS) \
+ $(OPENMP_CXXFLAGS) \
+ $< \
+ $(builddir)/.libs/libtesseract.a \
+ $(LEPTONICA_LIBS) \
+ $(libarchive_LIBS) \
+ $(libcurl_LIBS) \
+ -o $@
+
+# The seed corpus for fuzzer-raw-image is generated, so that no image files
+# are needed.
+fuzzer-raw-image_seed_corpus.zip: unittest/fuzzers/fuzzer-raw-image-seeds.py
+ python3 $< $@
+
CLEANFILES += fuzzer-api fuzzer-api-512x256
+CLEANFILES += fuzzer-raw-image fuzzer-raw-image_seed_corpus.zip
if ASCIIDOCTOR
diff --git a/unittest/fuzzers/fuzzer-raw-image-seeds.py b/unittest/fuzzers/fuzzer-raw-image-seeds.py
new file mode 100755
index 00000000..3ea3bb3c
--- /dev/null
+++ b/unittest/fuzzers/fuzzer-raw-image-seeds.py
@@ -0,0 +1,304 @@
+#!/usr/bin/env python3
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+# http://www.apache.org/licenses/LICENSE-2.0
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Write the seed corpus for fuzzer-raw-image as a ZIP archive.
+
+Usage: fuzzer-raw-image-seeds.py fuzzer-raw-image_seed_corpus.zip
+
+The seeds are small synthetic pages (text lines, columns, a table, ruling
+lines, a photo like region) in the input format of fuzzer-raw-image.cpp.
+They are drawn with a built-in 5 x 7 pixel font, so nothing but Python is
+needed and no image files have to be stored in the repository.
+"""
+
+import sys
+import zipfile
+
+# Glyphs of 5 x 7 pixels: 7 rows from top to bottom, each one a hexadecimal
+# number with 2 digits, most significant of the 5 bits for the left pixel.
+FONT = {
+ ' ': '00000000000000', ',': '000000000C0408', '-': '0000001F000000',
+ '.': '00000000000C0C', '0': '0E11131519110E', '1': '040C040404040E',
+ '2': '0E11010204081F', '3': '1E01010E01011E', '4': '02060A121F0202',
+ '5': '1F101E0101110E', '6': '0608101E11110E', '7': '1F010204080808',
+ '8': '0E11110E11110E', '9': '0E11110F01020C', 'A': '0E11111F111111',
+ 'B': '1E11111E11111E', 'C': '0E11101010110E', 'D': '1E11111111111E',
+ 'E': '1F10101E10101F', 'F': '1F10101E101010', 'G': '0E11101711110F',
+ 'H': '1111111F111111', 'I': '0E04040404040E', 'J': '0702020202120C',
+ 'K': '11121418141211', 'L': '1010101010101F', 'M': '111B1515111111',
+ 'N': '11191513111111', 'O': '0E11111111110E', 'P': '1E11111E101010',
+ 'Q': '0E11111115120D', 'R': '1E11111E141211', 'S': '0F10100E01011E',
+ 'T': '1F040404040404', 'U': '1111111111110E', 'V': '11111111110A04',
+ 'W': '11111115151B11', 'X': '11110A040A1111', 'Y': '11110A04040404',
+ 'Z': '1F01020408101F',
+}
+
+TEXT = ('THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG. A PAGE OF TEXT IS '
+ 'SPLIT INTO BLOCKS, LINES AND WORDS BEFORE THE WORDS ARE READ. '
+ 'IN 1985 THE FIRST VERSION RAN ON 2 MACHINES, AND 30 YEARS LATER '
+ 'IT READS MORE THAN 100 LANGUAGES. ').split()
+
+# Values for the header of the fuzz input (see fuzzer-raw-image.cpp).
+PSM_AUTO = 3
+PSM_SINGLE_COLUMN = 4
+PSM_SINGLE_BLOCK_VERT_TEXT = 5
+PSM_SINGLE_BLOCK = 6
+PSM_SINGLE_LINE = 7
+PSM_SINGLE_CHAR = 10
+PSM_SPARSE_TEXT = 11
+OTSU = 0
+LEPTONICA_OTSU = 1
+SAUVOLA = 2
+
+WHITE = 255
+BLACK = 0
+
+
+class Page:
+ """Grey image with simple drawing functions."""
+
+ def __init__(self, width, height, paper=WHITE):
+ self.width = width
+ self.height = height
+ self.rows = [bytearray([paper]) * width for _ in range(height)]
+
+ def rect(self, left, top, width, height, grey):
+ for y in range(max(top, 0), min(top + height, self.height)):
+ for x in range(max(left, 0), min(left + width, self.width)):
+ self.rows[y][x] = grey
+
+ def photo(self, left, top, width, height):
+ """Draw a region with a gradient and noise, like a halftone photo."""
+ state = 1
+ for y in range(top, min(top + height, self.height)):
+ for x in range(left, min(left + width, self.width)):
+ state = (state * 1103515245 + 12345) % 2**31
+ grey = 60 + 120 * (x - left) // width + (state >> 16) % 64
+ self.rows[y][x] = grey
+
+ def text(self, left, top, text, scale, ink=BLACK):
+ """Draw a text line and return the x position after it."""
+ for char in text:
+ glyph = FONT[char]
+ for row in range(7):
+ bits = int(glyph[2 * row:2 * row + 2], 16)
+ for column in range(5):
+ if bits & (0x10 >> column):
+ self.rect(left + column * scale, top + row * scale,
+ scale, scale, ink)
+ left += 6 * scale
+ return left
+
+ def paragraph(self, left, top, width, height, scale, ink=BLACK, skip=0):
+ """Fill a box with left aligned lines of words from TEXT."""
+ columns = width // (6 * scale)
+ index = skip
+ for y in range(top, top + height - 7 * scale + 1, 10 * scale):
+ line = ''
+ while True:
+ word = TEXT[index % len(TEXT)]
+ if len(line) + len(word) + (line != '') > columns:
+ break
+ line += (' ' if line else '') + word
+ index += 1
+ self.text(left, y, line, scale, ink)
+
+ def blur(self):
+ """Smooth the image, so the edges get grey values like in a scan."""
+ rows = [bytes(row) for row in self.rows]
+ for y in range(1, self.height - 1):
+ above, here, below = rows[y - 1], rows[y], rows[y + 1]
+ for x in range(1, self.width - 1):
+ self.rows[y][x] = (above[x] + below[x] + here[x - 1] +
+ here[x + 1] + 4 * here[x]) // 8
+
+ def rotate(self):
+ """Rotate the image clockwise by 90 degrees."""
+ rows = self.rows
+ self.rows = [bytearray(rows[self.height - 1 - x][y]
+ for x in range(self.height))
+ for y in range(self.width)]
+ self.width, self.height = self.height, self.width
+
+ def pixels(self, depth, ink, paper):
+ """Return the pixel data for the fuzz input."""
+ data = bytearray()
+ for row in self.rows:
+ if depth == 1:
+ for x in range(0, self.width, 8):
+ bits = 0
+ for grey in row[x:x + 8].ljust(8, b'\xff'):
+ bits = bits << 1 | (grey < 128)
+ data.append(bits)
+ elif depth == 8:
+ data += row
+ else:
+ for grey in row:
+ data += bytes((i * (255 - grey) + p * grey) // 255
+ for i, p in zip(ink, paper))
+ return bytes(data)
+
+
+def seed(page, mode, depth, method=None, resolution=None,
+ ink=(0, 0, 0), paper=(255, 255, 255)):
+ """Return the fuzz input (header line and pixel data) for a page.
+
+ The keys for method and resolution are left out if they are None, so
+ that the seeds also cover the default values.
+ """
+ header = {'psm': mode, 'depth': depth, 'thresholding_method': method,
+ 'width': page.width, 'height': page.height,
+ 'resolution': resolution}
+ line = ' '.join(f'{key}={value}' for key, value in header.items()
+ if value is not None)
+ return line.encode() + b'\n' + page.pixels(depth, ink, paper)
+
+
+def text_block(width, height, scale):
+ page = Page(width, height)
+ margin = 4 * scale
+ page.paragraph(margin, margin, width - 2 * margin, height - 2 * margin,
+ scale)
+ return page
+
+
+def two_columns(width, height, photo):
+ """Heading, ruling line and two columns of text, one with a photo."""
+ page = Page(width, height)
+ column = (width - 64) // 2
+ right = width - 12 - column
+ page.text(12, 6, 'THE DAILY PAGE', 2)
+ page.rect(12, 26, width - 24, 2, BLACK)
+ page.paragraph(12, 36, column, height - 40, 2)
+ if photo:
+ page.photo(right, 36, column, 34)
+ page.paragraph(right, 76, column, height - 80, 2, skip=17)
+ else:
+ page.paragraph(right, 36, column, height - 40, 2, skip=17)
+ return page
+
+
+def table(width, height):
+ """Table with ruling lines and a short text in each cell."""
+ page = Page(width, height)
+ columns, rows = 4, 4
+ cell_width = (width - 20) // columns
+ cell_height = (height - 20) // rows
+ for row in range(rows + 1):
+ page.rect(10, 10 + row * cell_height, columns * cell_width + 2, 2,
+ BLACK)
+ for column in range(columns + 1):
+ page.rect(10 + column * cell_width, 10, 2, rows * cell_height + 2,
+ BLACK)
+ for row in range(rows):
+ for column in range(columns):
+ word = TEXT[(5 * row + 3 * column) % len(TEXT)].strip('.,')
+ if column > 0 and row > 0:
+ word = str(137 * row * column + 1985)
+ page.text(18 + column * cell_width, 22 + row * cell_height,
+ word[:cell_width // 12 - 1], 2)
+ return page
+
+
+def sparse(width, height):
+ """Words of different sizes without any alignment."""
+ page = Page(width, height)
+ for index in range(9):
+ x = 10 + (index * 151) % (width - 130)
+ y = 6 + (index * 67) % (height - 30)
+ page.text(x, y, TEXT[3 * index % len(TEXT)].strip('.,'),
+ 2 + index % 2)
+ return page
+
+
+def single_column(width, height):
+ """Text of different sizes with an inverse heading."""
+ page = Page(width, height)
+ page.rect(0, 0, width, 44, 40)
+ page.text(12, 8, 'LARGE TITLE', 4, WHITE)
+ page.paragraph(12, 54, width - 24, 60, 3)
+ page.paragraph(12, 118, width - 24, height - 122, 2, skip=9)
+ return page
+
+
+def line(text, scale, margin=6):
+ page = Page(6 * scale * len(text) + 2 * margin, 7 * scale + 2 * margin)
+ page.text(margin, margin, text, scale)
+ return page
+
+
+def blurred(page):
+ page.blur()
+ return page
+
+
+def rotated(page):
+ page.rotate()
+ return page
+
+
+def seeds():
+ """Return the seeds as a dictionary of file names and contents."""
+ blue_on_yellow = {'ink': (20, 30, 120), 'paper': (250, 245, 200)}
+ green_on_grey = {'ink': (10, 70, 20), 'paper': (215, 215, 220)}
+ sentence = ' '.join(TEXT[:9])
+ return {
+ 'auto-columns-1bpp':
+ seed(two_columns(448, 144, False), PSM_AUTO, 1),
+ 'auto-columns-photo-8bpp':
+ seed(blurred(two_columns(448, 144, True)), PSM_AUTO, 8, OTSU, 0),
+ 'auto-columns-photo-32bpp':
+ seed(blurred(two_columns(400, 160, True)), PSM_AUTO, 32, SAUVOLA,
+ 150, **blue_on_yellow),
+ 'auto-table-1bpp':
+ seed(table(448, 144), PSM_AUTO, 1, resolution=200),
+ 'auto-table-8bpp':
+ seed(blurred(table(400, 160)), PSM_AUTO, 8, LEPTONICA_OTSU, 300),
+ 'single-column-8bpp':
+ seed(blurred(single_column(360, 180)), PSM_SINGLE_COLUMN, 8,
+ SAUVOLA),
+ 'single-block-vert-text-1bpp':
+ seed(rotated(text_block(400, 160, 2)), PSM_SINGLE_BLOCK_VERT_TEXT,
+ 1, resolution=300),
+ 'single-block-1bpp':
+ seed(text_block(448, 144, 2), PSM_SINGLE_BLOCK, 1),
+ 'single-block-32bpp':
+ seed(blurred(text_block(320, 160, 2)), PSM_SINGLE_BLOCK, 32,
+ LEPTONICA_OTSU, 72, **green_on_grey),
+ 'single-line-1bpp':
+ seed(line(sentence, 3), PSM_SINGLE_LINE, 1, resolution=300),
+ 'single-line-32bpp':
+ seed(blurred(line('100 LANGUAGES', 4)), PSM_SINGLE_LINE, 32,
+ resolution=4000, **blue_on_yellow),
+ 'single-line-8bpp':
+ seed(blurred(line(sentence[:30], 3)), PSM_SINGLE_LINE, 8,
+ LEPTONICA_OTSU, 30),
+ 'single-char-1bpp':
+ seed(line('R', 5), PSM_SINGLE_CHAR, 1),
+ 'sparse-text-1bpp':
+ seed(sparse(448, 144), PSM_SPARSE_TEXT, 1, resolution=120),
+ 'sparse-text-8bpp':
+ seed(blurred(sparse(400, 160)), PSM_SPARSE_TEXT, 8, SAUVOLA, 600),
+ }
+
+
+def main():
+ if len(sys.argv) != 2:
+ sys.exit(__doc__)
+ with zipfile.ZipFile(sys.argv[1], 'w', zipfile.ZIP_DEFLATED) as archive:
+ for name, data in seeds().items():
+ # Use a fixed time stamp to get a reproducible archive.
+ archive.writestr(zipfile.ZipInfo(name, (1980, 1, 1, 0, 0, 0)),
+ data, zipfile.ZIP_DEFLATED)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/unittest/fuzzers/fuzzer-raw-image.cpp b/unittest/fuzzers/fuzzer-raw-image.cpp
new file mode 100644
index 00000000..628ecb91
--- /dev/null
+++ b/unittest/fuzzers/fuzzer-raw-image.cpp
@@ -0,0 +1,472 @@
+///////////////////////////////////////////////////////////////////////
+// File: fuzzer-raw-image.cpp
+// Description: Fuzzer for layout analysis, thresholding and recognition
+// of raw images with a text header.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+// http://www.apache.org/licenses/LICENSE-2.0
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+///////////////////////////////////////////////////////////////////////
+
+// The fuzz input is a text line with parameters, followed by uncompressed
+// pixel data. No image file format is decoded, so the fuzzing time is spent
+// in Tesseract and not in the image decoders. Example:
+//
+// psm=3 depth=8 width=448 height=144 resolution=300\n<pixel data>
+//
+// The line ends with the first '\n' and has at most kMaxHeaderSize bytes.
+// It has any number of key=value pairs in any order, separated by spaces.
+// The values are decimal numbers:
+//
+// key values default
+// psm 3, 4, 5, 6, 7, 10, 6 page segmentation mode,
+// 11 see IsUsablePageSegMode
+// depth 1, 8, 32 1 bits per pixel
+// thresholding_method 0..2 0 Tesseract parameter with
+// that name
+// width 1..kMaxSide 128 image width in pixels
+// height 1..kMaxSide 128 image height in pixels
+// resolution 0..kMaxResolution 0 image resolution in ppi,
+// 0 = unknown
+//
+// The pixel data uses the layout of the binary PBM, PGM and PPM formats:
+// rows from top to bottom, pixels from left to right, and
+//
+// depth=1 1 bit per pixel, most significant bit first, 1 = black,
+// each row starts with a new byte
+// depth=8 1 byte per pixel, 0 = black
+// depth=32 3 bytes per pixel (red, green, blue)
+//
+// Missing pixels are white, so a short input gives an image with white rows
+// at the bottom. Pixel data which is not needed is ignored.
+//
+// Rules for changes of this format. The corpus of OSS-Fuzz and the test cases
+// of its bug reports are inputs in this format, and they must keep their
+// meaning:
+//
+// - An input which is not accepted is not run. That is the case for a missing
+// '\n', an unknown key, a key which is used twice, a value which is not
+// listed above, an image with more than kMaxPixels pixels, and an image
+// which is more than kMaxAspect times as wide as it is high. No input
+// which is in use can depend on something that is not accepted today, so
+// new keys, new values and higher limits can be added at any time.
+// - A new key needs a default which gives the behaviour without the key.
+// - Never change the meaning or the default of an existing key or value, and
+// never change the layout of the pixel data for an existing depth.
+//
+// Mutations of single bytes nearly always give a header which is not
+// accepted. Therefore libFuzzer gets a custom mutator which either sets one
+// of the parameters to another valid value or mutates the pixel data. The
+// other fuzzing engines do not use it. They depend on the seed corpus and on
+// the dictionary (fuzzer-raw-image.dict) for the header.
+
+#ifdef HAVE_CONFIG_H
+# include "config_auto.h" // DISABLED_LEGACY_ENGINE
+#endif
+
+#include <allheaders.h>
+#include <tesseract/baseapi.h>
+
+#include <libgen.h> // for dirname
+#include <algorithm> // for std::clamp, std::min
+#include <charconv> // for std::from_chars
+#include <cstddef> // for size_t
+#include <cstdint> // for uint8_t
+#include <cstdio> // for printf
+#include <cstdlib> // for std::getenv, setenv
+#include <cstring> // for memcpy, memmove
+#include <iterator> // for std::size
+#include <random> // for std::minstd_rand
+#include <string> // for std::string
+#include <string_view> // for std::string_view
+#include <system_error> // for std::errc
+
+// Largest size of the header line without the '\n'.
+static const size_t kMaxHeaderSize = 255;
+
+// Largest image width and height. It allows a long text line or a tall
+// column in an image which respects kMaxPixels.
+static const int kMaxSide = 2048;
+
+// Largest number of pixels. The run time grows with the image area, and
+// OSS-Fuzz stops a test case after 25 s. The slowest images are those with
+// many small words. With ASan and _GLIBCXX_DEBUG on a 3 GHz CPU, a page full
+// of 5 x 7 pixel characters needed up to 9 s with this limit and up to 14 s
+// with the 512 x 256 pixels of the larger one of the fuzzer-api targets.
+static const int kMaxPixels = 256 * 256;
+
+// Largest ratio of image width to image height. With PSM_SINGLE_LINE and
+// PSM_SINGLE_CHAR the whole image is one text line, and the LSTM recognizer
+// scales a text line to a fixed height, so a flat image gives a very long
+// line. With ASan and _GLIBCXX_DEBUG, a blank image of 2048 x 1 pixels needed
+// 34 s, 2048 x 8 pixels 3 s and 2048 x 32 pixels 2 s.
+static const int kMaxAspect = 64;
+
+// The resolution covers 0 (unknown) and values on both sides of the range
+// which Tesseract accepts (kMinCredibleResolution..kMaxCredibleResolution).
+static const int kMaxResolution = 9999;
+
+// Parameters from the header with their default values.
+struct Parameters {
+ int psm = tesseract::PSM_SINGLE_BLOCK;
+ int depth = 1;
+ int thresholding_method = 0;
+ int width = 128;
+ int height = 128;
+ int resolution = 0;
+};
+
+// Keys of the header with the range of their values.
+static const struct {
+ std::string_view key;
+ int Parameters::*value;
+ int min;
+ int max;
+} kKeys[] = {
+ {"psm", &Parameters::psm, 0, tesseract::PSM_COUNT - 1},
+ {"depth", &Parameters::depth, 1, 32},
+ {"thresholding_method", &Parameters::thresholding_method, 0, 2},
+ {"width", &Parameters::width, 1, kMaxSide},
+ {"height", &Parameters::height, 1, kMaxSide},
+ {"resolution", &Parameters::resolution, 0, kMaxResolution},
+};
+
+// Returns true for the page segmentation modes which the fuzzer uses.
+//
+// The modes with OSD are missing because they need osd.traineddata.
+// PSM_AUTO_ONLY is missing because it is the same as PSM_AUTO for
+// GetUTF8Text.
+//
+// PSM_SINGLE_WORD, PSM_CIRCLE_WORD and PSM_RAW_LINE are missing because they
+// make a single word from all blobs of the image. The time which the legacy
+// engine needs for a word (Tesseract::split_and_recog_word) grows much faster
+// than the number of its blobs. A checkerboard of 2 x 2 pixel squares needed
+// 19 s for 256 x 32 pixels with PSM_RAW_LINE, and 9 s for 512 x 32 pixels
+// and 58 s for 1024 x 32 pixels with PSM_SINGLE_WORD.
+static bool IsUsablePageSegMode(int mode) {
+ switch (mode) {
+ case tesseract::PSM_AUTO:
+ case tesseract::PSM_SINGLE_COLUMN:
+ case tesseract::PSM_SINGLE_BLOCK_VERT_TEXT:
+ case tesseract::PSM_SINGLE_BLOCK:
+ case tesseract::PSM_SINGLE_LINE:
+ case tesseract::PSM_SINGLE_CHAR:
+ case tesseract::PSM_SPARSE_TEXT:
+ return true;
+ default:
+ return false;
+ }
+}
+
+// Gets the parameters from the header line (without the '\n').
+// Returns false if the header is not accepted.
+static bool ParseHeader(std::string_view header, Parameters ¶meters) {
+ unsigned seen = 0;
+ while (!header.empty()) {
+ const auto token = header.substr(0, header.find(' '));
+ header.remove_prefix(std::min(token.size() + 1, header.size()));
+ if (token.empty()) {
+ continue;
+ }
+ const auto equals = token.find('=');
+ if (equals == std::string_view::npos) {
+ return false;
+ }
+ const auto key = token.substr(0, equals);
+ const char *first = token.data() + equals + 1;
+ const char *last = token.data() + token.size();
+ int value = 0;
+ const auto result = std::from_chars(first, last, value);
+ if (result.ec != std::errc() || result.ptr != last) {
+ return false;
+ }
+ unsigned index = 0;
+ while (index < std::size(kKeys) && key != kKeys[index].key) {
+ index++;
+ }
+ if (index == std::size(kKeys) || (seen & (1u << index)) != 0 ||
+ value < kKeys[index].min || value > kKeys[index].max) {
+ return false;
+ }
+ seen |= 1u << index;
+ parameters.*kKeys[index].value = value;
+ }
+ return IsUsablePageSegMode(parameters.psm) &&
+ (parameters.depth == 1 || parameters.depth == 8 ||
+ parameters.depth == 32) &&
+ parameters.width * parameters.height <= kMaxPixels &&
+ parameters.width <= kMaxAspect * parameters.height;
+}
+
+// Finds the header line at the start of the fuzz input and gets the
+// parameters from it. Returns the offset of the pixel data, or 0 if the input
+// is not accepted.
+static size_t ReadHeader(const uint8_t *data, size_t size,
+ Parameters ¶meters) {
+ // The '\n' may be the byte after kMaxHeaderSize.
+ const std::string_view start(reinterpret_cast<const char *>(data),
+ std::min(size, kMaxHeaderSize + 1));
+ const auto header_size = start.find('\n');
+ if (header_size == std::string_view::npos ||
+ !ParseHeader(start.substr(0, header_size), parameters)) {
+ return 0;
+ }
+ return header_size + 1;
+}
+
+// Returns the header line for the parameters. Keys with the default value
+// are left out.
+static std::string WriteHeader(const Parameters ¶meters) {
+ const Parameters defaults;
+ std::string header;
+ for (const auto &key : kKeys) {
+ if (parameters.*key.value != defaults.*key.value) {
+ if (!header.empty()) {
+ header += ' ';
+ }
+ header += key.key;
+ header += '=';
+ header += std::to_string(parameters.*key.value);
+ }
+ }
+ header += '\n';
+ return header;
+}
+
+// Sets one of the parameters to another valid value.
+static void MutateParameters(Parameters ¶meters, std::minstd_rand &random) {
+ static const int kPageSegModes[] = {
+ tesseract::PSM_AUTO,
+ tesseract::PSM_SINGLE_COLUMN,
+ tesseract::PSM_SINGLE_BLOCK_VERT_TEXT,
+ tesseract::PSM_SINGLE_BLOCK,
+ tesseract::PSM_SINGLE_LINE,
+ tesseract::PSM_SINGLE_CHAR,
+ tesseract::PSM_SPARSE_TEXT,
+ };
+ static const int kDepths[] = {1, 8, 32};
+ // Resolutions around the limits which Tesseract uses, and common ones.
+ static const int kResolutions[] = {
+ 0, 1, 69, 70, 71,
+ 72, 96, 150, 200, 300,
+ 600, 1200, 2400, 2401, kMaxResolution,
+ };
+ // A new size is either any size, a small size or a size near the old one.
+ const auto new_size = [&random](int old_size) {
+ switch (random() % 3) {
+ case 0:
+ return 1 + static_cast<int>(random() % kMaxSide);
+ case 1:
+ return 1 + static_cast<int>(random() % 64);
+ default:
+ return std::clamp(old_size + static_cast<int>(random() % 33) - 16, 1,
+ kMaxSide);
+ }
+ };
+ switch (random() % 6) {
+ case 0:
+ parameters.psm = kPageSegModes[random() % std::size(kPageSegModes)];
+ break;
+ case 1:
+ parameters.depth = kDepths[random() % std::size(kDepths)];
+ break;
+ case 2:
+ parameters.thresholding_method = random() % 3;
+ break;
+ case 3:
+ // Change the height if it is needed to get an accepted image size.
+ parameters.width = new_size(parameters.width);
+ parameters.height = std::clamp(
+ parameters.height, (parameters.width + kMaxAspect - 1) / kMaxAspect,
+ kMaxPixels / parameters.width);
+ break;
+ case 4:
+ // Change the width if it is needed to get an accepted image size.
+ parameters.height = new_size(parameters.height);
+ parameters.width =
+ std::min({parameters.width, kMaxPixels / parameters.height,
+ kMaxAspect * parameters.height});
+ break;
+ default:
+ parameters.resolution =
+ random() % 2 != 0 ? kResolutions[random() % std::size(kResolutions)]
+ : random() % (kMaxResolution + 1);
+ break;
+ }
+}
+
+// Mutation function of libFuzzer.
+extern "C" size_t LLVMFuzzerMutate(uint8_t *data, size_t size, size_t max_size);
+
+// Custom mutator for libFuzzer. It changes either a parameter or the pixel
+// data, so the header is always accepted.
+extern "C" size_t LLVMFuzzerCustomMutator(uint8_t *data, size_t size,
+ size_t max_size, unsigned int seed) {
+ std::minstd_rand random(seed);
+ Parameters parameters;
+ // An input which is not accepted is used as pixel data.
+ const size_t old_header_size = ReadHeader(data, size, parameters);
+ if (old_header_size == 0) {
+ parameters = Parameters();
+ }
+ const bool mutate_parameters = random() % 4 == 0;
+ if (mutate_parameters) {
+ MutateParameters(parameters, random);
+ }
+ const std::string header = WriteHeader(parameters);
+ if (header.size() >= max_size) {
+ return size;
+ }
+ uint8_t *pixels = data + header.size();
+ const size_t max_pixels_size = max_size - header.size();
+ size_t pixels_size = std::min(size - old_header_size, max_pixels_size);
+ memmove(pixels, data + old_header_size, pixels_size);
+ if (!mutate_parameters) {
+ pixels_size = LLVMFuzzerMutate(pixels, pixels_size, max_pixels_size);
+ }
+ memcpy(data, header.data(), header.size());
+ return header.size() + pixels_size;
+}
+
+// Reads the pixel data byte by byte.
+class ByteReader {
+private:
+ const uint8_t *data;
+ size_t size;
+
+public:
+ ByteReader(const uint8_t *data, size_t size) : data(data), size(size) {}
+
+ // Returns the next byte or fill if there is no more data.
+ unsigned Read(unsigned fill) {
+ if (size == 0) {
+ return fill;
+ }
+ size--;
+ return *data++;
+ }
+};
+
+static tesseract::TessBaseAPI *api = nullptr;
+
+extern "C" int LLVMFuzzerInitialize(int * /*pArgc*/, char ***pArgv) {
+ if (std::getenv("TESSDATA_PREFIX") == nullptr) {
+ std::string binary_path = *pArgv[0];
+ const std::string filepath = dirname(&binary_path[0]);
+
+ const std::string tessdata_path = filepath + "/" + "tessdata";
+ if (setenv("TESSDATA_PREFIX", tessdata_path.c_str(), 1) != 0) {
+ printf("Setenv failed\n");
+ std::abort();
+ }
+ }
+
+ api = new tesseract::TessBaseAPI();
+ if (api->Init(nullptr, "eng") != 0) {
+ printf("Cannot initialize API\n");
+ abort();
+ }
+
+ /* Silence output */
+ api->SetVariable("debug_file", "/dev/null");
+ setMsgSeverity(L_SEVERITY_NONE);
+
+ /* Bound the run time for images which give a huge number of blobs (OSS-Fuzz
+ issue 581720522). This is not the default, because it would also truncate
+ the text of normal pages. The parameter does not exist in builds without
+ the legacy engine, so the result is ignored. */
+ api->SetVariable("chop_max_classifications_pass", "5000");
+
+ return 0;
+}
+
+static Pix *createPix(ByteReader &reader, int width, int height, int depth) {
+ Pix *pix = pixCreate(width, height, depth);
+
+ if (pix == nullptr) {
+ printf("pix creation failed\n");
+ abort();
+ }
+
+ l_uint32 *line = pixGetData(pix);
+ const int wpl = pixGetWpl(pix);
+ for (int y = 0; y < height; y++, line += wpl) {
+ switch (depth) {
+ case 1:
+ for (int x = 0; x < width; x += 8) {
+ SET_DATA_BYTE(line, x / 8, reader.Read(0x00));
+ }
+ break;
+ case 8:
+ for (int x = 0; x < width; x++) {
+ SET_DATA_BYTE(line, x, reader.Read(0xff));
+ }
+ break;
+ default:
+ for (int x = 0; x < width; x++) {
+ const unsigned red = reader.Read(0xff);
+ const unsigned green = reader.Read(0xff);
+ const unsigned blue = reader.Read(0xff);
+ composeRGBPixel(red, green, blue, line + x);
+ }
+ break;
+ }
+ }
+
+ // Clear the unused bits at the end of the rows of a 1 bpp image.
+ pixSetPadBits(pix, 0);
+
+ return pix;
+}
+
+extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
+ Parameters parameters;
+ const size_t header_size = ReadHeader(data, size, parameters);
+ if (header_size == 0) {
+ // The input is not accepted. Return 0 nevertheless: libFuzzer and AFL++
+ // would not add the input to the corpus for -1, but honggfuzz ends with
+ // an error for any other value than 0.
+ return 0;
+ }
+
+ ByteReader reader(data + header_size, size - header_size);
+ auto pix =
+ createPix(reader, parameters.width, parameters.height, parameters.depth);
+ pixSetResolution(pix, parameters.resolution, parameters.resolution);
+
+ api->SetPageSegMode(static_cast<tesseract::PageSegMode>(parameters.psm));
+ api->SetVariable("thresholding_method",
+ std::to_string(parameters.thresholding_method).c_str());
+ api->SetImage(pix);
+
+ char *outText = api->GetUTF8Text();
+
+ delete[] outText;
+
+ // Release the image and the results, and forget what was learned from this
+ // image, so that the result for the next image does not depend on it.
+ api->Clear();
+#ifndef DISABLED_LEGACY_ENGINE
+ api->ClearAdaptiveClassifier();
+#endif
+ pixDestroy(&pix);
+
+ return 0;
+}
+
+// Release the API on exit (called by libFuzzer). Without this, the API's
+// legacy dictionary keeps references to the DAWGs of the static global DAWG
+// cache (Dict::GlobalDawgCache()), which still hold count > 0 when that cache
+// is destroyed during static teardown, printing spurious
+// "ObjectCache: WARNING! LEAK!" lines. Deleting the API runs the normal
+// ~Tesseract() -> Dict::End() path, which releases the references.
+extern "C" void LLVMFuzzerDone() {
+ delete api;
+ api = nullptr;
+}
diff --git a/unittest/fuzzers/fuzzer-raw-image.dict b/unittest/fuzzers/fuzzer-raw-image.dict
new file mode 100644
index 00000000..2ab2b6c5
--- /dev/null
+++ b/unittest/fuzzers/fuzzer-raw-image.dict
@@ -0,0 +1,26 @@
+# Dictionary for fuzzer-raw-image: keys and values of the header line.
+"psm="
+"depth="
+"thresholding_method="
+"width="
+"height="
+"resolution="
+"psm=3"
+"psm=4"
+"psm=5"
+"psm=6"
+"psm=7"
+"psm=10"
+"psm=11"
+"depth=1"
+"depth=8"
+"depth=32"
+"thresholding_method=0"
+"thresholding_method=1"
+"thresholding_method=2"
+"resolution=0"
+"resolution=70"
+"resolution=300"
+"resolution=2400"
+" "
+"\x0a"
diff --git a/unittest/fuzzers/oss-fuzz-build.sh b/unittest/fuzzers/oss-fuzz-build.sh
index 491e19ee..5478ed3e 100755
--- a/unittest/fuzzers/oss-fuzz-build.sh
+++ b/unittest/fuzzers/oss-fuzz-build.sh
@@ -60,3 +60,24 @@ $CXX $CXXFLAGS \
$LEPTONICA_CFLAGS \
-Wl,-Bstatic $LEPTONICA_LIBS $LIBTIFF_LIBS -Wl,-Bdynamic \
$LIB_FUZZING_ENGINE
+
+# fuzzer-raw-image reads the page segmentation mode and the size, depth and
+# resolution of the image from a text line at the start of the fuzz input.
+# The dictionary has the keys and values for that line. HAVE_CONFIG_H is
+# needed for config_auto.h which tells whether the legacy engine was built.
+
+$CXX $CXXFLAGS \
+ -DHAVE_CONFIG_H \
+ -I "$SRC"/tesseract/include \
+ "$SRC"/tesseract/unittest/fuzzers/fuzzer-raw-image.cpp -o "$OUT"/fuzzer-raw-image \
+ "$SRC"/tesseract/.libs/libtesseract.a \
+ $LEPTONICA_CFLAGS \
+ -Wl,-Bstatic $LEPTONICA_LIBS $LIBTIFF_LIBS -Wl,-Bdynamic \
+ $LIB_FUZZING_ENGINE
+
+cp "$SRC"/tesseract/unittest/fuzzers/fuzzer-raw-image.dict "$OUT"/
+
+# The seed corpus is generated, so that no image files are needed.
+
+python3 "$SRC"/tesseract/unittest/fuzzers/fuzzer-raw-image-seeds.py \
+ "$OUT"/fuzzer-raw-image_seed_corpus.zip