[php-src] PR #20900: ext/gmp: Prevent overflow in gmp_fact() for large GMP inputs (GH-16878)
| From: | khaledalam | Date: | Sat, 10 Jan 2026 20:21:55 +0000 |
| Subject: | [php-src] PR #20900: ext/gmp: Prevent overflow in gmp_fact() for large GMP inputs (GH-16878) | ||
| Groups: | php.git-pulls | ||
| Request: | Send a blank email to git-pulls+get-34506@lists.php.net to get a copy of this message | ||
Pull Request: https://github.com/php/php-src/pull/20900
Author: khaledalam
## Description
### Problem
gmp_fact() ends up calling mpz_fac_ui(), which accepts an unsigned long.
When the user passes a GMP number that does not fit into unsigned long, the conversion path could
overflow / truncate and compute factorial() of the wrong value (or behave unexpectedly).
### What this PR changes:
- Introduces a local zend_long num_long to store the validated input once.
- For IS_LONG:
- Keeps existing non-negative check.
- Stores the value in num_long.
- For GMP values:
- Ensures the number is non-negative (mpz_sgn < 0).
- Ensures it fits in unsigned long (mpz_fits_ulong_p()), otherwise throws ValueError (“is too
large”).
- Converts via mpz_get_ui() into num_long.
- Adds an additional safety cap:
- If num_long >
100,000, throw ValueError (“is too large”).
- Calls mpz_fac_ui(gmpnum_result, (unsigned long) num_long) (no repeated conversion).
### Why the 100,000 cap?
Factorials grow extremely fast; very large inputs can cause huge CPU/memory usage. The cap prevents
accidental DoS-style usage while still allowing very large practical values.
### Error behavior
- Negative input → ValueError: must be greater than or equal to 0
- Too large to fit in unsigned long (GMP input) → ValueError: is too large
- Above hard cap (all inputs) → ValueError: is too large