Subject: bug#66098: Crash in itree.c on macOS with incomplete backtrace

From: Robert Pluim <[email-masked]>
Date: Tue, 19 Sep 2023 12:09:24 +0200

>>>>> On Tue, 19 Sep 2023 11:23:36 +0200, Robert Pluim <[email-masked]> said:

>>>>> On Tue, 19 Sep 2023 01:47:41 -0700, Stefan Kangas <[email-masked]> said:
    Stefan> After rebuilding from master yesterday, I've started seeing frequent
    Stefan> crashes (several times a day) on macOS.  Thus, I re-built with all the
    Stefan> debug flags to investigate, and was able to get Emacs to crash almost
    Stefan> immediately after start, with the command `M-x notmuch'.

    Stefan> I'm not able to get much of a backtrace (see below).  Could it be that
    Stefan> the stack got corrupted somehow?  I've left the gdb session of the
    Stefan> crashed process open in case anyone has any ideas.  Is valgrind the best
    Stefan> tool for digging further, or are there any other tricks I can try?

    Robert> Does valgrind run on macOS these days? Iʼd start by adding
    Robert> '-fsanitize=address' to your CFLAGS.

Which I just tried, and it gave me

==22145==ERROR: AddressSanitizer: stack-buffer-underflow on address 0x00016dcc4540 at pc 0x000105924ee0 bp 0x00016dcc4090 sp 0x00016dcc3850
READ of size 8 at 0x00016dcc4540 thread T0
    #0 0x105924edc in __asan_memcpy+0x1a4 (libclang_rt.asan_osx_dynamic.dylib:arm64e+0x40edc) (BuildId: f0a7ac5c49bc3abc851181b6f92b308a32000000200000000100000000000b00)
    #1 0x1022d388c in vadd_to_log xdisp.c:11821
    #2 0x1022d32b4 in add_to_log xdisp.c:11798

Which I fixed like this:

diff --git a/src/xdisp.c b/src/xdisp.c
index 2944f3964e8..f1980c4f20c 100644
--- a/src/xdisp.c
+++ b/src/xdisp.c
@@ -11808,7 +11808,7 @@ vadd_to_log (char const *format, va_list ap)
   eassert (nargs <= ARRAYELTS (args));
   AUTO_STRING (args0, format);
   args[0] = args0;
-  for (ptrdiff_t i = 1; i <= nargs; i++)
+  for (ptrdiff_t i = 1; i < nargs; i++)
     args[i] = va_arg (ap, Lisp_Object);
   Lisp_Object msg = Qnil;
   msg = Fformat_message (nargs, args);

Given that this code has been like this since 2015, please sanity
check the patch whilst I up my caffeine levels :-)

Robert
--