Issue #14398: Fix size truncation and overflow bugs in bz2 module.
diff --git a/Modules/bz2module.c b/Modules/bz2module.c
index a671e8d..4795965 100644
--- a/Modules/bz2module.c
+++ b/Modules/bz2module.c
@@ -41,23 +41,8 @@
 #define MODE_READ_EOF 2
 #define MODE_WRITE    3
 
-#define BZ2FileObject_Check(v)  (Py_TYPE(v) == &BZ2File_Type)
 
-
-#ifdef BZ_CONFIG_ERROR
-
-#if SIZEOF_LONG >= 8
-#define BZS_TOTAL_OUT(bzs) \
-    (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
-#elif SIZEOF_LONG_LONG >= 8
-#define BZS_TOTAL_OUT(bzs) \
-    (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
-#else
-#define BZS_TOTAL_OUT(bzs) \
-    bzs->total_out_lo32
-#endif
-
-#else /* ! BZ_CONFIG_ERROR */
+#ifndef BZ_CONFIG_ERROR
 
 #define BZ2_bzRead bzRead
 #define BZ2_bzReadOpen bzReadOpen
@@ -72,8 +57,6 @@
 #define BZ2_bzDecompressInit bzDecompressInit
 #define BZ2_bzDecompressEnd bzDecompressEnd
 
-#define BZS_TOTAL_OUT(bzs) bzs->total_out
-
 #endif /* ! BZ_CONFIG_ERROR */
 
 
@@ -90,11 +73,7 @@
 #define RELEASE_LOCK(obj)
 #endif
 
-/* Bits in f_newlinetypes */
-#define NEWLINE_UNKNOWN 0       /* No newline seen, yet */
-#define NEWLINE_CR 1            /* \r newline seen */
-#define NEWLINE_LF 2            /* \n newline seen */
-#define NEWLINE_CRLF 4          /* \r\n newline seen */
+#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
 
 /* ===================================================================== */
 /* Structure definitions. */
@@ -228,6 +207,20 @@
     return currentsize + (currentsize >> 3) + 6;
 }
 
+static int
+Util_GrowBuffer(PyObject **buf)
+{
+    size_t size = PyBytes_GET_SIZE(*buf);
+    size_t new_size = Util_NewBufferSize(size);
+    if (new_size > size) {
+        return _PyBytes_Resize(buf, new_size);
+    } else {  /* overflow */
+        PyErr_SetString(PyExc_OverflowError,
+                        "Unable to allocate buffer - output too large");
+        return -1;
+    }
+}
+
 /* This is a hacked version of Python's fileobject.c:get_line(). */
 static PyObject *
 Util_GetLine(BZ2FileObject *f, int n)
@@ -1418,20 +1411,16 @@
 BZ2Comp_compress(BZ2CompObject *self, PyObject *args)
 {
     Py_buffer pdata;
-    char *data;
-    int datasize;
-    int bufsize = SMALLCHUNK;
-    PY_LONG_LONG totalout;
+    size_t input_left;
+    size_t output_size = 0;
     PyObject *ret = NULL;
     bz_stream *bzs = &self->bzs;
     int bzerror;
 
     if (!PyArg_ParseTuple(args, "y*:compress", &pdata))
         return NULL;
-    data = pdata.buf;
-    datasize = pdata.len;
 
-    if (datasize == 0) {
+    if (pdata.len == 0) {
         PyBuffer_Release(&pdata);
         return PyBytes_FromStringAndSize("", 0);
     }
@@ -1443,41 +1432,51 @@
         goto error;
     }
 
-    ret = PyBytes_FromStringAndSize(NULL, bufsize);
+    ret = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
     if (!ret)
         goto error;
 
-    bzs->next_in = data;
-    bzs->avail_in = datasize;
-    bzs->next_out = BUF(ret);
-    bzs->avail_out = bufsize;
+    bzs->next_in = pdata.buf;
+    bzs->avail_in = MIN(pdata.len, UINT_MAX);
+    input_left = pdata.len - bzs->avail_in;
 
-    totalout = BZS_TOTAL_OUT(bzs);
+    bzs->next_out = BUF(ret);
+    bzs->avail_out = PyBytes_GET_SIZE(ret);
 
     for (;;) {
+        char *saved_next_out;
+
         Py_BEGIN_ALLOW_THREADS
+        saved_next_out = bzs->next_out;
         bzerror = BZ2_bzCompress(bzs, BZ_RUN);
+        output_size += bzs->next_out - saved_next_out;
         Py_END_ALLOW_THREADS
+
         if (bzerror != BZ_RUN_OK) {
             Util_CatchBZ2Error(bzerror);
             goto error;
         }
-        if (bzs->avail_in == 0)
-            break; /* no more input data */
+        if (bzs->avail_in == 0) {
+            if (input_left == 0)
+                break; /* no more input data */
+            bzs->avail_in = MIN(input_left, UINT_MAX);
+            input_left -= bzs->avail_in;
+        }
         if (bzs->avail_out == 0) {
-            bufsize = Util_NewBufferSize(bufsize);
-            if (_PyBytes_Resize(&ret, bufsize) < 0) {
-                BZ2_bzCompressEnd(bzs);
-                goto error;
+            size_t buffer_left = PyBytes_GET_SIZE(ret) - output_size;
+            if (buffer_left == 0) {
+                if (Util_GrowBuffer(&ret) < 0) {
+                    BZ2_bzCompressEnd(bzs);
+                    goto error;
+                }
+                bzs->next_out = BUF(ret) + output_size;
+                buffer_left = PyBytes_GET_SIZE(ret) - output_size;
             }
-            bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
-                                        - totalout);
-            bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+            bzs->avail_out = MIN(buffer_left, UINT_MAX);
         }
     }
 
-    if (_PyBytes_Resize(&ret,
-                       (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
+    if (_PyBytes_Resize(&ret, output_size) < 0)
         goto error;
 
     RELEASE_LOCK(self);
@@ -1501,33 +1500,34 @@
 static PyObject *
 BZ2Comp_flush(BZ2CompObject *self)
 {
-    int bufsize = SMALLCHUNK;
+    size_t output_size = 0;
     PyObject *ret = NULL;
     bz_stream *bzs = &self->bzs;
-    PY_LONG_LONG totalout;
     int bzerror;
 
     ACQUIRE_LOCK(self);
     if (!self->running) {
-        PyErr_SetString(PyExc_ValueError, "object was already "
-                                          "flushed");
+        PyErr_SetString(PyExc_ValueError, "object was already flushed");
         goto error;
     }
     self->running = 0;
 
-    ret = PyBytes_FromStringAndSize(NULL, bufsize);
+    ret = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
     if (!ret)
         goto error;
 
     bzs->next_out = BUF(ret);
-    bzs->avail_out = bufsize;
-
-    totalout = BZS_TOTAL_OUT(bzs);
+    bzs->avail_out = PyBytes_GET_SIZE(ret);
 
     for (;;) {
+        char *saved_next_out;
+
         Py_BEGIN_ALLOW_THREADS
+        saved_next_out = bzs->next_out;
         bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
+        output_size += bzs->next_out - saved_next_out;
         Py_END_ALLOW_THREADS
+
         if (bzerror == BZ_STREAM_END) {
             break;
         } else if (bzerror != BZ_FINISH_OK) {
@@ -1535,21 +1535,20 @@
             goto error;
         }
         if (bzs->avail_out == 0) {
-            bufsize = Util_NewBufferSize(bufsize);
-            if (_PyBytes_Resize(&ret, bufsize) < 0)
-                goto error;
-            bzs->next_out = BUF(ret);
-            bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
-                                        - totalout);
-            bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+            size_t buffer_left = PyBytes_GET_SIZE(ret) - output_size;
+            if (buffer_left == 0) {
+                if (Util_GrowBuffer(&ret) < 0)
+                    goto error;
+                bzs->next_out = BUF(ret) + output_size;
+                buffer_left = PyBytes_GET_SIZE(ret) - output_size;
+            }
+            bzs->avail_out = MIN(buffer_left, UINT_MAX);
         }
     }
 
-    if (bzs->avail_out != 0) {
-        if (_PyBytes_Resize(&ret,
-                    (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
+    if (output_size != PyBytes_GET_SIZE(ret))
+        if (_PyBytes_Resize(&ret, output_size) < 0)
             goto error;
-    }
 
     RELEASE_LOCK(self);
     return ret;
@@ -1714,18 +1713,14 @@
 BZ2Decomp_decompress(BZ2DecompObject *self, PyObject *args)
 {
     Py_buffer pdata;
-    char *data;
-    int datasize;
-    int bufsize = SMALLCHUNK;
-    PY_LONG_LONG totalout;
+    size_t input_left;
+    size_t output_size = 0;
     PyObject *ret = NULL;
     bz_stream *bzs = &self->bzs;
     int bzerror;
 
     if (!PyArg_ParseTuple(args, "y*:decompress", &pdata))
         return NULL;
-    data = pdata.buf;
-    datasize = pdata.len;
 
     ACQUIRE_LOCK(self);
     if (!self->running) {
@@ -1734,55 +1729,65 @@
         goto error;
     }
 
-    ret = PyBytes_FromStringAndSize(NULL, bufsize);
+    ret = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
     if (!ret)
         goto error;
 
-    bzs->next_in = data;
-    bzs->avail_in = datasize;
-    bzs->next_out = BUF(ret);
-    bzs->avail_out = bufsize;
+    bzs->next_in = pdata.buf;
+    bzs->avail_in = MIN(pdata.len, UINT_MAX);
+    input_left = pdata.len - bzs->avail_in;
 
-    totalout = BZS_TOTAL_OUT(bzs);
+    bzs->next_out = BUF(ret);
+    bzs->avail_out = PyBytes_GET_SIZE(ret);
 
     for (;;) {
+        char *saved_next_out;
+
         Py_BEGIN_ALLOW_THREADS
+        saved_next_out = bzs->next_out;
         bzerror = BZ2_bzDecompress(bzs);
+        output_size += bzs->next_out - saved_next_out;
         Py_END_ALLOW_THREADS
+
         if (bzerror == BZ_STREAM_END) {
-            if (bzs->avail_in != 0) {
+            self->running = 0;
+            input_left += bzs->avail_in;
+            if (input_left != 0) {
                 Py_DECREF(self->unused_data);
                 self->unused_data =
-                    PyBytes_FromStringAndSize(bzs->next_in,
-                                               bzs->avail_in);
+                    PyBytes_FromStringAndSize(bzs->next_in, input_left);
+                if (self->unused_data == NULL)
+                    goto error;
             }
-            self->running = 0;
             break;
         }
         if (bzerror != BZ_OK) {
             Util_CatchBZ2Error(bzerror);
             goto error;
         }
-        if (bzs->avail_in == 0)
-            break; /* no more input data */
+        if (bzs->avail_in == 0) {
+            if (input_left == 0)
+                break; /* no more input data */
+            bzs->avail_in = MIN(input_left, UINT_MAX);
+            input_left -= bzs->avail_in;
+        }
         if (bzs->avail_out == 0) {
-            bufsize = Util_NewBufferSize(bufsize);
-            if (_PyBytes_Resize(&ret, bufsize) < 0) {
-                BZ2_bzDecompressEnd(bzs);
-                goto error;
+            size_t buffer_left = PyBytes_GET_SIZE(ret) - output_size;
+            if (buffer_left == 0) {
+                if (Util_GrowBuffer(&ret) < 0) {
+                    BZ2_bzDecompressEnd(bzs);
+                    goto error;
+                }
+                bzs->next_out = BUF(ret) + output_size;
+                buffer_left = PyBytes_GET_SIZE(ret) - output_size;
             }
-            bzs->next_out = BUF(ret);
-            bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
-                                        - totalout);
-            bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+            bzs->avail_out = MIN(buffer_left, UINT_MAX);
         }
     }
 
-    if (bzs->avail_out != 0) {
-        if (_PyBytes_Resize(&ret,
-                    (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout)) < 0)
+    if (output_size != PyBytes_GET_SIZE(ret))
+        if (_PyBytes_Resize(&ret, output_size) < 0)
             goto error;
-    }
 
     RELEASE_LOCK(self);
     PyBuffer_Release(&pdata);
@@ -1929,10 +1934,10 @@
 bz2_compress(PyObject *self, PyObject *args, PyObject *kwargs)
 {
     int compresslevel=9;
+    int action;
     Py_buffer pdata;
-    char *data;
-    int datasize;
-    int bufsize;
+    size_t input_left;
+    size_t output_size = 0;
     PyObject *ret = NULL;
     bz_stream _bzs;
     bz_stream *bzs = &_bzs;
@@ -1943,8 +1948,6 @@
                                      kwlist, &pdata,
                                      &compresslevel))
         return NULL;
-    data = pdata.buf;
-    datasize = pdata.len;
 
     if (compresslevel < 1 || compresslevel > 9) {
         PyErr_SetString(PyExc_ValueError,
@@ -1953,11 +1956,7 @@
         return NULL;
     }
 
-    /* Conforming to bz2 manual, this is large enough to fit compressed
-     * data in one shot. We will check it later anyway. */
-    bufsize = datasize + (datasize/100+1) + 600;
-
-    ret = PyBytes_FromStringAndSize(NULL, bufsize);
+    ret = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
     if (!ret) {
         PyBuffer_Release(&pdata);
         return NULL;
@@ -1965,10 +1964,12 @@
 
     memset(bzs, 0, sizeof(bz_stream));
 
-    bzs->next_in = data;
-    bzs->avail_in = datasize;
+    bzs->next_in = pdata.buf;
+    bzs->avail_in = MIN(pdata.len, UINT_MAX);
+    input_left = pdata.len - bzs->avail_in;
+
     bzs->next_out = BUF(ret);
-    bzs->avail_out = bufsize;
+    bzs->avail_out = PyBytes_GET_SIZE(ret);
 
     bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0);
     if (bzerror != BZ_OK) {
@@ -1978,38 +1979,53 @@
         return NULL;
     }
 
+    action = BZ_RUN;
+
     for (;;) {
+        char *saved_next_out;
+
         Py_BEGIN_ALLOW_THREADS
-        bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
+        saved_next_out = bzs->next_out;
+        bzerror = BZ2_bzCompress(bzs, action);
+        output_size += bzs->next_out - saved_next_out;
         Py_END_ALLOW_THREADS
+
         if (bzerror == BZ_STREAM_END) {
             break;
-        } else if (bzerror != BZ_FINISH_OK) {
+        } else if (bzerror != BZ_RUN_OK && bzerror != BZ_FINISH_OK) {
             BZ2_bzCompressEnd(bzs);
             Util_CatchBZ2Error(bzerror);
             PyBuffer_Release(&pdata);
             Py_DECREF(ret);
             return NULL;
         }
-        if (bzs->avail_out == 0) {
-            bufsize = Util_NewBufferSize(bufsize);
-            if (_PyBytes_Resize(&ret, bufsize) < 0) {
-                BZ2_bzCompressEnd(bzs);
-                PyBuffer_Release(&pdata);
-                return NULL;
+        if (action == BZ_RUN && bzs->avail_in == 0) {
+            if (input_left == 0) {
+                action = BZ_FINISH;
+            } else {
+                bzs->avail_in = MIN(input_left, UINT_MAX);
+                input_left -= bzs->avail_in;
             }
-            bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
-            bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+        }
+        if (bzs->avail_out == 0) {
+            size_t buffer_left = PyBytes_GET_SIZE(ret) - output_size;
+            if (buffer_left == 0) {
+                if (Util_GrowBuffer(&ret) < 0) {
+                    BZ2_bzCompressEnd(bzs);
+                    PyBuffer_Release(&pdata);
+                    return NULL;
+                }
+                bzs->next_out = BUF(ret) + output_size;
+                buffer_left = PyBytes_GET_SIZE(ret) - output_size;
+            }
+            bzs->avail_out = MIN(buffer_left, UINT_MAX);
         }
     }
 
-    if (bzs->avail_out != 0) {
-        if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) {
-            ret = NULL;
-        }
-    }
+    if (output_size != PyBytes_GET_SIZE(ret))
+        _PyBytes_Resize(&ret, output_size);  /* Sets ret to NULL on failure. */
+
     BZ2_bzCompressEnd(bzs);
-
     PyBuffer_Release(&pdata);
     return ret;
 }
@@ -2025,9 +2041,8 @@
 bz2_decompress(PyObject *self, PyObject *args)
 {
     Py_buffer pdata;
-    char *data;
-    int datasize;
-    int bufsize = SMALLCHUNK;
+    size_t input_left;
+    size_t output_size = 0;
     PyObject *ret;
     bz_stream _bzs;
     bz_stream *bzs = &_bzs;
@@ -2035,15 +2050,13 @@
 
     if (!PyArg_ParseTuple(args, "y*:decompress", &pdata))
         return NULL;
-    data = pdata.buf;
-    datasize = pdata.len;
 
-    if (datasize == 0) {
+    if (pdata.len == 0) {
         PyBuffer_Release(&pdata);
         return PyBytes_FromStringAndSize("", 0);
     }
 
-    ret = PyBytes_FromStringAndSize(NULL, bufsize);
+    ret = PyBytes_FromStringAndSize(NULL, SMALLCHUNK);
     if (!ret) {
         PyBuffer_Release(&pdata);
         return NULL;
@@ -2051,10 +2064,12 @@
 
     memset(bzs, 0, sizeof(bz_stream));
 
-    bzs->next_in = data;
-    bzs->avail_in = datasize;
+    bzs->next_in = pdata.buf;
+    bzs->avail_in = MIN(pdata.len, UINT_MAX);
+    input_left = pdata.len - bzs->avail_in;
+
     bzs->next_out = BUF(ret);
-    bzs->avail_out = bufsize;
+    bzs->avail_out = PyBytes_GET_SIZE(ret);
 
     bzerror = BZ2_bzDecompressInit(bzs, 0, 0);
     if (bzerror != BZ_OK) {
@@ -2065,9 +2080,14 @@
     }
 
     for (;;) {
+        char *saved_next_out;
+
         Py_BEGIN_ALLOW_THREADS
+        saved_next_out = bzs->next_out;
         bzerror = BZ2_bzDecompress(bzs);
+        output_size += bzs->next_out - saved_next_out;
         Py_END_ALLOW_THREADS
+
         if (bzerror == BZ_STREAM_END) {
             break;
         } else if (bzerror != BZ_OK) {
@@ -2078,33 +2098,37 @@
             return NULL;
         }
         if (bzs->avail_in == 0) {
-            BZ2_bzDecompressEnd(bzs);
-            PyErr_SetString(PyExc_ValueError,
-                            "couldn't find end of stream");
-            PyBuffer_Release(&pdata);
-            Py_DECREF(ret);
-            return NULL;
-        }
-        if (bzs->avail_out == 0) {
-            bufsize = Util_NewBufferSize(bufsize);
-            if (_PyBytes_Resize(&ret, bufsize) < 0) {
+            if (input_left == 0) {
                 BZ2_bzDecompressEnd(bzs);
+                PyErr_SetString(PyExc_ValueError,
+                                "couldn't find end of stream");
                 PyBuffer_Release(&pdata);
+                Py_DECREF(ret);
                 return NULL;
             }
-            bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
-            bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+            bzs->avail_in = MIN(input_left, UINT_MAX);
+            input_left -= bzs->avail_in;
+        }
+        if (bzs->avail_out == 0) {
+            size_t buffer_left = PyBytes_GET_SIZE(ret) - output_size;
+            if (buffer_left == 0) {
+                if (Util_GrowBuffer(&ret) < 0) {
+                    BZ2_bzDecompressEnd(bzs);
+                    PyBuffer_Release(&pdata);
+                    return NULL;
+                }
+                bzs->next_out = BUF(ret) + output_size;
+                buffer_left = PyBytes_GET_SIZE(ret) - output_size;
+            }
+            bzs->avail_out = MIN(buffer_left, UINT_MAX);
         }
     }
 
-    if (bzs->avail_out != 0) {
-        if (_PyBytes_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs)) < 0) {
-            ret = NULL;
-        }
-    }
+    if (output_size != PyBytes_GET_SIZE(ret))
+        _PyBytes_Resize(&ret, output_size);  /* Sets ret to NULL on failure. */
+
     BZ2_bzDecompressEnd(bzs);
     PyBuffer_Release(&pdata);
-
     return ret;
 }