[PATCH] cmd: setexpr: reject division and modulo by zero
Naveen Kumar Chaudhary
naveen.osdev at gmail.com
Wed Jul 8 16:33:37 CEST 2026
The '/' and '%' arms of the operator switch in do_setexpr() perform
a / b and a % b directly on the user-supplied ulongs with no check
that b is non-zero. The consequences are architecture-dependent:
- On x86 and sandbox, integer divide-by-zero raises an exception
(#DE / SIGFPE) which aborts the shell.
- On arm64, arm, and RISC-V, the UDIV/SDIV instructions are defined
to return 0 on a zero divisor and do not trap, so 'setexpr x 10
/ 0' silently succeeds and stores 0 into the environment
variable, which is a plausible-looking but garbage result.
Neither behaviour is acceptable for a scripting primitive. Check b
before dividing and print a clear error, returning failure so
scripts can detect it.
++++++ Before Fix ++++++++
=> setexpr x 0xa / 0
=> printenv x
x=0
++++++ After Fix +++++++++
=> setexpr x 0xa / 0
Error: division by zero
=> setexpr x 0xa % 0
Error: modulo by zero
=>
Signed-off-by: Naveen Kumar Chaudhary <naveen.osdev at gmail.com>
---
cmd/setexpr.c | 8 ++++++++
1 file changed, 8 insertions(+)
diff --git a/cmd/setexpr.c b/cmd/setexpr.c
index c45fa85c887..38a7fbeb86c 100644
--- a/cmd/setexpr.c
+++ b/cmd/setexpr.c
@@ -517,9 +517,17 @@ static int do_setexpr(struct cmd_tbl *cmdtp, int flag, int argc,
value = a * b;
break;
case '/':
+ if (b == 0) {
+ printf("Error: division by zero\n");
+ return 1;
+ }
value = a / b;
break;
case '%':
+ if (b == 0) {
+ printf("Error: modulo by zero\n");
+ return 1;
+ }
value = a % b;
break;
default:
--
2.43.0
More information about the U-Boot
mailing list