[BUG] Potential undefined behavior in calc_log2() due to missing zero check before __builtin_clz

0 views
Skip to first unread message

Huazhao Chen

unread,
Nov 6, 2025, 9:42:20 AMNov 6
to embox...@googlegroups.com
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

Anton Bondarev

unread,
Nov 11, 2025, 3:24:49 AMNov 11
to embox...@googlegroups.com
Hello Huazhao Chen

Thank you for the report and suggestions!
Would you please create a PR on embox's github with your changes?

Best regards,
Anton Bondarev


чт, 6 нояб. 2025 г. в 17:42, Huazhao Chen <lyic...@gmail.com>:
--
You received this message because you are subscribed to the Google Groups "embox-devel" group.
To unsubscribe from this group and stop receiving emails from it, send an email to embox-devel...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/embox-devel/8DC873F6-AE6B-4616-A00E-06ACF6C6AA24%40gmail.com.
Reply all
Reply to author
Forward
0 new messages