diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 9ac5460f..cb55b0eb 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -41,6 +41,7 @@ jobs: -Darch.id=amd64 \ -Dnative.cc=gcc \ -Dsurefire.reportFormat=plain \ + -Dfailsafe.reportFormat=plain \ -Pcoverage \ verify - name: Install uv diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 74dd57d7..f5f0eaeb 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,6 +29,7 @@ jobs: # Disable fuzzing until https://github.com/CodeIntelligenceTesting/jazzer supports linux-riscv64 maven-flags: >- -Dtest='!net/jpountz/fuzz/*' + -Dit.test='!net/jpountz/fuzz/*' -Dmaven.compiler.source=8 -Dmaven.compiler.target=8 steps: @@ -57,8 +58,11 @@ jobs: -Darch.id=${arch_id} \ -Dnative.cc=gcc \ -Dsurefire.reportFormat=plain \ + -Dfailsafe.reportFormat=plain \ ${{ matrix.maven-flags }} \ verify - name: Summarize coverage if: matrix.coverage - run: python3 scripts/jacoco_summary.py target/site/jacoco/jacoco.csv >> "$GITHUB_STEP_SUMMARY" + run: >- + python3 scripts/jacoco_summary.py target/site/jacoco/jacoco.csv target/site/jacoco-java9/jacoco.csv + >> "$GITHUB_STEP_SUMMARY" diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 99bfea0a..c9d4b1d1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -20,6 +20,8 @@ To be accepted, a contribution must meet these requirements: - **The build passes.** `./mvnw verify` must succeed, and CI must be green on all platforms. See the [README](README.md#building) for build prerequisites. - **Java 7 compatibility.** The library is compiled with Java 7 and must not use newer language features or APIs. + The one exception is `src/java9`, compiled for Java 9 into `META-INF/versions/9` of the multi-release JAR. It only + holds the Java 9+ variant of `net.jpountz.util.ByteArrays`, which must keep the same methods as the Java 7 one. Tests may use the newer Java version configured in `pom.xml`. - **No breaking API changes.** Public API must stay source and binary compatible. Deprecate instead of removing, and keep new non-user-facing members as private as possible. diff --git a/README.md b/README.md index 1aa5187f..030001fe 100644 --- a/README.md +++ b/README.md @@ -87,7 +87,9 @@ now always uses the (slower) safe Java implementation, regardless of which facto `LZ4Factory` and `XXHashFactory` provide the following implementations, which all produce compatible output: - `nativeInstance()`: JNI bindings to the reference C implementation. -- `safeInstance()`: A pure Java port. +- `safeInstance()`: A pure Java port. On Java 9 and newer, on platforms with fast unaligned memory access (x86, + aarch64, ppc64le), it reads, writes and compares several bytes at a time with `VarHandle` and `Arrays.mismatch`, + still without `sun.misc.Unsafe`. - `unsafeInstance()`: A Java port using `sun.misc.Unsafe`. For LZ4, this is currently an alias for the safe instance out of caution. @@ -96,6 +98,20 @@ to Java otherwise. Obtaining a factory is expensive, so store it in a static fie [LZ4Factory javadoc](https://lz4-java.yawk.at/current/javadoc/net/jpountz/lz4/LZ4Factory) for caveats of the native implementation (temporary files, class loaders). +### Multi-release jar + +The Java 9+ code of `safeInstance()` is in `META-INF/versions/9` of the jar, so tools that rewrite or analyze the jar +must handle multi-release jars: + +- **Shading with relocation:** maven-shade-plugin (3.2.1 to 3.6.2) relocates the contents of `META-INF/versions/9` + classes, not their path. If the shaded jar keeps `Multi-Release: true`, its unrelocated + `META-INF/versions/9/net/jpountz/...` entry shadows a regular lz4-java on the same class path. Exclude + `META-INF/versions/9/net/jpountz/**` from the shaded jar; the relocated copy then uses the Java 7 code, which it + would do anyway. +- **jdeps** refuses a multi-release jar on the class path without `--multi-release`, e.g. `--multi-release 9`. +- **Tools that only read Java 8 class files**, such as ProGuard before 6.0 or ASM before 6.0, reject the Java 9 class. + Exclude `META-INF/versions/9/**` for them. + ## Examples ### LZ4 frame streams diff --git a/docs/justfile b/docs/justfile index 48a97b08..c043537d 100644 --- a/docs/justfile +++ b/docs/justfile @@ -115,7 +115,8 @@ rewrite-version-links: coverage: if [ -f ../target/site/jacoco/jacoco.csv ]; then \ cp -r ../target/site/jacoco '{{build}}/site/{{latest_version_name}}/coverage' && \ - python3 ../scripts/jacoco_summary.py ../target/site/jacoco/jacoco.csv --badge '{{build}}/site/{{latest_version_name}}/coverage/badge.json'; \ + cp -r ../target/site/jacoco-java9 '{{build}}/site/{{latest_version_name}}/coverage/java9' && \ + python3 ../scripts/jacoco_summary.py ../target/site/jacoco/jacoco.csv ../target/site/jacoco-java9/jacoco.csv --badge '{{build}}/site/{{latest_version_name}}/coverage/badge.json'; \ fi prepare: diff --git a/lz4-java.bnd b/lz4-java.bnd index a06ba026..28a5d11d 100644 --- a/lz4-java.bnd +++ b/lz4-java.bnd @@ -4,3 +4,6 @@ Bundle-Version: ${version_cleanup;${ivy.version}} Export-Package: net.jpountz.*;version:=${version_cleanup;${packages.version}} -noee: true -removeheaders: Require-Capability +# No per-release OSGI-INF/MANIFEST.MF: bnd writes an empty Require-Capability there, which Felix and Equinox reject. +# The Java 9 classes in META-INF/versions/9 only add java.lang.invoke, and java.* always comes from the boot loader. +-jpms-multi-release: false diff --git a/pom.xml b/pom.xml index 277aca5f..e2093ad6 100644 --- a/pom.xml +++ b/pom.xml @@ -70,6 +70,8 @@ 7.5.0 + + 3.6.1 ${project.version} ${project.version} @@ -188,6 +190,24 @@ + + + compile-java9 + compile + + compile + + + 9 + + ${project.basedir}/src/java9 + + true + ${project.build.sourceEncoding} + true + true + + default-testCompile test-compile @@ -213,6 +233,7 @@ ${project.build.outputDirectory}/META-INF/MANIFEST.MF org.lz4.java + true @@ -275,7 +296,38 @@ org.apache.maven.plugins maven-surefire-plugin - 3.6.1 + ${surefire.version} + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${surefire.version} + + + + integration-test + verify + + + + + + net/jpountz/util/MultiReleaseJarTest.java + net/jpountz/lz4/LZ4Test.java + net/jpountz/lz4/OutOfBoundsTest.java + net/jpountz/lz4/OverlappingMatchTest.java + net/jpountz/lz4/UtilsTest.java + net/jpountz/xxhash/XXHash32Test.java + net/jpountz/xxhash/XXHash64Test.java + net/jpountz/fuzz/*Test.java + + + true + + org.apache.maven.plugins @@ -363,6 +415,25 @@ report + + + + META-INF/versions/** + + + + + report-java9 + verify + + report + + + + META-INF/versions/9/** + + ${project.reporting.outputDirectory}/jacoco-java9 + @@ -657,6 +728,7 @@ -O1 -g -fPIC -fno-omit-frame-pointer 5s + true @@ -684,7 +756,7 @@ org.apache.maven.plugins maven-surefire-plugin - 3.6.1 + ${surefire.version} true diff --git a/scripts/fuzz_runner.py b/scripts/fuzz_runner.py index 96bb3be6..3dabcd97 100755 --- a/scripts/fuzz_runner.py +++ b/scripts/fuzz_runner.py @@ -118,6 +118,9 @@ def read_pom_executions(pom_path: Path, profile_id: str = "fuzz") -> List[FuzzEx if artifact_id == "maven-surefire-plugin": surefire_nodes.append(plugin) v = plugin.findtext("m:version", default="", namespaces=POM_NS) + m = re.fullmatch(r"\$\{(.+)\}", v) + if m: + v = root.findtext(f"m:properties/m:{m.group(1)}", default="", namespaces=POM_NS) if v: surefire_version = v diff --git a/scripts/jacoco_summary.py b/scripts/jacoco_summary.py index 672e7232..52d29250 100644 --- a/scripts/jacoco_summary.py +++ b/scripts/jacoco_summary.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Summarize line coverage from a JaCoCo CSV report. +"""Summarize line coverage from one or more JaCoCo CSV reports. Prints a Markdown summary line, and with --badge also writes a shields.io endpoint badge JSON file. """ @@ -8,15 +8,16 @@ import json parser = argparse.ArgumentParser(description=__doc__) -parser.add_argument("csv", help="JaCoCo CSV report, e.g. target/site/jacoco/jacoco.csv") +parser.add_argument("csv", nargs="+", help="JaCoCo CSV reports, e.g. target/site/jacoco/jacoco.csv") parser.add_argument("--badge", help="write shields.io endpoint badge JSON to this file") args = parser.parse_args() missed = covered = 0 -with open(args.csv, newline="") as f: - for row in csv.DictReader(f): - missed += int(row["LINE_MISSED"]) - covered += int(row["LINE_COVERED"]) +for path in args.csv: + with open(path, newline="") as f: + for row in csv.DictReader(f): + missed += int(row["LINE_MISSED"]) + covered += int(row["LINE_COVERED"]) total = missed + covered pct = 100 * covered / total diff --git a/src/java/net/jpountz/lz4/LZ4SafeUtils.java b/src/java/net/jpountz/lz4/LZ4SafeUtils.java index 1d62b991..5a36c5df 100644 --- a/src/java/net/jpountz/lz4/LZ4SafeUtils.java +++ b/src/java/net/jpountz/lz4/LZ4SafeUtils.java @@ -16,6 +16,7 @@ * limitations under the License. */ +import net.jpountz.util.ByteArrays; import net.jpountz.util.SafeUtils; import static net.jpountz.lz4.LZ4Constants.LAST_LITERALS; @@ -38,7 +39,7 @@ static int hash64k(byte[] buf, int i) { } static boolean readIntEquals(byte[] buf, int i, int j) { - return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] && buf[i + 3] == buf[j + 3]; + return ByteArrays.readIntEquals(buf, i, j); } static void safeIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchLen) { @@ -48,25 +49,11 @@ static void safeIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchLe } static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { - do { - copy8Bytes(dest, matchOff, dest, dOff); - matchOff += 8; - dOff += 8; - } while (dOff < matchCopyEnd); - } - - static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { - for (int i = 0; i < 8; ++i) { - dest[dOff + i] = src[sOff + i]; - } + ByteArrays.wildIncrementalCopy(dest, matchOff, dOff, matchCopyEnd); } static int commonBytes(byte[] b, int o1, int o2, int limit) { - int count = 0; - while (o2 < limit && b[o1++] == b[o2++]) { - ++count; - } - return count; + return ByteArrays.commonBytes(b, o1, o2, limit); } static int commonBytesBackward(byte[] b, int o1, int o2, int l1, int l2) { @@ -84,9 +71,9 @@ static void safeArraycopy(byte[] src, int sOff, byte[] dest, int dOff, int len) static void wildArraycopy(byte[] src, int sOff, byte[] dest, int dOff, int len) { try { for (int i = 0; i < len; i += 8) { - copy8Bytes(src, sOff + i, dest, dOff + i); + ByteArrays.copy8Bytes(src, sOff + i, dest, dOff + i); } - } catch (ArrayIndexOutOfBoundsException e) { + } catch (IndexOutOfBoundsException e) { // the Java 9+ ByteArrays may throw the superclass throw new LZ4Exception("Malformed input at offset " + sOff); } } diff --git a/src/java/net/jpountz/util/ByteArrays.java b/src/java/net/jpountz/util/ByteArrays.java new file mode 100644 index 00000000..e2261181 --- /dev/null +++ b/src/java/net/jpountz/util/ByteArrays.java @@ -0,0 +1,88 @@ +package net.jpountz.util; + +/* + * Copyright 2020 Adrien Grand and the lz4-java contributors. + * + * Licensed 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. + */ + +/** + * FOR INTERNAL USE ONLY + *

+ * Not part of the public API: it is public only because net.jpountz.lz4 uses it, and it may change or go away in any + * release. + *

+ * Multi-byte reads, writes, copies and comparisons on byte arrays for the safe implementations. This is the only class + * with a Java 9+ variant: src/java9/net/jpountz/util/ByteArrays.java, loaded from META-INF/versions/9 of the + * multi-release jar. Keep the two in sync, and keep everything else out of them. The byte loops themselves are in + * {@link PortableByteArrays}, which the Java 9+ variant also uses where unaligned access is not allowed. + */ +public final class ByteArrays { + + private ByteArrays() {} + + static int readShortLE(byte[] buf, int i) { + return PortableByteArrays.readShortLE(buf, i); + } + + static void writeShortLE(byte[] buf, int off, int v) { + PortableByteArrays.writeShortLE(buf, off, v); + } + + static int readIntBE(byte[] buf, int i) { + return PortableByteArrays.readIntBE(buf, i); + } + + static int readIntLE(byte[] buf, int i) { + return PortableByteArrays.readIntLE(buf, i); + } + + /** Reads an int in native byte order. */ + static int readInt(byte[] buf, int i) { + return PortableByteArrays.readInt(buf, i); + } + + static long readLongLE(byte[] buf, int i) { + return PortableByteArrays.readLongLE(buf, i); + } + + /** Whether the 4 bytes at i equal the 4 bytes at j. All 8 bytes must be in bounds. */ + public static boolean readIntEquals(byte[] buf, int i, int j) { + return PortableByteArrays.readIntEquals(buf, i, j); + } + + /** + * Copies 8 bytes from src[sOff] to dest[dOff]. Both ranges must be in bounds, and must not overlap if src and dest + * are the same array: the Java 7 variant copies one byte at a time, the Java 9 variant may read all 8 bytes first. + */ + public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { + PortableByteArrays.copy8Bytes(src, sOff, dest, dOff); + } + + /** + * The number of equal bytes at o1 and o2, scanning forward until o2 reaches limit. Requires o1 < o2 and + * limit <= b.length: the Java 9 variant checks the whole range up front, not only the bytes it compares. + */ + public static int commonBytes(byte[] b, int o1, int o2, int limit) { + return PortableByteArrays.commonBytes(b, o1, o2, limit); + } + + /** + * Copies an LZ4 match: dest[dOff, matchCopyEnd) from dest[matchOff, ...), where the ranges may overlap. Requires + * matchOff < dOff and matchCopyEnd - dOff >= 4 (the minimum match length), and writes up to 7 bytes past + * matchCopyEnd, which must be in bounds. The bytes written past matchCopyEnd differ between the variants. + */ + public static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { + PortableByteArrays.wildIncrementalCopy(dest, matchOff, dOff, matchCopyEnd); + } +} diff --git a/src/java/net/jpountz/util/PortableByteArrays.java b/src/java/net/jpountz/util/PortableByteArrays.java new file mode 100644 index 00000000..74c811fe --- /dev/null +++ b/src/java/net/jpountz/util/PortableByteArrays.java @@ -0,0 +1,85 @@ +package net.jpountz.util; + +/* + * Copyright 2020 Adrien Grand and the lz4-java contributors. + * + * Licensed 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. + */ + +import java.nio.ByteOrder; + +/** + * The {@link ByteArrays} methods as byte-at-a-time loops, which work on any JVM and CPU. The Java 7 ByteArrays uses + * them for everything, and the Java 9+ ByteArrays where {@link Utils#isUnalignedAccessAllowed()} is false. See + * ByteArrays for what each method requires. + */ +final class PortableByteArrays { + + private PortableByteArrays() {} + + static int readShortLE(byte[] buf, int i) { + return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8); + } + + static void writeShortLE(byte[] buf, int off, int v) { + buf[off] = (byte) v; + buf[off + 1] = (byte) (v >>> 8); + } + + static int readIntBE(byte[] buf, int i) { + return ((buf[i] & 0xFF) << 24) | ((buf[i + 1] & 0xFF) << 16) | ((buf[i + 2] & 0xFF) << 8) | (buf[i + 3] & 0xFF); + } + + static int readIntLE(byte[] buf, int i) { + return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8) | ((buf[i + 2] & 0xFF) << 16) | ((buf[i + 3] & 0xFF) << 24); + } + + static int readInt(byte[] buf, int i) { + if (Utils.NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN) { + return readIntBE(buf, i); + } else { + return readIntLE(buf, i); + } + } + + static long readLongLE(byte[] buf, int i) { + return (buf[i] & 0xFFL) | ((buf[i + 1] & 0xFFL) << 8) | ((buf[i + 2] & 0xFFL) << 16) | ((buf[i + 3] & 0xFFL) << 24) + | ((buf[i + 4] & 0xFFL) << 32) | ((buf[i + 5] & 0xFFL) << 40) | ((buf[i + 6] & 0xFFL) << 48) | ((buf[i + 7] & 0xFFL) << 56); + } + + static boolean readIntEquals(byte[] buf, int i, int j) { + return buf[i] == buf[j] && buf[i + 1] == buf[j + 1] && buf[i + 2] == buf[j + 2] && buf[i + 3] == buf[j + 3]; + } + + static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { + for (int i = 0; i < 8; ++i) { + dest[dOff + i] = src[sOff + i]; + } + } + + static int commonBytes(byte[] b, int o1, int o2, int limit) { + int count = 0; + while (o2 < limit && b[o1++] == b[o2++]) { + ++count; + } + return count; + } + + static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { + do { + copy8Bytes(dest, matchOff, dest, dOff); + matchOff += 8; + dOff += 8; + } while (dOff < matchCopyEnd); + } +} diff --git a/src/java/net/jpountz/util/SafeUtils.java b/src/java/net/jpountz/util/SafeUtils.java index 1cbead11..26380a52 100644 --- a/src/java/net/jpountz/util/SafeUtils.java +++ b/src/java/net/jpountz/util/SafeUtils.java @@ -16,8 +16,6 @@ * limitations under the License. */ -import java.nio.ByteOrder; - /** FOR INTERNAL USE ONLY */ public enum SafeUtils { ; @@ -47,29 +45,23 @@ public static byte readByte(byte[] buf, int i) { } public static int readIntBE(byte[] buf, int i) { - return ((buf[i] & 0xFF) << 24) | ((buf[i + 1] & 0xFF) << 16) | ((buf[i + 2] & 0xFF) << 8) | (buf[i + 3] & 0xFF); + return ByteArrays.readIntBE(buf, i); } public static int readIntLE(byte[] buf, int i) { - return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8) | ((buf[i + 2] & 0xFF) << 16) | ((buf[i + 3] & 0xFF) << 24); + return ByteArrays.readIntLE(buf, i); } public static int readInt(byte[] buf, int i) { - if (Utils.NATIVE_BYTE_ORDER == ByteOrder.BIG_ENDIAN) { - return readIntBE(buf, i); - } else { - return readIntLE(buf, i); - } + return ByteArrays.readInt(buf, i); } public static long readLongLE(byte[] buf, int i) { - return (buf[i] & 0xFFL) | ((buf[i + 1] & 0xFFL) << 8) | ((buf[i + 2] & 0xFFL) << 16) | ((buf[i + 3] & 0xFFL) << 24) - | ((buf[i + 4] & 0xFFL) << 32) | ((buf[i + 5] & 0xFFL) << 40) | ((buf[i + 6] & 0xFFL) << 48) | ((buf[i + 7] & 0xFFL) << 56); + return ByteArrays.readLongLE(buf, i); } public static void writeShortLE(byte[] buf, int off, int v) { - buf[off++] = (byte) v; - buf[off++] = (byte) (v >>> 8); + ByteArrays.writeShortLE(buf, off, v); } public static void writeInt(int[] buf, int off, int v) { @@ -89,7 +81,7 @@ public static void writeShort(short[] buf, int off, int v) { } public static int readShortLE(byte[] buf, int i) { - return (buf[i] & 0xFF) | ((buf[i + 1] & 0xFF) << 8); + return ByteArrays.readShortLE(buf, i); } public static int readShort(short[] buf, int off) { diff --git a/src/java9/net/jpountz/util/ByteArrays.java b/src/java9/net/jpountz/util/ByteArrays.java new file mode 100644 index 00000000..be5ca138 --- /dev/null +++ b/src/java9/net/jpountz/util/ByteArrays.java @@ -0,0 +1,168 @@ +package net.jpountz.util; + +/* + * Copyright 2020 Adrien Grand and the lz4-java contributors. + * + * Licensed 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. + */ + +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; +import java.nio.ByteOrder; +import java.util.Arrays; + +/** + * FOR INTERNAL USE ONLY + *

+ * Not part of the public API: it is public only because net.jpountz.lz4 uses it, and it may change or go away in any + * release. + *

+ * Java 9+ variant of src/java/net/jpountz/util/ByteArrays.java, loaded from META-INF/versions/9 of the multi-release + * jar. VarHandle views and Arrays.mismatch read, write and compare several bytes per bounds check. The copies follow + * LZ4UnsafeUtils, without Unsafe. + *

+ * Where {@link Utils#isUnalignedAccessAllowed()} is false, HotSpot does not compile the VarHandle views and + * Arrays.mismatch to wide accesses, and they are slower than byte loops. There every method uses the byte loops of + * {@link PortableByteArrays}, as the Java 7 variant does. + */ +public final class ByteArrays { + + private ByteArrays() {} + + private static final VarHandle SHORT_LE = MethodHandles.byteArrayViewVarHandle(short[].class, ByteOrder.LITTLE_ENDIAN); + private static final VarHandle INT_LE = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.LITTLE_ENDIAN); + private static final VarHandle INT_BE = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.BIG_ENDIAN); + private static final VarHandle INT = MethodHandles.byteArrayViewVarHandle(int[].class, ByteOrder.nativeOrder()); + private static final VarHandle LONG_LE = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.LITTLE_ENDIAN); + private static final VarHandle LONG = MethodHandles.byteArrayViewVarHandle(long[].class, ByteOrder.nativeOrder()); + private static final boolean UNALIGNED = Utils.isUnalignedAccessAllowed(); + + static int readShortLE(byte[] buf, int i) { + if (!UNALIGNED) { + return PortableByteArrays.readShortLE(buf, i); + } + return (short) SHORT_LE.get(buf, i) & 0xFFFF; + } + + static void writeShortLE(byte[] buf, int off, int v) { + if (!UNALIGNED) { + PortableByteArrays.writeShortLE(buf, off, v); + return; + } + SHORT_LE.set(buf, off, (short) v); + } + + static int readIntBE(byte[] buf, int i) { + if (!UNALIGNED) { + return PortableByteArrays.readIntBE(buf, i); + } + return (int) INT_BE.get(buf, i); + } + + static int readIntLE(byte[] buf, int i) { + if (!UNALIGNED) { + return PortableByteArrays.readIntLE(buf, i); + } + return (int) INT_LE.get(buf, i); + } + + /** Reads an int in native byte order. */ + static int readInt(byte[] buf, int i) { + if (!UNALIGNED) { + return PortableByteArrays.readInt(buf, i); + } + return (int) INT.get(buf, i); + } + + static long readLongLE(byte[] buf, int i) { + if (!UNALIGNED) { + return PortableByteArrays.readLongLE(buf, i); + } + return (long) LONG_LE.get(buf, i); + } + + /** Whether the 4 bytes at i equal the 4 bytes at j. All 8 bytes must be in bounds. */ + public static boolean readIntEquals(byte[] buf, int i, int j) { + if (!UNALIGNED) { + return PortableByteArrays.readIntEquals(buf, i, j); + } + return (int) INT.get(buf, i) == (int) INT.get(buf, j); + } + + /** + * Copies 8 bytes from src[sOff] to dest[dOff]. Both ranges must be in bounds, and must not overlap if src and dest + * are the same array: the Java 7 variant copies one byte at a time, the Java 9 variant may read all 8 bytes first. + */ + public static void copy8Bytes(byte[] src, int sOff, byte[] dest, int dOff) { + if (!UNALIGNED) { + PortableByteArrays.copy8Bytes(src, sOff, dest, dOff); + return; + } + LONG.set(dest, dOff, (long) LONG.get(src, sOff)); + } + + /** + * The number of equal bytes at o1 and o2, scanning forward until o2 reaches limit. Requires o1 < o2 and + * limit <= b.length: the Java 9 variant checks the whole range up front, not only the bytes it compares. + */ + public static int commonBytes(byte[] b, int o1, int o2, int limit) { + final int len = limit - o2; + if (len < 8 || !UNALIGNED) { + return PortableByteArrays.commonBytes(b, o1, o2, limit); + } + // Most matches end within a few bytes, so compare one word before paying for the setup of Arrays.mismatch. + final long diff = (long) LONG_LE.get(b, o1) ^ (long) LONG_LE.get(b, o2); + if (diff != 0) { + return Long.numberOfTrailingZeros(diff) >>> 3; + } + final int mismatch = Arrays.mismatch(b, o1 + 8, o1 + len, b, o2 + 8, limit); + return mismatch < 0 ? len : 8 + mismatch; + } + + /** + * Copies an LZ4 match: dest[dOff, matchCopyEnd) from dest[matchOff, ...), where the ranges may overlap. Requires + * matchOff < dOff and matchCopyEnd - dOff >= 4 (the minimum match length), and writes up to 7 bytes past + * matchCopyEnd, which must be in bounds. The bytes written past matchCopyEnd differ between the variants. + */ + public static void wildIncrementalCopy(byte[] dest, int matchOff, int dOff, int matchCopyEnd) { + // An 8-byte copy reads bytes it has not written yet while the distance is below 8. Write the start of the repeating + // pattern first, so that matchOff can trail dOff by a multiple of the pattern length of at least 8: 8 for distances + // 1 and 2, 9 for 3, and twice the distance for 4 to 7. + if (!UNALIGNED) { + PortableByteArrays.wildIncrementalCopy(dest, matchOff, dOff, matchCopyEnd); + return; + } + final int distance = dOff - matchOff; + assert distance > 0 : distance; + if (distance < 4) { + for (int i = 0; i < 4; ++i) { + dest[dOff + i] = dest[matchOff + i]; + } + // The next 4 bytes continue the pattern from matchOff + 1 (distances 1 and 3) or matchOff + 2 (distance 2). + matchOff += distance == 2 ? 2 : 1; + INT.set(dest, dOff + 4, (int) INT.get(dest, matchOff)); + dOff += 8; + if (distance == 3) { + ++matchOff; + } + } else if (distance < 8) { + copy8Bytes(dest, matchOff, dest, dOff); + dOff += distance; + } + while (dOff < matchCopyEnd) { + copy8Bytes(dest, matchOff, dest, dOff); + dOff += 8; + matchOff += 8; + } + } +} diff --git a/src/test/net/jpountz/lz4/LZ4Test.java b/src/test/net/jpountz/lz4/LZ4Test.java index 8ad6fc2d..317d0469 100644 --- a/src/test/net/jpountz/lz4/LZ4Test.java +++ b/src/test/net/jpountz/lz4/LZ4Test.java @@ -375,7 +375,7 @@ private static void assertAllReject(byte[] block, int maxDestLen, int destLen) { * Asserts that every decompressor decodes {@code block} to the same {@code decompressedLen} bytes, with an * exact-size destination and with a larger one. */ - private static void assertAllDecode(byte[] block, int decompressedLen) { + static void assertAllDecode(byte[] block, int decompressedLen) { final byte[] expected = LZ4Factory.safeInstance().safeDecompressor().decompress(block, decompressedLen); assertEquals(decompressedLen, expected.length); for (LZ4SafeDecompressor decompressor : SAFE_DECOMPRESSORS) { diff --git a/src/test/net/jpountz/lz4/OverlappingMatchTest.java b/src/test/net/jpountz/lz4/OverlappingMatchTest.java new file mode 100644 index 00000000..bc0f66df --- /dev/null +++ b/src/test/net/jpountz/lz4/OverlappingMatchTest.java @@ -0,0 +1,78 @@ +package net.jpountz.lz4; + +/* + * Copyright 2026 Jonas Konrad and the lz4-java contributors. + * + * Licensed 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. + */ + +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; + +import static net.jpountz.lz4.LZ4Constants.MIN_MATCH; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; + +/** + * A match whose distance is shorter than its length repeats a pattern. The decompressors copy matches in 4 and 8 byte + * steps, which must not read bytes before they are written. Every decompressor must decode each block to the expected + * bytes, into an exact-size destination and into a larger one. + */ +public class OverlappingMatchTest { + private static final int LITERALS = 12; + private static final int TRAILING_LITERALS = 12; + + @Test + public void overlappingMatches() { + for (int distance = 1; distance <= LITERALS; distance++) { + for (int matchLen = MIN_MATCH; matchLen <= 40; matchLen++) { + byte[] expected = expected(distance, matchLen); + byte[] block = block(expected, distance, matchLen); + String what = "distance " + distance + ", match length " + matchLen; + assertArrayEquals(expected, LZ4Factory.safeInstance().safeDecompressor().decompress(block, expected.length), + what); + try { + LZ4Test.assertAllDecode(block, expected.length); + } catch (AssertionError e) { + throw new AssertionError(what, e); + } + } + } + } + + /** LITERALS distinct bytes, the match expanded one byte at a time, then TRAILING_LITERALS more bytes. */ + private static byte[] expected(int distance, int matchLen) { + byte[] out = new byte[LITERALS + matchLen + TRAILING_LITERALS]; + for (int i = 0; i < out.length; i++) { + boolean inMatch = i >= LITERALS && i < LITERALS + matchLen; + out[i] = inMatch ? out[i - distance] : (byte) (i + 1); + } + return out; + } + + /** One sequence with the literals and the match, then a last sequence with only the trailing literals. */ + private static byte[] block(byte[] expected, int distance, int matchLen) { + ByteArrayOutputStream block = new ByteArrayOutputStream(); + int extraMatchLen = matchLen - MIN_MATCH; + block.write(LITERALS << 4 | Math.min(extraMatchLen, 15)); + block.write(expected, 0, LITERALS); + block.write(distance); + block.write(distance >>> 8); + if (extraMatchLen >= 15) { + block.write(extraMatchLen - 15); + } + block.write(TRAILING_LITERALS << 4); + block.write(expected, LITERALS + matchLen, TRAILING_LITERALS); + return block.toByteArray(); + } +} diff --git a/src/test/net/jpountz/util/MultiReleaseJarTest.java b/src/test/net/jpountz/util/MultiReleaseJarTest.java new file mode 100644 index 00000000..43bab43f --- /dev/null +++ b/src/test/net/jpountz/util/MultiReleaseJarTest.java @@ -0,0 +1,119 @@ +package net.jpountz.util; + +/* + * Copyright 2026 Jonas Konrad and the lz4-java contributors. + * + * Licensed 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. + */ + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +import java.io.DataInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Member; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.Enumeration; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; +import java.util.jar.Manifest; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +/** + * The failsafe execution sets lz4.testJar and runs the tests against the multi-release jar. There ByteArrays must be + * the Java 9 variant, or that run tests the Java 7 class a second time. + */ +@EnabledIfSystemProperty(named = "lz4.testJar", matches = "true", disabledReason = "only runs against the packaged jar") +public class MultiReleaseJarTest { + private static final int JAVA_9_CLASS_FILE = 53; + + @Test + public void jarServesJava9ByteArrays() throws Exception { + assertEquals(JAVA_9_CLASS_FILE, classFileMajorVersion(ByteArrays.class)); + } + + /** + * Code compiles against the Java 7 ByteArrays, so a method or field missing from the Java 9 one fails only at run + * time. Private and synthetic members are not reachable from other classes and may differ. + */ + @Test + public void java9ByteArraysHasTheSameMembers() throws Exception { + byte[] java7Class; + // Without a runtime version, JarFile returns the base entry rather than the META-INF/versions/9 one. + try (JarFile jarFile = new JarFile(jar()); + InputStream in = jarFile.getInputStream(jarFile.getEntry("net/jpountz/util/ByteArrays.class"))) { + java7Class = in.readAllBytes(); + } + class Java7Loader extends ClassLoader { + Java7Loader() { + super(null); + } + + Class define() { + return defineClass(ByteArrays.class.getName(), java7Class, 0, java7Class.length); + } + } + assertEquals(accessibleMembers(new Java7Loader().define()), accessibleMembers(ByteArrays.class)); + } + + private static Set accessibleMembers(Class c) { + return Stream.concat(Arrays.stream(c.getDeclaredMethods()), Arrays.stream(c.getDeclaredFields())) + .filter(m -> !Modifier.isPrivate(m.getModifiers()) && !m.isSynthetic()) + .map(Member::toString) + .collect(Collectors.toCollection(TreeSet::new)); + } + + /** + * Felix and Equinox refuse to resolve a bundle with an empty manifest header. bnd writes an empty Require-Capability + * into META-INF/versions/9/OSGI-INF/MANIFEST.MF unless lz4-java.bnd disables those per-release manifests. + */ + @Test + public void manifestsHaveNoEmptyHeaders() throws Exception { + try (JarFile jarFile = new JarFile(jar())) { + for (Enumeration entries = jarFile.entries(); entries.hasMoreElements(); ) { + JarEntry entry = entries.nextElement(); + if (!entry.getName().endsWith("MANIFEST.MF")) { + continue; + } + try (InputStream in = jarFile.getInputStream(entry)) { + for (Map.Entry header : new Manifest(in).getMainAttributes().entrySet()) { + assertFalse(header.getValue().toString().trim().isEmpty(), entry.getName() + ": empty " + header.getKey()); + } + } + } + } + } + + private static File jar() throws Exception { + return new File(ByteArrays.class.getProtectionDomain().getCodeSource().getLocation().toURI()); + } + + private static int classFileMajorVersion(Class c) throws IOException { + try (InputStream resource = c.getResourceAsStream(c.getSimpleName() + ".class"); + DataInputStream in = new DataInputStream(resource)) { + in.readInt(); // magic + in.readUnsignedShort(); // minor version + return in.readUnsignedShort(); + } + } +}