From bffd24a73685d091132763a6995536d396ddaa2a Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Sat, 12 Jul 2025 14:22:02 -0700 Subject: [PATCH] Fix insert-file-contents integer overflows MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * src/fileio.c (Finsert_file_contents): Change ‘total’ from ptrdiff_t to off_t since it might not fit in ptrdiff_t. Check for overflow when estimating the insertion size. (cherry picked from commit 56091b6d5cccecf320796bd62e36adc64f45b614) --- src/fileio.c | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/fileio.c b/src/fileio.c index b639be1493b..3c371dea98d 100644 --- a/src/fileio.c +++ b/src/fileio.c @@ -4065,7 +4065,7 @@ by calling `format-decode', which see. */) specpdl_ref count = SPECPDL_INDEX (); Lisp_Object handler, val, insval, orig_filename, old_undo; Lisp_Object p; - ptrdiff_t total = 0; + off_t total = 0; bool regular; int save_errno = 0; char read_buf[READ_BUF_SIZE]; @@ -4818,10 +4818,16 @@ by calling `format-decode', which see. */) move_gap_both (PT, PT_BYTE); /* Ensure the gap is at least one byte larger than needed for the - estimated file size, so that in the usual case we read to EOF + estimated insertion, so that in the usual case we read without reallocating. */ - if (GAP_SIZE <= total) - make_gap (total - GAP_SIZE + 1); + off_t inserted_estimate = min (end_offset, file_size_hint) - beg_offset; + if (GAP_SIZE <= inserted_estimate) + { + ptrdiff_t growth; + if (ckd_sub (&growth, inserted_estimate, GAP_SIZE - 1)) + buffer_overflow (); + make_gap (growth); + } if (beg_offset != 0 || (!NILP (replace) && !BASE_EQ (replace, Qunbound))) -- 2.39.5