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.
Description
Utils.ReadAllBytes(Stream stream, int position)has an off-by-one bug in the byte count passed toReadExactly:buffer.Lengthis alreadystream.Length - position, sobuffer.Length - positionevaluates tostream.Length - 2 * position. Whenposition > 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 - positiontobuffer.Length:This bug predates the
next-major/drop-old-runtimesbranch (the oldUtils.ReadExactlywrapper had the same wrong count), but now is a good time to fix it since the method is already being touched.