|
|
Log in / Subscribe / Register

UB in Rust vs C

UB in Rust vs C

Posted Aug 16, 2024 0:05 UTC (Fri) by tialaramex (subscriber, #21167)
In reply to: UB in Rust vs C by ralfj
Parent article: Standards for use of unsafe Rust in the kernel

> it is considered a bug when `+` overflows and using `wrapping_add` is how you mark this as not-a-bug

I assume Rust-for-Linux is in practice never compiled in debug mode, if so as we start to see some more Linux developers with C experience deciding to write some Rust it will be important to correct the C instinct to assume that adding N in the usual way "just wraps" because in practice adding N really does just wrap in Rust (because by default the optimized build wraps on overflow), but as you say it's a bug to overflow, you should explicitly write what you meant even though that produces the same machine code, it makes maintenance much more robust.


to post comments

UB in Rust vs C

Posted Aug 16, 2024 9:20 UTC (Fri) by farnz (subscriber, #17727) [Link] (1 responses)

It's complicated, because Rust defines addition as "either wrap (in twos' complement if signed) or panic", and says that which of those behaviours you get is unspecified, just that it'll be one of those two. So, while it's a bug to depend on wrapping without using wrapping_add etc or Wrapping<T> to indicate that it's deliberate, it's not as bad as it is in C, where it's UB.

With that said, the kernel's current compiler flags for Rust include -C overflow-checks so that the chosen behaviour is locked at "panic", even in release mode, if the CONFIG_RUST_OVERFLOW_CHECKS option is set. Hopefully enough developers leave this at the current default that Rust for Linux code never actually has a dependency on wrapping behaviour that's not expressed in code.

UB in Rust vs C

Posted Aug 16, 2024 10:14 UTC (Fri) by tialaramex (subscriber, #21167) [Link]

Oh that's actually really good news, thanks


Copyright © 2026, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds