Subject: Re: bug#57211: 29.0.50; generate-new-buffer-name sprintf format overflow warning
From: Paul Eggert <[email-masked]>
To: "Basil L. Contovounesios" <[email-masked]>
Cc: [email-masked]
Date: Sun, 14 Aug 2022 13:54:08 -0700
List-Id: <debbugs-submit.debbugs.gnu.org>

On 8/14/22 09:50, Basil L. Contovounesios wrote:

> Can the upper bound 9 ever be achieved?  If so, how?  If not, is this a
> GCC bug?  Either way, is there a way to pacify the warning?

It can't be achieved, and it's arguably a GCC bug. I installed the 
attached to pacify GCC.

>    int i = r % 1000000;
> 
> can the result of % ever exceed INT_MAX?

No.

On 8/14/22 11:59, Matt Armstrong wrote:

> Gcc doesn't know that get_random() returns only non-negative numbers,
> and the eassume() call doesn't seem to be enough to convince gcc this
> fact, or gcc does not infer i is also non-negative.

It's worse than that. Even if you add 'eassume (0 <= i && i < 1000000);" 
GCC still doesn't assume that the sprintf is in range.

> Personally, I'd change this code to use a buffer
> 
>    INT_BUFSIZE_BOUND(int) + sizeof "-"

The problem with overallocating buffers is not the memory loss (it's 
trivial, as you say), it's that later readers like me will wonder why 
the buffer is being overallocated, which is maintenance overhead.

I installed the attached to pacify GCC while also attempting to not 
entirely mystify later readers.

From 23561f9665609bcb4cbe89a993a70eeccbec600e Mon Sep 17 00:00:00 2001
From: Paul Eggert <[email-masked]>
Date: Sun, 14 Aug 2022 13:48:11 -0700
Subject: [PATCH] Work around Bug#57211

* src/buffer.c (Fgenerate_new_buffer_name): Allocate a bigger buffer.
---
 src/buffer.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/buffer.c b/src/buffer.c
index 6ab516d5f5..98066a2eb6 100644
--- a/src/buffer.c
+++ b/src/buffer.c
@@ -1160,7 +1160,8 @@ DEFUN ("generate-new-buffer-name", Fgenerate_new_buffer_name,
     genbase = name;
   else
     {
-      char number[sizeof "-999999"];
+      enum { bug_52711 = true };  /* https://bugs.gnu.org/57211 */
+      char number[bug_52711 ? INT_BUFSIZE_BOUND (int) + 1 : sizeof "-999999"];
       EMACS_INT r = get_random ();
       eassume (0 <= r);
       int i = r % 1000000;
-- 
2.34.1