Subject: bug#23397: 25.0.92; assertion failure auto-reverting a file being overwritten

From: Ken Raeburn <[email-masked]>
Date: Tue, 03 May 2016 17:04:24 -0400

Eli Zaretskii <[email-masked]> writes:
> That is still better than aborting, right?

Of course. But it seems to me we should have the information we need to
keep the Emacs processing self-consistent whether we iterate or not.
Other code in the function already clearly expects that the number of
bytes we can read may be different from st_size.

(Arguably, in case we're trying to preserve point or markers in a later
part of the file than might have been rewritten so far, it might be
desirable for insert-file-contents to restart or pause briefly and retry
reading more content if it detects a change, but I think that's mostly a
separate question.)

I've finally reproduced the problem. A key issue was that the whole
block containing the failing code would be skipped by the conditional
below if the coding system were "undecided", which seems to be the norm
in my testing with "emacs -Q", but not in my working environment for
whatever reason; maybe one of the minor modes I've loaded is setting a
more specific coding system.

  if (!NILP (replace)
      && BEGV < ZV
      && (NILP (coding_system)
	  || ! CODING_REQUIRE_DECODING (&coding)))

If the coding system is "undecided-unix", we enter this block, and I can
get it to blow up.

Recipe:

Get two similar files differing in the middle; I started with emacs-25
charset.h:

    cp .../src/charset.h file.h
    sed -e 400,499s/a/b/g < file.h > file2.h

Set a breakpoint just after the fstat call in Finsert_file_contents,
run emacs -Q, and read in file.h (continuing whenever the breakpoint is
hit). Turn on auto-revert-mode in the buffer.

Set the coding system with "C-x RET f" to "undecided-unix". That marks
the buffer as modified, so clear that by saving the file.

Copy file2.h over file.h, and when the breakpoint is triggered, change
st.st_size to zero, to simulate rereading before the file overwriting
has finished, and continue. My debugging printfs show that an
out-of-range same_at_end is generated as in my original case:

    (gdb) c
    Continuing.
    Finsert_file_contents:3871: same_at_start=13993 same_at_end=17747
         st_size=0 ZV=19498
      => overlap=15743
      => new same_at_end=33490

    ../../src/marker.c:297: Emacs fatal error: assertion failed: BUF_BEG_BYTE (b) <= bytepos && bytepos <= BUF_Z_BYTE (b)