Skip to content
Merged
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
1 change: 1 addition & 0 deletions .github/workflows/docs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ jobs:
-Darch.id=amd64 \
-Dnative.cc=gcc \
-Dsurefire.reportFormat=plain \
-Dfailsafe.reportFormat=plain \
-Pcoverage \
verify
- name: Install uv
Expand Down
6 changes: 5 additions & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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"
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
18 changes: 17 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion docs/justfile
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
3 changes: 3 additions & 0 deletions lz4-java.bnd
Original file line number Diff line number Diff line change
Expand Up @@ -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
76 changes: 74 additions & 2 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,8 @@

<!-- plugin versions -->
<bnd.maven.plugin.version>7.5.0</bnd.maven.plugin.version>
<!-- surefire and failsafe are released together and must stay at the same version -->
<surefire.version>3.6.1</surefire.version>
<packages.version>${project.version}</packages.version>
<ivy.version>${project.version}</ivy.version>

Expand Down Expand Up @@ -188,6 +190,24 @@
</jdkToolchain>
</configuration>
</execution>
<!-- Java 9+ variant of net.jpountz.util.ByteArrays, loaded from META-INF/versions/9 of the multi-release jar -->
<execution>
<id>compile-java9</id>
<phase>compile</phase>
<goals>
<goal>compile</goal>
</goals>
<configuration>
<release>9</release>
<compileSourceRoots>
<compileSourceRoot>${project.basedir}/src/java9</compileSourceRoot>
</compileSourceRoots>
<multiReleaseOutput>true</multiReleaseOutput>
<encoding>${project.build.sourceEncoding}</encoding>
<debug>true</debug>
<fork>true</fork>
</configuration>
</execution>
<execution>
<id>default-testCompile</id>
<phase>test-compile</phase>
Expand All @@ -213,6 +233,7 @@
<manifestFile>${project.build.outputDirectory}/META-INF/MANIFEST.MF</manifestFile>
<manifestEntries>
<Automatic-Module-Name>org.lz4.java</Automatic-Module-Name>
<Multi-Release>true</Multi-Release>
</manifestEntries>
</archive>
</configuration>
Expand Down Expand Up @@ -275,7 +296,38 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.1</version>
<version>${surefire.version}</version>
</plugin>
<!-- Surefire tests target/classes, where Java 9+ does not apply META-INF/versions. Rerun the tests that reach the
safe Java implementations against the multi-release jar so the Java 9+ ByteArrays is tested too. The stream
and factory tests mostly run the JNI code, which the jar does not change. -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>${surefire.version}</version>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
<configuration>
<includes>
<include>net/jpountz/util/MultiReleaseJarTest.java</include>
<include>net/jpountz/lz4/LZ4Test.java</include>
<include>net/jpountz/lz4/OutOfBoundsTest.java</include>
<include>net/jpountz/lz4/OverlappingMatchTest.java</include>
<include>net/jpountz/lz4/UtilsTest.java</include>
<include>net/jpountz/xxhash/XXHash32Test.java</include>
<include>net/jpountz/xxhash/XXHash64Test.java</include>
<include>net/jpountz/fuzz/*Test.java</include>
</includes>
<systemPropertyVariables>
<lz4.testJar>true</lz4.testJar>
</systemPropertyVariables>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
Expand Down Expand Up @@ -363,6 +415,25 @@
<goals>
<goal>report</goal>
</goals>
<configuration>
<!-- A report cannot hold two classes of the same name; report-java9 covers the Java 9+ ByteArrays -->
<excludes>
<exclude>META-INF/versions/**</exclude>
</excludes>
</configuration>
</execution>
<execution>
<id>report-java9</id>
<phase>verify</phase>
<goals>
<goal>report</goal>
</goals>
<configuration>
<includes>
<include>META-INF/versions/9/**</include>
</includes>
<outputDirectory>${project.reporting.outputDirectory}/jacoco-java9</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
Expand Down Expand Up @@ -657,6 +728,7 @@
<native.cflags>-O1 -g -fPIC -fno-omit-frame-pointer</native.cflags>
<native.ldflags></native.ldflags>
<jazzer.max_duration>5s</jazzer.max_duration>
<skipITs>true</skipITs>
</properties>
<build>
<plugins>
Expand Down Expand Up @@ -684,7 +756,7 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.6.1</version>
<version>${surefire.version}</version>
<configuration>
<failIfNoTests>true</failIfNoTests>
<systemPropertyVariables>
Expand Down
3 changes: 3 additions & 0 deletions scripts/fuzz_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
13 changes: 7 additions & 6 deletions scripts/jacoco_summary.py
Original file line number Diff line number Diff line change
@@ -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.
"""
Expand All @@ -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

Expand Down
25 changes: 6 additions & 19 deletions src/java/net/jpountz/lz4/LZ4SafeUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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) {
Expand All @@ -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) {
Expand All @@ -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);
}
}
Expand Down
88 changes: 88 additions & 0 deletions src/java/net/jpountz/util/ByteArrays.java
Original file line number Diff line number Diff line change
@@ -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.
*/

/**
* <b>FOR INTERNAL USE ONLY</b>
* <p>
* 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.
* <p>
* 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 &lt; o2 and
* limit &lt;= 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 &lt; dOff and matchCopyEnd - dOff &gt;= 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);
}
}
Loading
Loading