From ff53af0d4ff9291aa5039522f5553a2850dd569d Mon Sep 17 00:00:00 2001
From: Sebastian Rasmussen <sebras@gmail.com>
Date: Thu, 12 Mar 2020 00:26:59 +0800
Subject: [PATCH] jbig2dec: Always use uint32_t when counting pages.

---
 jbig2dec/jbig2.c      |  4 ++--
 jbig2dec/jbig2_page.c | 10 +++++++++-
 jbig2dec/jbig2_priv.h |  4 ++--
 3 files changed, 13 insertions(+), 5 deletions(-)

diff --git a/jbig2dec/jbig2.c b/jbig2dec/jbig2.c
index 126e7a9..9fbb340 100644
--- a/jbig2dec/jbig2.c
+++ b/jbig2dec/jbig2.c
@@ -154,7 +154,7 @@ jbig2_ctx_new_imp(Jbig2Allocator *allocator, Jbig2Options options, Jbig2GlobalCt
         return NULL;
     }
     {
-        int index;
+        uint32_t index;
 
         for (index = 0; index < result->max_page_index; index++) {
             result->pages[index].state = JBIG2_PAGE_FREE;
@@ -412,7 +412,7 @@ Jbig2Allocator *
 jbig2_ctx_free(Jbig2Ctx *ctx)
 {
     Jbig2Allocator *ca;
-    int i;
+    uint32_t i;
 
     if (ctx == NULL)
         return NULL;
diff --git a/jbig2dec/jbig2_page.c b/jbig2dec/jbig2_page.c
index 21483e8..31b31f7 100644
--- a/jbig2dec/jbig2_page.c
+++ b/jbig2dec/jbig2_page.c
@@ -72,13 +72,21 @@ jbig2_page_info(Jbig2Ctx *ctx, Jbig2Segment *segment, const uint8_t *segment_dat
 
     /* find a free page */
     {
-        int index, j;
+        size_t index, j;
 
         index = ctx->current_page;
         while (ctx->pages[index].state != JBIG2_PAGE_FREE) {
             index++;
             if (index >= ctx->max_page_index) {
                 /* grow the list */
+
+                if (ctx->max_page_index == SIZE_MAX) {
+                    return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "too many pages in jbig2 image");
+                }
+                else if (ctx->max_page_index > (SIZE_MAX >> 2)) {
+                    ctx->max_page_index = SIZE_MAX;
+                }
+
                 pages = jbig2_renew(ctx, ctx->pages, Jbig2Page, (ctx->max_page_index <<= 2));
                 if (pages == NULL) {
                     return jbig2_error(ctx, JBIG2_SEVERITY_FATAL, segment->number, "failed to reallocate pages");
diff --git a/jbig2dec/jbig2_priv.h b/jbig2dec/jbig2_priv.h
index e5a1eb5..d464208 100644
--- a/jbig2dec/jbig2_priv.h
+++ b/jbig2dec/jbig2_priv.h
@@ -101,8 +101,8 @@ struct _Jbig2Ctx {
 
     /* list of decoded pages, including the one in progress,
        currently stored as a contiguous, 0-indexed array. */
-    int current_page;
-    int max_page_index;
+    uint32_t current_page;
+    uint32_t max_page_index;
     Jbig2Page *pages;
 };
 
-- 
1.8.3.1

