rust-pcap / pcap

Rust language pcap library
Apache License 2.0
620 stars 142 forks source link

Make struct repr transparent so transmute is safe. #242

Closed yotamofek closed 2 years ago

yotamofek commented 2 years ago

A lot of the code assumes that BpfInstruction and BpfProgram have the same size and layout as their raw counterparts, but they have to have a repr(transparent) for that to be safe.

The nomicon says:

When transmuting between different compound types, you have to make sure they are laid out the same way! If layouts differ, the wrong fields are going to get filled with the wrong data, which will make you unhappy and can also be UB (see above).

So how do you know if the layouts are the same? For repr(C) types and repr(transparent) types, layout is precisely defined. ...

Stargateur commented 2 years ago

Can you pin where there transmute are I didn't find them.

yotamofek commented 2 years ago

Here's one example: https://github.com/rust-pcap/pcap/blob/bc8a3c0cbb8bcf4365fd959b9c79b0729fd79482/src/lib.rs#L1392 It's not a std::mem::transmute, rather a pointer cast, but the structs still need to be transparent for it to be safe :)