Re: [PATCH] iio: core: fix signed integer overflow in

From: Andy Shevchenko

Date: Thu Oct 22 2026 - 03:08:26 EST


+Cc: Rodrigo

On Thu, Oct 22, 2026 at 04:22:48AM +0530, Arnav Kapoor wrote:
> __iio_str_to_fixpoint() accumulates the integer part of the parsed number
> into an int. Feeding it a string with more digits than an int can hold
> overflows that variable, which is undefined behaviour. The same happens
> when the parsed value is INT_MIN and the sign is applied afterwards.
>
> The parser is reachable from userspace via the writable IIO channel
> attributes, for example the "sampling_frequency" or "in_voltage_scale"
> ones, and via the exported iio_str_to_fixpoint() helper used by a
> number of IIO drivers. A user writing a long enough string therefore
> triggers a signed integer overflow.
>
> Accumulate the integer and the fractional part in a s64 and reject
> values that do not fit into an int with -ERANGE. The limit for the
> integer part depends on the sign as the sign is applied only after the
> whole string has been parsed.

This needs a Fixes tag, otherwise it probably won't needed as Rodrigo working
towards tons of improvements in this area.

OTOH, Rodrigo's test cases might be good as part of this fix as well.

...

> - int i = 0, f = 0;
> + s64 i = 0, f = 0;
> + s64 limit;
> bool integer_part = true, negative = false;

While at it, make it reversed xmas tree order.

...

> + /*
> + * The integer part is accumulated as a magnitude and the sign is only
> + * applied once the whole string has been parsed. Hence the limit
> + * depends on the sign.
> + */
> + limit = negative ? (s64)INT_MAX + 1 : INT_MAX;

Wow, what's wrong with INT_MIN?

> while (*str) {
> if ('0' <= *str && *str <= '9') {
> if (integer_part) {
> - i = i * 10 + *str - '0';
> + i = i * 10 + (*str - '0');

What's the point in changing this line?

> + if (i > limit)
> + return -ERANGE;
> } else {
> - f += fract_mult * (*str - '0');
> + f += (s64)fract_mult * (*str - '0');
> fract_mult /= 10;
> }
> } else if (*str == '\n') {

> }

...

> + *integer = (int)i;
> + *fract = (int)f;

Why do you need explicit castings?

...

Do you know about APIs in overflow.h? I think you wanted to use something
from there.

--
With Best Regards,
Andy Shevchenko