lucenenet icon indicating copy to clipboard operation
lucenenet copied to clipboard

negative readCount in IndexInputStream.Read

Open ChaoMaWisetech opened this issue 11 months ago • 0 comments

Is there an existing issue for this?

  • [x] I have searched the existing issues

Describe the bug

The readCount might be negative in IndexInputStream.Read and the exception is thrown

  • Message :Non-negative number required. Parameter name: length
  • StackTrace: at J2N.IO.MemoryMappedFiles.MemoryMappedViewByteBuffer.Get(Byte[] destination, Int32 offset, Int32 length), at Lucene.Net.Replicator.IndexInputStream.Read(Byte[] buffer, Int32 offset, Int32 count),
public override int Read(byte[] buffer, int offset, int count)
{
	int remaining = (int) (input.Length - input.Position); // remaining might be a negative number due to (int) longNum
	int readCount = Math.Min(remaining, count); //  readCount might be a negative number
	input.ReadBytes(buffer, offset, readCount);
	return readCount;
}

a possible fix could be

public override int Read(byte[] buffer, int offset, int count)
{
	long remaining = input.Length - input.Position; 
	int readCount = (int)Math.Min(remaining, count);
	input.ReadBytes(buffer, offset, readCount);
	return readCount;
}

Expected Behavior

No response

Steps To Reproduce

[Test]
public void IndexInputStream_ReadIssueWhenInputLengthGreaterThanIntMax()
{
	var mockIndexInput = new Mock<IndexInput>(MockBehavior.Strict, "abc");
	mockIndexInput.Setup(x => x.Length).Returns(long.MaxValue).Verifiable();
	mockIndexInput.Setup(x => x.Position).Returns(0).Verifiable();
	mockIndexInput.Setup(x => x.ReadBytes(It.IsAny<byte[]>(), It.IsAny<int>(), It.Is<int>(v => v < 0)))
		.Throws(new ArgumentException("length cannot be negative"))
		.Verifiable();

	var indexInputStream = new IndexInputStream(mockIndexInput.Object);

	Assert.That(() => indexInputStream.Read(new byte[1], 0, 1), Throws.InstanceOf<ArgumentException>());
	mockIndexInput.VerifyAll();
}

Exceptions (if any)

No response

Lucene.NET Version

No response

.NET Version

No response

Operating System

No response

Anything else?

No response

ChaoMaWisetech avatar May 09 '25 02:05 ChaoMaWisetech