top | item 46215263

(no title)

ykonstant | 2 months ago

I need to check the rust parts of the kernel, I presume there is significant amounts of unsafe. Is unsafe Rust a bit better nowadays? I remember a couple of years ago people complained that unsafe is really hard to write and very "un-ergonomic".

discuss

order

jenadine|2 months ago

The idea is that most of the unsafe code to interact with the C API of the kernel is abstracted in the kernel crate, and the drivers themselves should use very little amount of unsafe code, if any.

IshKebab|2 months ago

I don't think unsafe Rust has gotten any easier to write, but I'd also be surprised if there was much unsafe except in the low-level stuff (hard to write Vec without unsafe), and to interface with C which is actually not hard to write.

Mostly Rust has been used for drivers so far. Here's the first Rust driver I found:

https://github.com/torvalds/linux/blob/2137cb863b80187103151...

It has one trivial use of `unsafe` - to support Send & Sync for a type - and that is apparently temporary. Everything else uses safe APIs.

johncolanduoni|2 months ago

Drivers are interesting from a safety perspective, because on systems without an IOMMU sending the wrong command to devices can potentially overwrite most of RAM. For example, if the safe wrappers let you write arbitrary data to a PCIe network card’s registers you could retarget a receive queue to the middle of a kernel memory page.

jdub|2 months ago

    unsafe {
        // this is normal Rust code, you can write as much of it as you like!
        // (and you can bend some crucial safety rules)
        // but try to limit and document what you put inside an unsafe block.
        // then wrap it in a safe interface so no one has to look at it again
    }

Cthulhu_|2 months ago

Wouldn't that be by design? If it isn't pleasant, people will avoid using it if they can.

(but as others pointed out, unsafe should only be used at the 'edges', the vast majority should never need to use unsafe)