Skip to content

Windows: File::truncate silently wraps u64 > i64::MAX via as-cast #449

@SebTardif

Description

@SebTardif

Bug

In library/std/src/sys/fs/windows.rs:517-518, File::truncate() casts the u64 size to i64 using as:

pub fn truncate(&self, size: u64) -> io::Result<()> {
    let info = c::FILE_END_OF_FILE_INFO { EndOfFile: size as i64 };

For values > i64::MAX (9.2 EB), this silently wraps to a negative number, causing unpredictable behavior from SetFileInformationByHandle.

The Unix implementation correctly uses try_into() with an error:

pub fn truncate(&self, size: u64) -> io::Result<()> {
    let size: off64_t = size.try_into().map_err(|e| io::Error::new(...))?;

Fix

Replace size as i64 with size.try_into() matching the Unix behavior.

Impact

Calling file.set_len(u64::MAX) or any value > i64::MAX on Windows silently corrupts the file length instead of returning an error. Cross-platform code that works correctly on Unix may silently corrupt files on Windows.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-libsStandard libraryI-wrongWrong result or data corruptionO-windowsWindows-specificP-mediumMedium impact: affects specific usage patternsbugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions