Stream: t-lang/wg-unsafe-code-guidelines

Topic: bincode


Jethro (Jan 27 2019 at 08:07, on Zulip):

is this safe? https://github.com/TyOverby/bincode/blob/72bb6ef050f065161d476ce2ee0231140eb08d2a/src/de/read.rs#L144-L149

rkruppe (Jan 27 2019 at 11:22, on Zulip):

I don't think it is. If self.reader.read_exact doesn't fill the buffer (e.g. there is an I/O error while reading, or it's implemented incorrectly, or it panics for some reason) then this code exposes uninitialized bytes to the world. And while it's still up for debate whether there are some things that can be done in careful unsafe code with uninitialized bytes, it's certain that uninitialized memory can lead to UB when used in unsuspecting safe code.

rkruppe (Jan 27 2019 at 11:23, on Zulip):

It also exposes uninitialized memory to the implementation of read_exact so if that reads from the buffer (which it "shouldn't" but safe code can do it) it'll get uninitialized bytes too, with the same consequences.

Jethro (Jan 27 2019 at 11:50, on Zulip):

yeah I was thinking the same

Jethro (Jan 27 2019 at 11:56, on Zulip):

I would like it to be the case that passing a slice of uninitialized memory to read, read_exact, etc. is not UB

RalfJ (Jan 27 2019 at 13:54, on Zulip):

for this to work with unknown implementations of Read, we'd have to make these functions unsafe

Jethro (Jan 27 2019 at 15:27, on Zulip):

Oh yeah I guess you're right. This seems to be a compelling argument for &uninit

nagisa (Jan 27 2019 at 15:30, on Zulip):

What is usually done is set_len after you know the length.

nagisa (Jan 27 2019 at 15:31, on Zulip):

but then you need to figure out how to get yourself the buffer before set_len is made :slight_smile:

RalfJ (Jan 27 2019 at 18:03, on Zulip):

Oh yeah I guess you're right. This seems to be a compelling argument for &uninit

an alternative might be to use &mut [MaybeUninit<u8>]

RalfJ (Jan 27 2019 at 18:03, on Zulip):

that doesn't encode that the data will be initialized, but it also doesn't require an all-new reference type

Last update: Nov 20 2019 at 13:50UTC