From 19181c95d1b1cd3e1941ace4da3c1c5cbe073f98 Mon Sep 17 00:00:00 2001 From: Radhika Date: Tue, 27 Oct 2026 21:49:23 +0530 Subject: [PATCH 1/3] reject symbol ids and varints that overflow int in the binary reader --- .../com/amazon/ion/impl/IonCursorBinary.java | 23 ++- .../impl/IonReaderContinuableCoreBinary.java | 50 +++++-- .../IonReaderContinuableCoreBinaryTest.java | 132 ++++++++++++++++++ ...onReaderContinuableTopLevelBinaryTest.java | 33 +++++ 4 files changed, 226 insertions(+), 12 deletions(-) diff --git a/src/main/java/com/amazon/ion/impl/IonCursorBinary.java b/src/main/java/com/amazon/ion/impl/IonCursorBinary.java index 8555c03422..7175072b0b 100644 --- a/src/main/java/com/amazon/ion/impl/IonCursorBinary.java +++ b/src/main/java/com/amazon/ion/impl/IonCursorBinary.java @@ -810,6 +810,19 @@ private long slowReadVarUInt_1_0() { throw new IonException("Found a VarUInt that was too large to fit in a `long`"); } + /** + * Narrows the given symbol ID to an `int`, throwing if it does not fit. A symbol ID that does not fit in an `int` + * can never be mapped by a symbol table; wrapping it around would silently resolve it to a different symbol. + * @param sid the symbol ID. + * @return the symbol ID as an `int`. + */ + static int symbolIdToInt(long sid) { + if (sid < 0 || sid > Integer.MAX_VALUE) { + throw new IonException("Found a symbol ID that was too large to fit in an `int`."); + } + return (int) sid; + } + /** * Reads the header of an annotation wrapper. This must only be called when it is known that the buffer already * contains all the bytes in the header. Sets `valueMarker` with the start and end indices of the wrapped value. @@ -976,8 +989,12 @@ private boolean slowReadFieldName_1_0() { if (!fillAt(peekIndex, 2)) { return true; } - fieldSid = (int) slowReadVarUInt_1_0(); - return fieldSid < 0; + long sid = slowReadVarUInt_1_0(); + if (sid < 0) { + return true; + } + fieldSid = symbolIdToInt(sid); + return false; } /* ---- Ion 1.1 ---- */ @@ -1571,7 +1588,7 @@ private boolean uncheckedNextContainedToken() { if (b < 0) { fieldSid = (b & LOWER_SEVEN_BITS_BITMASK); } else { - fieldSid = (int) uncheckedReadVarUInt_1_0(b); + fieldSid = symbolIdToInt(uncheckedReadVarUInt_1_0(b)); } } else { uncheckedReadFieldName_1_1(); diff --git a/src/main/java/com/amazon/ion/impl/IonReaderContinuableCoreBinary.java b/src/main/java/com/amazon/ion/impl/IonReaderContinuableCoreBinary.java index f0ce3e41be..cd6794b033 100644 --- a/src/main/java/com/amazon/ion/impl/IonReaderContinuableCoreBinary.java +++ b/src/main/java/com/amazon/ion/impl/IonReaderContinuableCoreBinary.java @@ -61,6 +61,10 @@ class IonReaderContinuableCoreBinary extends IonCursorBinary implements IonReade // The second-most significant bit in the most significant byte of a VarInt is the sign. private static final int VAR_INT_SIGN_BITMASK = 0x40; + // The largest VarInt magnitude that can be decoded. This allows -2^31 (Integer.MIN_VALUE) as well as the + // exponent 2^31, which corresponds to a BigDecimal scale of Integer.MIN_VALUE. + private static final long MAXIMUM_VAR_INT_MAGNITUDE = -(long) Integer.MIN_VALUE; + // 32-bit floats must declare length 4. private static final int FLOAT_32_BYTE_LENGTH = 4; @@ -160,6 +164,9 @@ int readVarUInt_1_0() { throw new IonException("Malformed data: declared length exceeds the number of bytes remaining in the stream."); } currentByte = buffer[(int)(peekIndex++)]; + if (result > (Integer.MAX_VALUE >>> VALUE_BITS_PER_VARUINT_BYTE)) { + throw new IonException("Found a VarUInt that was too large to fit in an `int`."); + } result = (result << VALUE_BITS_PER_VARUINT_BYTE) | (currentByte & LOWER_SEVEN_BITS_BITMASK); } return result; @@ -168,33 +175,51 @@ int readVarUInt_1_0() { /** * Reads a 2+ byte VarInt, given the first byte. When called, `peekIndex` must point at the second byte in the * VarInt. at `peekIndex`.When this method returns, `peekIndex` will point at the first byte that follows the - * VarInt. NOTE: the VarInt must fit in an `int`. + * VarInt. NOTE: the magnitude of the VarInt must not exceed `MAXIMUM_VAR_INT_MAGNITUDE`; callers must check that + * the value fits in an `int` before narrowing it. * @param firstByte the first byte of the VarInt representation, which has already been retrieved from the buffer. * @return the value. */ - private int readVarInt_1_0(int firstByte) { + private long readVarInt_1_0(int firstByte) { int currentByte = firstByte; int sign = (currentByte & VAR_INT_SIGN_BITMASK) == 0 ? 1 : -1; - int result = currentByte & LOWER_SIX_BITS_BITMASK; + long result = currentByte & LOWER_SIX_BITS_BITMASK; while ((currentByte & HIGHEST_BIT_BITMASK) == 0) { if (peekIndex >= limit) { throw new IonException("Malformed data: declared length exceeds the number of bytes remaining in the stream."); } currentByte = buffer[(int)(peekIndex++)]; result = (result << VALUE_BITS_PER_VARUINT_BYTE) | (currentByte & LOWER_SEVEN_BITS_BITMASK); + if (result > MAXIMUM_VAR_INT_MAGNITUDE) { + throw new IonException("Found a VarInt that was too large to fit in an `int`."); + } } return result * sign; } /** * Reads the VarInt starting at `peekIndex`. When this method returns, `peekIndex` will point at the first byte - * that follows the VarUInt. NOTE: the VarInt must fit in an `int`. + * that follows the VarUInt. NOTE: the magnitude of the VarInt must not exceed `MAXIMUM_VAR_INT_MAGNITUDE`; + * callers must check that the value fits in an `int` before narrowing it. * @return the value. */ - private int readVarInt_1_0() { + private long readVarInt_1_0() { return readVarInt_1_0(buffer[(int)(peekIndex++)]); } + /** + * Reads the VarInt exponent of the decimal that begins at `peekIndex` and negates it to produce the scale of the + * decimal. When this method returns, `peekIndex` will point at the first byte of the decimal's coefficient. + * @return the scale. + */ + private int readDecimalScale_1_0() { + long scale = -readVarInt_1_0(); + if (scale < Integer.MIN_VALUE || scale > Integer.MAX_VALUE) { + throw new IonException("Found a decimal exponent that was too large to fit in an `int`."); + } + return (int) scale; + } + /** * Reads into a BigInteger the UInt value that begins at `valueMarker.startIndex` and ends at * `valueMarker.endIndex`. @@ -250,7 +275,7 @@ private BigInteger readIntAsBigInteger_1_0(int length) { * @return the value. */ private BigDecimal readBigDecimal_1_0() { - int scale = -readVarInt_1_0(); + int scale = readDecimalScale_1_0(); BigDecimal value; int length = (int) (valueMarker.endIndex - peekIndex); if (length < LONG_SIZE_IN_BYTES) { @@ -278,7 +303,7 @@ private BigDecimal readBigDecimal_1_0() { * @return the value. */ private Decimal readDecimal_1_0() { - int scale = -readVarInt_1_0(); + int scale = readDecimalScale_1_0(); BigInteger coefficient; int length = (int) (valueMarker.endIndex - peekIndex); if (length > 0) { @@ -338,7 +363,11 @@ private Timestamp readTimestamp_1_0() { int firstByte = buffer[(int)(peekIndex++)] & SINGLE_BYTE_MASK; Integer offset = null; if (firstByte != VAR_INT_NEGATIVE_ZERO) { - offset = readVarInt_1_0(firstByte); + long offsetMinutes = readVarInt_1_0(firstByte); + if (offsetMinutes < Integer.MIN_VALUE || offsetMinutes > Integer.MAX_VALUE) { + throw new IonException("Found a timestamp offset that was too large to fit in an `int`."); + } + offset = (int) offsetMinutes; } int year = readVarUInt_1_0(); int month = 0; @@ -796,7 +825,10 @@ public int symbolValueId() { return -1; } prepareScalar(); - return (int) readUInt(valueMarker.startIndex, valueMarker.endIndex); + if (valueMarker.endIndex - valueMarker.startIndex > Long.BYTES) { + throw new IonException("Found a symbol ID that was too large to fit in an `int`."); + } + return symbolIdToInt(readUInt(valueMarker.startIndex, valueMarker.endIndex)); } /** diff --git a/src/test/java/com/amazon/ion/impl/IonReaderContinuableCoreBinaryTest.java b/src/test/java/com/amazon/ion/impl/IonReaderContinuableCoreBinaryTest.java index 4b5c92fa2e..49a06d8484 100644 --- a/src/test/java/com/amazon/ion/impl/IonReaderContinuableCoreBinaryTest.java +++ b/src/test/java/com/amazon/ion/impl/IonReaderContinuableCoreBinaryTest.java @@ -664,4 +664,136 @@ public void timestampLengthZeroFailsCleanly(boolean constructFromBytes) { assertThrows(IonException.class, reader::timestampValue); } } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void fieldSidThatDoesNotFitInIntFailsCleanly(boolean constructFromBytes) { + try ( + IonReaderContinuableCoreBinary reader = initializeReader( + constructFromBytes, + 0xE0, 0x01, 0x00, 0xEA, // IVM + 0xD7, // Struct, length 7 + 0x10, 0x00, 0x00, 0x00, 0x84, // Field name VarUInt 2^32 + 4, which wraps to 4 if narrowed to an int + 0x21, 0x01 // Int 1 + ) + ) { + assertEquals(IonCursor.Event.START_CONTAINER, reader.nextValue()); + reader.stepIntoContainer(); + assertThrows(IonException.class, reader::nextValue); + } + } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void annotationSidThatDoesNotFitInIntFailsCleanly(boolean constructFromBytes) { + try ( + IonReaderContinuableCoreBinary reader = initializeReader( + constructFromBytes, + 0xE0, 0x01, 0x00, 0xEA, // IVM + 0xE8, // Annotation wrapper, length 8 + 0x85, // Annotations length 5 + 0x10, 0x00, 0x00, 0x00, 0x84, // Annotation VarUInt 2^32 + 4, which wraps to 4 if narrowed to an int + 0x21, 0x01 // Int 1 + ) + ) { + assertEquals(START_SCALAR, reader.nextValue()); + assertThrows(IonException.class, reader::getAnnotationIds); + } + } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void symbolValueIdThatDoesNotFitInIntFailsCleanly(boolean constructFromBytes) { + try ( + IonReaderContinuableCoreBinary reader = initializeReader( + constructFromBytes, + 0xE0, 0x01, 0x00, 0xEA, // IVM + 0x75, // Symbol, length 5 + 0x01, 0x00, 0x00, 0x00, 0x04 // UInt 2^32 + 4, which wraps to 4 if narrowed to an int + ) + ) { + assertEquals(START_SCALAR, reader.nextValue()); + assertThrows(IonException.class, reader::symbolValueId); + } + } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void timestampYearThatDoesNotFitInIntFailsCleanly(boolean constructFromBytes) { + try ( + IonReaderContinuableCoreBinary reader = initializeReader( + constructFromBytes, + 0xE0, 0x01, 0x00, 0xEA, // IVM + 0x66, // Timestamp, length 6 + 0x80, // VarInt 0 (UTC offset) + 0x10, 0x00, 0x00, 0x0F, 0xD0 // Year VarUInt 2^32 + 2000, which wraps to 2000 if narrowed to an int + ) + ) { + assertEquals(START_SCALAR, reader.nextValue()); + assertThrows(IonException.class, reader::timestampValue); + } + } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void timestampOffsetThatDoesNotFitInIntFailsCleanly(boolean constructFromBytes) { + try ( + IonReaderContinuableCoreBinary reader = initializeReader( + constructFromBytes, + 0xE0, 0x01, 0x00, 0xEA, // IVM + 0x67, // Timestamp, length 7 + 0x08, 0x00, 0x00, 0x00, 0x80, // Offset VarInt 2^31 + 0x0F, 0xD0 // Year VarUInt 2000 + ) + ) { + assertEquals(START_SCALAR, reader.nextValue()); + assertThrows(IonException.class, reader::timestampValue); + } + } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void decimalExponentThatDoesNotFitInIntFailsCleanly(boolean constructFromBytes) { + try ( + IonReaderContinuableCoreBinary reader = initializeReader( + constructFromBytes, + 0xE0, 0x01, 0x00, 0xEA, // IVM + 0x56, // Decimal, length 6 + 0x08, 0x00, 0x00, 0x00, 0x81, // Exponent VarInt 2^31 + 1, which becomes -(2^31 - 1) if narrowed to an int + 0x01, // Coefficient 1 + 0x56, // Decimal, length 6 + 0x48, 0x00, 0x00, 0x00, 0x80, // Exponent VarInt -2^31, whose scale 2^31 does not fit in an int + 0x01 // Coefficient 1 + ) + ) { + assertEquals(START_SCALAR, reader.nextValue()); + assertThrows(IonException.class, reader::decimalValue); + assertThrows(IonException.class, reader::bigDecimalValue); + assertEquals(START_SCALAR, reader.nextValue()); + assertThrows(IonException.class, reader::decimalValue); + assertThrows(IonException.class, reader::bigDecimalValue); + } + } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void decimalExponentAtIntBoundariesSucceeds(boolean constructFromBytes) { + try ( + IonReaderContinuableCoreBinary reader = initializeReader( + constructFromBytes, + 0xE0, 0x01, 0x00, 0xEA, // IVM + 0x56, // Decimal, length 6 + 0x08, 0x00, 0x00, 0x00, 0x80, // Exponent VarInt 2^31, i.e. scale Integer.MIN_VALUE + 0x01, // Coefficient 1 + 0x56, // Decimal, length 6 + 0x47, 0x7F, 0x7F, 0x7F, 0xFF, // Exponent VarInt -(2^31 - 1), i.e. scale Integer.MAX_VALUE + 0x01 // Coefficient 1 + ) + ) { + assertEquals(START_SCALAR, reader.nextValue()); + assertEquals(Integer.MIN_VALUE, reader.bigDecimalValue().scale()); + assertEquals(START_SCALAR, reader.nextValue()); + assertEquals(Integer.MAX_VALUE, reader.bigDecimalValue().scale()); + } + } } diff --git a/src/test/java/com/amazon/ion/impl/IonReaderContinuableTopLevelBinaryTest.java b/src/test/java/com/amazon/ion/impl/IonReaderContinuableTopLevelBinaryTest.java index 1080dc3962..d0d3e47a36 100644 --- a/src/test/java/com/amazon/ion/impl/IonReaderContinuableTopLevelBinaryTest.java +++ b/src/test/java/com/amazon/ion/impl/IonReaderContinuableTopLevelBinaryTest.java @@ -796,6 +796,39 @@ public void unknownSymbolInAnnotation(boolean constructFromBytes) throws Excepti reader.close(); } + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void fieldNameSidThatDoesNotFitInIntIsNotWrapped(boolean constructFromBytes) throws Exception { + // The field name SID is 2^32 + 4, which would resolve to $4 ('name') if it were narrowed to an int. + reader = readerFor(constructFromBytes, 0xD7, 0x10, 0x00, 0x00, 0x00, 0x84, 0x21, 0x01); + assertSequence(next(IonType.STRUCT), STEP_IN); + assertThrows(IonException.class, reader::next); + reader.close(); + } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void annotationSidThatDoesNotFitInIntIsNotWrapped(boolean constructFromBytes) throws Exception { + // The annotation SID is 2^32 + 4, which would resolve to $4 ('name') if it were narrowed to an int. + reader = readerFor(constructFromBytes, 0xE8, 0x85, 0x10, 0x00, 0x00, 0x00, 0x84, 0x21, 0x01); + assertThrows(IonException.class, () -> { + reader.next(); + reader.getTypeAnnotations(); + }); + reader.close(); + } + + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void symbolValueSidThatDoesNotFitInIntIsNotWrapped(boolean constructFromBytes) throws Exception { + // The symbol value SID is 2^32 + 4, which would resolve to $4 ('name') if it were narrowed to an int. + reader = readerFor(constructFromBytes, 0x75, 0x01, 0x00, 0x00, 0x00, 0x04); + assertSequence(next(IonType.SYMBOL)); + assertThrows(IonException.class, reader::symbolValue); + assertThrows(IonException.class, reader::stringValue); + reader.close(); + } + @ParameterizedTest(name = "constructFromBytes={0}") @ValueSource(booleans = {true, false}) public void unknownSymbolInValue(boolean constructFromBytes) throws Exception { From dfb54118ffb706de9258637f82c9a6fe23101787 Mon Sep 17 00:00:00 2001 From: Tyler Gregg Date: Thu, 3 Dec 2026 23:59:21 +0000 Subject: [PATCH 2/3] Allow zero-padded symbol value IDs and fix decimal exponent overflow in the binary writer - symbolValueId now skips leading zero bytes before checking that the symbol ID fits in an int, so zero-padded IDs that fit are accepted. - IonRawBinaryWriter computes the decimal (and fractional second) exponent as -(long) scale, so a scale of Integer.MIN_VALUE is written as exponent 2^31 rather than overflowing to -2^31. Co-authored-by: Radhika --- .../impl/IonReaderContinuableCoreBinary.java | 9 +++-- .../ion/impl/bin/IonRawBinaryWriter.java | 4 +-- .../IonReaderContinuableCoreBinaryTest.java | 27 ++++++++++++++ .../ion/impl/bin/IonRawBinaryWriterTest.java | 36 +++++++++++-------- 4 files changed, 57 insertions(+), 19 deletions(-) diff --git a/src/main/java/com/amazon/ion/impl/IonReaderContinuableCoreBinary.java b/src/main/java/com/amazon/ion/impl/IonReaderContinuableCoreBinary.java index cd6794b033..859ca91fee 100644 --- a/src/main/java/com/amazon/ion/impl/IonReaderContinuableCoreBinary.java +++ b/src/main/java/com/amazon/ion/impl/IonReaderContinuableCoreBinary.java @@ -825,10 +825,15 @@ public int symbolValueId() { return -1; } prepareScalar(); - if (valueMarker.endIndex - valueMarker.startIndex > Long.BYTES) { + // Skip any leading zero-padding bytes, which do not contribute to the magnitude. + long startIndex = valueMarker.startIndex; + while (startIndex < valueMarker.endIndex && buffer[(int) startIndex] == 0) { + startIndex++; + } + if (valueMarker.endIndex - startIndex > Integer.BYTES) { throw new IonException("Found a symbol ID that was too large to fit in an `int`."); } - return symbolIdToInt(readUInt(valueMarker.startIndex, valueMarker.endIndex)); + return symbolIdToInt(readUInt(startIndex, valueMarker.endIndex)); } /** diff --git a/src/main/java/com/amazon/ion/impl/bin/IonRawBinaryWriter.java b/src/main/java/com/amazon/ion/impl/bin/IonRawBinaryWriter.java index 8cf6fc9865..95a32ded8c 100644 --- a/src/main/java/com/amazon/ion/impl/bin/IonRawBinaryWriter.java +++ b/src/main/java/com/amazon/ion/impl/bin/IonRawBinaryWriter.java @@ -1041,7 +1041,7 @@ private void writeDecimalValue(final BigDecimal value) { final boolean isNegZero = isNegativeZero(value); final int signum = value.signum(); - final int exponent = -value.scale(); + final long exponent = -(long) value.scale(); writeVarInt(exponent); @@ -1234,7 +1234,7 @@ public void writeTimestamp(final Timestamp value) throws IOException final BigDecimal fraction = value.getZFractionalSecond(); if (fraction != null) { final BigInteger mantissaBigInt = fraction.unscaledValue(); - final int exponent = -fraction.scale(); + final long exponent = -(long) fraction.scale(); if (!(mantissaBigInt.equals(BigInteger.ZERO) && exponent > -1)) { writeDecimalValue(fraction); } diff --git a/src/test/java/com/amazon/ion/impl/IonReaderContinuableCoreBinaryTest.java b/src/test/java/com/amazon/ion/impl/IonReaderContinuableCoreBinaryTest.java index 49a06d8484..f0520fb2be 100644 --- a/src/test/java/com/amazon/ion/impl/IonReaderContinuableCoreBinaryTest.java +++ b/src/test/java/com/amazon/ion/impl/IonReaderContinuableCoreBinaryTest.java @@ -717,6 +717,33 @@ public void symbolValueIdThatDoesNotFitInIntFailsCleanly(boolean constructFromBy } } + @ParameterizedTest(name = "constructFromBytes={0}") + @ValueSource(booleans = {true, false}) + public void zeroPaddedSymbolValueIdsThatFitInIntSucceed(boolean constructFromBytes) { + try ( + IonReaderContinuableCoreBinary reader = initializeReader( + constructFromBytes, + 0xE0, 0x01, 0x00, 0xEA, // IVM + 0x7A, // Symbol, length 10 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, // UInt 4, zero-padded beyond 8 bytes + 0x7D, // Symbol, length 13 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7F, 0xFF, 0xFF, 0xFF, // Integer.MAX_VALUE + 0x70, // Symbol, length 0, i.e. symbol ID 0 + 0x76, // Symbol, length 6 + 0x00, 0x00, 0x80, 0x00, 0x00, 0x00 // UInt 2^31, zero-padded, which does not fit in an int + ) + ) { + assertEquals(START_SCALAR, reader.nextValue()); + assertEquals(4, reader.symbolValueId()); + assertEquals(START_SCALAR, reader.nextValue()); + assertEquals(Integer.MAX_VALUE, reader.symbolValueId()); + assertEquals(START_SCALAR, reader.nextValue()); + assertEquals(0, reader.symbolValueId()); + assertEquals(START_SCALAR, reader.nextValue()); + assertThrows(IonException.class, reader::symbolValueId); + } + } + @ParameterizedTest(name = "constructFromBytes={0}") @ValueSource(booleans = {true, false}) public void timestampYearThatDoesNotFitInIntFailsCleanly(boolean constructFromBytes) { diff --git a/src/test/java/com/amazon/ion/impl/bin/IonRawBinaryWriterTest.java b/src/test/java/com/amazon/ion/impl/bin/IonRawBinaryWriterTest.java index f13a61d520..64bdec8351 100644 --- a/src/test/java/com/amazon/ion/impl/bin/IonRawBinaryWriterTest.java +++ b/src/test/java/com/amazon/ion/impl/bin/IonRawBinaryWriterTest.java @@ -1,18 +1,5 @@ -/* - * Copyright 2007-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.amazon.ion.impl.bin; import static com.amazon.ion.IonType.BLOB; @@ -34,6 +21,7 @@ import static com.amazon.ion.TestUtils.hexDump; import static com.amazon.ion.impl.bin.Symbols.systemSymbol; +import com.amazon.ion.IonDecimal; import com.amazon.ion.IonException; import com.amazon.ion.IonSystem; import com.amazon.ion.IonType; @@ -312,6 +300,24 @@ public void testDecimal() throws Exception assertValue(DECIMAL_45_DIGIT); } + @Test + public void testDecimalWithScaleAtIntBoundaries() throws Exception + { + assertDecimalWithScaleRoundTrips(Integer.MIN_VALUE); + assertDecimalWithScaleRoundTrips(Integer.MAX_VALUE); + } + + private void assertDecimalWithScaleRoundTrips(final int scale) throws Exception + { + final BigDecimal expected = new BigDecimal(BigInteger.ONE, scale); + writer.writeDecimal(expected); + writer.finish(); + final IonValue actual = system().singleValue(writer.getBytes()); + assertEquals(expected, ((IonDecimal) actual).bigDecimalValue()); + writer.reset(); + writeIVMIfPossible(); + } + @Test public void testTimestamp() throws Exception { From b6bacf53158a227ec47f392630f12c6e8c1ca79a Mon Sep 17 00:00:00 2001 From: Tyler Gregg Date: Fri, 4 Dec 2026 00:34:32 +0000 Subject: [PATCH 3/3] Fix decimal exponent overflow in ReverseBinaryEncoder IonDatagram.getBytes() negated the decimal scale in int arithmetic, and writeVarInt(int) mis-encoded Integer.MIN_VALUE as -0. A BigDecimal with scale Integer.MIN_VALUE was therefore silently written as exponent -0 (e.g. 1d2147483648 round tripped as 1d0). The exponent is now computed as a long and writeVarInt accepts a long magnitude up to 2^31. Co-authored-by: Radhika --- .../ion/impl/lite/ReverseBinaryEncoder.java | 35 +++++-------------- .../java/com/amazon/ion/DatagramTest.java | 34 ++++++++++-------- 2 files changed, 27 insertions(+), 42 deletions(-) diff --git a/src/main/java/com/amazon/ion/impl/lite/ReverseBinaryEncoder.java b/src/main/java/com/amazon/ion/impl/lite/ReverseBinaryEncoder.java index 8db8187856..6f4b5359b9 100644 --- a/src/main/java/com/amazon/ion/impl/lite/ReverseBinaryEncoder.java +++ b/src/main/java/com/amazon/ion/impl/lite/ReverseBinaryEncoder.java @@ -1,18 +1,5 @@ -/* - * Copyright 2007-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.amazon.ion.impl.lite; import static com.amazon.ion.SymbolTable.UNKNOWN_SYMBOL_ID; @@ -527,13 +514,13 @@ else if (v < (1 << (7 * 4))) // 4 bytes - 28 bits used - 0xfffffff max * sign flag in the first octet of the representation, but part of the * extension bits for all other octets. *

- * Writes at least one byte, even for zero values. int parameter is enough - * as the scalar and container writers do not have APIs that return long or - * BigInteger representations. + * Writes at least one byte, even for zero values. The magnitude of the + * value must not exceed 2^31, which allows the exponent of a decimal whose + * scale is {@link Integer#MIN_VALUE}. * * @param v */ - private void writeVarInt(int v) + private void writeVarInt(long v) { if (v == 0) { @@ -546,9 +533,6 @@ private void writeVarInt(int v) boolean is_negative = (v < 0); if (is_negative) { - // note that for Integer.MIN_VALUE (0x80000000) the negative - // is the same, but that's also the bit pattern we need to - // write out - so no worries v = -v; } @@ -594,15 +578,12 @@ else if (v < (1 << (7 * 4 - 1))) // 4 bytes - 27 bits used - 0x7ffffff max myBuffer[offset + 2] = (byte) ((v >>> (7 * 1)) & 0x7f); myBuffer[offset + 3] = (byte) ( v | 0x80); } - else // 5 bytes - 31 bits used - 0x7fffffff max (Integer.MAX_VALUE) + else // 5 bytes - 34 bits available; magnitude is at most 2^31 { if ((offset -= 5) < 0) { offset = growBuffer(offset); } - // This is different from the previous if-blocks because we - // cannot represent a int with more than 32 bits to perform - // the "OR-assignment" (|=). myBuffer[offset] = (byte) ((v >>> (7 * 4)) & 0x7f); if (is_negative) { myBuffer[offset] |= 0x40; @@ -840,7 +821,7 @@ private void writeIonDecimalContent(BigDecimal bd) writeBytes(mantissaBits); // Ion stores exponent, BigDecimal uses the negation 'scale' instead - int exponent = -bd.scale(); + long exponent = -(long) bd.scale(); writeVarInt(exponent); } diff --git a/src/test/java/com/amazon/ion/DatagramTest.java b/src/test/java/com/amazon/ion/DatagramTest.java index 831ccfd036..fdd810faad 100644 --- a/src/test/java/com/amazon/ion/DatagramTest.java +++ b/src/test/java/com/amazon/ion/DatagramTest.java @@ -1,18 +1,5 @@ -/* - * Copyright 2007-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"). - * You may not use this file except in compliance with the License. - * A copy of the License is located at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * or in the "license" file accompanying this file. This file is distributed - * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either - * express or implied. See the License for the specific language governing - * permissions and limitations under the License. - */ - +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +// SPDX-License-Identifier: Apache-2.0 package com.amazon.ion; import static com.amazon.ion.SymbolTable.UNKNOWN_SYMBOL_ID; @@ -28,6 +15,8 @@ import com.amazon.ion.impl._Private_IonValue; import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.math.BigDecimal; +import java.math.BigInteger; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Iterator; @@ -744,4 +733,19 @@ public void modifySymbolsAfterLoadThenSerialize() assertEquals("abc", annotations[1]); } } + + @Test + public void testGetBytesWithDecimalScaleAtIntBoundaries() + { + assertDecimalWithScaleRoundTripsThroughGetBytes(Integer.MIN_VALUE); + assertDecimalWithScaleRoundTripsThroughGetBytes(Integer.MAX_VALUE); + } + + private void assertDecimalWithScaleRoundTripsThroughGetBytes(int scale) + { + BigDecimal expected = new BigDecimal(BigInteger.ONE, scale); + IonDatagram datagram = system().newDatagram(system().newDecimal(expected)); + IonDatagram actual = myLoader.load(datagram.getBytes()); + assertEquals(expected, ((IonDecimal) actual.get(0)).bigDecimalValue()); + } }