From 2598ab4e827528125764453d6cecf0531fb7d808 Mon Sep 17 00:00:00 2001 From: Arthur Chan Date: Thu, 3 Aug 2023 19:33:06 +0000 Subject: [PATCH] Fix possible large array index Signed-off-by: Arthur Chan --- diffutils/src/me/xdrop/diffutils/DiffUtils.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/diffutils/src/me/xdrop/diffutils/DiffUtils.java b/diffutils/src/me/xdrop/diffutils/DiffUtils.java index e9e1ab2..cdce4a6 100644 --- a/diffutils/src/me/xdrop/diffutils/DiffUtils.java +++ b/diffutils/src/me/xdrop/diffutils/DiffUtils.java @@ -16,6 +16,9 @@ * so it is mostly non readable (eg. var names) */ public class DiffUtils { + /* Set the maximum size of the integer array for storing the + matrix to avoid filling up the heap and result in OOM */ + public static int MAX_MATRIX_SIZE = 100000; public static EditOp[] getEditOps(String s1, String s2) { return getEditOps(s1.length(), s1, s2.length(), s2); @@ -58,7 +61,16 @@ private static EditOp[] getEditOps(int len1, String s1, int len2, String s2) { len1++; len2++; - matrix = new int[len2 * len1]; + /* Special checking to avoid creating a very large integer array + which will up the heap and cause OOM. It also avoid possible + negative index because of integer wrap around on the result + of large number multiplication. */ + int matrixSize = len2 * len1; + if ((matrixSize > DiffUtils.MAX_MATRIX_SIZE) || (matrixSize <= 0)) { + throw new IllegalArgumentException("Provided strings are too long to handle."); + } + + matrix = new int[matrixSize]; for (i = 0; i < len2; i++) matrix[i] = i;