From f17cbdb2339164abe2de22963a506a20688833a8 Mon Sep 17 00:00:00 2001 From: haoxiang Yan <108142374+Yanhaoxi@users.noreply.github.com> Date: Sat, 13 Jun 2026 22:07:47 +0800 Subject: [PATCH] Reject NaN in floating-point to fixed-point conversions png_fixed(), png_fixed_ITU(), and convert_gamma_value() use range guards of the form 'if (r > MAX || r < MIN)' which fail to catch NaN input (NaN > X and NaN < X are both false per IEEE 754). When NaN bypasses the guard, the subsequent float-to-integer cast invokes undefined behavior. Rewrite the range guards in inverted form: 'if (!(r >= MIN && r <= MAX))'. This expression evaluates to true for NaN (since NaN >= X is false for all X), correctly routing NaN to the error handler. The behavior for all non-NaN inputs is unchanged. --- png.c | 4 ++-- pngrtran.c | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/png.c b/png.c index aacba1a61d..84f166e434 100644 --- a/png.c +++ b/png.c @@ -2699,7 +2699,7 @@ png_fixed(const png_struct *png_ptr, double fp, const char *text) { double r = floor(100000 * fp + .5); - if (r > 2147483647. || r < -2147483648.) + if (!(r >= -2147483648. && r <= 2147483647.)) png_fixed_error(png_ptr, text); # ifndef PNG_ERROR_TEXT_SUPPORTED @@ -2718,7 +2718,7 @@ png_fixed_ITU(const png_struct *png_ptr, double fp, const char *text) { double r = floor(10000 * fp + .5); - if (r > 2147483647. || r < 0) + if (!(r >= 0. && r <= 2147483647.)) png_fixed_error(png_ptr, text); # ifndef PNG_ERROR_TEXT_SUPPORTED diff --git a/pngrtran.c b/pngrtran.c index 25a333fe8a..39ee1943e7 100644 --- a/pngrtran.c +++ b/pngrtran.c @@ -304,7 +304,7 @@ convert_gamma_value(png_struct *png_ptr, double output_gamma) /* This preserves -1 and -2 exactly: */ output_gamma = floor(output_gamma + .5); - if (output_gamma > PNG_FP_MAX || output_gamma < PNG_FP_MIN) + if (!(output_gamma >= PNG_FP_MIN && output_gamma <= PNG_FP_MAX)) png_fixed_error(png_ptr, "gamma value"); return (png_fixed_point)output_gamma;