From 54b70bd6354873c706fc34a6310294e5018628fd Mon Sep 17 00:00:00 2001 From: Curt Hagenlocher Date: Sat, 5 Dec 2026 06:24:25 -0800 Subject: [PATCH] fix: Size decimal string buffers by the value rather than the type's precision (#546) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ### What's changed? Formatting a decimal as a string (`GetString`, and so `ToString` on the decimal arrays) and parsing one from a string sized their buffers by the type's precision and scale. On .NET Core the buffers were on the stack, so a type with a very large precision or scale could exhaust it. - The buffers are now sized by the digits the value can have. A value of a given byte width has at most 2.5 digits per byte, plus any zeros the scale adds. - Buffers of up to 256 chars stay on the stack; larger ones go on the heap. Sizes are computed so they can't overflow. - On .NET Framework the buffers were already on the heap, but were sized by the precision; they are now sized the same way. The precision is still used to reject values with too many digits, and results are unchanged. ### Testing New tests in `DecimalUtilityTests` format and parse values with a precision of up to `int.MaxValue` and a scale of 1,000,000, at byte widths 4, 8, 16 and 32, and format the largest and smallest value of each width with a very large precision. All of `Apache.Arrow.Tests` passes on net8.0, net462 and net472. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_012dFdcrBz22tRjiyNwBd7VB --------- Co-authored-by: Claude Opus 5.5 (cherry picked from commit 266791f0efe81d88c4f8a8f39a8b7c9fff40ccfe) --- src/Apache.Arrow/DecimalUtility.cs | 73 +++++++++-- .../Apache.Arrow.Tests/DecimalUtilityTests.cs | 124 ++++++++++++++++++ 2 files changed, 189 insertions(+), 8 deletions(-) diff --git a/src/Apache.Arrow/DecimalUtility.cs b/src/Apache.Arrow/DecimalUtility.cs index 968894a5..e606e774 100644 --- a/src/Apache.Arrow/DecimalUtility.cs +++ b/src/Apache.Arrow/DecimalUtility.cs @@ -192,6 +192,44 @@ private static bool TryGetDecimalViaBigInteger(ReadOnlySpan value, int sca } } + // The most chars formatting or parsing a decimal puts on the stack + private const int StackAllocThreshold = 256; + + /// + /// The most decimal digits a value of bytes can have: a byte + /// holds fewer than 2.5 digits. + /// + private static int MaxDigits(int byteWidth) => byteWidth * 5 / 2 + 1; + + /// + /// The zeros to append to the digits of to give it + /// digits after the point. The scale comes from the type, which + /// can come from untrusted data, so this doesn't pad further than any value can use: a + /// nonzero value padded more than the width holds overflows, and padding zero changes + /// nothing. + /// + private static int ParsePadding(string value, int scale, int neededScale, int byteWidth) + { + int padding = scale - neededScale; + if (padding <= MaxDigits(byteWidth)) + { + return padding; + } + + foreach (char c in value) + { + if (c > '0' && c <= '9') + { + throw new OverflowException($"Decimal size greater than {byteWidth} bytes: {value} with scale {scale}"); + } + if (c != '0' && c != '.' && c != '-' && c != '+') + { + throw new ArgumentException($"Unable to parse {value} as decimal"); + } + } + return 0; + } + #if NETCOREAPP internal unsafe static string GetString(in ArrowBuffer valueBuffer, int index, int precision, int scale, int byteWidth) { @@ -209,8 +247,17 @@ internal unsafe static string GetString(in ArrowBuffer valueBuffer, int index, i integerValue = -integerValue; } + // The precision and scale come from the type, which can come from untrusted data, so + // size the buffer by the digits the value can have, and keep large buffers off the stack. int start = scale + 3; - Span result = stackalloc char[start + precision]; + long bufferLength = (long)start + Math.Min(precision, MaxDigits(byteWidth)); + if (bufferLength < 0 || bufferLength > int.MaxValue) + { + throw new OverflowException($"Value: {integerValue} cannot be formatted with scale {scale}"); + } + Span result = bufferLength <= StackAllocThreshold + ? stackalloc char[StackAllocThreshold].Slice(0, (int)bufferLength) + : new char[bufferLength]; if (!integerValue.TryFormat(result.Slice(start), out int charsWritten) || charsWritten > precision) { throw new OverflowException($"Value: {integerValue} cannot be formatted"); @@ -267,7 +314,14 @@ internal unsafe static string GetString(in ArrowBuffer valueBuffer, int index, i throw new OverflowException($"Value: {integerValue} cannot be formatted"); } - char[] result = new char[precision + 2]; + // The precision comes from the type, which can come from untrusted data, so size the + // buffer by the value instead. + long bufferLength = (long)Math.Max(charsWritten, scale) + 3; + if (bufferLength > int.MaxValue) + { + throw new OverflowException($"Value: {integerValue} cannot be formatted with scale {scale}"); + } + char[] result = new char[bufferLength]; int pos = 0; if (negative) { @@ -483,7 +537,11 @@ internal static void GetBytes(string value, int precision, int scale, int byteWi #if NETCOREAPP ReadOnlySpan src = value.AsSpan(); - Span buffer = stackalloc char[precision + start + 1]; + int padding = ParsePadding(value, scale, neededScale, byteWidth); + int bufferLength = value.Length + padding; + Span buffer = bufferLength <= StackAllocThreshold + ? stackalloc char[StackAllocThreshold] + : new char[bufferLength]; int end; if (pos == -1) @@ -498,10 +556,9 @@ internal static void GetBytes(string value, int precision, int scale, int byteWi end = src.Length - 1; } - while (neededScale < scale) + for (int i = 0; i < padding; i++) { buffer[end++] = '0'; - neededScale++; } if (!BigInteger.TryParse(buffer.Slice(0, end), out BigInteger bigInt)) @@ -514,7 +571,8 @@ internal static void GetBytes(string value, int precision, int scale, int byteWi throw new OverflowException("Could not extract bytes from integer value " + bigInt); } #else - char[] buffer = new char[precision + start + 1]; + int padding = ParsePadding(value, scale, neededScale, byteWidth); + char[] buffer = new char[value.Length + padding]; int end; if (pos == -1) @@ -529,10 +587,9 @@ internal static void GetBytes(string value, int precision, int scale, int byteWi end = value.Length - 1; } - while (neededScale < scale) + for (int i = 0; i < padding; i++) { buffer[end++] = '0'; - neededScale++; } if (!BigInteger.TryParse(new string(buffer, 0, end), out BigInteger bigInt)) diff --git a/test/Apache.Arrow.Tests/DecimalUtilityTests.cs b/test/Apache.Arrow.Tests/DecimalUtilityTests.cs index 7f2b3ef5..1f5f633f 100644 --- a/test/Apache.Arrow.Tests/DecimalUtilityTests.cs +++ b/test/Apache.Arrow.Tests/DecimalUtilityTests.cs @@ -15,6 +15,7 @@ using System; using System.Data.SqlTypes; +using System.Numerics; using Apache.Arrow.Types; using Xunit; @@ -188,6 +189,129 @@ private void TestFromString(string s, int precision, int scale, int byteWidth, s Assert.Equal(result, DecimalUtility.GetString(new ArrowBuffer(bytes), 0, precision, scale, byteWidth)); } + // The precision and scale come from the type, which may come from untrusted data, so + // they must not decide how much stack is used. + [Theory] + [InlineData(100_000_000)] + [InlineData(int.MaxValue)] + public void ToStringWithAHugePrecision(int precision) + { + foreach (int byteWidth in new[] { 4, 8, 16, 32 }) + { + var bytes = new byte[byteWidth]; + DecimalUtility.GetBytes(-100.12m, 9, 2, byteWidth, bytes); + Assert.Equal("-100.12", DecimalUtility.GetString(new ArrowBuffer(bytes), 0, precision, 2, byteWidth)); + } + } + + [Theory] + [InlineData(4)] + [InlineData(8)] + [InlineData(16)] + [InlineData(32)] + public void ToStringOfTheLargestValuesWithAHugePrecision(int byteWidth) + { + var largest = new byte[byteWidth]; + largest.AsSpan().Fill(0xFF); + largest[byteWidth - 1] = 0x7F; + var smallest = new byte[byteWidth]; + smallest[byteWidth - 1] = 0x80; + + foreach (byte[] bytes in new[] { largest, smallest }) + { + string digits = new BigInteger(bytes).ToString(); + string expected = digits.Substring(0, digits.Length - 1) + "." + digits.Substring(digits.Length - 1); + Assert.Equal(expected, DecimalUtility.GetString(new ArrowBuffer(bytes), 0, int.MaxValue, 1, byteWidth)); + } + } + + [Fact] + public void ToStringWithAHugeScale() + { + const int scale = 1_000_000; + foreach (int byteWidth in new[] { 4, 8, 16, 32 }) + { + var bytes = new byte[byteWidth]; + bytes[0] = 1; + string expected = "0." + new string('0', scale - 1) + "1"; + Assert.Equal(expected, DecimalUtility.GetString(new ArrowBuffer(bytes), 0, 10, scale, byteWidth)); + } + } + + [Theory] + [InlineData(100_000_000)] + [InlineData(int.MaxValue - 10)] + public void FromStringWithAHugePrecision(int precision) + { + foreach (int byteWidth in new[] { 4, 8, 16, 32 }) + { + var bytes = new byte[byteWidth]; + DecimalUtility.GetBytes("-100.12", precision, 3, byteWidth, bytes); + Assert.Equal("-100.120", DecimalUtility.GetString(new ArrowBuffer(bytes), 0, 10, 3, byteWidth)); + } + } + + // Parsing pads the digits with zeros up to the scale. Buffers of up to 256 chars are + // on the stack and larger ones on the heap, so cover both sides of that boundary. + [Theory] + [InlineData(254)] + [InlineData(255)] + [InlineData(256)] + [InlineData(257)] + [InlineData(1_000_000)] + public void FromStringPaddedToALargeScale(int scale) + { + string expected = "0." + new string('0', scale); + foreach (int byteWidth in new[] { 4, 8, 16, 32 }) + { + TestFromString("0", int.MaxValue, scale, byteWidth, expected); + } + } + + [Theory] + [InlineData(254)] + [InlineData(255)] + [InlineData(256)] + [InlineData(257)] + [InlineData(1_000_000)] + public void FromStringWithALongFraction(int scale) + { + string value = "0." + new string('0', scale - 1) + "1"; + foreach (int byteWidth in new[] { 4, 8, 16, 32 }) + { + TestFromString(value, int.MaxValue, scale, byteWidth, value); + } + } + + [Theory] + [InlineData(4)] + [InlineData(8)] + [InlineData(16)] + [InlineData(32)] + public void FromStringPaddedBeyondTheWidth_Throws(int byteWidth) + { + byte[] bytes = new byte[byteWidth]; + Assert.Throws(() => DecimalUtility.GetBytes("1", int.MaxValue, 300, byteWidth, bytes)); + } + + // Padding to a huge scale must not allocate for it: zero stays zero, a nonzero value + // overflows, and an invalid string is still rejected as one. + [Theory] + [InlineData(4)] + [InlineData(8)] + [InlineData(16)] + [InlineData(32)] + public void FromStringWithAHugeScale(int byteWidth) + { + byte[] bytes = new byte[byteWidth]; + bytes.AsSpan().Fill(0xFF); + DecimalUtility.GetBytes("-0.0", int.MaxValue, int.MaxValue, byteWidth, bytes); + Assert.All(bytes, b => Assert.Equal(0, b)); + + Assert.Throws(() => DecimalUtility.GetBytes("0.01", int.MaxValue, int.MaxValue, byteWidth, bytes)); + Assert.Throws(() => DecimalUtility.GetBytes("0x", int.MaxValue, int.MaxValue, byteWidth, bytes)); + } + [Theory] [InlineData("", 10, 2, 16, typeof(ArgumentException))] [InlineData("", 10, 2, 32, typeof(ArgumentException))]