Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cursor position silently wraps around during write to Vec<u8> #36884

Closed
ghost opened this issue Oct 1, 2016 · 4 comments
Closed

Cursor position silently wraps around during write to Vec<u8> #36884

ghost opened this issue Oct 1, 2016 · 4 comments
Labels
T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.

Comments

@ghost
Copy link

ghost commented Oct 1, 2016

use std::io::{Cursor, Write};

fn main() {
    let v = vec![0];
    let mut c = Cursor::new(v);
    c.set_position(std::usize::MAX as u64 + 1);
    c.write(&[1]).unwrap();
    println!("{:?}", c.into_inner());
}

On 32-bit platform it currently prints: "[1]". It should fail or panic instead.

@TimNN TimNN added the A-libs label Oct 1, 2016
@abonander
Copy link
Contributor

@abonander
Copy link
Contributor

Also, I don't know why zero-filling is necessary, as they'll just be immediately overwritten. If it's an issue of panic safety, then there's probably a better way to do it.

@ghost
Copy link
Author

ghost commented Oct 2, 2016

The cursor implementation for vector is similar to file operations. If cursor
position is set past the current size of vector, then on subsequent write,
first the hole between vector length and position is filled with zeros.
Ensuring that the position is guaranteed to be within vector (or one past the
end).

Second, the data is actually written starting from cursor position, extending
vector even further. This is potentially unfortunate allocation-wise, but no
data is overwritten (when resize actually took place).

In general the Cursor interface seems potentially error prone for in-memory
buffers due to mismatch between u64 and usize. It works fine for files, but
that's it.

Manishearth added a commit to Manishearth/rust that referenced this issue Oct 4, 2016
…xcrichton

Check for overflow in Cursor<Vec<u8>>::write.

Ensure that cursor position fits into usize, before proceeding with
write. Fixes issue rust-lang#36884.
@steveklabnik steveklabnik added T-libs-api Relevant to the library API team, which will review and decide on the PR/issue. and removed A-libs labels Mar 24, 2017
@Mark-Simulacrum
Copy link
Member

This is no longer an issue, since we check for the potential overflow and return an error instead:

let pos: usize = self.position().try_into().map_err(|_| {
. Closing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
T-libs-api Relevant to the library API team, which will review and decide on the PR/issue.
Projects
None yet
Development

No branches or pull requests

4 participants