From bef6c4c11a9e98cde3cf6ec52608e888468ad15c Mon Sep 17 00:00:00 2001 From: James Newton-King Date: Sat, 30 Mar 2013 17:39:08 +1300 Subject: [PATCH] -Fixed integer parsing overflow bug --- .../JsonTextReaderTest.cs | 1 + Src/Newtonsoft.Json/Utilities/ConvertUtils.cs | 31 +++++++++++-------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs index e4bf2e15..6eea9951 100644 --- a/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs +++ b/Src/Newtonsoft.Json.Tests/JsonTextReaderTest.cs @@ -1134,6 +1134,7 @@ bye", reader.Value); Assert.AreEqual(int.MinValue, reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader(long.MaxValue.ToString())); + ExceptionAssert.Throws("Arithmetic operation resulted in an overflow.", () => reader.ReadAsInt32()); reader = new JsonTextReader(new StringReader("1E-06")); ExceptionAssert.Throws("Input string was not in a correct format.", () => reader.ReadAsInt32()); diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index 8dd01558..f03aab77 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -573,7 +573,7 @@ namespace Newtonsoft.Json.Utilities if (isNegative) { - // just a negative sign + // text just a negative sign if (length == 1) throw new FormatException("Input string was not in a correct format."); @@ -581,22 +581,27 @@ namespace Newtonsoft.Json.Utilities length--; } - int result = 0; - int end = start + length; - for (int i = start; i < end; i++) + checked { - char c = value[i]; + int result = 0; + int end = start + length; + for (int i = start; i < end; i++) + { + char c = value[i]; - if (!(c >= '0' && c <= '9')) - throw new FormatException("Input string was not in a correct format."); + if (c < '0' || c > '9') + throw new FormatException("Input string was not in a correct format."); - result = 10 * result + (c - 48); + result = 10*result + -(c - 48); + } + + // go from negative to positive to avoids overflow + // negative can be slightly bigger than positive + if (!isNegative) + result = -result; + + return result; } - - if (isNegative) - result = 0 - result; - - return result; } } }