Skip to content
Open
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 @@ -84,14 +84,15 @@ public String[] deserializeFromMemory(final Memory mem, final int numItems) {
public String[] deserializeFromMemory(final Memory mem, final long offsetBytes, final int numItems) {
Objects.requireNonNull(mem, "Memory must not be null");
if (numItems <= 0) { return new String[0]; }
Util.checkBounds(offsetBytes, (long) numItems * Integer.BYTES, mem.getCapacity());
final String[] array = new String[numItems];
long offset = offsetBytes;
for (int i = 0; i < numItems; i++) {
Util.checkBounds(offset, Integer.BYTES, mem.getCapacity());
final int strLength = mem.getInt(offset);
offset += Integer.BYTES;
final byte[] utf8Bytes = new byte[strLength];
Util.checkBounds(offset, strLength, mem.getCapacity());
final byte[] utf8Bytes = new byte[strLength];
mem.getByteArray(offset, utf8Bytes, 0, strLength);
offset += strLength;
array[i] = new String(utf8Bytes, StandardCharsets.UTF_8);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,15 @@ public String[] deserializeFromMemory(final Memory mem, final int numItems) {
public String[] deserializeFromMemory(final Memory mem, final long offsetBytes, final int numItems) {
Objects.requireNonNull(mem, "Memory must not be null");
if (numItems <= 0) { return new String[0]; }
Util.checkBounds(offsetBytes, (long) numItems * Integer.BYTES, mem.getCapacity());
final String[] array = new String[numItems];
long offset = offsetBytes;
for (int i = 0; i < numItems; i++) {
Util.checkBounds(offset, Integer.BYTES, mem.getCapacity());
final int strLength = mem.getInt(offset);
offset += Integer.BYTES;
final byte[] utf16Bytes = new byte[strLength];
Util.checkBounds(offset, strLength, mem.getCapacity());
final byte[] utf16Bytes = new byte[strLength];
mem.getByteArray(offset, utf16Bytes, 0, strLength);
offset += strLength;
array[i] = new String(utf16Bytes, StandardCharsets.UTF_16);
Expand Down
25 changes: 25 additions & 0 deletions src/main/java/org/apache/datasketches/frequencies/LongsSketch.java
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,16 @@ public static LongsSketch getInstance(final Memory srcMem) {
throw new SketchesArgumentException(
"Possible Corruption: (PreLongs == 1) ^ Empty == True.");
}
if (lgCurMapSize < LG_MIN_MAP_SIZE) { //Byte 4
throw new SketchesArgumentException(
"Possible Corruption: LgCurMapSize must be at least " + LG_MIN_MAP_SIZE + ": "
+ lgCurMapSize);
}
if (lgCurMapSize > lgMaxMapSize) { //Byte 4 and Byte 3
throw new SketchesArgumentException(
"Possible Corruption: LgCurMapSize must not exceed LgMaxMapSize: "
+ lgCurMapSize + " > " + lgMaxMapSize);
}

if (empty) {
return new LongsSketch(lgMaxMapSize, LG_MIN_MAP_SIZE);
Expand Down Expand Up @@ -328,6 +338,21 @@ public static LongsSketch getInstance(final String string) {
"Possible Corruption: Incorrect # of tokens: " + numTokens
+ ", numActive: " + numActive);
}
if (lgCur < LG_MIN_MAP_SIZE) {
throw new SketchesArgumentException(
"Possible Corruption: Map length must be at least " + (1 << LG_MIN_MAP_SIZE) + ": "
+ tokens[STR_PREAMBLE_TOKENS + 1]);
}
if (lgCur > lgMax) {
throw new SketchesArgumentException(
"Possible Corruption: Map length must not exceed max map length " + (1L << lgMax) + ": "
+ tokens[STR_PREAMBLE_TOKENS + 1]);
}
final long maxActive = (long) ((1L << lgCur) * ReversePurgeLongHashMap.getLoadFactor());
if ((numActive < 0) || (numActive > maxActive)) {
throw new SketchesArgumentException(
"Possible Corruption: numActive exceeds map capacity: " + numActive);
}

final LongsSketch sketch = new LongsSketch(lgMax, lgCur);
sketch.streamWeight = streamWt;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@
import org.apache.datasketches.common.SketchesStateException;
import org.apache.datasketches.memory.Memory;
import org.apache.datasketches.memory.WritableMemory;
import org.apache.datasketches.thetacommon.ThetaUtil;

/**
* @author Lee Rhodes
Expand Down Expand Up @@ -171,9 +172,15 @@ static CompactSketch memoryToCompact(
//extract hashArr > 1
final long[] hashArr;
if (srcCompactFlag) {
PreambleUtil.checkCompactImage(srcMem);
hashArr = new long[curCount];
srcMem.getLongArray(srcPreLongs << 3, hashArr, 0, curCount);
} else { //update sketch, thus hashTable form
if ((srcLgArrLongs > (ThetaUtil.MAX_LG_NOM_LONGS + 1))
|| (srcMem.getCapacity() < (((long) srcPreLongs << 3) + (8L << srcLgArrLongs)))) {
throw new SketchesArgumentException("Possible corruption: lgArrLongs " + srcLgArrLongs
+ " is too large for the Memory size " + srcMem.getCapacity());
}
final int srcCacheLen = 1 << srcLgArrLongs;
final long[] tempHashArr = new long[srcCacheLen];
srcMem.getLongArray(srcPreLongs << 3, tempHashArr, 0, srcCacheLen);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,7 @@ private static CompactSketch heapifyV4(final Memory srcMem, final long seed, fin
final short seedHash = (short) extractSeedHash(srcMem);
final boolean isEmpty = (flags & EMPTY_FLAG_MASK) > 0;
if (enforceSeed && !isEmpty) { PreambleUtil.checkMemorySeedHash(srcMem, seed); }
PreambleUtil.checkCompressedImage(srcMem);
int offsetBytes = 8;
long theta = Long.MAX_VALUE;
if (preLongs > 1) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ class DirectCompactSketch extends CompactSketch {
*/
static DirectCompactSketch wrapInstance(final Memory srcMem, final short seedHash) {
ThetaUtil.checkSeedHashes((short) extractSeedHash(srcMem), seedHash);
PreambleUtil.checkCompactImage(srcMem);
return new DirectCompactSketch(srcMem);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@ static final CompactSketch heapify1to3(final Memory srcMem, final short seedHash
return EmptyCompactSketch.getInstance();
}

final int reqCap = (curCount + preLongs) << 3;
checkCurCount(curCount);
final long reqCap = ((long) curCount + preLongs) << 3;
validateInputSize(reqCap, memCap);

if ((thetaLong == Long.MAX_VALUE) && (curCount == 1)) {
Expand Down Expand Up @@ -98,7 +99,7 @@ static final CompactSketch heapify2to3(final Memory srcMem, final short seedHash
if ((familyId < 1) || (familyId > 4)) {
throw new SketchesArgumentException("Family (Sketch Type) must be 1 to 4: " + familyId);
}
int reqBytesIn = 8;
long reqBytesIn = 8;
int curCount = 0;
long thetaLong = Long.MAX_VALUE;
if (preLongs == 1) {
Expand All @@ -120,7 +121,8 @@ static final CompactSketch heapify2to3(final Memory srcMem, final short seedHash
return new SingleItemSketch(hash, seedHash);
}
//curCount > 1
reqBytesIn = (curCount + preLongs) << 3;
checkCurCount(curCount);
reqBytesIn = ((long) curCount + preLongs) << 3;
validateInputSize(reqBytesIn, memCap);
final long[] compactOrderedCache = new long[curCount];
srcMem.getLongArray(preLongs << 3, compactOrderedCache, 0, curCount);
Expand All @@ -141,7 +143,8 @@ static final CompactSketch heapify2to3(final Memory srcMem, final short seedHash
return new SingleItemSketch(hash, seedHash);
}
//curCount > 1 and/or theta < 1.0
reqBytesIn = (curCount + preLongs) << 3;
checkCurCount(curCount);
reqBytesIn = ((long) curCount + preLongs) << 3;
validateInputSize(reqBytesIn, memCap);
final long[] compactOrderedCache = new long[curCount];
srcMem.getLongArray(preLongs << 3, compactOrderedCache, 0, curCount);
Expand All @@ -150,7 +153,13 @@ static final CompactSketch heapify2to3(final Memory srcMem, final short seedHash
throw new SketchesArgumentException("PreLongs must be 1,2, or 3: " + preLongs);
}

private static final void validateInputSize(final int reqBytesIn, final int memCap) {
private static final void checkCurCount(final int curCount) {
if (curCount < 0) {
throw new SketchesArgumentException("Possible corruption: negative curCount: " + curCount);
}
}

private static final void validateInputSize(final long reqBytesIn, final long memCap) {
if (reqBytesIn > memCap) {
throw new SketchesArgumentException(
"Input Memory or byte[] size is too small: Required Bytes: " + reqBytesIn
Expand Down
16 changes: 16 additions & 0 deletions src/main/java/org/apache/datasketches/theta/Intersection.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import static org.apache.datasketches.theta.PreambleUtil.extractCurCount;
import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID;
import static org.apache.datasketches.theta.PreambleUtil.extractFlags;
import static org.apache.datasketches.theta.PreambleUtil.extractLgArrLongs;
import static org.apache.datasketches.theta.PreambleUtil.extractPreLongs;
import static org.apache.datasketches.theta.PreambleUtil.extractSerVer;

Expand Down Expand Up @@ -216,6 +217,21 @@ protected static void memChecks(final Memory srcMem) {
}
//empty = true AND curCount_ = 0: OK
} //else empty = false, curCount could be anything
//The hash table holds curCount entries and is no larger than for the largest nominal entries.
//A curCount of -1 means the intersection has no result yet.
final int lgArrLongs = extractLgArrLongs(srcMem);
if ((lgArrLongs < 0) || (lgArrLongs > (ThetaUtil.MAX_LG_NOM_LONGS + 1))
|| (curCount < -1) || (curCount > (1 << lgArrLongs))) {
throw new SketchesArgumentException("Possible corruption: lgArrLongs: " + lgArrLongs
+ ", curCount: " + curCount);
}
if (curCount > 0) { //the image must hold the hash table
final long reqBytes = ((long) CONST_PREAMBLE_LONGS << 3) + (8L << lgArrLongs);
if (srcMem.getCapacity() < reqBytes) {
throw new SketchesArgumentException("Possible corruption: Memory size " + srcMem.getCapacity()
+ " < required " + reqBytes);
}
}
}

}
61 changes: 61 additions & 0 deletions src/main/java/org/apache/datasketches/theta/PreambleUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -347,6 +347,67 @@ else if (preLongs == 3) {

//@formatter:on

/**
* Checks that the Memory holds the preamble longs it declares, and returns them.
* @param mem the sketch image
* @return the number of preamble longs
* @throws SketchesArgumentException if the Memory is smaller than the preamble
*/
static int checkMemPreambleCap(final Memory mem) {
Util.checkBounds(0, 8, mem.getCapacity());
final int preLongs = extractPreLongs(mem);
final long reqBytes = (long) preLongs << 3;
if (mem.getCapacity() < reqBytes) {
throw new SketchesArgumentException("Possible corruption: preLongs " + preLongs
+ " needs " + reqBytes + " bytes, Memory has " + mem.getCapacity());
}
return preLongs;
}

/**
* Checks that a serial version 3 compact image, which is not empty and not a single item, holds the
* number of hashes it declares, before anything is allocated or read from it.
* @param mem the compact image
* @throws SketchesArgumentException if the image is too small or the count is invalid
*/
static void checkCompactImage(final Memory mem) {
final int preLongs = checkMemPreambleCap(mem);
final int curCount = (preLongs > 1) ? extractCurCount(mem) : 1;
final long reqBytes = ((long) preLongs << 3) + ((long) curCount << 3);
if ((curCount < 0) || (mem.getCapacity() < reqBytes)) {
throw new SketchesArgumentException("Possible corruption: curCount " + curCount
+ " needs " + reqBytes + " bytes, Memory has " + mem.getCapacity());
}
}

/**
* Checks that a serial version 4 (compressed) compact image holds the number of entries it
* declares, before anything is allocated or read from it.
* @param mem the compressed compact image
* @throws SketchesArgumentException if the image is too small or its fields are invalid
*/
static void checkCompressedImage(final Memory mem) {
final int preLongs = checkMemPreambleCap(mem);
final int entryBits = extractEntryBitsV4(mem);
final int numEntriesBytes = extractNumEntriesBytesV4(mem);
if ((preLongs < 1) || (preLongs > 2) || (entryBits < 1) || (entryBits > 63)
|| (numEntriesBytes < 1) || (numEntriesBytes > 4)) {
throw new SketchesArgumentException("Possible corruption: preLongs: " + preLongs
+ ", entryBits: " + entryBits + ", numEntriesBytes: " + numEntriesBytes);
}
final int offsetBytes = preLongs << 3;
Util.checkBounds(0, offsetBytes + numEntriesBytes, mem.getCapacity());
long numEntries = 0;
for (int i = 0; i < numEntriesBytes; i++) {
numEntries |= (long) Byte.toUnsignedInt(mem.getByte(offsetBytes + i)) << (i << 3);
}
if (numEntries > Integer.MAX_VALUE) {
throw new SketchesArgumentException("Possible corruption: numEntries: " + numEntries);
}
final long packedBytes = ((numEntries * entryBits) + 7) >>> 3;
Util.checkBounds(offsetBytes + numEntriesBytes, packedBytes, mem.getCapacity());
}

static int extractPreLongs(final Memory mem) {
return mem.getByte(PREAMBLE_LONGS_BYTE) & 0X3F;
}
Expand Down
16 changes: 13 additions & 3 deletions src/main/java/org/apache/datasketches/theta/UpdateSketch.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@
import static org.apache.datasketches.theta.PreambleUtil.SER_VER;
import static org.apache.datasketches.theta.PreambleUtil.SER_VER_BYTE;
import static org.apache.datasketches.theta.PreambleUtil.checkMemorySeedHash;
import static org.apache.datasketches.theta.PreambleUtil.extractCurCount;
import static org.apache.datasketches.theta.PreambleUtil.extractFamilyID;
import static org.apache.datasketches.theta.PreambleUtil.extractFlags;
import static org.apache.datasketches.theta.PreambleUtil.extractLgResizeFactor;
import static org.apache.datasketches.theta.PreambleUtil.extractP;
import static org.apache.datasketches.theta.PreambleUtil.extractSerVer;
import static org.apache.datasketches.theta.PreambleUtil.extractThetaLong;
import static org.apache.datasketches.theta.PreambleUtil.getMemBytes;
import static org.apache.datasketches.theta.UpdateReturnState.RejectedNullOrEmpty;

import java.nio.ByteBuffer;
Expand Down Expand Up @@ -430,9 +430,19 @@ static void checkMemIntegrity(final Memory srcMem, final long expectedSeed, fina
final short seedHash = checkMemorySeedHash(srcMem, expectedSeed); //byte 6,7
ThetaUtil.checkSeedHashes(seedHash, ThetaUtil.computeSeedHash(expectedSeed));

//Check mem capacity, lgArrLongs
//Check lgNomLongs, lgArrLongs and curCount. The hash table grows to at most twice the nominal entries.
if ((lgNomLongs > ThetaUtil.MAX_LG_NOM_LONGS) || (lgArrLongs < 0) || (lgArrLongs > (lgNomLongs + 1))) {
throw new SketchesArgumentException("Possible corruption: lgNomLongs: " + lgNomLongs
+ ", lgArrLongs: " + lgArrLongs);
}
final int curCount = extractCurCount(srcMem);
if ((curCount < 0) || (curCount > (1 << lgArrLongs))) {
throw new SketchesArgumentException("Possible corruption: invalid curCount: " + curCount);
}

//Check mem capacity, computed in long arithmetic so that it cannot overflow
final long curCapBytes = srcMem.getCapacity();
final int minReqBytes = getMemBytes(lgArrLongs, preambleLongs);
final long minReqBytes = (8L << lgArrLongs) + ((long) preambleLongs << 3);
if (curCapBytes < minReqBytes) {
throw new SketchesArgumentException(
"Possible corruption: Current Memory size < min required size: "
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/*
* 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
*
* http://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.datasketches.common;

import static org.apache.datasketches.common.ByteArrayUtil.putIntLE;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.expectThrows;

import java.util.Arrays;

import org.apache.datasketches.memory.Memory;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class StringSerDeBoundsTest {
@DataProvider(name = "stringSerDes")
public Object[][] stringSerDes() {
return new Object[][] {
{new ArrayOfStringsSerDe()},
{new ArrayOfUtf16StringsSerDe()}
};
}

@Test(dataProvider = "stringSerDes")
public void rejectInvalidLengthsBeforeAllocation(final ArrayOfItemsSerDe<String> serDe) {
for (final int length : new int[] {-1, Integer.MAX_VALUE, 5}) {
final byte[] bytes = new byte[Integer.BYTES];
putIntLE(bytes, 0, length);
final Memory mem = Memory.wrap(bytes);
expectThrows(SketchesArgumentException.class,
() -> serDe.deserializeFromMemory(mem, 1));
expectThrows(SketchesArgumentException.class, () -> serDe.sizeOf(mem, 0, 1));
}
}

@Test(dataProvider = "stringSerDes")
public void rejectImpossibleCountsBeforeAllocation(final ArrayOfItemsSerDe<String> serDe) {
final Memory mem = Memory.wrap(new byte[Integer.BYTES]);
expectThrows(SketchesArgumentException.class,
() -> serDe.deserializeFromMemory(mem, Integer.MAX_VALUE));
expectThrows(SketchesArgumentException.class,
() -> serDe.deserializeFromMemory(mem, 2));
}

@Test(dataProvider = "stringSerDes")
public void rejectInvalidOffsetsAndTruncatedPrefixes(final ArrayOfItemsSerDe<String> serDe) {
final Memory mem = Memory.wrap(new byte[Integer.BYTES]);
for (final long offset : new long[] {-1, Long.MAX_VALUE, 1, 4}) {
expectThrows(SketchesArgumentException.class,
() -> serDe.deserializeFromMemory(mem, offset, 1));
}
}

@Test(dataProvider = "stringSerDes")
public void preserveValidOffsetUnicodeAndOwnership(final ArrayOfItemsSerDe<String> serDe) {
final String[] expected = {"", "hello", "\u65e5\u672c\u8a9e", "\ud83d\ude00", "a\u0000b"};
final byte[] encoded = serDe.serializeToByteArray(expected);
final byte[] padded = new byte[3 + encoded.length + 1];
System.arraycopy(encoded, 0, padded, 3, encoded.length);
final Memory mem = Memory.wrap(padded);
final String[] actual = serDe.deserializeFromMemory(mem, 3, expected.length);
assertEquals(actual, expected);
assertEquals(serDe.sizeOf(mem, 3, expected.length), encoded.length);
Arrays.fill(padded, (byte) 0);
assertEquals(actual, expected);
}

@Test(dataProvider = "stringSerDes")
public void preserveEmptyCount(final ArrayOfItemsSerDe<String> serDe) {
assertEquals(serDe.deserializeFromMemory(Memory.wrap(new byte[0]), 0).length, 0);
}
}
Loading