From 4f9222643cf41ed422da9447ac973257ed1171d2 Mon Sep 17 00:00:00 2001
From: Grisha Levit <grishalevit@gmail.com>
Date: Wed, 1 Oct 2025 01:37:51 -0400
Subject: [PATCH] parse.y: use PTRDIFF_MAX as allocation size bound

Ref: https://lists.gnu.org/archive/html/bug-bash/2025-09/msg00399.html
---
 include/typemax.h |  4 ++++
 parse.y           | 14 +++++++-------
 2 files changed, 11 insertions(+), 7 deletions(-)

diff --git a/include/typemax.h b/include/typemax.h
index e3b98f47..41142f14 100644
--- a/include/typemax.h
+++ b/include/typemax.h
@@ -119,6 +119,10 @@ static const unsigned long long int maxquad = ULLONG_MAX;
 #  define SIZE_MAX	((size_t) ~(size_t)0)
 #endif
 
+#ifndef PTRDIFF_MAX
+#  define PTRDIFF_MAX	TYPE_MAXIMUM(ptrdiff_t)
+#endif
+
 #ifndef sh_imaxabs
 #  define sh_imaxabs(x)	(((x) >= 0) ? (x) : -(x))
 #endif
diff --git a/parse.y b/parse.y
index b698f86b..5fdf58e5 100644
--- a/parse.y
+++ b/parse.y
@@ -47,7 +47,7 @@
 
 #include "shell.h"
 #include "execute_cmd.h"
-#include "typemax.h"		/* SIZE_MAX if needed */
+#include "typemax.h"		/* PTRDIFF_MAX if needed */
 #include "trap.h"
 #include "flags.h"
 #include "parser.h"
@@ -2579,21 +2579,21 @@ shell_getc (int remove_quoted_newline)
 	  /* If we can't put 256 bytes more into the buffer, allocate
 	     everything we can and fill it as full as we can. */
 	  /* XXX - we ignore rest of line using `truncating' flag */
-	  if (shell_input_line_size > (SIZE_MAX - 256))
+	  if (shell_input_line_size > (PTRDIFF_MAX - 256))
 	    {
 	      size_t n;
 
-	      n = SIZE_MAX - i;	/* how much more can we put into the buffer? */
+	      n = PTRDIFF_MAX - i;	/* how much more can we put into the buffer? */
 	      if (n <= 2)	/* we have to save 1 for the newline added below */
 		{
 		  if (truncating == 0)
-		    internal_warning(_("shell_getc: shell_input_line_size (%zu) exceeds SIZE_MAX (%lu): line truncated"), shell_input_line_size, (unsigned long)SIZE_MAX);
+		    internal_warning(_("shell_getc: shell_input_line_size (%zu) exceeds PTRDIFF_MAX (%ld): line truncated"), shell_input_line_size, (long)PTRDIFF_MAX);
 		  shell_input_line[i] = '\0';
 		  truncating = 1;
 		}
-	      if (shell_input_line_size < SIZE_MAX)
+	      if (shell_input_line_size < PTRDIFF_MAX)
 		{
-		  shell_input_line_size = SIZE_MAX;
+		  shell_input_line_size = PTRDIFF_MAX;
 		  shell_input_line = xrealloc (shell_input_line, shell_input_line_size);
 		}
 	    }
@@ -2735,7 +2735,7 @@ shell_getc (int remove_quoted_newline)
 	 not already end in an EOF character.  */
       if (shell_input_line_terminator != EOF && shell_input_line_terminator != READERR)
 	{
-	  if (shell_input_line_size + 3 < SIZE_MAX && (shell_input_line_len+3 > shell_input_line_size))
+	  if (shell_input_line_size + 3 < PTRDIFF_MAX && (shell_input_line_len+3 > shell_input_line_size))
 	    shell_input_line = (char *)xrealloc (shell_input_line,
 					1 + (shell_input_line_size += 2));
 
-- 
2.51.0

