From: Lyican <
lyic...@gmail.com>
To:
embox...@googlegroups.com
Date: Thu, 6 Nov 2025 20:30:00 +0800
Subject: [BUG] Potential undefined behavior in calc_log2() due to missing zero check before __builtin_clz
Content-Type: text/plain; charset=UTF-8
Hello Embox developers,
I would like to report a potential undefined behavior in the function
`calc_log2()` found in:
embox/src/arch/arm/subarch/cortexm3/armv7m_cpu_cache.c
lines 35–37:
static inline uint32_t calc_log2(uint32_t val) {
return 31 - __builtin_clz(val);
}
According to GCC’s documentation, and the resolved bug
[PR101175 – "builtin_clz generates wrong bsr instruction"](
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101175),
the behavior of `__builtin_clz(x)` is *undefined when x == 0*.
In some cases, this can cause incorrect instruction selection or
unpredictable runtime behavior, especially on targets without a defined
behavior for zero operands (e.g., `bsr` on x86, or potential faults on ARM).
Although `calc_log2()` is designed for ARM Cortex-M3, the undefined
behavior remains relevant at the C semantic level. If this function is
ever called with `val == 0`, it would result in undefined behavior.
A simple fix would be to add a guard clause before the builtin call:
static inline uint32_t calc_log2(uint32_t val) {
if (val <= 1)
return 0;
return 31 - __builtin_clz(val);
}
This ensures correctness even when the input is zero or one, while
preserving the intended behavior for power-of-two inputs.
Best regards,
Huazhao Chen