Skip to content
Merged
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 @@ -203,17 +203,22 @@ private static long parseInner(String rawNumber)
break;
}

final long value;
try {
long value = Long.parseLong(number.substring(0, lastDigitIndex + 1)) * base;
if (base > 1 && value < base) {
//for base == 1, overflow has been checked in parseLong
throw new IAE("Number overflow: %s", rawNumber);
}
return value;
value = Long.parseLong(number.substring(0, lastDigitIndex + 1));
}
catch (NumberFormatException e) {
throw new IAE("Invalid format or out of range of long: %s", rawNumber);
}

try {
// Math.multiplyExact catches every overflow, including those that wrap around to a positive value which the
// previous "value < base" check missed (e.g. 20000000000000000k).
return Math.multiplyExact(value, base);
}
catch (ArithmeticException e) {
throw new IAE("Number overflow: %s", rawNumber);
}
}

public enum UnitSystem
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import org.apache.druid.utils.CollectionUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -335,6 +337,32 @@ public void testOverflowPiB()
Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}

/**
* The overflow tests above all use the smallest multiplier that overflows, which wraps around to a negative value.
* A large enough multiplier overflows to a positive value instead, which used to slip through the overflow check
* and return a silently wrong result. 20000000000000000 multiplied by any unit base is well beyond Long.MAX_VALUE
* (e.g. 20000000000000000 * 1000 = 2e19), so every suffix must report an overflow.
*/
@ParameterizedTest
@ValueSource(strings = {"k", "m", "g", "t", "p", "KiB", "MiB", "GiB", "TiB", "PiB"})
public void testOverflowPositiveWrap(String suffix)
{
final IAE exception =
Assertions.assertThrows(IAE.class, () -> HumanReadableBytes.parse("20000000000000000" + suffix));
Assertions.assertTrue(exception.getMessage().startsWith(OVERFLOW_PREFIX));
}

/**
* Zero with a unit suffix multiplies to 0 and must not be rejected. The previous "value < base" overflow check
* treated 0 as an overflow and threw; after the fix it correctly returns 0.
*/
@ParameterizedTest
@ValueSource(strings = {"0k", "0m", "0g", "0t", "0p", "0KiB", "0MiB", "0GiB", "0TiB", "0PiB"})
public void testZeroWithUnit(String input)
{
Assertions.assertEquals(0L, HumanReadableBytes.parse(input));
}

@Test
public void testJSON() throws JsonProcessingException
{
Expand Down
Loading