Re: Rust kernel policy

From: Dan Carpenter
Date: Fri Feb 21 2025 - 04:52:42 EST


On Thu, Feb 20, 2025 at 04:40:02PM +0100, Martin Uecker wrote:
> I mean "memory safe" in the sense that you can not have an OOB access
> or use-after-free or any other UB. The idea would be to mark certain
> code regions as safe, e.g.
>
> #pragma MEMORY_SAFETY STATIC

Could we tie this type of thing to a scope instead? Maybe there
would be a compiler parameter to default on/off and then functions
and scopes could be on/off if we need more fine control.

This kind of #pragma is basically banned in the kernel. It's used
in drivers/gpu/drm but it disables the Sparse static checker.

> unsigned int foo(unsigned int a, unsigned int b)
> {
> return a * b;
> }
>
> static int foo(const int a[static 2])
> {
> int r = 0;
> if (ckd_mul(&r, a[0], a[1]))
> return -1;
> return r;
> }
>
> static int bar(int x)
> {
> int a[2] = { x, x };
> return foo(a);
> }
>
>
> and the compiler would be required to emit a diagnostic when there
> is any operation that could potentially cause UB.

I'm less convinced by the static analysis parts of this... The kernel
disables checking for unsigned less than zero by default because there
are too many places which do:

if (x < 0 || x >= 10) {

That code is perfectly fine so why is the compiler complaining? But at
the same time, being super strict is the whole point of Rust and people
love Rust so maybe I have misread the room.

>
> I would also have a DYNAMIC mode that traps for UB detected at
> run-time (but I understand that this is not useful for the kernel).

No, this absolutely is useful. This is what UBSan does now. You're
basically talking about exception handling. How could that not be
the most useful thing ever?

regards,
dan carpenter