Skip to content

Bug: Utils.ReadAllBytes reads too few bytes when position > 0 #211

@dkropachev

Description

@dkropachev

Description

Utils.ReadAllBytes(Stream stream, int position) has an off-by-one bug in the byte count passed to ReadExactly:

// src/Cassandra/Utils.cs:187-192
public static byte[] ReadAllBytes(Stream stream, int position)
{
    var buffer = new byte[stream.Length - position];
    stream.Position = position;
    stream.ReadExactly(buffer, 0, buffer.Length - position); // BUG
    return buffer;
}

buffer.Length is already stream.Length - position, so buffer.Length - position evaluates to stream.Length - 2 * position. When position > 0, this reads fewer bytes than the buffer was allocated for, leaving trailing zeroes and silently returning corrupt data.

Example: stream.Length = 10, position = 4 → buffer is 6 bytes, but only 2 bytes are read.

Current impact

Low — all current callers pass position = 0, which makes the math correct by coincidence. The bug is latent but will trigger if anyone calls this method with a non-zero position in the future.

Fix

Change the third argument from buffer.Length - position to buffer.Length:

stream.ReadExactly(buffer, 0, buffer.Length);

This bug predates the next-major/drop-old-runtimes branch (the old Utils.ReadExactly wrapper had the same wrong count), but now is a good time to fix it since the method is already being touched.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions