Skip to content

Commit 19a0aaf

Browse files
committed
Zero out padding in custom Default trait implementations
Previously, we were using `std::mem::zeroed()` which unfortunately does not necessarily zero out padding. It'd be better if the padding is zeroed out because some libraries are sensitive to non-zero'd out bytes, especially when forward/backward compatability is involved. This commit ensures all bytes are zeroed out in custom Default trait implementations.
1 parent 910d2be commit 19a0aaf

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

src/codegen/mod.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2196,9 +2196,32 @@ impl CodeGenerator for CompInfo {
21962196

21972197
if needs_default_impl {
21982198
let prefix = ctx.trait_prefix();
2199+
let body = if ctx.options().rust_features().maybe_uninit {
2200+
quote! {
2201+
let mut s = ::#prefix::mem::MaybeUninit::<Self>::uninit();
2202+
unsafe {
2203+
::#prefix::ptr::write_bytes(s.as_mut_ptr(), 0, 1);
2204+
s.assume_init()
2205+
}
2206+
}
2207+
} else {
2208+
quote! {
2209+
unsafe {
2210+
let mut s: Self = ::#prefix::mem::uninitialized();
2211+
::#prefix::ptr::write_bytes(&mut s, 0, 1);
2212+
s
2213+
}
2214+
}
2215+
};
2216+
// Note we use `ptr::write_bytes()` instead of `mem::zeroed()` because the latter does
2217+
// not necessarily ensure padding bytes are zeroed. Some C libraries are sensitive to
2218+
// non-zero padding bytes, especially when forwards/backwards compatability is
2219+
// involved.
21992220
result.push(quote! {
22002221
impl #generics Default for #ty_for_impl {
2201-
fn default() -> Self { unsafe { ::#prefix::mem::zeroed() } }
2222+
fn default() -> Self {
2223+
#body
2224+
}
22022225
}
22032226
});
22042227
}

0 commit comments

Comments
 (0)