diff --git a/src/main/java/org/apache/commons/imaging/common/Allocator.java b/src/main/java/org/apache/commons/imaging/common/Allocator.java index fe51c90c72..097a843681 100644 --- a/src/main/java/org/apache/commons/imaging/common/Allocator.java +++ b/src/main/java/org/apache/commons/imaging/common/Allocator.java @@ -62,7 +62,7 @@ public static T apply(final int request, final IntFunction factory) { * @see #check(int) */ public static T[] array(final int request, final IntFunction factory, final int eltShallowByteSize) { - check(request * eltShallowByteSize); + check(request, eltShallowByteSize); return factory.apply(request); } @@ -76,7 +76,7 @@ public static T[] array(final int request, final IntFunction factory, f * @see #check(int) */ public static ArrayList arrayList(final int request) { - check(24 + request * 4); // 4 bytes per element + check(request, Integer.BYTES); // 4 bytes per element return apply(request, ArrayList::new); } diff --git a/src/test/java/org/apache/commons/imaging/common/AllocatorTest.java b/src/test/java/org/apache/commons/imaging/common/AllocatorTest.java new file mode 100644 index 0000000000..fa2f2bfc57 --- /dev/null +++ b/src/test/java/org/apache/commons/imaging/common/AllocatorTest.java @@ -0,0 +1,37 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License 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. + */ + +package org.apache.commons.imaging.common; + +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class AllocatorTest { + + /** 107374183 * 40 overflows int to 24, slipping past the byte-cost limit. */ + @Test + void testArrayOverflowIsRejected() { + assertThrows(AllocationRequestException.class, () -> Allocator.array(107374183, Object[]::new, 40)); + } + + /** 536870912 * Integer.BYTES overflows int to a negative value. */ + @Test + void testArrayListOverflowIsRejected() { + assertThrows(AllocationRequestException.class, () -> Allocator.arrayList(536870912)); + } +}