Skip to content

Prevent int overflow on $decimals in number_format for PHP < 8.3 #11714

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion ext/standard/math.c
Original file line number Diff line number Diff line change
Expand Up @@ -1136,6 +1136,7 @@ PHP_FUNCTION(number_format)
{
double num;
zend_long dec = 0;
int dec_int;
char *thousand_sep = NULL, *dec_point = NULL;
size_t thousand_sep_len = 0, dec_point_len = 0;

Expand All @@ -1156,7 +1157,17 @@ PHP_FUNCTION(number_format)
thousand_sep_len = 1;
}

RETURN_STR(_php_math_number_format_ex(num, (int)dec, dec_point, dec_point_len, thousand_sep, thousand_sep_len));
#if SIZEOF_ZEND_LONG > SIZEOF_INT
Copy link
Member

@nielsdos nielsdos Jul 16, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use ZEND_LONG_INT_OVFL & ZEND_LONG_INT_UDFL which will allow you to avoid this #if and make the code a bit cleaner. These macros will resolve to false if zend_long and int are the same size.
There's also ZEND_LONG_EXCEEDS_INT, but that's unusable here because you still want to set dec_int to a sane value.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

updated

if (dec >= 0) {
dec_int = dec > INT_MAX ? INT_MAX : (int)dec;
} else {
dec_int = dec <= INT_MIN ? INT_MIN : (int)dec;
}
#else
dec_int = dec;
#endif

RETURN_STR(_php_math_number_format_ex(num, dec_int, dec_point, dec_point_len, thousand_sep, thousand_sep_len));
}
/* }}} */

Expand Down