mailing list of musl libc
 help / color / mirror / code / Atom feed
From: Peter Ammon <corydoras@ridiculousfish.com>
To: musl@lists.openwall.com
Subject: [musl] [PATCH] printf: Fix int overflow in rounding calculation
Date: Sun, 14 Apr 2024 10:53:39 -0700	[thread overview]
Message-ID: <81F5BE1D-3AA2-479E-8F4D-6AF0DAC7D010@ridiculousfish.com> (raw)

In printf float formatting, a calculation of digits to round may trigger signed int overflow, if the precision is large and the exponent is large and negative. For example, `printf("%.*g", INT_MAX, 1e-100)` will reproduce it.

The overflow case corresponds to a huge number of digits after the decimal, which means no rounding is required, so I opted to saturate j at INT_MAX. Using a wider type is an alternative.

Note that p is non-negative, so underflow is impossible.

---
src/stdio/vfprintf.c | 3 ++-
1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/src/stdio/vfprintf.c b/src/stdio/vfprintf.c
index 497c5e19..eb4c755a 100644
--- a/src/stdio/vfprintf.c
+++ b/src/stdio/vfprintf.c
@@ -307,7 +307,8 @@ static int fmt_fp(FILE *f, long double y, int w, int p, int fl, int t)
	else e=0;

	/* Perform rounding: j is precision after the radix (possibly neg) */
-	j = p - ((t|32)!='f')*e - ((t|32)=='g' && p);
+	i = ((t|32)!='f')*e + ((t|32)=='g' && p);
+	j = (i < 0 && p > INT_MAX+i) ? INT_MAX : p-i;
	if (j < 9*(z-r-1)) {
		uint32_t x;
		/* We avoid C's broken division of negative numbers */
--
2.39.2


                 reply	other threads:[~2024-04-14 17:54 UTC|newest]

Thread overview: [no followups] expand[flat|nested]  mbox.gz  Atom feed

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=81F5BE1D-3AA2-479E-8F4D-6AF0DAC7D010@ridiculousfish.com \
    --to=corydoras@ridiculousfish.com \
    --cc=musl@lists.openwall.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
Code repositories for project(s) associated with this public inbox

	https://git.vuxu.org/mirror/musl/

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).