Commit 1490fe89 for tesseract

commit 1490fe89b1d1123489cbaa98624a739712440dfc
Author: Stefan Weil <sw@weilnetz.de>
Date:   Fri Nov 13 21:26:30 2026 +0100

    textord: make sure that a grid has at least one cell

    GridBase::Init() rounds the size of the grid up to a multiple of the
    cell size. The cell size is derived from the line size, which depends
    on parameters like textord_min_xheight. For a huge or a negative cell
    size the rounding overflowed or the quotient was not positive, and
    the grid got no cells. ClipGridCoords() then clipped to index -1, and
    BBGrid::InsertBBox() wrote a pointer in front of the array.

    Clip the cell size to [1, INT16_MAX] and give each grid at least one
    cell in both directions, also for an empty or inverted box.

    Fix proposed by the Anthropic OSS Scanner (finding ANT-2026-LOI6BY6K).

    Assisted-by: OpenCode / Claude Fable 5.2 (Anthropic)
    Signed-off-by: Stefan Weil <sw@weilnetz.de>

diff --git a/src/textord/bbgrid.cpp b/src/textord/bbgrid.cpp
index 9189cb85..d6a62d3b 100644
--- a/src/textord/bbgrid.cpp
+++ b/src/textord/bbgrid.cpp
@@ -22,6 +22,8 @@
 #include "image.h"    // for Image
 #include "ocrblock.h"

+#include <cstdint> // for INT16_MAX
+
 namespace tesseract {

 ///////////////////////////////////////////////////////////////////////
@@ -39,14 +41,22 @@ GridBase::~GridBase() = default;
 // (Re)Initialize the grid. The gridsize is the size in pixels of each cell,
 // and bleft, tright are the bounding box of everything to go in it.
 void GridBase::Init(int gridsize, const ICOORD &bleft, const ICOORD &tright) {
-  gridsize_ = gridsize;
+  // Clip the cell size to the coordinate range: a cell larger than any box is
+  // pointless, and would overflow the rounding up below (as would a negative
+  // size), leaving a grid with no cells for ClipGridCoords() to clip to.
+  gridsize_ = ClipToRange<int>(gridsize, 1, INT16_MAX);
   bleft_ = bleft;
   tright_ = tright;
-  if (gridsize_ == 0) {
-    gridsize_ = 1;
-  }
   gridwidth_ = (tright.x() - bleft.x() + gridsize_ - 1) / gridsize_;
   gridheight_ = (tright.y() - bleft.y() + gridsize_ - 1) / gridsize_;
+  // ClipGridCoords() clips to [0, gridwidth_ - 1], so the grid must have at
+  // least one cell in each direction, even for an empty or inverted box.
+  if (gridwidth_ < 1) {
+    gridwidth_ = 1;
+  }
+  if (gridheight_ < 1) {
+    gridheight_ = 1;
+  }
   gridbuckets_ = gridwidth_ * gridheight_;
 }