Unbounded allocation in Decimal.round/3 driven by the places argument
Description
Decimal.round/3 does work proportional to its places argument instead of to the size of its result. A caller who controls places can make a single call allocate gigabytes of memory, which can get the BEAM VM killed.
Details
round/3 sets the target exponent to -places (lib/decimal.ex:1313 in v3.1.1) and do_round/5 builds the complete result at that exponent before the context precision (34 digits by default) cuts it back:
- When
placesis larger than the number's scale,do_round/5appendsplaceszero digits to the coefficient as a charlist,digits ++ Enum.map(1..(exp - target_exp), fn _ -> ?0 end)(lib/decimal.ex:2409), and converts it with:erlang.list_to_integer/1. The list is built beforelist_to_integer/1raisesSystemLimitErrorfor results over about 1.26 million digits. - When
placesis negative, it builds:lists.duplicate(target_exp - exp, ?0)and copies it with++(lib/decimal.ex:2385-2386).
Each list element costs 16 bytes, plus the copies made by ++ and garbage collection. Measured on OTP 29 with v3.1.1:
| Call | Time | Peak VM memory |
|---|---|---|
Decimal.round(Decimal.new("1.5"), -10_000_000) | 0.25 s | 0.8 GB |
Decimal.round(Decimal.new("1.5"), -50_000_000) | 1.2 s | 5.5 GB |
Decimal.round(Decimal.new("1.5"), 50_000_000) | 2.1 s, then SystemLimitError | 2.4 GB |
In a container limited to 2 GB of memory, either of the last two calls got the whole VM killed (exit status 137).
Releases before 1.1.0 instead loop once per decimal place when places is a large negative number, so the call consumes CPU in proportion to places.
The input limits added for CVE-2026-32686 (GHSA-rhv4-8758-jx7v) bound parsed decimals but not the places argument.
PoC
Mix.install([{:decimal, "3.1.1"}])
# Allocates about 5.5 GB.
Decimal.round(Decimal.new("1.5"), -50_000_000)
# Builds a 50 million element list, then raises SystemLimitError.
Decimal.round(Decimal.new("1.5"), 50_000_000)Impact
Denial of service through memory exhaustion. Applications that pass a user-supplied number of decimal places or scale to Decimal.round/2 or Decimal.round/3 without bounding it are affected. One request with places: -50_000_000 needs about 5.5 GB.
Workarounds
Bound places before calling Decimal.round/2,3, for example to -34..34 or to the scales the application supports.