On 3/13/24 11:13, Chet Ramey wrote:

Thanks for the report. The most appropriate fix for this particular issue
is to display an error message if printf returns < 0, instead of
suppressing it unless the -v option has been set.

Oh, good point. This simplifies things a bit, though Bash still needs to do its own overflow checking for cases like "printf '%2147483648q' ''" and "printf '%*s' 2147483648 ''" when the Bash code itself is parsing the integer, rather than relying on printf(3) to do it.

Revised patchset attached. The first patch uses the fix you suggested; the remaining patches are similar to what I sent earlier, except the last one is simplified since it doesn't need to worry about inline width and precision when printf will do the checking. These patches are relative to Bash devel commit bf944fe91ffa97743ad86f6db6f3b84c78207a78 dated today at 09:33:32 -0400.

From 4ca64cfc3de1d9cf75490b85891e88fbf0405538 Mon Sep 17 00:00:00 2001
From: Paul Eggert <egg...@cs.ucla.edu>
Date: Wed, 13 Mar 2024 17:00:17 -0700
Subject: [PATCH 1/5] printf now diagnoses underlying printf failure

* builtins/printf.def (printf_builtin):
Report an error if printf returns -1, even when
-v is not used, so that a shell command like
"printf '%10000000000000000000000000000s' ''"
does not fail silently.
---
 builtins/printf.def | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/builtins/printf.def b/builtins/printf.def
index 49757f5c..b1140dc4 100644
--- a/builtins/printf.def
+++ b/builtins/printf.def
@@ -178,8 +178,7 @@ extern int errno;
     if (nw < 0 || (vflag == 0 && ferror (stdout))) \
       { \
 	QUIT; \
-	if (vflag) \
-	  builtin_error ("%s", strerror (errno)); \
+	builtin_error ("%s", strerror (errno)); \
 	PRETURN (EXECUTION_FAILURE); \
       } \
     tw += nw; \
-- 
2.44.0

From 21a3752666536f390f9d5d8378171a4323745adc Mon Sep 17 00:00:00 2001
From: Paul Eggert <egg...@cs.ucla.edu>
Date: Fri, 8 Mar 2024 21:58:46 -0800
Subject: [PATCH 2/5] maint: add support for C23-style stdckdint.h
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This is so that Bash can do proper checking for internal
integer overflow.  This change doesn't change Bash proper;
it only adds the minimum changes needed so that
C23-style "#include <stdckdint.h>" will work portably
to older systems.
* Makefile.in (CREATED_CONFIGURE): Add stdckdint.h.
* configure.ac: Check for stdckdint.h.  If it works, remove
any stdckdint.h left over from a previous ‘configure’;
otherwise, create one.
* .gitignore: Add stdckdint.h.
* include/stdckdint.in.h, include/intprops-internal.h:
New files, copied verbatim from Gnulib.
---
 .gitignore                  |   1 +
 Makefile.in                 |   1 +
 configure.ac                |   7 +
 include/intprops-internal.h | 397 ++++++++++++++++++++++++++++++++++++
 include/stdckdint.in.h      |  35 ++++
 5 files changed, 441 insertions(+)
 create mode 100644 include/intprops-internal.h
 create mode 100644 include/stdckdint.in.h

diff --git a/.gitignore b/.gitignore
index 2c10177c..15b219d3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -70,6 +70,7 @@ support/bashbug.sh
 lsignames.h
 pathnames.h
 signames.h
+stdckdint.h
 version.h
 syntax.c
 stamp-h
diff --git a/Makefile.in b/Makefile.in
index 41443c6d..2b4b713c 100644
--- a/Makefile.in
+++ b/Makefile.in
@@ -584,6 +584,7 @@ CREATED_SUPPORT = signames.h recho$(EXEEXT) zecho$(EXEEXT) printenv$(EXEEXT) \
 		  mksyntax${EXEEXT} syntax.c $(VERSPROG) $(VERSOBJ) \
 		  buildversion.o mksignames.o signames.o buildsignames.o
 CREATED_CONFIGURE = config.h config.cache config.status config.log \
+		    stdckdint.h \
 		    stamp-h po/POTFILES config.status.lineno
 CREATED_MAKEFILES = Makefile builtins/Makefile doc/Makefile \
 		    lib/readline/Makefile lib/glob/Makefile \
diff --git a/configure.ac b/configure.ac
index d4ca74e5..7befb6c2 100644
--- a/configure.ac
+++ b/configure.ac
@@ -787,6 +787,7 @@ BASH_HEADER_INTTYPES
 
 AC_CHECK_HEADERS(unistd.h stdlib.h varargs.h limits.h string.h \
 		 memory.h locale.h termcap.h termio.h termios.h dlfcn.h \
+		 stdckdint.h \
 		 stdbool.h stddef.h stdint.h netdb.h pwd.h grp.h strings.h \
 		 regex.h syslog.h ulimit.h)
 AC_CHECK_HEADERS(sys/pte.h sys/stream.h sys/select.h sys/file.h sys/ioctl.h \
@@ -1352,4 +1353,10 @@ AC_CONFIG_FILES([Makefile builtins/Makefile lib/readline/Makefile \
 dnl Makefile uses this timestamp file to record whether config.h is up to date.
 AC_CONFIG_COMMANDS([stamp-h], [echo timestamp > stamp-h])
 
+if test "$ac_cv_header_stdckdint_h" = yes; then
+  rm -f stdckdint.h
+else
+  echo '#include <stdckdint.in.h>' >stdckdint.h
+fi
+
 AC_OUTPUT
diff --git a/include/intprops-internal.h b/include/intprops-internal.h
new file mode 100644
index 00000000..c8a87d2b
--- /dev/null
+++ b/include/intprops-internal.h
@@ -0,0 +1,397 @@
+/* intprops-internal.h -- properties of integer types not visible to users
+
+   Copyright (C) 2001-2024 Free Software Foundation, Inc.
+
+   This program is free software: you can redistribute it and/or modify it
+   under the terms of the GNU Lesser General Public License as published
+   by the Free Software Foundation; either version 2.1 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
+
+#ifndef _GL_INTPROPS_INTERNAL_H
+#define _GL_INTPROPS_INTERNAL_H
+
+#include <limits.h>
+
+/* Pacify GCC 13.2 in some calls to _GL_EXPR_SIGNED.  */
+#if defined __GNUC__ && 4 < __GNUC__ + (3 <= __GNUC_MINOR__)
+# pragma GCC diagnostic ignored "-Wtype-limits"
+#endif
+
+/* Return a value with the common real type of E and V and the value of V.
+   Do not evaluate E.  */
+#define _GL_INT_CONVERT(e, v) ((1 ? 0 : (e)) + (v))
+
+/* Act like _GL_INT_CONVERT (E, -V) but work around a bug in IRIX 6.5 cc; see
+   <https://lists.gnu.org/r/bug-gnulib/2011-05/msg00406.html>.  */
+#define _GL_INT_NEGATE_CONVERT(e, v) ((1 ? 0 : (e)) - (v))
+
+/* The extra casts in the following macros work around compiler bugs,
+   e.g., in Cray C 5.0.3.0.  */
+
+/* True if the real type T is signed.  */
+#define _GL_TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
+
+/* Return 1 if the real expression E, after promotion, has a
+   signed or floating type.  Do not evaluate E.  */
+#define _GL_EXPR_SIGNED(e) (_GL_INT_NEGATE_CONVERT (e, 1) < 0)
+
+
+/* Minimum and maximum values for integer types and expressions.  */
+
+/* The width in bits of the integer type or expression T.
+   Do not evaluate T.  T must not be a bit-field expression.
+   Padding bits are not supported; this is checked at compile-time below.  */
+#define _GL_TYPE_WIDTH(t) (sizeof (t) * CHAR_BIT)
+
+/* The maximum and minimum values for the type of the expression E,
+   after integer promotion.  E is not evaluated.  */
+#define _GL_INT_MINIMUM(e)                                              \
+  (_GL_EXPR_SIGNED (e)                                                  \
+   ? ~ _GL_SIGNED_INT_MAXIMUM (e)                                       \
+   : _GL_INT_CONVERT (e, 0))
+#define _GL_INT_MAXIMUM(e)                                              \
+  (_GL_EXPR_SIGNED (e)                                                  \
+   ? _GL_SIGNED_INT_MAXIMUM (e)                                         \
+   : _GL_INT_NEGATE_CONVERT (e, 1))
+#define _GL_SIGNED_INT_MAXIMUM(e)                                       \
+  (((_GL_INT_CONVERT (e, 1) << (_GL_TYPE_WIDTH (+ (e)) - 2)) - 1) * 2 + 1)
+
+/* Work around OpenVMS incompatibility with C99.  */
+#if !defined LLONG_MAX && defined __INT64_MAX
+# define LLONG_MAX __INT64_MAX
+# define LLONG_MIN __INT64_MIN
+#endif
+
+/* This include file assumes that signed types are two's complement without
+   padding bits; the above macros have undefined behavior otherwise.
+   If this is a problem for you, please let us know how to fix it for your host.
+   This assumption is tested by the intprops-tests module.  */
+
+/* Does the __typeof__ keyword work?  This could be done by
+   'configure', but for now it's easier to do it by hand.  */
+#if (2 <= __GNUC__ \
+     || (4 <= __clang_major__) \
+     || (1210 <= __IBMC__ && defined __IBM__TYPEOF__) \
+     || (0x5110 <= __SUNPRO_C && !__STDC__))
+# define _GL_HAVE___TYPEOF__ 1
+#else
+# define _GL_HAVE___TYPEOF__ 0
+#endif
+
+/* Return 1 if the integer type or expression T might be signed.  Return 0
+   if it is definitely unsigned.  T must not be a bit-field expression.
+   This macro does not evaluate its argument, and expands to an
+   integer constant expression.  */
+#if _GL_HAVE___TYPEOF__
+# define _GL_SIGNED_TYPE_OR_EXPR(t) _GL_TYPE_SIGNED (__typeof__ (t))
+#else
+# define _GL_SIGNED_TYPE_OR_EXPR(t) 1
+#endif
+
+/* Return 1 if - A would overflow in [MIN,MAX] arithmetic.
+   A should not have side effects, and A's type should be an
+   integer with minimum value MIN and maximum MAX.  */
+#define _GL_INT_NEGATE_RANGE_OVERFLOW(a, min, max) \
+  ((min) < 0 ? (a) < - (max) : 0 < (a))
+
+/* True if __builtin_add_overflow (A, B, P) and __builtin_sub_overflow
+   (A, B, P) work when P is non-null.  */
+#ifdef __EDG__
+/* EDG-based compilers like nvc 22.1 cannot add 64-bit signed to unsigned
+   <https://bugs.gnu.org/53256>.  */
+# define _GL_HAS_BUILTIN_ADD_OVERFLOW 0
+#elif defined __has_builtin
+# define _GL_HAS_BUILTIN_ADD_OVERFLOW __has_builtin (__builtin_add_overflow)
+/* __builtin_{add,sub}_overflow exists but is not reliable in GCC 5.x and 6.x,
+   see <https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98269>.  */
+#elif 7 <= __GNUC__
+# define _GL_HAS_BUILTIN_ADD_OVERFLOW 1
+#else
+# define _GL_HAS_BUILTIN_ADD_OVERFLOW 0
+#endif
+
+/* True if __builtin_mul_overflow (A, B, P) works when P is non-null.  */
+#if defined __clang_major__ && __clang_major__ < 14
+/* Work around Clang bug <https://bugs.llvm.org/show_bug.cgi?id=16404>.  */
+# define _GL_HAS_BUILTIN_MUL_OVERFLOW 0
+#else
+# define _GL_HAS_BUILTIN_MUL_OVERFLOW _GL_HAS_BUILTIN_ADD_OVERFLOW
+#endif
+
+/* True if __builtin_add_overflow_p (A, B, C) works, and similarly for
+   __builtin_sub_overflow_p and __builtin_mul_overflow_p.  */
+#ifdef __EDG__
+/* In EDG-based compilers like ICC 2021.3 and earlier,
+   __builtin_add_overflow_p etc. are not treated as integral constant
+   expressions even when all arguments are.  */
+# define _GL_HAS_BUILTIN_OVERFLOW_P 0
+#elif defined __has_builtin
+# define _GL_HAS_BUILTIN_OVERFLOW_P __has_builtin (__builtin_mul_overflow_p)
+#else
+# define _GL_HAS_BUILTIN_OVERFLOW_P (7 <= __GNUC__)
+#endif
+
+#if (!defined _GL_STDCKDINT_H && 202311 <= __STDC_VERSION__ \
+     && ! (_GL_HAS_BUILTIN_ADD_OVERFLOW && _GL_HAS_BUILTIN_MUL_OVERFLOW))
+# include <stdckdint.h>
+#endif
+
+/* Store the low-order bits of A + B, A - B, A * B, respectively, into *R.
+   Return 1 if the result overflows.  Arguments should not have side
+   effects and A, B and *R can be of any integer type other than char,
+   bool, a bit-precise integer type, or an enumeration type.  */
+#if _GL_HAS_BUILTIN_ADD_OVERFLOW
+# define _GL_INT_ADD_WRAPV(a, b, r) __builtin_add_overflow (a, b, r)
+# define _GL_INT_SUBTRACT_WRAPV(a, b, r) __builtin_sub_overflow (a, b, r)
+#elif defined ckd_add && defined ckd_sub && !defined _GL_STDCKDINT_H
+# define _GL_INT_ADD_WRAPV(a, b, r) ckd_add (r, + (a), + (b))
+# define _GL_INT_SUBTRACT_WRAPV(a, b, r) ckd_sub (r, + (a), + (b))
+#else
+# define _GL_INT_ADD_WRAPV(a, b, r) \
+   _GL_INT_OP_WRAPV (a, b, r, +, _GL_INT_ADD_RANGE_OVERFLOW)
+# define _GL_INT_SUBTRACT_WRAPV(a, b, r) \
+   _GL_INT_OP_WRAPV (a, b, r, -, _GL_INT_SUBTRACT_RANGE_OVERFLOW)
+#endif
+#if _GL_HAS_BUILTIN_MUL_OVERFLOW
+# if ((9 < __GNUC__ + (3 <= __GNUC_MINOR__) \
+       || (__GNUC__ == 8 && 4 <= __GNUC_MINOR__)) \
+      && !defined __EDG__)
+#  define _GL_INT_MULTIPLY_WRAPV(a, b, r) __builtin_mul_overflow (a, b, r)
+# else
+   /* Work around GCC bug 91450.  */
+#  define _GL_INT_MULTIPLY_WRAPV(a, b, r) \
+    ((!_GL_SIGNED_TYPE_OR_EXPR (*(r)) && _GL_EXPR_SIGNED (a) && _GL_EXPR_SIGNED (b) \
+      && _GL_INT_MULTIPLY_RANGE_OVERFLOW (a, b, 0, (__typeof__ (*(r))) -1)) \
+     ? ((void) __builtin_mul_overflow (a, b, r), 1) \
+     : __builtin_mul_overflow (a, b, r))
+# endif
+#elif defined ckd_mul && !defined _GL_STDCKDINT_H
+# define _GL_INT_MULTIPLY_WRAPV(a, b, r) ckd_mul (r, + (a), + (b))
+#else
+# define _GL_INT_MULTIPLY_WRAPV(a, b, r) \
+   _GL_INT_OP_WRAPV (a, b, r, *, _GL_INT_MULTIPLY_RANGE_OVERFLOW)
+#endif
+
+/* Nonzero if this compiler has GCC bug 68193 or Clang bug 25390.  See:
+   https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68193
+   https://llvm.org/bugs/show_bug.cgi?id=25390
+   For now, assume all versions of GCC-like compilers generate bogus
+   warnings for _Generic.  This matters only for compilers that
+   lack relevant builtins.  */
+#if __GNUC__ || defined __clang__
+# define _GL__GENERIC_BOGUS 1
+#else
+# define _GL__GENERIC_BOGUS 0
+#endif
+
+/* Store the low-order bits of A <op> B into *R, where OP specifies
+   the operation and OVERFLOW the overflow predicate.  Return 1 if the
+   result overflows.  Arguments should not have side effects,
+   and A, B and *R can be of any integer type other than char, bool, a
+   bit-precise integer type, or an enumeration type.  */
+#if 201112 <= __STDC_VERSION__ && !_GL__GENERIC_BOGUS
+# define _GL_INT_OP_WRAPV(a, b, r, op, overflow) \
+   (_Generic \
+    (*(r), \
+     signed char: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+                        signed char, SCHAR_MIN, SCHAR_MAX), \
+     unsigned char: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+                        unsigned char, 0, UCHAR_MAX), \
+     short int: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+                        short int, SHRT_MIN, SHRT_MAX), \
+     unsigned short int: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+                        unsigned short int, 0, USHRT_MAX), \
+     int: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+                        int, INT_MIN, INT_MAX), \
+     unsigned int: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+                        unsigned int, 0, UINT_MAX), \
+     long int: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+                        long int, LONG_MIN, LONG_MAX), \
+     unsigned long int: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+                        unsigned long int, 0, ULONG_MAX), \
+     long long int: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
+                        long long int, LLONG_MIN, LLONG_MAX), \
+     unsigned long long int: \
+       _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
+                        unsigned long long int, 0, ULLONG_MAX)))
+#else
+/* Store the low-order bits of A <op> B into *R, where OP specifies
+   the operation and OVERFLOW the overflow predicate.  If *R is
+   signed, its type is ST with bounds SMIN..SMAX; otherwise its type
+   is UT with bounds U..UMAX.  ST and UT are narrower than int.
+   Return 1 if the result overflows.  Arguments should not have side
+   effects, and A, B and *R can be of any integer type other than
+   char, bool, a bit-precise integer type, or an enumeration type.  */
+# if _GL_HAVE___TYPEOF__
+#  define _GL_INT_OP_WRAPV_SMALLISH(a,b,r,op,overflow,st,smin,smax,ut,umax) \
+    (_GL_TYPE_SIGNED (__typeof__ (*(r))) \
+     ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, st, smin, smax) \
+     : _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, ut, 0, umax))
+# else
+#  define _GL_INT_OP_WRAPV_SMALLISH(a,b,r,op,overflow,st,smin,smax,ut,umax) \
+    (overflow (a, b, smin, smax) \
+     ? (overflow (a, b, 0, umax) \
+        ? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a,b,op,unsigned,st), 1) \
+        : (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a,b,op,unsigned,st)) < 0) \
+     : (overflow (a, b, 0, umax) \
+        ? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a,b,op,unsigned,st)) >= 0 \
+        : (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a,b,op,unsigned,st), 0)))
+# endif
+
+# define _GL_INT_OP_WRAPV(a, b, r, op, overflow) \
+   (sizeof *(r) == sizeof (signed char) \
+    ? _GL_INT_OP_WRAPV_SMALLISH (a, b, r, op, overflow, \
+                                 signed char, SCHAR_MIN, SCHAR_MAX, \
+                                 unsigned char, UCHAR_MAX) \
+    : sizeof *(r) == sizeof (short int) \
+    ? _GL_INT_OP_WRAPV_SMALLISH (a, b, r, op, overflow, \
+                                 short int, SHRT_MIN, SHRT_MAX, \
+                                 unsigned short int, USHRT_MAX) \
+    : sizeof *(r) == sizeof (int) \
+    ? (_GL_EXPR_SIGNED (*(r)) \
+       ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+                          int, INT_MIN, INT_MAX) \
+       : _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned int, \
+                          unsigned int, 0, UINT_MAX)) \
+    : _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow))
+# ifdef LLONG_MAX
+#  define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
+    (sizeof *(r) == sizeof (long int) \
+     ? (_GL_EXPR_SIGNED (*(r)) \
+        ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+                           long int, LONG_MIN, LONG_MAX) \
+        : _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+                           unsigned long int, 0, ULONG_MAX)) \
+     : (_GL_EXPR_SIGNED (*(r)) \
+        ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
+                           long long int, LLONG_MIN, LLONG_MAX) \
+        : _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long long int, \
+                           unsigned long long int, 0, ULLONG_MAX)))
+# else
+#  define _GL_INT_OP_WRAPV_LONGISH(a, b, r, op, overflow) \
+    (_GL_EXPR_SIGNED (*(r)) \
+     ? _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+                        long int, LONG_MIN, LONG_MAX) \
+     : _GL_INT_OP_CALC (a, b, r, op, overflow, unsigned long int, \
+                        unsigned long int, 0, ULONG_MAX))
+# endif
+#endif
+
+/* Store the low-order bits of A <op> B into *R, where the operation
+   is given by OP.  Use the unsigned type UT for calculation to avoid
+   overflow problems.  *R's type is T, with extrema TMIN and TMAX.
+   T can be any signed integer type other than char, bool, a
+   bit-precise integer type, or an enumeration type.
+   Return 1 if the result overflows.  */
+#define _GL_INT_OP_CALC(a, b, r, op, overflow, ut, t, tmin, tmax) \
+  (overflow (a, b, tmin, tmax) \
+   ? (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t), 1) \
+   : (*(r) = _GL_INT_OP_WRAPV_VIA_UNSIGNED (a, b, op, ut, t), 0))
+
+/* Return 1 if the integer expressions A - B and -A would overflow,
+   respectively.  Arguments should not have side effects,
+   and can be any signed integer type other than char, bool, a
+   bit-precise integer type, or an enumeration type.
+   These macros are tuned for their last input argument being a constant.  */
+
+#if _GL_HAS_BUILTIN_OVERFLOW_P
+# define _GL_INT_NEGATE_OVERFLOW(a) \
+   __builtin_sub_overflow_p (0, a, (__typeof__ (- (a))) 0)
+#else
+# define _GL_INT_NEGATE_OVERFLOW(a) \
+   _GL_INT_NEGATE_RANGE_OVERFLOW (a, _GL_INT_MINIMUM (a), _GL_INT_MAXIMUM (a))
+#endif
+
+/* Return the low-order bits of A <op> B, where the operation is given
+   by OP.  Use the unsigned type UT for calculation to avoid undefined
+   behavior on signed integer overflow, and convert the result to type T.
+   UT is at least as wide as T and is no narrower than unsigned int,
+   T is two's complement, and there is no padding or trap representations.
+   Assume that converting UT to T yields the low-order bits, as is
+   done in all known two's-complement C compilers.  E.g., see:
+   https://gcc.gnu.org/onlinedocs/gcc/Integers-implementation.html
+
+   According to the C standard, converting UT to T yields an
+   implementation-defined result or signal for values outside T's
+   range.  However, code that works around this theoretical problem
+   runs afoul of a compiler bug in Oracle Studio 12.3 x86.  See:
+   https://lists.gnu.org/r/bug-gnulib/2017-04/msg00049.html
+   As the compiler bug is real, don't try to work around the
+   theoretical problem.  */
+
+#define _GL_INT_OP_WRAPV_VIA_UNSIGNED(a, b, op, ut, t) \
+  ((t) ((ut) (a) op (ut) (b)))
+
+/* Return true if the numeric values A + B, A - B, A * B fall outside
+   the range TMIN..TMAX.  Arguments should not have side effects
+   and can be any integer type other than char, bool,
+   a bit-precise integer type, or an enumeration type.
+   TMIN should be signed and nonpositive.
+   TMAX should be positive, and should be signed unless TMIN is zero.  */
+#define _GL_INT_ADD_RANGE_OVERFLOW(a, b, tmin, tmax) \
+  ((b) < 0 \
+   ? (((tmin) \
+       ? ((_GL_EXPR_SIGNED (_GL_INT_CONVERT (a, (tmin) - (b))) || (b) < (tmin)) \
+          && (a) < (tmin) - (b)) \
+       : (a) <= -1 - (b)) \
+      || ((_GL_EXPR_SIGNED (a) ? 0 <= (a) : (tmax) < (a)) && (tmax) < (a) + (b))) \
+   : (a) < 0 \
+   ? (((tmin) \
+       ? ((_GL_EXPR_SIGNED (_GL_INT_CONVERT (b, (tmin) - (a))) || (a) < (tmin)) \
+          && (b) < (tmin) - (a)) \
+       : (b) <= -1 - (a)) \
+      || ((_GL_EXPR_SIGNED (_GL_INT_CONVERT (a, b)) || (tmax) < (b)) \
+          && (tmax) < (a) + (b))) \
+   : (tmax) < (b) || (tmax) - (b) < (a))
+#define _GL_INT_SUBTRACT_RANGE_OVERFLOW(a, b, tmin, tmax) \
+  (((a) < 0) == ((b) < 0) \
+   ? ((a) < (b) \
+      ? !(tmin) || -1 - (tmin) < (b) - (a) - 1 \
+      : (tmax) < (a) - (b)) \
+   : (a) < 0 \
+   ? ((!_GL_EXPR_SIGNED (_GL_INT_CONVERT ((a) - (tmin), b)) && (a) - (tmin) < 0) \
+      || (a) - (tmin) < (b)) \
+   : ((! (_GL_EXPR_SIGNED (_GL_INT_CONVERT (tmax, b)) \
+          && _GL_EXPR_SIGNED (_GL_INT_CONVERT ((tmax) + (b), a))) \
+       && (tmax) <= -1 - (b)) \
+      || (tmax) + (b) < (a)))
+#define _GL_INT_MULTIPLY_RANGE_OVERFLOW(a, b, tmin, tmax) \
+  ((b) < 0 \
+   ? ((a) < 0 \
+      ? (_GL_EXPR_SIGNED (_GL_INT_CONVERT (tmax, b)) \
+         ? (a) < (tmax) / (b) \
+         : ((_GL_INT_NEGATE_OVERFLOW (b) \
+             ? _GL_INT_CONVERT (b, tmax) >> (_GL_TYPE_WIDTH (+ (b)) - 1) \
+             : (tmax) / -(b)) \
+            <= -1 - (a))) \
+      : _GL_INT_NEGATE_OVERFLOW (_GL_INT_CONVERT (b, tmin)) && (b) == -1 \
+      ? (_GL_EXPR_SIGNED (a) \
+         ? 0 < (a) + (tmin) \
+         : 0 < (a) && -1 - (tmin) < (a) - 1) \
+      : (tmin) / (b) < (a)) \
+   : (b) == 0 \
+   ? 0 \
+   : ((a) < 0 \
+      ? (_GL_INT_NEGATE_OVERFLOW (_GL_INT_CONVERT (a, tmin)) && (a) == -1 \
+         ? (_GL_EXPR_SIGNED (b) ? 0 < (b) + (tmin) : -1 - (tmin) < (b) - 1) \
+         : (tmin) / (a) < (b)) \
+      : (tmax) / (b) < (a)))
+
+#endif /* _GL_INTPROPS_INTERNAL_H */
diff --git a/include/stdckdint.in.h b/include/stdckdint.in.h
new file mode 100644
index 00000000..91848806
--- /dev/null
+++ b/include/stdckdint.in.h
@@ -0,0 +1,35 @@
+/* stdckdint.h -- checked integer arithmetic
+
+   Copyright 2022-2024 Free Software Foundation, Inc.
+
+   This program is free software: you can redistribute it and/or modify it
+   under the terms of the GNU Lesser General Public License as published
+   by the Free Software Foundation; either version 2.1 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public License
+   along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
+
+#ifndef _GL_STDCKDINT_H
+#define _GL_STDCKDINT_H
+
+#include "intprops-internal.h"
+
+/* Store into *R the low-order bits of A + B, A - B, A * B, respectively.
+   Return 1 if the result overflows, 0 otherwise.
+   A, B, and *R can have any integer type other than char, bool, a
+   bit-precise integer type, or an enumeration type.
+
+   These are like the standard macros introduced in C23, except that
+   arguments should not have side effects.  */
+
+#define ckd_add(r, a, b) ((bool) _GL_INT_ADD_WRAPV (a, b, r))
+#define ckd_sub(r, a, b) ((bool) _GL_INT_SUBTRACT_WRAPV (a, b, r))
+#define ckd_mul(r, a, b) ((bool) _GL_INT_MULTIPLY_WRAPV (a, b, r))
+
+#endif /* _GL_STDCKDINT_H */
-- 
2.44.0

From 4d8a840e62ea051a4a869b157b4060c585a9535b Mon Sep 17 00:00:00 2001
From: Paul Eggert <egg...@cs.ucla.edu>
Date: Sun, 10 Mar 2024 12:11:35 -0700
Subject: [PATCH 3/5] Coalesce multiple PRIdMAX definitions

PRIdMAX is useful in multiple places, and as inttypes.h
defines it, move its definition to the include file that
includes inttypes.h, as it's logical to fix PRIdMAX just
after it's possibly incorrectly defined.
* bashtypes.h (PRIdMAX): Move definition here ...
* builtins/printf.def, examples/loadables/getconf.h:
* examples/loadables/seq.c: ... from these multiple locations.
---
 bashtypes.h                  | 11 +++++++++++
 builtins/printf.def          | 12 ------------
 examples/loadables/getconf.h |  8 --------
 examples/loadables/seq.c     | 12 ------------
 4 files changed, 11 insertions(+), 32 deletions(-)

diff --git a/bashtypes.h b/bashtypes.h
index 01afef4b..ceb08e59 100644
--- a/bashtypes.h
+++ b/bashtypes.h
@@ -35,6 +35,17 @@
 #  include <inttypes.h>
 #endif
 
+#ifdef PRI_MACROS_BROKEN
+#  undef PRIdMAX
+#endif
+#ifndef PRIdMAX
+#  if HAVE_LONG_LONG
+#    define PRIdMAX	"lld"
+#  else
+#    define PRIdMAX	"ld"
+#  endif
+#endif
+
 #if HAVE_STDINT_H
 #  include <stdint.h>
 #endif
diff --git a/builtins/printf.def b/builtins/printf.def
index b1140dc4..27e00a9e 100644
--- a/builtins/printf.def
+++ b/builtins/printf.def
@@ -89,18 +89,6 @@ $END
 #include "bashgetopt.h"
 #include "common.h"
 
-#if defined (PRI_MACROS_BROKEN)
-#  undef PRIdMAX
-#endif
-
-#if !defined (PRIdMAX)
-#  if HAVE_LONG_LONG
-#    define PRIdMAX	"lld"
-#  else
-#    define PRIdMAX	"ld"
-#  endif
-#endif
-
 #if !defined (errno)
 extern int errno;
 #endif
diff --git a/examples/loadables/getconf.h b/examples/loadables/getconf.h
index b8b9f102..98cc05e6 100644
--- a/examples/loadables/getconf.h
+++ b/examples/loadables/getconf.h
@@ -125,12 +125,4 @@
 #  define WORD_BIT	(sizeof (int) * CHAR_BIT)
 #endif
 
-#if !defined (PRIdMAX)
-#  if HAVE_LONG_LONG
-#    define PRIdMAX     "lld"
-#  else
-#    define PRIdMAX     "ld"
-#  endif
-#endif
-
 #endif /* _GETCONF_H */
diff --git a/examples/loadables/seq.c b/examples/loadables/seq.c
index 2a2be827..13834b8d 100644
--- a/examples/loadables/seq.c
+++ b/examples/loadables/seq.c
@@ -35,18 +35,6 @@
 extern int errno;
 #endif
 
-#if defined (PRI_MACROS_BROKEN)
-#  undef PRIdMAX
-#endif
-
-#if !defined (PRIdMAX)
-#  if HAVE_LONG_LONG
-#    define PRIdMAX     "lld"
-#  else
-#    define PRIdMAX     "ld"
-#  endif
-#endif
-
 #if defined (HAVE_LONG_DOUBLE) && HAVE_DECL_STRTOLD && !defined(STRTOLD_BROKEN)
 typedef long double floatmax_t;
 #  define FLOATMAX_CONV "L"
-- 
2.44.0

From ac0a3526c78a321ac5ecf51f6868caea65f04158 Mon Sep 17 00:00:00 2001
From: Paul Eggert <egg...@cs.ucla.edu>
Date: Mon, 11 Mar 2024 23:36:38 -0700
Subject: [PATCH 4/5] Fix problems with large brace expansions

Do not mishandle brace expansions with more than INT_MAX elements.
Check more carefully for integer overflow in brace expansions.
Use C23-style checking for integer overflow, as that is more
future-proof.
* braces.c: Include <stdckdint.h>.
(mkseq): Width arg is size_t, not int, to avoid imposing
an arbitrary limit.  All uses changed.
Do not assume number of elements fits in int, or that
INT_MAX <= SIZE_MAX.  Simplify overflow checks.
Add a FIXME about an unlikely crash on interrupt.
Zero pad by hand, since asprintf cannot handle widths > INT_MAX.
* include/typemax.h (sh_imaxabs, ADDOVERFLOW, SUBOVERFLOW):
Remove; no longer used.
* lib/sh/stringvec.c: Include <stdckdint.h>.
(strvec_mcreate): Check for integer overflow.
(strvec_flush): Don't assume vector size fits in int.
* stringlib.c (substring): Don't assume string size fits in int.
---
 braces.c           | 165 ++++++++++++++++++++++-----------------------
 externs.h          |   2 +-
 include/typemax.h  |  19 ------
 lib/sh/stringvec.c |   6 +-
 stringlib.c        |   4 +-
 5 files changed, 87 insertions(+), 109 deletions(-)

diff --git a/braces.c b/braces.c
index 17d28073..860c228a 100644
--- a/braces.c
+++ b/braces.c
@@ -32,6 +32,7 @@
 #endif
 
 #include <errno.h>
+#include <stdckdint.h>
 
 #include "bashansi.h"
 #include "bashintl.h"
@@ -77,7 +78,7 @@ static const int brace_arg_separator = ',';
 static int brace_gobbler (char *, size_t, int *, int);
 static char **expand_amble (char *, size_t, int);
 static char **expand_seqterm (char *, size_t);
-static char **mkseq (intmax_t, intmax_t, intmax_t, int, int);
+static char **mkseq (intmax_t, intmax_t, intmax_t, int, size_t);
 static char **array_concat (char **, char **);
 
 #if 0
@@ -349,120 +350,114 @@ expand_amble (char *text, size_t tlen, int flags)
 #define ST_ZINT	3
 
 static char **
-mkseq (intmax_t start, intmax_t end, intmax_t incr, int type, int width)
+mkseq (intmax_t start, intmax_t end, intmax_t incr, int type, size_t width)
 {
-  intmax_t n, prevn;
-  int i, nelem;
+  intmax_t prevn, abs_incr;
+  size_t nelem;
   char **result, *t;
+  char lbuf[INT_BUFSIZE_BOUND (uintmax_t)];
 
   if (incr == 0)
     incr = 1;
 
-  if (start > end && incr > 0)
-    incr = -incr;
-  else if (start < end && incr < 0)
-    {
-      if (incr == INTMAX_MIN)		/* Don't use -INTMAX_MIN */
-	return ((char **)NULL);
-      incr = -incr;
-    }
-
-  /* Check that end-start will not overflow INTMAX_MIN, INTMAX_MAX.  The +3
-     and -2, not strictly necessary, are there because of the way the number
-     of elements and value passed to strvec_create() are calculated below. */
-  if (SUBOVERFLOW (end, start, INTMAX_MIN+3, INTMAX_MAX-2))
+  /* abs_incr = abs (incr) */
+  abs_incr = incr;
+  if (incr < 0 && ckd_sub (&abs_incr, 0, incr))
     return ((char **)NULL);
 
-  prevn = sh_imaxabs (end - start);
-  /* Need to check this way in case INT_MAX == INTMAX_MAX */
-  if (INT_MAX == INTMAX_MAX && (ADDOVERFLOW (prevn, 2, INT_MIN, INT_MAX)))
+  /* Negate incr if it disagrees with start < end. */
+  if ((start < end) == (incr < 0) && ckd_sub (&incr, 0, incr))
     return ((char **)NULL);
-  /* Make sure the assignment to nelem below doesn't end up <= 0 due to
-     intmax_t overflow */
-  else if (ADDOVERFLOW ((prevn/sh_imaxabs(incr)), 1, INTMAX_MIN, INTMAX_MAX))
+
+  /* prevn = abs (end - start); */
+  if (start < end
+      ? ckd_sub (&prevn, end, start)
+      : ckd_sub (&prevn, start, end))
     return ((char **)NULL);
 
-  /* XXX - TOFIX: potentially allocating a lot of extra memory if
-     imaxabs(incr) != 1 */
-  /* Instead of a simple nelem = prevn + 1, something like:
-  	nelem = (prevn / imaxabs(incr)) + 1;
-     would work */
-  if ((prevn / sh_imaxabs (incr)) > INT_MAX - 3)	/* check int overflow */
+  /* The number of elements is floor (abs ((end - start) / incr)),
+     plus 1 for the first element, plus 1 for trailing nullptr. */
+  if (ckd_add (&nelem, prevn / abs_incr, 1 + 1))
     return ((char **)NULL);
-  nelem = (prevn / sh_imaxabs(incr)) + 1;
-  result = strvec_mcreate (nelem + 1);
-  if (result == 0)
-    {
-      internal_error (_("brace expansion: failed to allocate memory for %u elements"), (unsigned int)nelem);
-      return ((char **)NULL);
-    }
 
-  /* Make sure we go through the loop at least once, so {3..3} prints `3' */
-  i = 0;
-  n = start;
-  do
+  result = strvec_mcreate (nelem);
+  if (result)
     {
+      /* Go through the loop at least once, so {3..3} expands to 3. */
+      size_t i = 0;
+      intmax_t n;
+      for (n = start; ; n += incr)
+	{
 #if defined (SHELL)
-      if (ISINTERRUPT)
-        {
-          result[i] = (char *)NULL;
-          strvec_dispose (result);
-          result = (char **)NULL;
-        }
-      QUIT;
+	  if (ISINTERRUPT)
+	    {
+	      result[i] = (char *)NULL;
+	      strvec_dispose (result);
+	      result = (char **)NULL;
+	      /* FIXME: This crashes if QUIT does not throw to the
+		 top level, which seems possible albeit unlikely. */
+	    }
+	  QUIT;
 #endif
-      if (type == ST_INT)
-	result[i++] = t = itos (n);
-      else if (type == ST_ZINT)
-	{
-	  int len, arg;
-	  arg = n;
-	  len = asprintf (&t, "%0*d", width, arg);
-	  result[i++] = t;
-	}
-      else
-	{
-	  if (t = (char *)malloc (2))
+	  if (type == ST_CHAR)
 	    {
-	      t[0] = n;
-	      t[1] = '\0';
+	      t = (char *)malloc (2);
+	      if (t)
+		{
+		  t[0] = n;
+		  t[1] = '\0';
+		}
+	    }
+	  else
+	    {
+	      t = itos (n);
+	      if (type == ST_ZINT)
+		{
+		  size_t tlen = strlen (t);
+		  if (tlen < width)
+		    {
+		      /* Zero pad the result directly, as sprintf
+			 does not work when INT_MAX < width. */
+		      char *t0 = t;
+		      t = realloc (t, width + 1);
+		      if (!t)
+			free (t0);
+		      else
+			{
+			  memmove (t + (width - tlen), t, tlen + 1);
+			  memset (t + (n < 0), '0', width - tlen);
+			}
+		    }
+		}
 	    }
-	  result[i++] = t;
-	}
 
-      /* We failed to allocate memory for this number, so we bail. */
-      if (t == 0)
-	{
-	  char *p, lbuf[INT_STRLEN_BOUND(intmax_t) + 1];
-
-	  /* Easier to do this than mess around with various intmax_t printf
-	     formats (%ld? %lld? %jd?) and PRIdMAX. */
-	  p = inttostr (n, lbuf, sizeof (lbuf));
-	  internal_error (_("brace expansion: failed to allocate memory for `%s'"), p);
-	  strvec_dispose (result);
-	  return ((char **)NULL);
-	}
+	  result[i++] = t;
 
-      /* Handle overflow and underflow of n+incr */
-      if (ADDOVERFLOW (n, incr, INTMAX_MIN, INTMAX_MAX))
-        break;
+	  /* Bail if we failed to allocate memory for this number. */
+	  if (!t)
+	    break;
 
-      n += incr;
+	  if (i == nelem - 1)
+	    {
+	      result[i] = (char *)0;
+	      return (result);
+	    }
+	}
 
-      if ((incr < 0 && n < end) || (incr > 0 && n > end))
-	break;
+      strvec_dispose (result);
     }
-  while (1);
 
-  result[i] = (char *)0;
-  return (result);
+  internal_error (_("brace expansion: cannot allocate %s elements"),
+		  uinttostr (nelem - 1, lbuf, sizeof (lbuf)));
+  return ((char **)NULL);
 }
 
 static char **
 expand_seqterm (char *text, size_t tlen)
 {
   char *t, *lhs, *rhs;
-  int lhs_t, rhs_t, lhs_l, rhs_l, width;
+  int lhs_t, rhs_t;
+  size_t lhs_l, rhs_l, width;
   intmax_t lhs_v, rhs_v, incr;
   intmax_t tl, tr;
   char **result, *ep, *oep;
diff --git a/externs.h b/externs.h
index 6376bf41..b60fb79e 100644
--- a/externs.h
+++ b/externs.h
@@ -164,7 +164,7 @@ extern int find_string_in_alist (char *, STRING_INT_ALIST *, int);
 extern char *find_token_in_alist (int, STRING_INT_ALIST *, int);
 extern int find_index_in_alist (char *, STRING_INT_ALIST *, int);
 
-extern char *substring (const char *, int, int);
+extern char *substring (const char *, size_t, size_t);
 extern char *strsub (const char *, const char *, const char *, int);
 extern char *strcreplace (const char *, int, const char *, int);
 extern void strip_leading (char *);
diff --git a/include/typemax.h b/include/typemax.h
index e3b98f47..c93fda73 100644
--- a/include/typemax.h
+++ b/include/typemax.h
@@ -119,23 +119,4 @@ static const unsigned long long int maxquad = ULLONG_MAX;
 #  define SIZE_MAX	((size_t) ~(size_t)0)
 #endif
 
-#ifndef sh_imaxabs
-#  define sh_imaxabs(x)	(((x) >= 0) ? (x) : -(x))
-#endif
-
-/* Handle signed arithmetic overflow and underflow.  Have to do it this way
-   to avoid compilers optimizing out simpler overflow checks. */
-
-/* Make sure that a+b does not exceed MAXV or is smaller than MINV (if b < 0).
-   Assumes that b > 0 if a > 0 and b < 0 if a < 0 */
-#define ADDOVERFLOW(a,b,minv,maxv) \
-	((((a) > 0) && ((b) > ((maxv) - (a)))) || \
-	 (((a) < 0) && ((b) < ((minv) - (a)))))
-
-/* Make sure that a-b is not smaller than MINV or exceeds MAXV (if b < 0).
-   Assumes that b > 0 if a > 0 and b < 0 if a < 0 */
-#define SUBOVERFLOW(a,b,minv,maxv) \
-	((((b) > 0) && ((a) < ((minv) + (b)))) || \
-	 (((b) < 0) && ((a) > ((maxv) + (b)))))
-
 #endif /* _SH_TYPEMAX_H */
diff --git a/lib/sh/stringvec.c b/lib/sh/stringvec.c
index bf57d688..01e65a87 100644
--- a/lib/sh/stringvec.c
+++ b/lib/sh/stringvec.c
@@ -27,6 +27,7 @@
 #endif
 
 #include <bashansi.h>
+#include <stdckdint.h>
 #include <stdio.h>
 #include <chartypes.h>
 
@@ -43,7 +44,8 @@ strvec_create (size_t n)
 char **
 strvec_mcreate (size_t n)
 {
-  return ((char **)malloc ((n) * sizeof (char *)));
+  size_t nbytes;
+  return ckd_mul (&nbytes, n, sizeof (char *)) ? NULL : malloc (nbytes);
 }
 
 char **
@@ -72,7 +74,7 @@ strvec_len (char * const *array)
 void
 strvec_flush (char **array)
 {
-  register int i;
+  register size_t i;
 
   if (array == 0)
     return;
diff --git a/stringlib.c b/stringlib.c
index 7c24df62..fcfd5e2d 100644
--- a/stringlib.c
+++ b/stringlib.c
@@ -115,9 +115,9 @@ find_index_in_alist (char *string, STRING_INT_ALIST *alist, int flags)
 /* Cons a new string from STRING starting at START and ending at END,
    not including END. */
 char *
-substring (const char *string, int start, int end)
+substring (const char *string, size_t start, size_t end)
 {
-  int len;
+  size_t len;
   char *result;
 
   len = end - start;
-- 
2.44.0

From a891a95eff7546663572e71ee6c9263e9d091dac Mon Sep 17 00:00:00 2001
From: Paul Eggert <egg...@cs.ucla.edu>
Date: Tue, 12 Mar 2024 12:27:48 -0700
Subject: [PATCH 5/5] printf now diagnoses more width/prec overflow

Diagnose overflow when printf parses width or precision itself
as opposed to letting the underlying printf do it.
* printf.def: Include stdckdint.h.
(decodeint): New function, replacing decodeprec; name changed
since it also scans widths.  All uses changed.
(printf_builtin, printstr, printwidestr):
Diagnose out-of-range widths and precisions instead of relying on
undefined behavior, or silently doing the wrong thing.
(getint): New arg IFOVERFLOW.  All uses changed.
Check for overflow properly.
---
 builtins/printf.def | 149 ++++++++++++++++++++------------------------
 1 file changed, 66 insertions(+), 83 deletions(-)

diff --git a/builtins/printf.def b/builtins/printf.def
index 27e00a9e..5b6a3718 100644
--- a/builtins/printf.def
+++ b/builtins/printf.def
@@ -69,7 +69,7 @@ $END
 #endif
 
 #include <stdarg.h>
-
+#include <stdckdint.h>
 #include <stdio.h>
 #include <chartypes.h>
 
@@ -191,7 +191,7 @@ extern int vsnprintf (char *, size_t, const char *, va_list) __attribute__((__fo
 #endif
 
 static void printf_erange (char *);
-static int printstr (char *, char *, int, int, int);
+static int printstr (char *, char *, int, int, int, int);
 static int tescape (char *, char *, int *, int *);
 static char *bexpand (char *, int, int *, int *);
 static char *vbadd (char *, int);
@@ -199,7 +199,7 @@ static int vbprintf (const char *, ...) __attribute__((__format__ (printf, 1, 2)
 static char *mklong (char *, char *, size_t);
 static int getchr (void);
 static char *getstr (void);
-static int  getint (void);
+static int getint (int);
 static intmax_t getintmax (void);
 static uintmax_t getuintmax (void);
 
@@ -224,7 +224,7 @@ static wchar_t *getwidestr (size_t *);
 static wint_t getwidechar (void);
 static char *convwidestr (wchar_t *, int);
 static char *convwidechar (wint_t, int);
-static int printwidestr (char *, wchar_t *, size_t, int, int);
+static int printwidestr (char *, wchar_t *, size_t, int, int, int);
 #endif
 
 static WORD_LIST *garglist, *orig_arglist;
@@ -243,22 +243,38 @@ static intmax_t tw;
 static char *conv_buf;
 static size_t conv_bufsize;
 
+/* Convert the unsigned decimal integer at the start of *STR to int.
+   **STR must be a digit.
+   Update *STR to point past the end of the integer.
+   If DIAGNOSE, diagnose if the integer does not fit in int.
+   Return the scanned value, or IFOVERFLOW if it does fit in int. */
 static inline int
-decodeprec (char *ps)
+decodeint (char **str, int diagnose, int ifoverflow)
 {
-  intmax_t mpr;
+  char *ps = *str;
+  int pr = *ps++ - '0';
+  int v = 0;
 
-  mpr = *ps++ - '0';
-  while (DIGIT (*ps))
-    mpr = (mpr * 10) + (*ps++ - '0');
-  return (mpr < 0 || mpr > INT_MAX) ? INT_MAX : mpr;
+  for (; DIGIT (*ps); ps++)
+    {
+      v |= ckd_mul (&pr, pr, 10);
+      v |= ckd_add (&pr, pr, *ps - '0');
+    }
+  if (v && diagnose)
+    {
+      char *prefix = substring (*str, 0, ps - *str);
+      printf_erange (prefix);
+      free (prefix);
+    }
+  *str = ps;
+  return v ? ifoverflow : pr;
 }
 
 int
 printf_builtin (WORD_LIST *list)
 {
   int ch, fieldwidth, precision;
-  int have_fieldwidth, have_precision, use_Lmod, altform, longform;
+  int have_fieldwidth, have_precision, use_Lmod, altform, longform, diagnose;
   char convch, thisch, nextch, *format, *modstart, *precstart, *fmt, *start;
 #if defined (HANDLE_MULTIBYTE)
   char mbch[25];		/* 25 > MB_LEN_MAX, plus can handle 4-byte UTF-8 and large Unicode characters*/
@@ -329,6 +345,7 @@ printf_builtin (WORD_LIST *list)
 
   format = list->word->word;
   tw = 0;
+  diagnose = 1;
   retval = EXECUTION_SUCCESS;
 
   garglist = orig_arglist = list->next;
@@ -406,10 +423,7 @@ printf_builtin (WORD_LIST *list)
 	    {
 	      fmt++;
 	      have_fieldwidth = 1;
-	      fieldwidth = getint ();
-	      /* Handle field with overflow by ignoring it. */
-	      if (fieldwidth == INT_MAX || fieldwidth == INT_MIN)
-		  fieldwidth = 0;
+	      fieldwidth = getint (0);
 	    }
 	  else
 	    while (DIGIT (*fmt))
@@ -423,11 +437,7 @@ printf_builtin (WORD_LIST *list)
 		{
 		  fmt++;
 		  have_precision = 1;
-		  precision = getint ();
-		  /* Handle precision overflow by ignoring it. "A negative
-		     precision is treated as if it were missing." */
-		  if (precision == INT_MAX || precision == INT_MIN)
-		    precision = -1;
+		  precision = getint (-1);
 		}
 	      else
 		{
@@ -491,9 +501,11 @@ printf_builtin (WORD_LIST *list)
 		    /* If %lc is supplied a null argument, posix interp 1647
 		       says it should produce a single null byte. */
 		    if (wc == L'\0')
-		      r = printstr (start, "", 1, fieldwidth, precision);
+		      r = printstr (start, "", 1, fieldwidth, precision,
+				    diagnose);
 		    else
-		      r = printwidestr (start, ws, 1, fieldwidth, precision);
+		      r = printwidestr (start, ws, 1, fieldwidth, precision,
+					diagnose);
 		    if (r < 0)
 		      PRETURN (EXECUTION_FAILURE);
 		    break;
@@ -516,7 +528,8 @@ printf_builtin (WORD_LIST *list)
 		    int r;
 
 		    wp = getwidestr (&slen);
-		    r = printwidestr (start, wp, slen, fieldwidth, precision);
+		    r = printwidestr (start, wp, slen, fieldwidth, precision,
+				      diagnose);
 		    FREE (wp);
 		    if (r < 0)
 		      PRETURN (EXECUTION_FAILURE);
@@ -547,7 +560,8 @@ printf_builtin (WORD_LIST *list)
 		  {
 		    /* Have to use printstr because of possible NUL bytes
 		       in XP -- printf does not handle that well. */
-		    r = printstr (start, xp, rlen, fieldwidth, precision);
+		    r = printstr (start, xp, rlen, fieldwidth, precision,
+				  diagnose);
 		    if (r < 0)
 		      retval = EXECUTION_FAILURE;
 		    free (xp);
@@ -622,7 +636,9 @@ printf_builtin (WORD_LIST *list)
 		/* convert to %s format that preserves fieldwidth and precision */
 		modstart[0] = 's';
 		modstart[1] = '\0';
-		r = printstr (start, timebuf, strlen (timebuf), fieldwidth, precision);	/* XXX - %s for now */
+		/* XXX - %s for now */
+		r = printstr (start, timebuf, strlen (timebuf),
+			      fieldwidth, precision, diagnose);
 		if (r < 0)
 		  PRETURN (EXECUTION_FAILURE);
 		break;
@@ -659,7 +675,10 @@ printf_builtin (WORD_LIST *list)
 		if (convch == 'Q' && (have_precision || precstart))
 		  {
 		    if (precstart)
-		      precision = decodeprec (precstart);
+		      {
+			char *prec = precstart;
+			precision = decodeint (&prec, 0, -1);
+		      }
 		    slen = strlen (p);
 		    /* printf precision works in bytes. */
 		    if (precision >= 0 && precision < slen)
@@ -682,7 +701,8 @@ printf_builtin (WORD_LIST *list)
 			  precision = slen;
 		      }		    
 		    /* Use printstr to get fieldwidth and precision right. */
-		    r = printstr (start, xp, slen, fieldwidth, precision);
+		    r = printstr (start, xp, slen, fieldwidth, precision,
+				  diagnose);
 		    /* Let PRETURN print the error message. */
 		    free (xp);
 		  }
@@ -699,8 +719,8 @@ printf_builtin (WORD_LIST *list)
 		long p;
 		intmax_t pp;
 
-		p = pp = getintmax ();
-		if (p != pp)
+		pp = getintmax ();
+		if (! (LONG_MIN <= pp && pp <= LONG_MAX))
 		  {
 		    f = mklong (start, PRIdMAX, sizeof (PRIdMAX) - 2);
 		    PF (f, pp);
@@ -711,6 +731,7 @@ printf_builtin (WORD_LIST *list)
 		       in "long".  This also works around some long
 		       long and/or intmax_t library bugs in the common
 		       case, e.g. glibc 2.2 x86.  */
+		    p = pp;
 		    f = mklong (start, "l", 1);
 		    PF (f, p);
 		  }
@@ -789,6 +810,8 @@ printf_builtin (WORD_LIST *list)
 	  /* PRETURN will print error message. */
 	  PRETURN (EXECUTION_FAILURE);
 	}
+
+      diagnose = 0;
     }
   while (garglist && garglist != list->next);
 
@@ -815,14 +838,14 @@ printf_erange (char *s)
    Returns -1 on detectable write error, 0 otherwise. */
 
 static int
-printstr (char *fmt, char *string, int len, int fieldwidth, int precision)
+printstr (char *fmt, char *string, int len, int fieldwidth, int precision,
+	  int diagnose)
 {
 #if 0
   char *s;
 #endif
   int padlen, nc, ljust, i;
   int fw, pr;			/* fieldwidth and precision */
-  intmax_t mfw, mpr;
 
   if (string == 0)
     string = "";
@@ -833,10 +856,8 @@ printstr (char *fmt, char *string, int len, int fieldwidth, int precision)
   if (*fmt == '%')
     fmt++;
 
-  ljust = fw = 0;
+  ljust = 0;
   pr = -1;
-  mfw = 0;
-  mpr = -1;
 
   /* skip flags */
   while (strchr (SKIP1, *fmt))
@@ -858,13 +879,7 @@ printstr (char *fmt, char *string, int len, int fieldwidth, int precision)
 	}
     }
   else if (DIGIT (*fmt))
-    {
-      mfw = *fmt++ - '0';
-      while (DIGIT (*fmt))
-	mfw = (mfw * 10) + (*fmt++ - '0');
-      /* Error if fieldwidth > INT_MAX here? */
-      fw = (mfw < 0 || mfw > INT_MAX) ? INT_MAX : mfw;
-    }
+    fw = decodeint (&fmt, diagnose, 0);
 
   /* get precision, if present. doesn't handle negative precisions */
   if (*fmt == '.')
@@ -876,15 +891,7 @@ printstr (char *fmt, char *string, int len, int fieldwidth, int precision)
 	  pr = precision;
 	}
       else if (DIGIT (*fmt))
-	{
-	  mpr = *fmt++ - '0';
-	  while (DIGIT (*fmt))
-	    mpr = (mpr * 10) + (*fmt++ - '0');
-	  /* Error if precision > INT_MAX here? */
-	  pr = (mpr < 0 || mpr > INT_MAX) ? INT_MAX : mpr;
-	  if (pr < precision && precision < INT_MAX)
-	    pr = precision;		/* XXX */
-	}
+	pr = decodeint (&fmt, diagnose, -1);
       else
 	pr = 0;		/* "a null digit string is treated as zero" */
     }
@@ -925,7 +932,8 @@ printstr (char *fmt, char *string, int len, int fieldwidth, int precision)
 #if defined (HANDLE_MULTIBYTE)
 /* A wide-character version of printstr */
 static int
-printwidestr (char *fmt, wchar_t *wstring, size_t len, int fieldwidth, int precision)
+printwidestr (char *fmt, wchar_t *wstring, size_t len,
+	      int fieldwidth, int precision, int diagnose)
 {
 #if 0
   char *s;
@@ -933,7 +941,6 @@ printwidestr (char *fmt, wchar_t *wstring, size_t len, int fieldwidth, int preci
   char *string;
   int padlen, nc, ljust, i;
   int fw, pr;			/* fieldwidth and precision */
-  intmax_t mfw, mpr;
 
   if (wstring == 0)
     wstring = L"";
@@ -946,8 +953,6 @@ printwidestr (char *fmt, wchar_t *wstring, size_t len, int fieldwidth, int preci
 
   ljust = fw = 0;
   pr = -1;
-  mfw = 0;
-  mpr = -1;
 
   /* skip flags */
   while (strchr (SKIP1, *fmt))
@@ -969,13 +974,7 @@ printwidestr (char *fmt, wchar_t *wstring, size_t len, int fieldwidth, int preci
 	}
     }
   else if (DIGIT (*fmt))
-    {
-      mfw = *fmt++ - '0';
-      while (DIGIT (*fmt))
-	mfw = (mfw * 10) + (*fmt++ - '0');
-      /* Error if fieldwidth > INT_MAX here? */
-      fw = (mfw < 0 || mfw > INT_MAX) ? INT_MAX : mfw;
-    }
+    fw = decodeint (&fmt, diagnose, 0);
 
   /* get precision, if present. doesn't handle negative precisions */
   if (*fmt == '.')
@@ -987,15 +986,7 @@ printwidestr (char *fmt, wchar_t *wstring, size_t len, int fieldwidth, int preci
 	  pr = precision;
 	}
       else if (DIGIT (*fmt))
-	{
-	  mpr = *fmt++ - '0';
-	  while (DIGIT (*fmt))
-	    mpr = (mpr * 10) + (*fmt++ - '0');
-	  /* Error if precision > INT_MAX here? */
-	  pr = (mpr < 0 || mpr > INT_MAX) ? INT_MAX : mpr;
-	  if (pr < precision && precision < INT_MAX)
-	    pr = precision;		/* XXX */
-	}
+	pr = decodeint (&fmt, diagnose, -1);
       else
 	pr = 0;		/* "a null digit string is treated as zero" */
     }
@@ -1345,10 +1336,11 @@ getstr (void)
 /* Don't call getintmax here because it may consume an argument on error, and
    we call this to get field width/precision arguments. */
 static int
-getint (void)
+getint (int ifoverflow)
 {
   intmax_t ret;
   char *ep;
+  int overflow;
 
   if (garglist == 0)
     return (0);
@@ -1358,27 +1350,18 @@ getint (void)
 
   errno = 0;
   ret = strtoimax (garglist->word->word, &ep, 0);
+  overflow = errno == ERANGE || ! (-INT_MAX <= ret && ret <= INT_MAX);
 
   if (*ep)
     {
       sh_invalidnum (garglist->word->word);
       conversion_error = 1;
     }
-  else if (errno == ERANGE)
+  else if (overflow)
     printf_erange (garglist->word->word);
-  else if (ret > INT_MAX)
-    {
-      printf_erange (garglist->word->word);
-      ret = INT_MAX;
-    }
-  else if (ret < INT_MIN)
-    {
-      printf_erange (garglist->word->word);
-      ret = INT_MIN;
-    }
 
   garglist = garglist->next;
-  return ((int)ret);
+  return (overflow ? ifoverflow : (int)ret);
 }
 
 static intmax_t
-- 
2.44.0

Reply via email to