Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -3418,6 +3418,11 @@ private int ReadData()
{
_ps.bytesUsed = 0;
}
else if (bytesLeft < 0)
{
// This can happen when encoding switch causes bytePos to be calculated incorrectly for malformed data
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be better to detect this situation earlier to avoid introducing invalid ParsingState in the first place?

It is hard to reason about what all else can misbehave due to invalid ParsingState.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I agree and that was my hesitation in this comment too. It was worth a shot seeing if Copilot could tackle this, but I'm going to close the PR and leave the issue open for further investigation later.

Throw(SR.Xml_InvalidCharInThisEncoding);
}
else
{
Debug.Assert(_ps.bytes != null);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,5 +122,19 @@ public static void ReadWithIncompleteBytes()
XmlException ex = Assert.Throws<XmlException>(() => reader.Read());
Assert.Contains(_invalidCharMessageStart, ex.Message);
}

[Fact]
public static void ReadWithMalformedUtf8InXmlDeclaration()
{
// This test verifies the fix for issue dotnet/runtime#113061 where malformed UTF-8 sequences
// in XML declaration caused ArgumentOutOfRangeException instead of XmlException
string data = "<?xml version=\"1.0\xbf\"?>";
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
var reader = XmlReader.Create(new MemoryStream(bytes));

// Should throw XmlException, not ArgumentOutOfRangeException
XmlException ex = Assert.Throws<XmlException>(() => reader.Read());
Assert.Contains(_invalidCharInThisEncoding, ex.Message);
}
}
}
Loading