rust-lang / libc

Raw bindings to platform APIs for Rust
https://docs.rs/libc
Apache License 2.0
2.1k stars 1.04k forks source link

Make the `Debug` implementation for `union`s always opaque #4118

Open tgross35 opened 6 days ago

tgross35 commented 6 days ago

We currently have a lot of unsafe reads of unions fields which is source of easy unsoundness. Let's make things easier while avoiding this completely:

  1. Change s_no_extra_traits to do an opaque Debug implementation on unions, here https://github.com/rust-lang/libc/blob/2f931d9d5789039fdde0419df79eee92c29b1270/src/macros.rs#L122-L129
  2. Delete all existing Debug implementations on unions (which will now conflict).

The implementation is easy, this will just print the types as some_union { .. }:

#[cfg(feature = "extra_traits")]
impl ::core::fmt::Debug for $i {
    fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
        f.debug_struct(stringify!($i)).finish_non_exhaustive()
    }
}

We can backport this to libc-0.2 since it fixes some soundness issues without breaking any API.