mbox series

[0/4] hwmon: Fix underflows seen when writing limit attributes

Message ID 20240707144730.1490208-1-linux@roeck-us.net (mailing list archive)
Headers show
Series hwmon: Fix underflows seen when writing limit attributes | expand

Message

Guenter Roeck July 7, 2024, 2:47 p.m. UTC
DIV_ROUND_CLOSEST() after kstrtol() results in an underflow if a large
negative number such as -9223372036854775808 is provided by the user.
Fix it by reordering clamp_val() and DIV_ROUND_CLOSEST() operations.

The problem was fixed using the following a coccinelle script. The python
arithmetic is used to fold constant multiplications.

@lc@
expression range, val, err, buf, res;
position p;
expression divisor, l1, l2;
@@
	err = \( kstrtol \| kstrtoint \| kstrtos64 \)(buf, range, &val);
	... when != val
	res = clamp_val(DIV_ROUND_CLOSEST@p(val, divisor), l1, l2);

@script:python mult@
l1 << lc.l1;
l2 << lc.l2;
d << lc.divisor;
m1;
m2;
de;
l1e;
l2e;
@@

coccinelle.dn = d.isnumeric()
coccinelle.l1e = l1.replace(' ', '')
coccinelle.l2e = l2.replace(' ', '')
coccinelle.l1n = l1.isnumeric() or (coccinelle.l1e[0] == '-' and coccinelle.l1e[1:].isnumeric())
coccinelle.l2n = l2.isnumeric() or (coccinelle.l2e[0] == '-' and coccinelle.l2e[1:].isnumeric())

if coccinelle.dn and coccinelle.l1n and coccinelle.l2n:
    coccinelle.m1 = str(eval(l1) * int(d))
    coccinelle.m2 = str(eval(l2) * int(d))
elif coccinelle.dn and coccinelle.l1n:
    coccinelle.m1 = str(eval(l1) * int(d))
    coccinelle.m2 = l2 + ' * ' + d
elif coccinelle.dn and coccinelle.l2n:
    coccinelle.m1 = l1 + ' * ' + d
    coccinelle.m2 = str(eval(l2) * int(d))
else:
    coccinelle.m1 = l1 + ' * ' + d
    coccinelle.m2 = l2 + ' * ' + d

@@
identifier mult.m1, mult.m2;
position lc.p;
expression res, val;
expression divisor, l1, l2;
@@
- res = clamp_val(DIV_ROUND_CLOSEST@p(val, divisor), l1, l2);
+ res = DIV_ROUND_CLOSEST(clamp_val(val, m1, m2), divisor);

----------------------------------------------------------------
Guenter Roeck (4):
      hwmon: (adc128d818) Fix underflows seen when writing limit attributes
      hwmon: (lm95234) Fix underflows seen when writing limit attributes
      hwmon: (nct6775-core) Fix underflows seen when writing limit attributes
      hwmon: (w83627ehf) Fix underflows seen when writing limit attributes

 drivers/hwmon/adc128d818.c   | 4 ++--
 drivers/hwmon/lm95234.c      | 9 +++++----
 drivers/hwmon/nct6775-core.c | 2 +-
 drivers/hwmon/w83627ehf.c    | 4 ++--
 4 files changed, 10 insertions(+), 9 deletions(-)