From ceefc348eb3c3844c7f9796ef2cc3a7dd5fbba7b Mon Sep 17 00:00:00 2001
From: Andrew Murray <3112309+radarhere@users.noreply.github.com>
Date: Mon, 22 Jun 2026 12:56:41 +1000
Subject: [PATCH] Use int64_t to calculate paste box dimensions (#9703)

---
 Tests/test_image_paste.py | 14 ++++++++++++++
 src/libImaging/Paste.c    | 12 ++++++------
 2 files changed, 20 insertions(+), 6 deletions(-)

Index: pillow-11.3.0/Tests/test_image_paste.py
===================================================================
--- pillow-11.3.0.orig/Tests/test_image_paste.py
+++ pillow-11.3.0/Tests/test_image_paste.py
@@ -342,6 +342,20 @@ class TestImagingPaste:
         im.copy().paste(im2)
         im.copy().paste(im2, (0, 0))
 
+    @pytest.mark.parametrize(
+        "box",
+        (
+            (2**31 - 1, 0, -(2**31), 1),
+            (0, 2**31 - 1, 1, -(2**31)),
+        ),
+    )
+    def test_overflow(self, box: tuple[int, int, int, int]) -> None:
+        im = Image.new("1", (1, 1))
+        im.paste(1, box)
+
+        with pytest.raises(ValueError, match="images do not match"):
+            im.paste(im.copy(), box)
+
     def test_incorrect_abbreviated_form(self) -> None:
         im = Image.new("L", (1, 1))
         with pytest.raises(ValueError):
Index: pillow-11.3.0/src/libImaging/Paste.c
===================================================================
--- pillow-11.3.0.orig/src/libImaging/Paste.c
+++ pillow-11.3.0/src/libImaging/Paste.c
@@ -259,7 +259,7 @@ int
 ImagingPaste(
     Imaging imOut, Imaging imIn, Imaging imMask, int dx0, int dy0, int dx1, int dy1
 ) {
-    int xsize, ysize;
+    int64_t xsize, ysize;
     int pixelsize;
     int sx0, sy0;
     ImagingSectionCookie cookie;
@@ -271,8 +271,8 @@ ImagingPaste(
 
     pixelsize = imOut->pixelsize;
 
-    xsize = dx1 - dx0;
-    ysize = dy1 - dy0;
+    xsize = (int64_t)dx1 - dx0;
+    ysize = (int64_t)dy1 - dy0;
 
     if (xsize != imIn->xsize || ysize != imIn->ysize || pixelsize != imIn->pixelsize) {
         (void)ImagingError_Mismatch();
@@ -575,7 +575,7 @@ ImagingFill2(
     Imaging imOut, const void *ink, Imaging imMask, int dx0, int dy0, int dx1, int dy1
 ) {
     ImagingSectionCookie cookie;
-    int xsize, ysize;
+    int64_t xsize, ysize;
     int pixelsize;
     int sx0, sy0;
 
@@ -586,8 +586,8 @@ ImagingFill2(
 
     pixelsize = imOut->pixelsize;
 
-    xsize = dx1 - dx0;
-    ysize = dy1 - dy0;
+    xsize = (int64_t)dx1 - dx0;
+    ysize = (int64_t)dy1 - dy0;
 
     if (imMask && (xsize != imMask->xsize || ysize != imMask->ysize)) {
         (void)ImagingError_Mismatch();
