Skip to content

drivers: fix overflow in ClockDevice.sleep_ms - #1088

Open
matpala wants to merge 2 commits into
ZigEmbeddedGroup:mainfrom
matpala:drivers/clock-sleep-ms
Open

matpala wants to merge 2 commits into
ZigEmbeddedGroup:mainfrom
matpala:drivers/clock-sleep-ms

Conversation

@matpala

@matpala matpala commented Oct 13, 2026

Copy link
Copy Markdown
Contributor

ClockDevice.sleep_ms computed time_ms * 1000 in u32, which overflows from 4,294,968 ms (about 71.6 minutes): a panic in Debug/ReleaseSafe and illegal behavior in ReleaseFast/ReleaseSmall. This converts in u64 instead, still with a single sleep_us call.

The conversion uses shifts (1000 = 1024 - 16 - 8) rather than a multiply: on AVR, which doesn't link compiler_rt, a runtime u32 multiply needs __mulsi3 and a u64 one __muldi3, so sleep_ms with a runtime argument (e.g. TLV493D) didn't link there. Checked with Zig 0.17.0, ReleaseSmall, on the ATmega328P: the shift version links and has no multiply calls.

Adds a test for 0, 1, the last value that fit, the first that overflowed, and maxInt(u32); it fails on the current code with integer overflow.

@mattnite

Copy link
Copy Markdown
Contributor

Did you try enabling compiler_rt?

@matpala

matpala commented Oct 13, 2026

Copy link
Copy Markdown
Contributor Author

Yes. With .bundle_compiler_rt = true on the ATmega328P, compiler_rt itself fails to build with Zig 0.17.0 (address space 'flash' cannot cast into address space 'generic', ziglang/zig#37090, still open), which is why the AVR ports turn it off.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants