[PATCH v2 12/13] rust: support the new `-Zub-checks` flag

From: Miguel Ojeda
Date: Tue Jul 09 2024 - 12:10:15 EST


Rust 1.79.0 has introduced a new codegen flag, `-Zub-checks` [1], to
allow to independently configure (from `-Cdebug-assertions`) whether the
extra runtime checks for UB are emitted, in a similar fashion to
`-Coverflow-checks`.

This allows to configure the kernel with only the UB checks enabled,
but not the `debug_assert!`s; or vice versa, e.g. [2].

It also showcases how `RUSTC_VERSION` and the Kbuild macros, introduced
in the previous commit, can be used.

Link: https://github.com/rust-lang/compiler-team/issues/725 [1]
Link: https://godbolt.org/z/jY69ezx5K [2]
Reviewed-by: Finn Behrens <me@xxxxxxxxxx>
Tested-by: Benno Lossin <benno.lossin@xxxxxxxxx>
Tested-by: Andreas Hindborg <a.hindborg@xxxxxxxxxxx>
Signed-off-by: Miguel Ojeda <ojeda@xxxxxxxxxx>
---
Makefile | 9 +++++++--
lib/Kconfig.debug | 18 ++++++++++++++++++
2 files changed, 25 insertions(+), 2 deletions(-)

diff --git a/Makefile b/Makefile
index 9044fdb9adb1..4cf3b9799ec9 100644
--- a/Makefile
+++ b/Makefile
@@ -821,10 +821,15 @@ KBUILD_CFLAGS += -Os
KBUILD_RUSTFLAGS += -Copt-level=s
endif

-# Always set `debug-assertions` and `overflow-checks` because their default
-# depends on `opt-level` and `debug-assertions`, respectively.
+# Always set `debug-assertions` because its default depends on `opt-level`.
KBUILD_RUSTFLAGS += -Cdebug-assertions=$(if $(CONFIG_RUST_DEBUG_ASSERTIONS),y,n)
+
+# Always set `overflow-checks` and `ub-checks` because their default depends on
+# `debug-assertions`.
KBUILD_RUSTFLAGS += -Coverflow-checks=$(if $(CONFIG_RUST_OVERFLOW_CHECKS),y,n)
+ifeq ($(call rustc-min-version, 107900),y)
+KBUILD_RUSTFLAGS += -Zub-checks=$(if $(CONFIG_RUST_UNDEFINED_BEHAVIOR_CHECKS),y,n)
+endif

# Tell gcc to never replace conditional load with a non-conditional one
ifdef CONFIG_CC_IS_GCC
diff --git a/lib/Kconfig.debug b/lib/Kconfig.debug
index 59b6765d86b8..6b4f512f9e13 100644
--- a/lib/Kconfig.debug
+++ b/lib/Kconfig.debug
@@ -3020,6 +3020,24 @@ config RUST_OVERFLOW_CHECKS

If unsure, say Y.

+config RUST_UNDEFINED_BEHAVIOR_CHECKS
+ bool "Undefined Behavior checks"
+ depends on RUST && RUSTC_VERSION >= 107900
+ help
+ Enables rustc's `-Zub-checks` codegen option.
+
+ This flag allows you to control whether additional runtime checks that
+ detect some causes of Undefined Behavior at runtime will be emitted.
+ When enabled, a Rust panic will occur if UB is detected.
+
+ All checks are generated on a best-effort basis; even if there is a check
+ implemented for some cause of Undefined Behavior, it may be possible for
+ the check to not fire.
+
+ Note that this will apply to all Rust code, including `core`.
+
+ If unsure, say N.
+
config RUST_BUILD_ASSERT_ALLOW
bool "Allow unoptimized build-time assertions"
depends on RUST
--
2.45.2