Skip to content

Stop using mem::zeroed for FFI #136737

Closed
Closed
@joboet

Description

@joboet

Quite a lot of stds FFI code uses mem::zeroed to create empty structures that are to be filled by FFI. E.g.:

unsafe {
let mut t: SystemTime = mem::zeroed();
c::GetSystemTimePreciseAsFileTime(&mut t.t);
t
}

This is unnecessary, since the C code does not require the structures to be initialized (you wouldn't zero out structures in C either). Thus, this pattern just reduces performance, as it results in the initialization of potentially very large structures such as sockaddr_storage. We should get rid of this pattern and replace it with proper handling of uninitialized data through MaybeUninit.

Edit (after discussion below): In some instances one might decide to keep the zero-initialization behaviour, but I think this should still go through MaybeUninit::zeroed instead of mem::zeroed to make the point of initialization explicit (by introducing .assume_init() calls in the right places.

I'll probably do the network code myself (I want to clean some things up there anyway), but I'm happy to mentor you if you'd like to help with other instances such as the filesystem code (library/std/src/sys/pal/*/fs.rs). Just contact me here or on Zulip. The best way to find the pattern is probably by searching for mem::zeroed in library/std/src/sys.

Metadata

Metadata

Assignees

Labels

A-FFIArea: Foreign function interface (FFI)E-hardCall for participation: Hard difficulty. Experience needed to fix: A lot.E-help-wantedCall for participation: Help is requested to fix this issue.E-mentorCall for participation: This issue has a mentor. Use #t-compiler/help on Zulip for discussion.T-libsRelevant to the library team, which will review and decide on the PR/issue.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions