From d1d591c53baf09f27cb37ac197433af0d1b5f29c Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Wed, 23 Jul 2025 17:44:38 -0700 Subject: [PATCH] =?utf8?q?Don=E2=80=99t=20read=20before=20BEG=20in=20inser?= =?utf8?q?t-file-contents?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * src/fileio.c (Finsert_file_contents): Don’t sample bytes before BEG. Give up optimizing if the file size shrinks to less than BEG. (cherry picked from commit e026b57f077e4a6dcce9c24e31dbf7107b88d409) --- src/fileio.c | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/fileio.c b/src/fileio.c index c042089ac85..2dad90ac600 100644 --- a/src/fileio.c +++ b/src/fileio.c @@ -4347,9 +4347,11 @@ by calling `format-decode', which see. */) curpos = beg_offset + nread; else { - off_t curmax = end_offset - 3 * 1024; - if (curmax < curpos) - curpos = xlseek (fd, curmax, SEEK_SET, orig_filename); + off_t tailbeg = (curpos <= beg_offset + nread + ? beg_offset + nread + : min (curpos, end_offset - 3 * 1024)); + if (tailbeg != curpos) + curpos = xlseek (fd, tailbeg, SEEK_SET, orig_filename); } /* When appending the last 3 KiB, read extra bytes @@ -4544,7 +4546,13 @@ by calling `format-decode', which see. */) be smaller than its head. */ off_t offset_from_beg = endpos - beg_offset; if (offset_from_beg < same_at_start - BEGV_BYTE) - same_at_start = max (0, offset_from_beg) + BEGV_BYTE; + { + /* Give up if the file shrank to less than BEG. */ + giveup_match_end = offset_from_beg < 0; + + if (!giveup_match_end) + same_at_start = offset_from_beg + BEGV_BYTE; + } } } } -- 2.39.5