Fix integer overflow in string.IndexOf range validation#128191
Conversation
The validation `startIndex + count > Length` can overflow when comparisonType is OrdinalIgnoreCase and startIndex + count exceeds int.MaxValue. Change it to `count > Length - startIndex` to avoid the overflow. This ensures an ArgumentOutOfRangeException is thrown when startIndex + count exceeds int.MaxValue. Also update IndexOf(Rune, int, int, StringComparison) to use ThrowIfNegative and ThrowIfGreaterThan consistently with the char overload.
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Updates string.IndexOf argument validation to avoid overflow and produce more accurate ArgumentOutOfRangeException parameter names, with added regression tests.
Changes:
- Adjusted
startIndex/countrange checks to usecount > Length - startIndexinstead ofstartIndex + count > Length. - Added tests asserting correct
ArgumentOutOfRangeExceptionparameter names forIndexOfoverloads withStringComparison.OrdinalIgnoreCaseandRune.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| src/libraries/System.Runtime/tests/System.Runtime.Tests/System/StringTests.cs | Adds regression tests for argument validation/paramName behavior in IndexOf overloads. |
| src/libraries/System.Private.CoreLib/src/System/String.Searching.cs | Fixes validation to be overflow-safe and to surface correct failing parameter names (startIndex vs count). |
|
Tagging subscribers to this area: @dotnet/area-system-runtime |
MihaZupan
left a comment
There was a problem hiding this comment.
Thanks
Looks like tons of these methods also skip all arg validation if the string is empty for some reason.
Btw you can do Closes #123 in the PR description so that the issue gets automatically closed when a PR is merged
@MihaZupan Thank you! I didn't realize that's how |
Closes #128192
This PR change
string.IndexOfrange validation fromcount + startIndex > Lengthtocount > Length - startIndexto avoid the overflow.This ensures an
ArgumentOutOfRangeExceptionis thrown whenstartIndex + countexceedsint.MaxValuewhen comparisonType isStringComparison.OrdinalIgnoreCase.Also applied the same fix to
IndexOf(Rune, int, int, StringComparison)and updated it to useArgumentOutOfRangeException.ThrowIfNegativeandArgumentOutOfRangeException.ThrowIfGreaterThanconsistently with the char overload.