This is an automated email from the ASF dual-hosted git repository. garydgregory pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-lang.git
commit a5ff3be60ebe6b586a07e0639c149b96d8d782f0 Author: Gary Gregory <[email protected]> AuthorDate: Sun Nov 15 11:12:08 2026 -0500 Fix StringUtils capacity and length overflows Use long arithmetic for join and replacement capacity estimates, and fall back to a growable buffer when estimates exceed safe limits. Avoid overflow when checking wrapping-token lengths in unwrap(). Add boundary and opt-in large-input regression tests. Correct abbreviation and repeated-replacement Javadoc, and update release notes. Assisted-By: OpenAI Codex --- src/changes/changes.xml | 21 ++++ .../java/org/apache/commons/lang3/StringUtils.java | 51 +++++--- .../commons/lang3/StringUtilsAbbreviateTest.java | 28 ++--- .../commons/lang3/StringUtilsOverflowTest.java | 133 +++++++++++++++++++++ 4 files changed, 203 insertions(+), 30 deletions(-) diff --git a/src/changes/changes.xml b/src/changes/changes.xml index 9d6244ed0..e95168c89 100644 --- a/src/changes/changes.xml +++ b/src/changes/changes.xml @@ -68,6 +68,27 @@ The <action> type attribute can be add,update,fix,remove. <action type="fix" dev="ggregory" due-to="Gary Gregory, Amar Ghugare">Handle incompatible array types in DiffBuilder (#1867).</action> <action type="fix" dev="ggregory" due-to="Hai Zhang, Gary Gregory, Amar Ghugare" issue="LANG-1730">Parse GMT independently of platform aliases (#1874).</action> <action type="fix" dev="ggregory" due-to="Gary Gregory, Amar Ghugare">Fix abbreviation overflow for extreme negative offsets (#1875).</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent buffer estimate overflow and excessive initial capacities in StringUtils.replaceEach(String, String[], String[]), including unused replacement rules.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent buffer estimate overflow and excessive initial capacities in StringUtils.replaceEachRepeatedly(String, String[], String[]), including unused replacement rules; clarify the iteration-limit Javadoc.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(boolean[], char) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(boolean[], char, int, int) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(byte[], char) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(byte[], char, int, int) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(char[], char) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(char[], char, int, int) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(double[], char) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(double[], char, int, int) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(float[], char) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(float[], char, int, int) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(int[], char) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(int[], char, int, int) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(long[], char) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(long[], char, int, int) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(short[], char) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent capacity estimate overflow and excessive initial capacities in StringUtils.join(short[], char, int, int) when the actual result is representable.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Prevent length-check overflow in StringUtils.unwrap(String, String) for very large wrapping tokens.</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Javadoc: Correct the null-marker example, null-marker handling, and minimum width in StringUtils.abbreviate(String, String, int).</action> + <action type="fix" dev="ggregory" due-to="Gary Gregory">Javadoc: Correct the null-marker example, null-marker handling, and minimum widths in StringUtils.abbreviate(String, String, int, int).</action> <!-- ADD --> <!-- UPDATE --> </release> diff --git a/src/main/java/org/apache/commons/lang3/StringUtils.java b/src/main/java/org/apache/commons/lang3/StringUtils.java index dba9e8256..fe232fdc0 100644 --- a/src/main/java/org/apache/commons/lang3/StringUtils.java +++ b/src/main/java/org/apache/commons/lang3/StringUtils.java @@ -308,7 +308,7 @@ public static String abbreviate(final String str, final int offset, final int ma * * <pre> * StringUtils.abbreviate(null, "...", *) = null - * StringUtils.abbreviate("abcdefg", null, *) = "abcdefg" + * StringUtils.abbreviate("abcdefg", null, 4) = "abcd" * StringUtils.abbreviate("", "...", 4) = "" * StringUtils.abbreviate("abcdefg", ".", 5) = "abcd." * StringUtils.abbreviate("abcdefg", ".", 7) = "abcdefg" @@ -320,8 +320,8 @@ public static String abbreviate(final String str, final int offset, final int ma * </pre> * * @param str The String to check, may be null. - * @param abbrevMarker The String used as replacement marker. - * @param maxWidth maximum length of result String, must be at least {@code abbrevMarker.length + 1}. + * @param abbrevMarker The String used as replacement marker, null is treated as an empty marker. + * @param maxWidth maximum length of result String, must be at least the marker length plus one (one for a null or empty marker). * @return abbreviated String, {@code null} if null String input. * @throws IllegalArgumentException Thrown if the width is too small. * @since 3.6 @@ -343,7 +343,7 @@ public static String abbreviate(final String str, final String abbrevMarker, fin * * <pre> * StringUtils.abbreviate(null, null, *, *) = null - * StringUtils.abbreviate("abcdefghijklmno", null, *, *) = "abcdefghijklmno" + * StringUtils.abbreviate("abcdefghijklmno", null, 0, 10) = "abcdefghij" * StringUtils.abbreviate("", "...", 0, 4) = "" * StringUtils.abbreviate("abcdefghijklmno", "---", -1, 10) = "abcdefg---" * StringUtils.abbreviate("abcdefghijklmno", ",", 0, 10) = "abcdefghi," @@ -360,9 +360,11 @@ public static String abbreviate(final String str, final String abbrevMarker, fin * </pre> * * @param str The String to check, may be null. - * @param abbrevMarker The String used as replacement marker, for example "...", or Unicode HORIZONTAL ELLIPSIS, U+2026 '…'. + * @param abbrevMarker The String used as replacement marker, for example "...", or Unicode HORIZONTAL ELLIPSIS, U+2026 '…'; + * null is treated as an empty marker. * @param offset left edge of source String. - * @param maxWidth maximum length of result String, must be at least 4. + * @param maxWidth maximum length of result String, must be at least the marker length plus one (one for a null or empty marker). + * When markers are needed at both ends, must be at least twice the marker length plus one. * @return abbreviated String, {@code null} if null String input. * @throws IllegalArgumentException Thrown if the width is too small. * @since 3.6 @@ -538,15 +540,18 @@ public static String appendIfMissingIgnoreCase(final String str, final CharSeque } /** - * Computes the capacity required for a StringBuilder to hold {@code items} of {@code maxElementChars} characters plus the separators between them. The - * separator is assumed to be 1 character. + * Creates a StringBuilder using an estimated capacity for {@code count} items of at most {@code maxElementChars} characters plus one-character separators. + * + * <p> + * If the estimate exceeds the safe array length, uses the default initial capacity and lets the builder grow to fit the actual values. + * </p> * * @param count The number of items. * @param maxElementChars The maximum number of characters per item. * @return A StringBuilder with the appropriate capacity. */ private static StringBuilder capacity(final int count, final byte maxElementChars) { - return new StringBuilder(count * maxElementChars + count - 1); + return newStringBuilder((long) count * maxElementChars + count - 1); } /** @@ -5493,6 +5498,20 @@ public static String mid(final String str, int pos, final int len) { return str.substring(start, Math.max(start, end)); } + /** + * Creates a StringBuilder with an estimated initial capacity. + * + * <p> + * An excessive estimate does not imply that the actual result is too large. Use the default capacity in that case and let the builder grow as needed. + * </p> + * + * @param estimatedCapacity The non-negative estimated capacity. + * @return A StringBuilder with the estimated or default capacity. + */ + private static StringBuilder newStringBuilder(final long estimatedCapacity) { + return estimatedCapacity > ArrayUtils.SAFE_MAX_ARRAY_LENGTH ? new StringBuilder() : new StringBuilder((int) estimatedCapacity); + } + /** * Normalizes whitespace in a String. * @@ -6601,6 +6620,8 @@ private static String replaceEachOnce(final String text, final String[] searchLi // get a good guess on the size of the result buffer so it doesn't have to double if it goes over a bit int increase = 0; + // Cap estimated growth at 20%; the initial capacity is only a hint. + final int increaseLimit = text.length() / 5; // count the replacement text elements that are larger than their corresponding text being replaced for (int i = 0; i < searchList.length; i++) { @@ -6609,13 +6630,10 @@ private static String replaceEachOnce(final String text, final String[] searchLi } final int greater = replacementList[i].length() - searchList[i].length(); if (greater > 0) { - increase += 3 * greater; // assume 3 matches + increase = (int) Math.min(increaseLimit, increase + 3L * greater); // assume 3 matches } } - // have upper-bound at 20% increase, then let Java take over - increase = Math.min(increase, text.length() / 5); - - final StringBuilder buf = new StringBuilder(text.length() + increase); + final StringBuilder buf = newStringBuilder((long) text.length() + increase); while (textIndex != -1) { @@ -6680,7 +6698,8 @@ private static String replaceEachOnce(final String text, final String[] searchLi * @param searchList The Strings to search for, no-op if null. * @param replacementList The Strings to replace them with, no-op if null. * @return The text with any replacements processed, {@code null} if null String input. - * @throws IllegalStateException Thrown if the search is repeating and there is an endless loop due to outputs of one being inputs to another. + * @throws IllegalStateException Thrown if replacement does not finish within the iteration limit, including endless loops and terminating + * replacements that require too many passes. * @throws IllegalArgumentException Thrown if the lengths of the arrays are not the same (null is ok, and/or size 0). * @since 2.4 */ @@ -9224,7 +9243,7 @@ public static String unwrap(final String str, final char wrapChar) { * @since 3.6 */ public static String unwrap(final String str, final String wrapToken) { - if (isEmpty(str) || isEmpty(wrapToken) || str.length() < 2 * wrapToken.length()) { + if (isEmpty(str) || isEmpty(wrapToken) || wrapToken.length() > str.length() / 2) { return str; } if (Strings.CS.startsWith(str, wrapToken) && Strings.CS.endsWith(str, wrapToken)) { diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsAbbreviateTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsAbbreviateTest.java index c9a73d257..9dc019b6a 100644 --- a/src/test/java/org/apache/commons/lang3/StringUtilsAbbreviateTest.java +++ b/src/test/java/org/apache/commons/lang3/StringUtilsAbbreviateTest.java @@ -174,20 +174,6 @@ void testAbbreviate_StringStringIntInt() { assertEquals("....fg", StringUtils.abbreviate("abcdefg", "....", 5, 6)); } - @ParameterizedTest - @ValueSource(ints = { Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 15, Integer.MIN_VALUE + 16, -1, 0 }) - void testAbbreviateNonPositiveOffset(final int offset) { - assertAbbreviateWithOffset("abcdefg...", offset, 10); - } - - @ParameterizedTest - @ValueSource(ints = { Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 15, Integer.MIN_VALUE + 16, -1, 0 }) - void testAbbreviateNonPositiveOffsetWithMarker(final int offset) { - assertAbbreviateWithAbbrevMarkerAndOffset("abcdefgh++", "++", offset, 10); - assertAbbreviateWithAbbrevMarkerAndOffset("abcdefghij", "", offset, 10); - assertAbbreviateWithAbbrevMarkerAndOffset("abcdefghij", null, offset, 10); - } - // Fixed LANG-1463 @Test void testAbbreviateMarkerWithEmptyString() { @@ -252,6 +238,20 @@ void testAbbreviateMiddleSurrogatePair() { } } + @ParameterizedTest + @ValueSource(ints = { Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 15, Integer.MIN_VALUE + 16, -1, 0 }) + void testAbbreviateNonPositiveOffset(final int offset) { + assertAbbreviateWithOffset("abcdefg...", offset, 10); + } + + @ParameterizedTest + @ValueSource(ints = { Integer.MIN_VALUE, Integer.MIN_VALUE + 1, Integer.MIN_VALUE + 15, Integer.MIN_VALUE + 16, -1, 0 }) + void testAbbreviateNonPositiveOffsetWithMarker(final int offset) { + assertAbbreviateWithAbbrevMarkerAndOffset("abcdefgh++", "++", offset, 10); + assertAbbreviateWithAbbrevMarkerAndOffset("abcdefghij", "", offset, 10); + assertAbbreviateWithAbbrevMarkerAndOffset("abcdefghij", null, offset, 10); + } + @Test void testAbbreviateSurrogatePair() { // U+1F600 GRINNING FACE is a single supplementary code point stored as a surrogate pair diff --git a/src/test/java/org/apache/commons/lang3/StringUtilsOverflowTest.java b/src/test/java/org/apache/commons/lang3/StringUtilsOverflowTest.java new file mode 100644 index 000000000..10f5bcdb4 --- /dev/null +++ b/src/test/java/org/apache/commons/lang3/StringUtilsOverflowTest.java @@ -0,0 +1,133 @@ +/* + * 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.lang3; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; + +/** + * Regression tests for overflow in string length and capacity calculations. + * + * <p> + * Enable the large-input tests with {@code -Dtest.stringutils.large.heap=true -DheapSize=-Xmx8g}. + * </p> + */ +class StringUtilsOverflowTest extends AbstractLangTest { + + @ParameterizedTest + @ValueSource(bytes = { 1, 4, 5, 6, 11, 12, 20, 22 }) + void testJoinCapacityOverflow(final byte maxElementChars) throws Exception { + // Exercise the shared helper without allocating a multi-gigabyte primitive array. + final Method method = StringUtils.class.getDeclaredMethod("capacity", int.class, byte.class); + method.setAccessible(true); + final int firstUnsafe = (int) (((long) ArrayUtils.SAFE_MAX_ARRAY_LENGTH + 1) / (maxElementChars + 1) + 1); + final int firstOverflow = (int) (((long) Integer.MAX_VALUE + 1) / (maxElementChars + 1) + 1); + for (final int count : new int[] { firstUnsafe, firstOverflow, Integer.MAX_VALUE }) { + final StringBuilder builder = (StringBuilder) method.invoke(null, count, maxElementChars); + assertEquals(new StringBuilder().capacity(), builder.capacity()); + assertEquals("0,0", builder.append("0,0").toString()); + } + assertEquals(2 * maxElementChars + 1, ((StringBuilder) method.invoke(null, 2, maxElementChars)).capacity()); + } + + @Test + @EnabledIfSystemProperty(named = "test.stringutils.large.heap", matches = "true") + void testJoinLongArrayCapacityOverflow() { + // The maximum-width estimate overflows, but the actual zero values need only one character each. + final int count = 102_261_127; + final String result = StringUtils.join(new long[count], ','); + assertEquals(2 * count - 1, result.length()); + assertEquals(count, StringUtils.countMatches(result, '0')); + assertEquals(count - 1, StringUtils.countMatches(result, ',')); + } + + @ParameterizedTest + @ValueSource(longs = { (long) ArrayUtils.SAFE_MAX_ARRAY_LENGTH + 1, Integer.MAX_VALUE, (long) Integer.MAX_VALUE + 1, Long.MAX_VALUE }) + void testOversizedCapacityEstimate(final long estimate) throws Exception { + final Method method = StringUtils.class.getDeclaredMethod("newStringBuilder", long.class); + method.setAccessible(true); + final StringBuilder builder = (StringBuilder) method.invoke(null, estimate); + assertEquals(new StringBuilder().capacity(), builder.capacity()); + assertEquals("result", builder.append("result").toString()); + } + + @Test + @EnabledIfSystemProperty(named = "test.stringutils.large.heap", matches = "true") + void testReplaceEachSingleRuleEstimateOverflow() { + // Multiplication by three overflows even before estimates from different rules are added. + final String[] search = { "a", "z" }; + final String[] replacement = { "b", StringUtils.repeat('x', Integer.MAX_VALUE / 3 + 2) }; + assertAll( + () -> assertEquals("b", StringUtils.replaceEach("a", search, replacement)), + () -> assertEquals("b", StringUtils.replaceEachRepeatedly("a", search, replacement))); + } + + @Test + @EnabledIfSystemProperty(named = "test.stringutils.large.heap", matches = "true") + void testReplaceEachTotalCapacityOverflow() { + // The input fits in a String, but input length plus the 20% estimate exceeds Integer.MAX_VALUE. + final String text = new String(new byte[1_800_000_000], StandardCharsets.ISO_8859_1); + final String[] search = { text, "a" }; + final String[] replacement = { "", text }; + assertAll( + () -> assertEquals("", StringUtils.replaceEach(text, search, replacement)), + () -> assertEquals("", StringUtils.replaceEachRepeatedly(text, search, replacement))); + } + + @ParameterizedTest + @ValueSource(ints = { 715, 716, 717, 1432 }) + void testReplaceEachUnusedRulesOverflow(final int unusedRules) { + final String[] search = new String[unusedRules + 1]; + final String[] replacement = new String[unusedRules + 1]; + Arrays.fill(search, "z"); + Arrays.fill(replacement, StringUtils.repeat('x', 1_000_001)); + search[0] = "a"; + replacement[0] = "b"; + assertAll( + () -> assertEquals("b", StringUtils.replaceEach("a", search, replacement)), + () -> assertEquals("b", StringUtils.replaceEachRepeatedly("a", search, replacement))); + } + + @Test + void testUnwrapLengthBoundaries() { + assertEquals("ababa", StringUtils.unwrap("ababa", "aba")); + assertEquals("", StringUtils.unwrap("abaaba", "aba")); + assertEquals("x", StringUtils.unwrap("abaxaba", "aba")); + assertEquals("aba", StringUtils.unwrap("aba", "aba")); + } + + /** + * Allocates a token whose doubled length overflows an int; see the class documentation for the required heap setting. + */ + @Test + @EnabledIfSystemProperty(named = "test.stringutils.large.heap", matches = "true") + void testUnwrapLengthOverflow() { + final String token = StringUtils.repeat('x', 1 << 30); + assertSame(token, StringUtils.unwrap(token, token)); + } +}
