Merge "Set the container field of aconfig flags" into main
diff --git a/EXPECTED_UPSTREAM b/EXPECTED_UPSTREAM
index 70b62f0..6acf96d 100644
--- a/EXPECTED_UPSTREAM
+++ b/EXPECTED_UPSTREAM
@@ -1251,12 +1251,12 @@
ojluni/src/main/java/java/util/zip/CheckedOutputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/CheckedOutputStream.java
ojluni/src/main/java/java/util/zip/Checksum.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/Checksum.java
ojluni/src/main/java/java/util/zip/DataFormatException.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/DataFormatException.java
-ojluni/src/main/java/java/util/zip/Deflater.java,jdk8u/jdk8u121-b13,jdk/src/share/classes/java/util/zip/Deflater.java
+ojluni/src/main/java/java/util/zip/Deflater.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/Deflater.java
ojluni/src/main/java/java/util/zip/DeflaterInputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/DeflaterInputStream.java
ojluni/src/main/java/java/util/zip/DeflaterOutputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/DeflaterOutputStream.java
ojluni/src/main/java/java/util/zip/GZIPInputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/GZIPInputStream.java
ojluni/src/main/java/java/util/zip/GZIPOutputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/GZIPOutputStream.java
-ojluni/src/main/java/java/util/zip/Inflater.java,jdk8u/jdk8u121-b13,jdk/src/share/classes/java/util/zip/Inflater.java
+ojluni/src/main/java/java/util/zip/Inflater.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/Inflater.java
ojluni/src/main/java/java/util/zip/InflaterInputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/InflaterInputStream.java
ojluni/src/main/java/java/util/zip/InflaterOutputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/InflaterOutputStream.java
ojluni/src/main/java/java/util/zip/ZStreamRef.java,jdk8u/jdk8u121-b13,jdk/src/share/classes/java/util/zip/ZStreamRef.java
@@ -1266,7 +1266,7 @@
ojluni/src/main/java/java/util/zip/ZipEntry.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/ZipEntry.java
ojluni/src/main/java/java/util/zip/ZipError.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/ZipError.java
ojluni/src/main/java/java/util/zip/ZipException.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/ZipException.java
-ojluni/src/main/java/java/util/zip/ZipFile.java,jdk8u/jdk8u121-b13,jdk/src/share/classes/java/util/zip/ZipFile.java
+ojluni/src/main/java/java/util/zip/ZipFile.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/ZipFile.java
ojluni/src/main/java/java/util/zip/ZipInputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/ZipInputStream.java
ojluni/src/main/java/java/util/zip/ZipOutputStream.java,jdk17u/jdk-17.0.6-ga,src/java.base/share/classes/java/util/zip/ZipOutputStream.java
ojluni/src/main/java/java/util/zip/ZipUtils.java,jdk17u/jdk-17.0.5-ga,src/java.base/share/classes/java/util/zip/ZipUtils.java
@@ -1836,7 +1836,7 @@
ojluni/src/main/native/Console_md.c,jdk8u/jdk8u121-b13,jdk/src/solaris/native/java/io/Console_md.c
ojluni/src/main/native/DatagramChannelImpl.c,jdk8u/jdk8u121-b13,jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c
ojluni/src/main/native/DatagramDispatcher.c,jdk8u/jdk8u121-b13,jdk/src/solaris/native/sun/nio/ch/DatagramDispatcher.c
-ojluni/src/main/native/Deflater.c,jdk8u/jdk8u60-b31,jdk/src/share/native/java/util/zip/Deflater.c
+ojluni/src/main/native/Deflater.c,jdk17u/jdk-17.0.6-ga,src/java.base/share/native/libzip/Deflater.c
ojluni/src/main/native/Double.c,jdk8u/jdk8u121-b13,jdk/src/share/native/java/lang/Double.c
ojluni/src/main/native/EPoll.c,jdk8u/jdk8u121-b13,jdk/src/solaris/native/sun/nio/ch/EPoll.c
ojluni/src/main/native/EPollPort.c,jdk8u/jdk8u121-b13,jdk/src/solaris/native/sun/nio/ch/EPollPort.c
@@ -1851,7 +1851,7 @@
ojluni/src/main/native/Inet4Address.c,jdk7u/jdk7u40-b60,jdk/src/share/native/java/net/Inet4Address.c
ojluni/src/main/native/Inet6Address.c,jdk8u/jdk8u121-b13,jdk/src/share/native/java/net/Inet6Address.c
ojluni/src/main/native/InetAddress.c,jdk8u/jdk8u60-b31,jdk/src/share/native/java/net/InetAddress.c
-ojluni/src/main/native/Inflater.c,jdk8u/jdk8u60-b31,jdk/src/share/native/java/util/zip/Inflater.c
+ojluni/src/main/native/Inflater.c,jdk17u/jdk-17.0.6-ga,src/java.base/share/native/libzip/Inflater.c
# JniConstants.cpp doesn’t come from the upstream OpenJDK.
ojluni/src/main/native/LinuxNativeDispatcher.c,jdk8u/jdk8u121-b13,jdk/src/solaris/native/sun/nio/fs/LinuxNativeDispatcher.c
ojluni/src/main/native/LinuxWatchService.c,jdk8u/jdk8u121-b13,jdk/src/solaris/native/sun/nio/fs/LinuxWatchService.c
diff --git a/api/current.txt b/api/current.txt
index e812848..0fa682f 100644
--- a/api/current.txt
+++ b/api/current.txt
@@ -18382,9 +18382,10 @@
ctor public Deflater();
method public int deflate(byte[], int, int);
method public int deflate(byte[]);
+ method @FlaggedApi("com.android.libcore.v_apis") public int deflate(java.nio.ByteBuffer);
method public int deflate(byte[], int, int, int);
+ method @FlaggedApi("com.android.libcore.v_apis") public int deflate(java.nio.ByteBuffer, int);
method public void end();
- method protected void finalize();
method public void finish();
method public boolean finished();
method public int getAdler();
@@ -18396,8 +18397,10 @@
method public void reset();
method public void setDictionary(byte[], int, int);
method public void setDictionary(byte[]);
+ method @FlaggedApi("com.android.libcore.v_apis") public void setDictionary(java.nio.ByteBuffer);
method public void setInput(byte[], int, int);
method public void setInput(byte[]);
+ method @FlaggedApi("com.android.libcore.v_apis") public void setInput(java.nio.ByteBuffer);
method public void setLevel(int);
method public void setStrategy(int);
field public static final int BEST_COMPRESSION = 9; // 0x9
@@ -18454,7 +18457,6 @@
ctor public Inflater(boolean);
ctor public Inflater();
method public void end();
- method protected void finalize();
method public boolean finished();
method public int getAdler();
method public long getBytesRead();
@@ -18464,13 +18466,16 @@
method public int getTotalOut();
method public int inflate(byte[], int, int) throws java.util.zip.DataFormatException;
method public int inflate(byte[]) throws java.util.zip.DataFormatException;
+ method @FlaggedApi("com.android.libcore.v_apis") public int inflate(java.nio.ByteBuffer) throws java.util.zip.DataFormatException;
method public boolean needsDictionary();
method public boolean needsInput();
method public void reset();
method public void setDictionary(byte[], int, int);
method public void setDictionary(byte[]);
+ method @FlaggedApi("com.android.libcore.v_apis") public void setDictionary(java.nio.ByteBuffer);
method public void setInput(byte[], int, int);
method public void setInput(byte[]);
+ method @FlaggedApi("com.android.libcore.v_apis") public void setInput(java.nio.ByteBuffer);
}
public class InflaterInputStream extends java.io.FilterInputStream {
@@ -18583,7 +18588,6 @@
ctor public ZipFile(java.io.File, java.nio.charset.Charset) throws java.io.IOException;
method public void close() throws java.io.IOException;
method public java.util.Enumeration<? extends java.util.zip.ZipEntry> entries();
- method protected void finalize() throws java.io.IOException;
method public String getComment();
method public java.util.zip.ZipEntry getEntry(String);
method public java.io.InputStream getInputStream(java.util.zip.ZipEntry) throws java.io.IOException;
diff --git a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java
index d0747de..aaa0c32 100644
--- a/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java
+++ b/harmony-tests/src/test/java/org/apache/harmony/tests/java/util/zip/DeflaterTest.java
@@ -42,10 +42,6 @@
super(lvl);
}
- void myFinalize() {
- finalize();
- }
-
int getDefCompression() {
return DEFAULT_COMPRESSION;
}
@@ -188,16 +184,6 @@
}
/**
- * java.util.zip.Deflater#finalize()
- */
- public void test_finalize() {
- MyDeflater mdefl = new MyDeflater();
- mdefl.myFinalize();
- System.gc();
- helper_end_test(mdefl, "finalize");
- }
-
- /**
* java.util.zip.Deflater#finish()
*/
public void test_finish() throws Exception {
diff --git a/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java b/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
index 67d560e..b9e942e 100644
--- a/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/ZipFileTest.java
@@ -24,6 +24,7 @@
import java.io.FileDescriptor;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
+import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
@@ -39,44 +40,6 @@
return new ZipOutputStream(wrapped);
}
- // http://b/30407219
- public void testZipFileOffsetNeverChangesAfterInit() throws Exception {
- final File f = createTemporaryZipFile();
- writeEntries(createZipOutputStream(new BufferedOutputStream(new FileOutputStream(f))),
- 2 /* number of entries */, 1024 /* entry size */, true /* setEntrySize */);
-
- ZipFile zipFile = new ZipFile(f);
- FileDescriptor fd = new FileDescriptor();
- fd.setInt$(zipFile.getFileDescriptor());
-
- long initialOffset = android.system.Os.lseek(fd, 0, OsConstants.SEEK_CUR);
-
- Enumeration<? extends ZipEntry> entries = zipFile.entries();
- assertOffset(initialOffset, fd);
-
- // Get references to the two elements in the file.
- ZipEntry entry1 = entries.nextElement();
- ZipEntry entry2 = entries.nextElement();
- assertFalse(entries.hasMoreElements());
- assertOffset(initialOffset, fd);
-
- InputStream is1 = zipFile.getInputStream(entry1);
- assertOffset(initialOffset, fd);
- is1.read(new byte[256]);
- assertOffset(initialOffset, fd);
- is1.close();
-
- assertNotNull(zipFile.getEntry(entry2.getName()));
- assertOffset(initialOffset, fd);
-
- zipFile.close();
- }
-
- private static void assertOffset(long initialOffset, FileDescriptor fd) throws Exception {
- long currentOffset = android.system.Os.lseek(fd, 0, OsConstants.SEEK_CUR);
- assertEquals(initialOffset, currentOffset);
- }
-
// b/31077136
public void test_FileNotFound() throws Exception {
File nonExistentFile = new File("fileThatDefinitelyDoesntExist.zip");
@@ -84,7 +47,7 @@
try (ZipFile zipFile = new ZipFile(nonExistentFile, ZipFile.OPEN_READ)) {
fail();
- } catch(FileNotFoundException expected) {}
+ } catch(IOException expected) {}
}
/**
diff --git a/ojluni/annotations/flagged_api/java/util/zip/Deflater.annotated.java b/ojluni/annotations/flagged_api/java/util/zip/Deflater.annotated.java
new file mode 100644
index 0000000..b9ca845
--- /dev/null
+++ b/ojluni/annotations/flagged_api/java/util/zip/Deflater.annotated.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+package java.util.zip;
+
+@SuppressWarnings({"unchecked", "deprecation", "all"})
+public class Deflater {
+
+public Deflater(int level, boolean nowrap) { throw new RuntimeException("Stub!"); }
+
+public Deflater(int level) { throw new RuntimeException("Stub!"); }
+
+public Deflater() { throw new RuntimeException("Stub!"); }
+
+public void setInput(byte[] input, int off, int len) { throw new RuntimeException("Stub!"); }
+
+public void setInput(byte[] input) { throw new RuntimeException("Stub!"); }
+
+@android.annotation.FlaggedApi("com.android.libcore.v_apis")
+public void setInput(java.nio.ByteBuffer input) { throw new RuntimeException("Stub!"); }
+
+public void setDictionary(byte[] dictionary, int off, int len) { throw new RuntimeException("Stub!"); }
+
+public void setDictionary(byte[] dictionary) { throw new RuntimeException("Stub!"); }
+
+@android.annotation.FlaggedApi("com.android.libcore.v_apis")
+public void setDictionary(java.nio.ByteBuffer dictionary) { throw new RuntimeException("Stub!"); }
+
+public void setStrategy(int strategy) { throw new RuntimeException("Stub!"); }
+
+public void setLevel(int level) { throw new RuntimeException("Stub!"); }
+
+public boolean needsInput() { throw new RuntimeException("Stub!"); }
+
+public void finish() { throw new RuntimeException("Stub!"); }
+
+public boolean finished() { throw new RuntimeException("Stub!"); }
+
+public int deflate(byte[] output, int off, int len) { throw new RuntimeException("Stub!"); }
+
+public int deflate(byte[] output) { throw new RuntimeException("Stub!"); }
+
+@android.annotation.FlaggedApi("com.android.libcore.v_apis")
+public int deflate(java.nio.ByteBuffer output) { throw new RuntimeException("Stub!"); }
+
+public int deflate(byte[] output, int off, int len, int flush) { throw new RuntimeException("Stub!"); }
+
+@android.annotation.FlaggedApi("com.android.libcore.v_apis")
+public int deflate(java.nio.ByteBuffer output, int flush) { throw new RuntimeException("Stub!"); }
+
+public int getAdler() { throw new RuntimeException("Stub!"); }
+
+public int getTotalIn() { throw new RuntimeException("Stub!"); }
+
+public long getBytesRead() { throw new RuntimeException("Stub!"); }
+
+public int getTotalOut() { throw new RuntimeException("Stub!"); }
+
+public long getBytesWritten() { throw new RuntimeException("Stub!"); }
+
+public void reset() { throw new RuntimeException("Stub!"); }
+
+public void end() { throw new RuntimeException("Stub!"); }
+
+public static final int BEST_COMPRESSION = 9; // 0x9
+
+public static final int BEST_SPEED = 1; // 0x1
+
+public static final int DEFAULT_COMPRESSION = -1; // 0xffffffff
+
+public static final int DEFAULT_STRATEGY = 0; // 0x0
+
+public static final int DEFLATED = 8; // 0x8
+
+public static final int FILTERED = 1; // 0x1
+
+public static final int FULL_FLUSH = 3; // 0x3
+
+public static final int HUFFMAN_ONLY = 2; // 0x2
+
+public static final int NO_COMPRESSION = 0; // 0x0
+
+public static final int NO_FLUSH = 0; // 0x0
+
+public static final int SYNC_FLUSH = 2; // 0x2
+}
+
diff --git a/ojluni/annotations/flagged_api/java/util/zip/Inflater.annotated.java b/ojluni/annotations/flagged_api/java/util/zip/Inflater.annotated.java
new file mode 100644
index 0000000..cd9e17c
--- /dev/null
+++ b/ojluni/annotations/flagged_api/java/util/zip/Inflater.annotated.java
@@ -0,0 +1,80 @@
+/*
+ * Copyright (C) 2014 The Android Open Source Project
+ * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+package java.util.zip;
+
+@SuppressWarnings({"unchecked", "deprecation", "all"})
+public class Inflater {
+
+public Inflater(boolean nowrap) { throw new RuntimeException("Stub!"); }
+
+public Inflater() { throw new RuntimeException("Stub!"); }
+
+public void setInput(byte[] input, int off, int len) { throw new RuntimeException("Stub!"); }
+
+public void setInput(byte[] input) { throw new RuntimeException("Stub!"); }
+
+@android.annotation.FlaggedApi("com.android.libcore.v_apis")
+public void setInput(java.nio.ByteBuffer input) { throw new RuntimeException("Stub!"); }
+
+public void setDictionary(byte[] dictionary, int off, int len) { throw new RuntimeException("Stub!"); }
+
+public void setDictionary(byte[] dictionary) { throw new RuntimeException("Stub!"); }
+
+@android.annotation.FlaggedApi("com.android.libcore.v_apis")
+public void setDictionary(java.nio.ByteBuffer dictionary) { throw new RuntimeException("Stub!"); }
+
+public int getRemaining() { throw new RuntimeException("Stub!"); }
+
+public boolean needsInput() { throw new RuntimeException("Stub!"); }
+
+public boolean needsDictionary() { throw new RuntimeException("Stub!"); }
+
+public boolean finished() { throw new RuntimeException("Stub!"); }
+
+public int inflate(byte[] output, int off, int len) throws java.util.zip.DataFormatException { throw new RuntimeException("Stub!"); }
+
+public int inflate(byte[] output) throws java.util.zip.DataFormatException { throw new RuntimeException("Stub!"); }
+
+@android.annotation.FlaggedApi("com.android.libcore.v_apis")
+public int inflate(java.nio.ByteBuffer output) throws java.util.zip.DataFormatException { throw new RuntimeException("Stub!"); }
+
+public int getAdler() { throw new RuntimeException("Stub!"); }
+
+public int getTotalIn() { throw new RuntimeException("Stub!"); }
+
+public long getBytesRead() { throw new RuntimeException("Stub!"); }
+
+public int getTotalOut() { throw new RuntimeException("Stub!"); }
+
+public long getBytesWritten() { throw new RuntimeException("Stub!"); }
+
+public void reset() { throw new RuntimeException("Stub!"); }
+
+public void end() { throw new RuntimeException("Stub!"); }
+}
+
diff --git a/ojluni/src/main/java/java/io/RandomAccessFile.java b/ojluni/src/main/java/java/io/RandomAccessFile.java
index 06683ad..04b25f6 100644
--- a/ojluni/src/main/java/java/io/RandomAccessFile.java
+++ b/ojluni/src/main/java/java/io/RandomAccessFile.java
@@ -31,6 +31,8 @@
import sun.nio.ch.FileChannelImpl;
import android.system.Os;
import android.system.ErrnoException;
+import android.system.OsConstants;
+
import dalvik.system.CloseGuard;
import libcore.io.IoBridge;
import libcore.io.IoTracker;
@@ -231,6 +233,20 @@
public RandomAccessFile(File file, String mode)
throws FileNotFoundException
{
+ // Android-changed: delegate to constructor which controls O_CLOEXEC.
+ this(file, mode, /* setCloExecFlag= */ false);
+ }
+
+ /**
+ * Identical to {@link #RandomAccessFile(File, String)}, but with a capability to control
+ * O_CLOEXEC flag of file descriptor.
+ *
+ * @param setCloExecFlag if true file descriptor will be opened with O_CLOEXE flag set
+ * @hide
+ */
+ // Android-changed: added an extra argument to set O_CLOEXEC.
+ public RandomAccessFile(File file, String mode, boolean setCloExecFlag)
+ throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
int imode = -1;
if (mode.equals("r")) {
@@ -283,6 +299,8 @@
throw new FileNotFoundException("Invalid file path");
}
this.path = name;
+ // Android-added: set O_CLOEXEC flag if requested.
+ imode = setCloExecFlag ? imode | O_CLOEXEC : imode;
this.mode = imode;
// BEGIN Android-changed: Use IoBridge.open() instead of open.
diff --git a/ojluni/src/main/java/java/util/jar/JarFile.java b/ojluni/src/main/java/java/util/jar/JarFile.java
index 797d0bb..1d29e1c 100644
--- a/ojluni/src/main/java/java/util/jar/JarFile.java
+++ b/ojluni/src/main/java/java/util/jar/JarFile.java
@@ -306,10 +306,26 @@
Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
}
+ // Android-added: this method is from OpenJDK 17. Made public hidden to access it
+ // in ZipFile w/o SharedSecrets.
+ /**
+ * Creates a ZipEntry suitable for the given ZipFile.
+ * @hide
+ */
+ public JarEntry entryFor(String name) {
+ return new JarFileEntry(name);
+ }
+
private class JarFileEntry extends JarEntry {
JarFileEntry(ZipEntry ze) {
super(ze);
}
+
+ // Android-added: imported from OpenJDK 17 for entryFor(String) support.
+ JarFileEntry(String name) {
+ super(name);
+ }
+
public Attributes getAttributes() throws IOException {
Manifest man = JarFile.this.getManifest();
if (man != null) {
@@ -354,6 +370,8 @@
}
if (verify) {
+ // BEGIN Android-changed: use OpenJDK 17 implementation.
+ /*
String[] names = getMetaInfEntryNames();
if (names != null) {
for (int i = 0; i < names.length; i++) {
@@ -373,6 +391,21 @@
// No signature-related files; don't instantiate a
// verifier
verify = false;
+ */
+ // Gets the manifest name, but only if there are
+ // signature-related files. If so we can assume
+ // that the jar is signed and that we therefore
+ // need a JarVerifier and Manifest
+ // String name = JUZFA.getManifestName(this, true);
+ String name = getManifestName(true);
+ if (name != null) {
+ getManifest();
+ return;
+ }
+ // No signature-related files; don't instantiate a
+ // verifier
+ verify = false;
+ // END Android-changed: use OpenJDK 17 implementation.
}
}
@@ -385,6 +418,8 @@
ManifestEntryVerifier mev = null;
// Verify "META-INF/" entries...
+ // BEGIN Android-changed: use OpenJDK17 implementation.
+ /*
try {
String[] names = getMetaInfEntryNames();
if (names != null) {
@@ -419,6 +454,46 @@
ex.printStackTrace();
}
}
+ */
+ try {
+ List<String> names = getManifestAndSignatureRelatedFiles();
+ for (String name : names) {
+ JarEntry e = getJarEntry(name);
+ byte[] b;
+ if (e == null) {
+ throw new JarException("corrupted jar file");
+ }
+ if (mev == null) {
+ // BEGIN Android-changed: ManifestEntryVerifier(Manifest, String) is not imported yet.
+ /*
+ mev = new ManifestEntryVerifier
+ (getManifestFromReference()), jv.manifestName);
+ */
+ mev = new ManifestEntryVerifier(getManifestFromReference());
+ // END Android-changed: ManifestEntryVerifier(Manifest, String) is not imported yet.
+ }
+ if (name.equalsIgnoreCase(MANIFEST_NAME)) {
+ b = jv.manifestRawBytes;
+ } else {
+ b = getBytes(e);
+ }
+ if (b != null && b.length > 0) {
+ jv.beginEntry(e, mev);
+ jv.update(b.length, b, 0, b.length, mev);
+ jv.update(-1, null, 0, 0, mev);
+ }
+ }
+ } catch (IOException | IllegalArgumentException ex) {
+ // if we had an error parsing any blocks, just
+ // treat the jar file as being unsigned
+ jv = null;
+ verify = false;
+ if (JarVerifier.debug != null) {
+ JarVerifier.debug.println("jarfile parsing error!");
+ ex.printStackTrace();
+ }
+ }
+ // END Android-changed: use OpenJDK17 implementation.
// if after initializing the verifier we have nothing
// signed, we null it out.
@@ -484,7 +559,7 @@
return new JarVerifier.VerifierStream(
getManifestFromReference(),
ze instanceof JarFileEntry ?
- (JarEntry) ze : getJarEntry(ze.getName()),
+ (JarEntry) ze : getJarEntry(ze.getName()),
super.getInputStream(ze),
jv);
}
@@ -517,6 +592,8 @@
// private JarEntry getManEntry() {
private synchronized JarEntry getManEntry() {
// END Android-changed: Fix JarFile to be thread safe. http://b/27826114
+ // BEGIN Android-changed: use OpenJDK 17 implementation.
+ /*
if (manEntry == null) {
// First look up manifest entry using standard name
manEntry = getJarEntry(MANIFEST_NAME);
@@ -535,14 +612,24 @@
}
}
}
+ */
+ if (manEntry == null) {
+ // The manifest entry position is resolved during
+ // initialization
+ String name = getManifestName(false);
+ if (name != null) {
+ this.manEntry = (JarEntry)super.getEntry(name);
+ }
+ }
+ // END Android-changed: use OpenJDK 17 implementation.
return manEntry;
}
- /**
- * Returns {@code true} iff this JAR file has a manifest with the
- * Class-Path attribute
- * @hide
- */
+ /**
+ * Returns {@code true} iff this JAR file has a manifest with the
+ * Class-Path attribute
+ * @hide
+ */
// Android-changed: Make hasClassPathAttribute() @hide public, for internal use.
// Used by URLClassPath.JarLoader.
// boolean hasClassPathAttribute() throws IOException {
@@ -568,7 +655,7 @@
if (c != src[j]) {
i += Math.max(j + 1 - lastOcc[c&0x7F], optoSft[j]);
continue next;
- }
+ }
}
return true;
}
diff --git a/ojluni/src/main/java/java/util/zip/Deflater.java b/ojluni/src/main/java/java/util/zip/Deflater.java
index df59fb5..9910016 100644
--- a/ojluni/src/main/java/java/util/zip/Deflater.java
+++ b/ojluni/src/main/java/java/util/zip/Deflater.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -27,18 +27,32 @@
import dalvik.annotation.optimization.ReachabilitySensitive;
import dalvik.system.CloseGuard;
+import java.lang.ref.Cleaner.Cleanable;
+import java.lang.ref.Reference;
+import java.nio.ByteBuffer;
+import java.nio.ReadOnlyBufferException;
+import java.util.Objects;
+
+import jdk.internal.ref.CleanerFactory;
+import sun.nio.ch.DirectBuffer;
/**
* This class provides support for general purpose compression using the
* popular ZLIB compression library. The ZLIB compression library was
* initially developed as part of the PNG graphics standard and is not
* protected by patents. It is fully described in the specifications at
- * the <a href="package-summary.html#package_description">java.util.zip
+ * the <a href="package-summary.html#package-description">java.util.zip
* package description</a>.
- *
- * <p>The following code fragment demonstrates a trivial compression
- * and decompression of a string using <tt>Deflater</tt> and
- * <tt>Inflater</tt>.
+ * <p>
+ * This class deflates sequences of bytes into ZLIB compressed data format.
+ * The input byte sequence is provided in either byte array or byte buffer,
+ * via one of the {@code setInput()} methods. The output byte sequence is
+ * written to the output byte array or byte buffer passed to the
+ * {@code deflate()} methods.
+ * <p>
+ * The following code fragment demonstrates a trivial compression
+ * and decompression of a string using {@code Deflater} and
+ * {@code Inflater}.
*
* <blockquote><pre>
* try {
@@ -63,28 +77,31 @@
*
* // Decode the bytes into a String
* String outputString = new String(result, 0, resultLength, "UTF-8");
- * } catch(java.io.UnsupportedEncodingException ex) {
+ * } catch (java.io.UnsupportedEncodingException ex) {
* // handle
* } catch (java.util.zip.DataFormatException ex) {
* // handle
* }
* </pre></blockquote>
*
+ * @apiNote
+ * To release resources used by this {@code Deflater}, the {@link #end()} method
+ * should be called explicitly. Subclasses are responsible for the cleanup of resources
+ * acquired by the subclass. Subclasses that override {@link #finalize()} in order
+ * to perform cleanup should be modified to use alternative cleanup mechanisms such
+ * as {@link java.lang.ref.Cleaner} and remove the overriding {@code finalize} method.
+ *
* @see Inflater
* @author David Connelly
+ * @since 1.1
*/
-public
-class Deflater {
- // Android-added: @ReachabilitySensitive
- // Finalization clears zsRef, and thus can't be allowed to occur early.
- // Unlike some other CloseGuard uses, the spec allows clients to rely on finalization
- // here. Thus dropping a deflater without calling end() should work correctly.
- // It thus does not suffice to just rely on the CloseGuard annotation.
- @ReachabilitySensitive
- private final ZStreamRef zsRef;
- private byte[] buf = new byte[0];
- private int off, len;
+public class Deflater {
+
+ private final DeflaterZStreamRef zsRef;
+ private ByteBuffer input = ZipUtils.defaultBuf;
+ private byte[] inputArray;
+ private int inputPos, inputLim;
private int level, strategy;
private boolean setParams;
private boolean finish, finished;
@@ -165,11 +182,16 @@
*/
public static final int FULL_FLUSH = 3;
+ /**
+ * Flush mode to use at the end of output. Can only be provided by the
+ * user by way of {@link #finish()}.
+ */
+ private static final int FINISH = 4;
+
// Android-removed: initIDs handled in register method.
/*
static {
- /* Zip library is loaded from System.initializeSystemClass *
- initIDs();
+ ZipUtils.loadLibrary();
}
*/
@@ -184,7 +206,8 @@
public Deflater(int level, boolean nowrap) {
this.level = level;
this.strategy = DEFAULT_STRATEGY;
- this.zsRef = new ZStreamRef(init(level, DEFAULT_STRATEGY, nowrap));
+ this.zsRef = new DeflaterZStreamRef(this,
+ init(level, DEFAULT_STRATEGY, nowrap));
// Android-added: CloseGuard support.
guard.open("end");
}
@@ -207,35 +230,69 @@
}
/**
- * Sets input data for compression. This should be called whenever
- * needsInput() returns true indicating that more input data is required.
- * @param b the input data bytes
+ * Sets input data for compression.
+ * <p>
+ * One of the {@code setInput()} methods should be called whenever
+ * {@code needsInput()} returns true indicating that more input data
+ * is required.
+ * @param input the input data bytes
* @param off the start offset of the data
* @param len the length of the data
* @see Deflater#needsInput
*/
- public void setInput(byte[] b, int off, int len) {
- if (b== null) {
- throw new NullPointerException();
- }
- if (off < 0 || len < 0 || off > b.length - len) {
+ public void setInput(byte[] input, int off, int len) {
+ if (off < 0 || len < 0 || off > input.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
synchronized (zsRef) {
- this.buf = b;
- this.off = off;
- this.len = len;
+ this.input = null;
+ this.inputArray = input;
+ this.inputPos = off;
+ this.inputLim = off + len;
}
}
/**
- * Sets input data for compression. This should be called whenever
- * needsInput() returns true indicating that more input data is required.
- * @param b the input data bytes
+ * Sets input data for compression.
+ * <p>
+ * One of the {@code setInput()} methods should be called whenever
+ * {@code needsInput()} returns true indicating that more input data
+ * is required.
+ * @param input the input data bytes
* @see Deflater#needsInput
*/
- public void setInput(byte[] b) {
- setInput(b, 0, b.length);
+ public void setInput(byte[] input) {
+ setInput(input, 0, input.length);
+ }
+
+ /**
+ * Sets input data for compression.
+ * <p>
+ * One of the {@code setInput()} methods should be called whenever
+ * {@code needsInput()} returns true indicating that more input data
+ * is required.
+ * <p>
+ * The given buffer's position will be advanced as deflate
+ * operations are performed, up to the buffer's limit.
+ * The input buffer may be modified (refilled) between deflate
+ * operations; doing so is equivalent to creating a new buffer
+ * and setting it with this method.
+ * <p>
+ * Modifying the input buffer's contents, position, or limit
+ * concurrently with an deflate operation will result in
+ * undefined behavior, which may include incorrect operation
+ * results or operation failure.
+ *
+ * @param input the input data bytes
+ * @see Deflater#needsInput
+ * @since 11
+ */
+ public void setInput(ByteBuffer input) {
+ Objects.requireNonNull(input);
+ synchronized (zsRef) {
+ this.input = input;
+ this.inputArray = null;
+ }
}
/**
@@ -244,22 +301,19 @@
* uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
* in order to get the Adler-32 value of the dictionary required for
* decompression.
- * @param b the dictionary data bytes
+ * @param dictionary the dictionary data bytes
* @param off the start offset of the data
* @param len the length of the data
* @see Inflater#inflate
* @see Inflater#getAdler
*/
- public void setDictionary(byte[] b, int off, int len) {
- if (b == null) {
- throw new NullPointerException();
- }
- if (off < 0 || len < 0 || off > b.length - len) {
+ public void setDictionary(byte[] dictionary, int off, int len) {
+ if (off < 0 || len < 0 || off > dictionary.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
synchronized (zsRef) {
ensureOpen();
- setDictionary(zsRef.address(), b, off, len);
+ setDictionary(zsRef.address(), dictionary, off, len);
}
}
@@ -269,12 +323,47 @@
* uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
* in order to get the Adler-32 value of the dictionary required for
* decompression.
- * @param b the dictionary data bytes
+ * @param dictionary the dictionary data bytes
* @see Inflater#inflate
* @see Inflater#getAdler
*/
- public void setDictionary(byte[] b) {
- setDictionary(b, 0, b.length);
+ public void setDictionary(byte[] dictionary) {
+ setDictionary(dictionary, 0, dictionary.length);
+ }
+
+ /**
+ * Sets preset dictionary for compression. A preset dictionary is used
+ * when the history buffer can be predetermined. When the data is later
+ * uncompressed with Inflater.inflate(), Inflater.getAdler() can be called
+ * in order to get the Adler-32 value of the dictionary required for
+ * decompression.
+ * <p>
+ * The bytes in given byte buffer will be fully consumed by this method. On
+ * return, its position will equal its limit.
+ *
+ * @param dictionary the dictionary data bytes
+ * @see Inflater#inflate
+ * @see Inflater#getAdler
+ */
+ public void setDictionary(ByteBuffer dictionary) {
+ synchronized (zsRef) {
+ int position = dictionary.position();
+ int remaining = Math.max(dictionary.limit() - position, 0);
+ ensureOpen();
+ if (dictionary.isDirect()) {
+ long address = ((DirectBuffer) dictionary).address();
+ try {
+ setDictionaryBuffer(zsRef.address(), address + position, remaining);
+ } finally {
+ Reference.reachabilityFence(dictionary);
+ }
+ } else {
+ byte[] array = ZipUtils.getBufferArray(dictionary);
+ int offset = ZipUtils.getBufferOffset(dictionary);
+ setDictionary(zsRef.address(), array, offset + position, remaining);
+ }
+ dictionary.position(position + remaining);
+ }
}
/**
@@ -286,7 +375,7 @@
* effect only after that invocation.
*
* @param strategy the new compression strategy
- * @exception IllegalArgumentException if the compression strategy is
+ * @throws IllegalArgumentException if the compression strategy is
* invalid
*/
public void setStrategy(int strategy) {
@@ -315,7 +404,7 @@
* take effect only after that invocation.
*
* @param level the new compression level (0-9)
- * @exception IllegalArgumentException if the compression level is invalid
+ * @throws IllegalArgumentException if the compression level is invalid
*/
public void setLevel(int level) {
if ((level < 0 || level > 9) && level != DEFAULT_COMPRESSION) {
@@ -330,14 +419,17 @@
}
/**
- * Returns true if the input data buffer is empty and setInput()
- * should be called in order to provide more input.
+ * Returns true if no data remains in the input buffer. This can
+ * be used to determine if one of the {@code setInput()} methods should be
+ * called in order to provide more input.
+ *
* @return true if the input data buffer is empty and setInput()
* should be called in order to provide more input
*/
public boolean needsInput() {
synchronized (zsRef) {
- return len <= 0;
+ ByteBuffer input = this.input;
+ return input == null ? inputLim == inputPos : ! input.hasRemaining();
}
}
@@ -374,14 +466,14 @@
* yields the same result as the invocation of
* {@code deflater.deflate(b, off, len, Deflater.NO_FLUSH)}.
*
- * @param b the buffer for the compressed data
+ * @param output the buffer for the compressed data
* @param off the start offset of the data
* @param len the maximum number of bytes of compressed data
* @return the actual number of bytes of compressed data written to the
* output buffer
*/
- public int deflate(byte[] b, int off, int len) {
- return deflate(b, off, len, NO_FLUSH);
+ public int deflate(byte[] output, int off, int len) {
+ return deflate(output, off, len, NO_FLUSH);
}
/**
@@ -395,12 +487,32 @@
* yields the same result as the invocation of
* {@code deflater.deflate(b, 0, b.length, Deflater.NO_FLUSH)}.
*
- * @param b the buffer for the compressed data
+ * @param output the buffer for the compressed data
* @return the actual number of bytes of compressed data written to the
* output buffer
*/
- public int deflate(byte[] b) {
- return deflate(b, 0, b.length, NO_FLUSH);
+ public int deflate(byte[] output) {
+ return deflate(output, 0, output.length, NO_FLUSH);
+ }
+
+ /**
+ * Compresses the input data and fills specified buffer with compressed
+ * data. Returns actual number of bytes of compressed data. A return value
+ * of 0 indicates that {@link #needsInput() needsInput} should be called
+ * in order to determine if more input data is required.
+ *
+ * <p>This method uses {@link #NO_FLUSH} as its compression flush mode.
+ * An invocation of this method of the form {@code deflater.deflate(output)}
+ * yields the same result as the invocation of
+ * {@code deflater.deflate(output, Deflater.NO_FLUSH)}.
+ *
+ * @param output the buffer for the compressed data
+ * @return the actual number of bytes of compressed data written to the
+ * output buffer
+ * @since 11
+ */
+ public int deflate(ByteBuffer output) {
+ return deflate(output, NO_FLUSH);
}
/**
@@ -435,9 +547,16 @@
* <p>In the case of {@link #FULL_FLUSH} or {@link #SYNC_FLUSH}, if
* the return value is {@code len}, the space available in output
* buffer {@code b}, this method should be invoked again with the same
- * {@code flush} parameter and more output space.
+ * {@code flush} parameter and more output space. Make sure that
+ * {@code len} is greater than 6 to avoid flush marker (5 bytes) being
+ * repeatedly output to the output buffer every time this method is
+ * invoked.
*
- * @param b the buffer for the compressed data
+ * <p>If the {@link #setInput(ByteBuffer)} method was called to provide a buffer
+ * for input, the input buffer's position will be advanced by the number of bytes
+ * consumed by this operation.
+ *
+ * @param output the buffer for the compressed data
* @param off the start offset of the data
* @param len the maximum number of bytes of compressed data
* @param flush the compression flush mode
@@ -447,25 +566,248 @@
* @throws IllegalArgumentException if the flush mode is invalid
* @since 1.7
*/
- public int deflate(byte[] b, int off, int len, int flush) {
- if (b == null) {
- throw new NullPointerException();
- }
- if (off < 0 || len < 0 || off > b.length - len) {
+ public int deflate(byte[] output, int off, int len, int flush) {
+ if (off < 0 || len < 0 || off > output.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
+ if (flush != NO_FLUSH && flush != SYNC_FLUSH && flush != FULL_FLUSH) {
+ throw new IllegalArgumentException();
+ }
synchronized (zsRef) {
ensureOpen();
- if (flush == NO_FLUSH || flush == SYNC_FLUSH ||
- flush == FULL_FLUSH) {
- int thisLen = this.len;
- int n = deflateBytes(zsRef.address(), b, off, len, flush);
- bytesWritten += n;
- bytesRead += (thisLen - this.len);
- return n;
+
+ ByteBuffer input = this.input;
+ if (finish) {
+ // disregard given flush mode in this case
+ flush = FINISH;
}
+ int params;
+ if (setParams) {
+ // bit 0: true to set params
+ // bit 1-2: strategy (0, 1, or 2)
+ // bit 3-31: level (0..9 or -1)
+ params = 1 | strategy << 1 | level << 3;
+ } else {
+ params = 0;
+ }
+ int inputPos;
+ long result;
+ if (input == null) {
+ inputPos = this.inputPos;
+ result = deflateBytesBytes(zsRef.address(),
+ inputArray, inputPos, inputLim - inputPos,
+ output, off, len,
+ flush, params);
+ } else {
+ inputPos = input.position();
+ int inputRem = Math.max(input.limit() - inputPos, 0);
+ if (input.isDirect()) {
+ try {
+ long inputAddress = ((DirectBuffer) input).address();
+ result = deflateBufferBytes(zsRef.address(),
+ inputAddress + inputPos, inputRem,
+ output, off, len,
+ flush, params);
+ } finally {
+ Reference.reachabilityFence(input);
+ }
+ } else {
+ byte[] inputArray = ZipUtils.getBufferArray(input);
+ int inputOffset = ZipUtils.getBufferOffset(input);
+ result = deflateBytesBytes(zsRef.address(),
+ inputArray, inputOffset + inputPos, inputRem,
+ output, off, len,
+ flush, params);
+ }
+ }
+ int read = (int) (result & 0x7fff_ffffL);
+ int written = (int) (result >>> 31 & 0x7fff_ffffL);
+ if ((result >>> 62 & 1) != 0) {
+ finished = true;
+ }
+ if (params != 0 && (result >>> 63 & 1) == 0) {
+ setParams = false;
+ }
+ if (input != null) {
+ input.position(inputPos + read);
+ } else {
+ this.inputPos = inputPos + read;
+ }
+ bytesWritten += written;
+ bytesRead += read;
+ return written;
+ }
+ }
+
+ /**
+ * Compresses the input data and fills the specified buffer with compressed
+ * data. Returns actual number of bytes of data compressed.
+ *
+ * <p>Compression flush mode is one of the following three modes:
+ *
+ * <ul>
+ * <li>{@link #NO_FLUSH}: allows the deflater to decide how much data
+ * to accumulate, before producing output, in order to achieve the best
+ * compression (should be used in normal use scenario). A return value
+ * of 0 in this flush mode indicates that {@link #needsInput()} should
+ * be called in order to determine if more input data is required.
+ *
+ * <li>{@link #SYNC_FLUSH}: all pending output in the deflater is flushed,
+ * to the specified output buffer, so that an inflater that works on
+ * compressed data can get all input data available so far (In particular
+ * the {@link #needsInput()} returns {@code true} after this invocation
+ * if enough output space is provided). Flushing with {@link #SYNC_FLUSH}
+ * may degrade compression for some compression algorithms and so it
+ * should be used only when necessary.
+ *
+ * <li>{@link #FULL_FLUSH}: all pending output is flushed out as with
+ * {@link #SYNC_FLUSH}. The compression state is reset so that the inflater
+ * that works on the compressed output data can restart from this point
+ * if previous compressed data has been damaged or if random access is
+ * desired. Using {@link #FULL_FLUSH} too often can seriously degrade
+ * compression.
+ * </ul>
+ *
+ * <p>In the case of {@link #FULL_FLUSH} or {@link #SYNC_FLUSH}, if
+ * the return value is equal to the {@linkplain ByteBuffer#remaining() remaining space}
+ * of the buffer, this method should be invoked again with the same
+ * {@code flush} parameter and more output space. Make sure that
+ * the buffer has at least 6 bytes of remaining space to avoid the
+ * flush marker (5 bytes) being repeatedly output to the output buffer
+ * every time this method is invoked.
+ *
+ * <p>On success, the position of the given {@code output} byte buffer will be
+ * advanced by as many bytes as were produced by the operation, which is equal
+ * to the number returned by this method.
+ *
+ * <p>If the {@link #setInput(ByteBuffer)} method was called to provide a buffer
+ * for input, the input buffer's position will be advanced by the number of bytes
+ * consumed by this operation.
+ *
+ * @param output the buffer for the compressed data
+ * @param flush the compression flush mode
+ * @return the actual number of bytes of compressed data written to
+ * the output buffer
+ *
+ * @throws IllegalArgumentException if the flush mode is invalid
+ * @since 11
+ */
+ public int deflate(ByteBuffer output, int flush) {
+ if (output.isReadOnly()) {
+ throw new ReadOnlyBufferException();
+ }
+ if (flush != NO_FLUSH && flush != SYNC_FLUSH && flush != FULL_FLUSH) {
throw new IllegalArgumentException();
}
+ synchronized (zsRef) {
+ ensureOpen();
+
+ ByteBuffer input = this.input;
+ if (finish) {
+ // disregard given flush mode in this case
+ flush = FINISH;
+ }
+ int params;
+ if (setParams) {
+ // bit 0: true to set params
+ // bit 1-2: strategy (0, 1, or 2)
+ // bit 3-31: level (0..9 or -1)
+ params = 1 | strategy << 1 | level << 3;
+ } else {
+ params = 0;
+ }
+ int outputPos = output.position();
+ int outputRem = Math.max(output.limit() - outputPos, 0);
+ int inputPos;
+ long result;
+ if (input == null) {
+ inputPos = this.inputPos;
+ if (output.isDirect()) {
+ long outputAddress = ((DirectBuffer) output).address();
+ try {
+ result = deflateBytesBuffer(zsRef.address(),
+ inputArray, inputPos, inputLim - inputPos,
+ outputAddress + outputPos, outputRem,
+ flush, params);
+ } finally {
+ Reference.reachabilityFence(output);
+ }
+ } else {
+ byte[] outputArray = ZipUtils.getBufferArray(output);
+ int outputOffset = ZipUtils.getBufferOffset(output);
+ result = deflateBytesBytes(zsRef.address(),
+ inputArray, inputPos, inputLim - inputPos,
+ outputArray, outputOffset + outputPos, outputRem,
+ flush, params);
+ }
+ } else {
+ inputPos = input.position();
+ int inputRem = Math.max(input.limit() - inputPos, 0);
+ if (input.isDirect()) {
+ long inputAddress = ((DirectBuffer) input).address();
+ try {
+ if (output.isDirect()) {
+ long outputAddress = outputPos + ((DirectBuffer) output).address();
+ try {
+ result = deflateBufferBuffer(zsRef.address(),
+ inputAddress + inputPos, inputRem,
+ outputAddress, outputRem,
+ flush, params);
+ } finally {
+ Reference.reachabilityFence(output);
+ }
+ } else {
+ byte[] outputArray = ZipUtils.getBufferArray(output);
+ int outputOffset = ZipUtils.getBufferOffset(output);
+ result = deflateBufferBytes(zsRef.address(),
+ inputAddress + inputPos, inputRem,
+ outputArray, outputOffset + outputPos, outputRem,
+ flush, params);
+ }
+ } finally {
+ Reference.reachabilityFence(input);
+ }
+ } else {
+ byte[] inputArray = ZipUtils.getBufferArray(input);
+ int inputOffset = ZipUtils.getBufferOffset(input);
+ if (output.isDirect()) {
+ long outputAddress = ((DirectBuffer) output).address();
+ try {
+ result = deflateBytesBuffer(zsRef.address(),
+ inputArray, inputOffset + inputPos, inputRem,
+ outputAddress + outputPos, outputRem,
+ flush, params);
+ } finally {
+ Reference.reachabilityFence(output);
+ }
+ } else {
+ byte[] outputArray = ZipUtils.getBufferArray(output);
+ int outputOffset = ZipUtils.getBufferOffset(output);
+ result = deflateBytesBytes(zsRef.address(),
+ inputArray, inputOffset + inputPos, inputRem,
+ outputArray, outputOffset + outputPos, outputRem,
+ flush, params);
+ }
+ }
+ }
+ int read = (int) (result & 0x7fff_ffffL);
+ int written = (int) (result >>> 31 & 0x7fff_ffffL);
+ if ((result >>> 62 & 1) != 0) {
+ finished = true;
+ }
+ if (params != 0 && (result >>> 63 & 1) == 0) {
+ setParams = false;
+ }
+ if (input != null) {
+ input.position(inputPos + read);
+ } else {
+ this.inputPos = inputPos + read;
+ }
+ output.position(outputPos + written);
+ bytesWritten += written;
+ bytesRead += read;
+ return written;
+ }
}
/**
@@ -541,49 +883,36 @@
reset(zsRef.address());
finish = false;
finished = false;
- off = len = 0;
+ input = ZipUtils.defaultBuf;
+ inputArray = null;
bytesRead = bytesWritten = 0;
}
}
/**
* Closes the compressor and discards any unprocessed input.
+ *
* This method should be called when the compressor is no longer
- * being used, but will also be called automatically by the
- * finalize() method. Once this method is called, the behavior
- * of the Deflater object is undefined.
+ * being used. Once this method is called, the behavior of the
+ * Deflater object is undefined.
*/
public void end() {
synchronized (zsRef) {
+ zsRef.clean();
// Android-added: CloseGuard support.
- guard.close();
- long addr = zsRef.address();
- zsRef.clear();
- if (addr != 0) {
- end(addr);
- buf = null;
+ if (guard != null) {
+ guard.close();
}
+ input = ZipUtils.defaultBuf;
}
}
- /**
- * Closes the compressor when garbage is collected.
- */
- protected void finalize() {
- // Android-added: CloseGuard support.
- if (guard != null) {
- guard.warnIfOpen();
- }
- end();
- }
-
private void ensureOpen() {
assert Thread.holdsLock(zsRef);
if (zsRef.address() == 0)
throw new NullPointerException("Deflater has been closed");
}
- // Android-added: this method is from OpenJDK 17.
/**
* Returns the value of 'finish' flag.
* 'finish' will be set to true if def.finish() method is called.
@@ -594,13 +923,60 @@
}
}
- // Android-changed: initIDs handled in register method.
- // private native static void initIDs();
- private native static long init(int level, int strategy, boolean nowrap);
- private native static void setDictionary(long addr, byte[] b, int off, int len);
- private native int deflateBytes(long addr, byte[] b, int off, int len,
- int flush);
- private native static int getAdler(long addr);
- private native static void reset(long addr);
- private native static void end(long addr);
+ private static native long init(int level, int strategy, boolean nowrap);
+ private static native void setDictionary(long addr, byte[] b, int off,
+ int len);
+ private static native void setDictionaryBuffer(long addr, long bufAddress, int len);
+ private native long deflateBytesBytes(long addr,
+ byte[] inputArray, int inputOff, int inputLen,
+ byte[] outputArray, int outputOff, int outputLen,
+ int flush, int params);
+ private native long deflateBytesBuffer(long addr,
+ byte[] inputArray, int inputOff, int inputLen,
+ long outputAddress, int outputLen,
+ int flush, int params);
+ private native long deflateBufferBytes(long addr,
+ long inputAddress, int inputLen,
+ byte[] outputArray, int outputOff, int outputLen,
+ int flush, int params);
+ private native long deflateBufferBuffer(long addr,
+ long inputAddress, int inputLen,
+ long outputAddress, int outputLen,
+ int flush, int params);
+ private static native int getAdler(long addr);
+ private static native void reset(long addr);
+ private static native void end(long addr);
+
+ /**
+ * A reference to the native zlib's z_stream structure. It also
+ * serves as the "cleaner" to clean up the native resource when
+ * the Deflater is ended, closed or cleaned.
+ */
+ static class DeflaterZStreamRef implements Runnable {
+
+ private long address;
+ private final Cleanable cleanable;
+
+ private DeflaterZStreamRef(Deflater owner, long addr) {
+ this.cleanable = (owner != null) ? CleanerFactory.cleaner().register(owner, this) : null;
+ this.address = addr;
+ }
+
+ long address() {
+ return address;
+ }
+
+ void clean() {
+ cleanable.clean();
+ }
+
+ public synchronized void run() {
+ long addr = address;
+ address = 0;
+ if (addr != 0) {
+ end(addr);
+ }
+ }
+
+ }
}
diff --git a/ojluni/src/main/java/java/util/zip/Inflater.java b/ojluni/src/main/java/java/util/zip/Inflater.java
index eb8754e..6e6c83e 100644
--- a/ojluni/src/main/java/java/util/zip/Inflater.java
+++ b/ojluni/src/main/java/java/util/zip/Inflater.java
@@ -1,6 +1,6 @@
/*
* Copyright (C) 2014 The Android Open Source Project
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2018, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -28,18 +28,31 @@
import dalvik.annotation.optimization.ReachabilitySensitive;
import dalvik.system.CloseGuard;
+import java.lang.ref.Cleaner.Cleanable;
+import java.lang.ref.Reference;
+import java.nio.ByteBuffer;
+import java.nio.ReadOnlyBufferException;
+import java.util.Objects;
+
+import jdk.internal.ref.CleanerFactory;
+import sun.nio.ch.DirectBuffer;
/**
* This class provides support for general purpose decompression using the
* popular ZLIB compression library. The ZLIB compression library was
* initially developed as part of the PNG graphics standard and is not
* protected by patents. It is fully described in the specifications at
- * the <a href="package-summary.html#package_description">java.util.zip
+ * the <a href="package-summary.html#package-description">java.util.zip
* package description</a>.
- *
- * <p>The following code fragment demonstrates a trivial compression
- * and decompression of a string using <tt>Deflater</tt> and
- * <tt>Inflater</tt>.
+ * <p>
+ * This class inflates sequences of ZLIB compressed bytes. The input byte
+ * sequence is provided in either byte array or byte buffer, via one of the
+ * {@code setInput()} methods. The output byte sequence is written to the
+ * output byte array or byte buffer passed to the {@code deflate()} methods.
+ * <p>
+ * The following code fragment demonstrates a trivial compression
+ * and decompression of a string using {@code Deflater} and
+ * {@code Inflater}.
*
* <blockquote><pre>
* try {
@@ -63,29 +76,32 @@
*
* // Decode the bytes into a String
* String outputString = new String(result, 0, resultLength, "UTF-8");
- * } catch(java.io.UnsupportedEncodingException ex) {
+ * } catch (java.io.UnsupportedEncodingException ex) {
* // handle
* } catch (java.util.zip.DataFormatException ex) {
* // handle
* }
* </pre></blockquote>
*
+ * @apiNote
+ * To release resources used by this {@code Inflater}, the {@link #end()} method
+ * should be called explicitly. Subclasses are responsible for the cleanup of resources
+ * acquired by the subclass. Subclasses that override {@link #finalize()} in order
+ * to perform cleanup should be modified to use alternative cleanup mechanisms such
+ * as {@link java.lang.ref.Cleaner} and remove the overriding {@code finalize} method.
+ *
* @see Deflater
* @author David Connelly
+ * @since 1.1
*
*/
-public
-class Inflater {
- // Android-added: @ReachabilitySensitive
- // Finalization clears zsRef, and thus can't be allowed to occur early.
- // Unlike some other CloseGuard uses, the spec allows clients to rely on finalization
- // here. Thus dropping a deflater without calling end() should work correctly.
- // It thus does not suffice to just rely on the CloseGuard annotation.
- @ReachabilitySensitive
- private final ZStreamRef zsRef;
- private byte[] buf = defaultBuf;
- private int off, len;
+public class Inflater {
+
+ private final InflaterZStreamRef zsRef;
+ private ByteBuffer input = ZipUtils.defaultBuf;
+ private byte[] inputArray;
+ private int inputPos, inputLim;
private boolean finished;
private boolean needDict;
private long bytesRead;
@@ -95,12 +111,17 @@
@ReachabilitySensitive
private final CloseGuard guard = CloseGuard.get();
- private static final byte[] defaultBuf = new byte[0];
+ /*
+ * These fields are used as an "out" parameter from JNI when a
+ * DataFormatException is thrown during the inflate operation.
+ */
+ private int inputConsumed;
+ private int outputConsumed;
// Android-removed: initIDs handled in register method.
/*
static {
- /* Zip library is loaded from System.initializeSystemClass *
+ ZipUtils.loadLibrary();
initIDs();
}
*/
@@ -117,7 +138,7 @@
* @param nowrap if true then support GZIP compatible compression
*/
public Inflater(boolean nowrap) {
- zsRef = new ZStreamRef(init(nowrap));
+ this.zsRef = new InflaterZStreamRef(this, init(nowrap));
// Android-added: CloseGuard support.
guard.open("end");
}
@@ -130,37 +151,71 @@
}
/**
- * Sets input data for decompression. Should be called whenever
- * needsInput() returns true indicating that more input data is
- * required.
- * @param b the input data bytes
+ * Sets input data for decompression.
+ * <p>
+ * One of the {@code setInput()} methods should be called whenever
+ * {@code needsInput()} returns true indicating that more input data
+ * is required.
+ *
+ * @param input the input data bytes
* @param off the start offset of the input data
* @param len the length of the input data
* @see Inflater#needsInput
*/
- public void setInput(byte[] b, int off, int len) {
- if (b == null) {
- throw new NullPointerException();
- }
- if (off < 0 || len < 0 || off > b.length - len) {
+ public void setInput(byte[] input, int off, int len) {
+ if (off < 0 || len < 0 || off > input.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
synchronized (zsRef) {
- this.buf = b;
- this.off = off;
- this.len = len;
+ this.input = null;
+ this.inputArray = input;
+ this.inputPos = off;
+ this.inputLim = off + len;
}
}
/**
- * Sets input data for decompression. Should be called whenever
- * needsInput() returns true indicating that more input data is
- * required.
- * @param b the input data bytes
+ * Sets input data for decompression.
+ * <p>
+ * One of the {@code setInput()} methods should be called whenever
+ * {@code needsInput()} returns true indicating that more input data
+ * is required.
+ *
+ * @param input the input data bytes
* @see Inflater#needsInput
*/
- public void setInput(byte[] b) {
- setInput(b, 0, b.length);
+ public void setInput(byte[] input) {
+ setInput(input, 0, input.length);
+ }
+
+ /**
+ * Sets input data for decompression.
+ * <p>
+ * One of the {@code setInput()} methods should be called whenever
+ * {@code needsInput()} returns true indicating that more input data
+ * is required.
+ * <p>
+ * The given buffer's position will be advanced as inflate
+ * operations are performed, up to the buffer's limit.
+ * The input buffer may be modified (refilled) between inflate
+ * operations; doing so is equivalent to creating a new buffer
+ * and setting it with this method.
+ * <p>
+ * Modifying the input buffer's contents, position, or limit
+ * concurrently with an inflate operation will result in
+ * undefined behavior, which may include incorrect operation
+ * results or operation failure.
+ *
+ * @param input the input data bytes
+ * @see Inflater#needsInput
+ * @since 11
+ */
+ public void setInput(ByteBuffer input) {
+ Objects.requireNonNull(input);
+ synchronized (zsRef) {
+ this.input = input;
+ this.inputArray = null;
+ }
}
/**
@@ -168,22 +223,19 @@
* called when inflate() returns 0 and needsDictionary() returns true
* indicating that a preset dictionary is required. The method getAdler()
* can be used to get the Adler-32 value of the dictionary needed.
- * @param b the dictionary data bytes
+ * @param dictionary the dictionary data bytes
* @param off the start offset of the data
* @param len the length of the data
* @see Inflater#needsDictionary
* @see Inflater#getAdler
*/
- public void setDictionary(byte[] b, int off, int len) {
- if (b == null) {
- throw new NullPointerException();
- }
- if (off < 0 || len < 0 || off > b.length - len) {
+ public void setDictionary(byte[] dictionary, int off, int len) {
+ if (off < 0 || len < 0 || off > dictionary.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
synchronized (zsRef) {
ensureOpen();
- setDictionary(zsRef.address(), b, off, len);
+ setDictionary(zsRef.address(), dictionary, off, len);
needDict = false;
}
}
@@ -193,12 +245,48 @@
* called when inflate() returns 0 and needsDictionary() returns true
* indicating that a preset dictionary is required. The method getAdler()
* can be used to get the Adler-32 value of the dictionary needed.
- * @param b the dictionary data bytes
+ * @param dictionary the dictionary data bytes
* @see Inflater#needsDictionary
* @see Inflater#getAdler
*/
- public void setDictionary(byte[] b) {
- setDictionary(b, 0, b.length);
+ public void setDictionary(byte[] dictionary) {
+ setDictionary(dictionary, 0, dictionary.length);
+ }
+
+ /**
+ * Sets the preset dictionary to the bytes in the given buffer. Should be
+ * called when inflate() returns 0 and needsDictionary() returns true
+ * indicating that a preset dictionary is required. The method getAdler()
+ * can be used to get the Adler-32 value of the dictionary needed.
+ * <p>
+ * The bytes in given byte buffer will be fully consumed by this method. On
+ * return, its position will equal its limit.
+ *
+ * @param dictionary the dictionary data bytes
+ * @see Inflater#needsDictionary
+ * @see Inflater#getAdler
+ * @since 11
+ */
+ public void setDictionary(ByteBuffer dictionary) {
+ synchronized (zsRef) {
+ int position = dictionary.position();
+ int remaining = Math.max(dictionary.limit() - position, 0);
+ ensureOpen();
+ if (dictionary.isDirect()) {
+ long address = ((DirectBuffer) dictionary).address();
+ try {
+ setDictionaryBuffer(zsRef.address(), address + position, remaining);
+ } finally {
+ Reference.reachabilityFence(dictionary);
+ }
+ } else {
+ byte[] array = ZipUtils.getBufferArray(dictionary);
+ int offset = ZipUtils.getBufferOffset(dictionary);
+ setDictionary(zsRef.address(), array, offset + position, remaining);
+ }
+ dictionary.position(position + remaining);
+ needDict = false;
+ }
}
/**
@@ -209,19 +297,22 @@
*/
public int getRemaining() {
synchronized (zsRef) {
- return len;
+ ByteBuffer input = this.input;
+ return input == null ? inputLim - inputPos : input.remaining();
}
}
/**
* Returns true if no data remains in the input buffer. This can
- * be used to determine if #setInput should be called in order
- * to provide more input.
+ * be used to determine if one of the {@code setInput()} methods should be
+ * called in order to provide more input.
+ *
* @return true if no data remains in the input buffer
*/
public boolean needsInput() {
synchronized (zsRef) {
- return len <= 0;
+ ByteBuffer input = this.input;
+ return input == null ? inputLim == inputPos : ! input.hasRemaining();
}
}
@@ -255,30 +346,103 @@
* determine if more input data or a preset dictionary is required.
* In the latter case, getAdler() can be used to get the Adler-32
* value of the dictionary required.
- * @param b the buffer for the uncompressed data
+ * <p>
+ * If the {@link #setInput(ByteBuffer)} method was called to provide a buffer
+ * for input, the input buffer's position will be advanced by the number of bytes
+ * consumed by this operation, even in the event that a {@link DataFormatException}
+ * is thrown.
+ * <p>
+ * The {@linkplain #getRemaining() remaining byte count} will be reduced by
+ * the number of consumed input bytes. If the {@link #setInput(ByteBuffer)}
+ * method was called to provide a buffer for input, the input buffer's position
+ * will be advanced the number of consumed bytes.
+ * <p>
+ * These byte totals, as well as
+ * the {@linkplain #getBytesRead() total bytes read}
+ * and the {@linkplain #getBytesWritten() total bytes written}
+ * values, will be updated even in the event that a {@link DataFormatException}
+ * is thrown to reflect the amount of data consumed and produced before the
+ * exception occurred.
+ *
+ * @param output the buffer for the uncompressed data
* @param off the start offset of the data
* @param len the maximum number of uncompressed bytes
* @return the actual number of uncompressed bytes
- * @exception DataFormatException if the compressed data format is invalid
+ * @throws DataFormatException if the compressed data format is invalid
* @see Inflater#needsInput
* @see Inflater#needsDictionary
*/
- public int inflate(byte[] b, int off, int len)
+ public int inflate(byte[] output, int off, int len)
throws DataFormatException
{
- if (b == null) {
- throw new NullPointerException();
- }
- if (off < 0 || len < 0 || off > b.length - len) {
+ if (off < 0 || len < 0 || off > output.length - len) {
throw new ArrayIndexOutOfBoundsException();
}
synchronized (zsRef) {
ensureOpen();
- int thisLen = this.len;
- int n = inflateBytes(zsRef.address(), b, off, len);
- bytesWritten += n;
- bytesRead += (thisLen - this.len);
- return n;
+ ByteBuffer input = this.input;
+ long result;
+ int inputPos;
+ try {
+ if (input == null) {
+ inputPos = this.inputPos;
+ try {
+ result = inflateBytesBytes(zsRef.address(),
+ inputArray, inputPos, inputLim - inputPos,
+ output, off, len);
+ } catch (DataFormatException e) {
+ this.inputPos = inputPos + inputConsumed;
+ throw e;
+ }
+ } else {
+ inputPos = input.position();
+ try {
+ int inputRem = Math.max(input.limit() - inputPos, 0);
+ if (input.isDirect()) {
+ try {
+ long inputAddress = ((DirectBuffer) input).address();
+ result = inflateBufferBytes(zsRef.address(),
+ inputAddress + inputPos, inputRem,
+ output, off, len);
+ } finally {
+ Reference.reachabilityFence(input);
+ }
+ } else {
+ byte[] inputArray = ZipUtils.getBufferArray(input);
+ int inputOffset = ZipUtils.getBufferOffset(input);
+ result = inflateBytesBytes(zsRef.address(),
+ inputArray, inputOffset + inputPos, inputRem,
+ output, off, len);
+ }
+ } catch (DataFormatException e) {
+ input.position(inputPos + inputConsumed);
+ throw e;
+ }
+ }
+ } catch (DataFormatException e) {
+ bytesRead += inputConsumed;
+ inputConsumed = 0;
+ int written = outputConsumed;
+ bytesWritten += written;
+ outputConsumed = 0;
+ throw e;
+ }
+ int read = (int) (result & 0x7fff_ffffL);
+ int written = (int) (result >>> 31 & 0x7fff_ffffL);
+ if ((result >>> 62 & 1) != 0) {
+ finished = true;
+ }
+ if ((result >>> 63 & 1) != 0) {
+ needDict = true;
+ }
+ if (input != null) {
+ input.position(inputPos + read);
+ } else {
+ this.inputPos = inputPos + read;
+ }
+ bytesWritten += written;
+ bytesRead += read;
+ return written;
}
}
@@ -289,14 +453,177 @@
* determine if more input data or a preset dictionary is required.
* In the latter case, getAdler() can be used to get the Adler-32
* value of the dictionary required.
- * @param b the buffer for the uncompressed data
+ * <p>
+ * The {@linkplain #getRemaining() remaining byte count} will be reduced by
+ * the number of consumed input bytes. If the {@link #setInput(ByteBuffer)}
+ * method was called to provide a buffer for input, the input buffer's position
+ * will be advanced the number of consumed bytes.
+ * <p>
+ * These byte totals, as well as
+ * the {@linkplain #getBytesRead() total bytes read}
+ * and the {@linkplain #getBytesWritten() total bytes written}
+ * values, will be updated even in the event that a {@link DataFormatException}
+ * is thrown to reflect the amount of data consumed and produced before the
+ * exception occurred.
+ *
+ * @param output the buffer for the uncompressed data
* @return the actual number of uncompressed bytes
- * @exception DataFormatException if the compressed data format is invalid
+ * @throws DataFormatException if the compressed data format is invalid
* @see Inflater#needsInput
* @see Inflater#needsDictionary
*/
- public int inflate(byte[] b) throws DataFormatException {
- return inflate(b, 0, b.length);
+ public int inflate(byte[] output) throws DataFormatException {
+ return inflate(output, 0, output.length);
+ }
+
+ /**
+ * Uncompresses bytes into specified buffer. Returns actual number
+ * of bytes uncompressed. A return value of 0 indicates that
+ * needsInput() or needsDictionary() should be called in order to
+ * determine if more input data or a preset dictionary is required.
+ * In the latter case, getAdler() can be used to get the Adler-32
+ * value of the dictionary required.
+ * <p>
+ * On success, the position of the given {@code output} byte buffer will be
+ * advanced by as many bytes as were produced by the operation, which is equal
+ * to the number returned by this method. Note that the position of the
+ * {@code output} buffer will be advanced even in the event that a
+ * {@link DataFormatException} is thrown.
+ * <p>
+ * The {@linkplain #getRemaining() remaining byte count} will be reduced by
+ * the number of consumed input bytes. If the {@link #setInput(ByteBuffer)}
+ * method was called to provide a buffer for input, the input buffer's position
+ * will be advanced the number of consumed bytes.
+ * <p>
+ * These byte totals, as well as
+ * the {@linkplain #getBytesRead() total bytes read}
+ * and the {@linkplain #getBytesWritten() total bytes written}
+ * values, will be updated even in the event that a {@link DataFormatException}
+ * is thrown to reflect the amount of data consumed and produced before the
+ * exception occurred.
+ *
+ * @param output the buffer for the uncompressed data
+ * @return the actual number of uncompressed bytes
+ * @throws DataFormatException if the compressed data format is invalid
+ * @throws ReadOnlyBufferException if the given output buffer is read-only
+ * @see Inflater#needsInput
+ * @see Inflater#needsDictionary
+ * @since 11
+ */
+ public int inflate(ByteBuffer output) throws DataFormatException {
+ if (output.isReadOnly()) {
+ throw new ReadOnlyBufferException();
+ }
+ synchronized (zsRef) {
+ ensureOpen();
+ ByteBuffer input = this.input;
+ long result;
+ int inputPos;
+ int outputPos = output.position();
+ int outputRem = Math.max(output.limit() - outputPos, 0);
+ try {
+ if (input == null) {
+ inputPos = this.inputPos;
+ try {
+ if (output.isDirect()) {
+ long outputAddress = ((DirectBuffer) output).address();
+ try {
+ result = inflateBytesBuffer(zsRef.address(),
+ inputArray, inputPos, inputLim - inputPos,
+ outputAddress + outputPos, outputRem);
+ } finally {
+ Reference.reachabilityFence(output);
+ }
+ } else {
+ byte[] outputArray = ZipUtils.getBufferArray(output);
+ int outputOffset = ZipUtils.getBufferOffset(output);
+ result = inflateBytesBytes(zsRef.address(),
+ inputArray, inputPos, inputLim - inputPos,
+ outputArray, outputOffset + outputPos, outputRem);
+ }
+ } catch (DataFormatException e) {
+ this.inputPos = inputPos + inputConsumed;
+ throw e;
+ }
+ } else {
+ inputPos = input.position();
+ int inputRem = Math.max(input.limit() - inputPos, 0);
+ try {
+ if (input.isDirect()) {
+ long inputAddress = ((DirectBuffer) input).address();
+ try {
+ if (output.isDirect()) {
+ long outputAddress = ((DirectBuffer) output).address();
+ try {
+ result = inflateBufferBuffer(zsRef.address(),
+ inputAddress + inputPos, inputRem,
+ outputAddress + outputPos, outputRem);
+ } finally {
+ Reference.reachabilityFence(output);
+ }
+ } else {
+ byte[] outputArray = ZipUtils.getBufferArray(output);
+ int outputOffset = ZipUtils.getBufferOffset(output);
+ result = inflateBufferBytes(zsRef.address(),
+ inputAddress + inputPos, inputRem,
+ outputArray, outputOffset + outputPos, outputRem);
+ }
+ } finally {
+ Reference.reachabilityFence(input);
+ }
+ } else {
+ byte[] inputArray = ZipUtils.getBufferArray(input);
+ int inputOffset = ZipUtils.getBufferOffset(input);
+ if (output.isDirect()) {
+ long outputAddress = ((DirectBuffer) output).address();
+ try {
+ result = inflateBytesBuffer(zsRef.address(),
+ inputArray, inputOffset + inputPos, inputRem,
+ outputAddress + outputPos, outputRem);
+ } finally {
+ Reference.reachabilityFence(output);
+ }
+ } else {
+ byte[] outputArray = ZipUtils.getBufferArray(output);
+ int outputOffset = ZipUtils.getBufferOffset(output);
+ result = inflateBytesBytes(zsRef.address(),
+ inputArray, inputOffset + inputPos, inputRem,
+ outputArray, outputOffset + outputPos, outputRem);
+ }
+ }
+ } catch (DataFormatException e) {
+ input.position(inputPos + inputConsumed);
+ throw e;
+ }
+ }
+ } catch (DataFormatException e) {
+ bytesRead += inputConsumed;
+ inputConsumed = 0;
+ int written = outputConsumed;
+ output.position(outputPos + written);
+ bytesWritten += written;
+ outputConsumed = 0;
+ throw e;
+ }
+ int read = (int) (result & 0x7fff_ffffL);
+ int written = (int) (result >>> 31 & 0x7fff_ffffL);
+ if ((result >>> 62 & 1) != 0) {
+ finished = true;
+ }
+ if ((result >>> 63 & 1) != 0) {
+ needDict = true;
+ }
+ if (input != null) {
+ input.position(inputPos + read);
+ } else {
+ this.inputPos = inputPos + read;
+ }
+ // Note: this method call also serves to keep the byteBuffer ref alive
+ output.position(outputPos + written);
+ bytesWritten += written;
+ bytesRead += read;
+ return written;
+ }
}
/**
@@ -369,46 +696,33 @@
synchronized (zsRef) {
ensureOpen();
reset(zsRef.address());
- buf = defaultBuf;
+ // Android-added: CloseGuard support.
+ guard.close();
+ input = ZipUtils.defaultBuf;
+ inputArray = null;
finished = false;
needDict = false;
- off = len = 0;
bytesRead = bytesWritten = 0;
}
}
/**
* Closes the decompressor and discards any unprocessed input.
+ *
* This method should be called when the decompressor is no longer
- * being used, but will also be called automatically by the finalize()
- * method. Once this method is called, the behavior of the Inflater
- * object is undefined.
+ * being used. Once this method is called, the behavior of the
+ * Inflater object is undefined.
*/
public void end() {
synchronized (zsRef) {
+ zsRef.clean();
// Android-added: CloseGuard support.
guard.close();
-
- long addr = zsRef.address();
- zsRef.clear();
- if (addr != 0) {
- end(addr);
- buf = null;
- }
+ input = ZipUtils.defaultBuf;
+ inputArray = null;
}
}
- /**
- * Closes the decompressor when garbage is collected.
- */
- protected void finalize() {
- // Android-added: CloseGuard support.
- if (guard != null) {
- guard.warnIfOpen();
- }
-
- end();
- }
private void ensureOpen () {
assert Thread.holdsLock(zsRef);
@@ -416,20 +730,58 @@
throw new NullPointerException("Inflater has been closed");
}
- boolean ended() {
- synchronized (zsRef) {
- return zsRef.address() == 0;
- }
- }
-
// Android-changed: initIDs handled in register method.
// private native static void initIDs();
- private native static long init(boolean nowrap);
- private native static void setDictionary(long addr, byte[] b, int off,
+ private static native long init(boolean nowrap);
+ private static native void setDictionary(long addr, byte[] b, int off,
int len);
- private native int inflateBytes(long addr, byte[] b, int off, int len)
- throws DataFormatException;
- private native static int getAdler(long addr);
- private native static void reset(long addr);
- private native static void end(long addr);
+ private static native void setDictionaryBuffer(long addr, long bufAddress, int len);
+ private native long inflateBytesBytes(long addr,
+ byte[] inputArray, int inputOff, int inputLen,
+ byte[] outputArray, int outputOff, int outputLen) throws DataFormatException;
+ private native long inflateBytesBuffer(long addr,
+ byte[] inputArray, int inputOff, int inputLen,
+ long outputAddress, int outputLen) throws DataFormatException;
+ private native long inflateBufferBytes(long addr,
+ long inputAddress, int inputLen,
+ byte[] outputArray, int outputOff, int outputLen) throws DataFormatException;
+ private native long inflateBufferBuffer(long addr,
+ long inputAddress, int inputLen,
+ long outputAddress, int outputLen) throws DataFormatException;
+ private static native int getAdler(long addr);
+ private static native void reset(long addr);
+ private static native void end(long addr);
+
+ /**
+ * A reference to the native zlib's z_stream structure. It also
+ * serves as the "cleaner" to clean up the native resource when
+ * the Inflater is ended, closed or cleaned.
+ */
+ static class InflaterZStreamRef implements Runnable {
+
+ private long address;
+ private final Cleanable cleanable;
+
+ private InflaterZStreamRef(Inflater owner, long addr) {
+ this.cleanable = (owner != null) ? CleanerFactory.cleaner().register(owner, this) : null;
+ this.address = addr;
+ }
+
+ long address() {
+ return address;
+ }
+
+ void clean() {
+ cleanable.clean();
+ }
+
+ public synchronized void run() {
+ long addr = address;
+ address = 0;
+ if (addr != 0) {
+ end(addr);
+ }
+ }
+
+ }
}
diff --git a/ojluni/src/main/java/java/util/zip/InflaterInputStream.java b/ojluni/src/main/java/java/util/zip/InflaterInputStream.java
index fbbbc94..0eb85ad 100644
--- a/ojluni/src/main/java/java/util/zip/InflaterInputStream.java
+++ b/ojluni/src/main/java/java/util/zip/InflaterInputStream.java
@@ -84,6 +84,29 @@
}
}
+ // Android-added: constructor which explicitly sets whether Inflater is owned by this stream.
+ /**
+ * Creates a new input stream with the specified decompressor and
+ * buffer size.
+ * @param in the input stream
+ * @param inf the decompressor ("inflater")
+ * @param size the input buffer size
+ * @param ownsInflater whether this {@code InflaterInputStream} controls its inflater
+ * lifetime and should call {@link Inflater#end} when it is closed.
+ * @throws IllegalArgumentException if {@code size <= 0}
+ * @hide
+ */
+ InflaterInputStream(InputStream in, Inflater inf, int size, boolean ownsInflater) {
+ super(in);
+ if (in == null || inf == null) {
+ throw new NullPointerException();
+ } else if (size <= 0) {
+ throw new IllegalArgumentException("buffer size <= 0");
+ }
+ this.inf = inf;
+ buf = new byte[size];
+ this.ownsInflater = ownsInflater;
+ }
/**
* Creates a new input stream with the specified decompressor and
@@ -94,6 +117,8 @@
* @throws IllegalArgumentException if {@code size <= 0}
*/
public InflaterInputStream(InputStream in, Inflater inf, int size) {
+ // Android-changed: refer initialization to constructor which specifies ownInflater.
+ /*
super(in);
if (in == null || inf == null) {
throw new NullPointerException();
@@ -102,6 +127,8 @@
}
this.inf = inf;
buf = new byte[size];
+ */
+ this(in, inf, size, /* ownsInflater= */ true);
}
/**
@@ -118,6 +145,12 @@
// See http://b/111630946 for more details.
// boolean usesDefaultInflater = false;
+ // Android-added: functionally this is identical to usesDefaultInflater, but re-using
+ // it will be confusing. Setting it to true keeps old Android behaviour.
+ // This is added just for ZipFileInflaterInputStream - moving to usesDefaultInflater
+ // is trickier.
+ private final boolean ownsInflater;
+
/**
* Creates a new input stream with a default decompressor and buffer size.
* @param in the input stream
@@ -245,9 +278,17 @@
*/
public void close() throws IOException {
if (!closed) {
- // Android-changed: Unconditionally close external inflaters (b/26462400)
- //if (usesDefaultInflater)
- inf.end();
+ // BEGIN Android-changed: close inflater only if it is owned by this
+ // InflaterInputStream. (b/26462400)
+ /*
+ if (usesDefaultInflater)
+ inf.end();
+ */
+ if (ownsInflater) {
+ inf.end();
+ }
+ // END Android-changed: close inflater only if it is owned by this
+ // InflaterInputStream. (b/26462400)
in.close();
closed = true;
}
diff --git a/ojluni/src/main/java/java/util/zip/ZipFile.java b/ojluni/src/main/java/java/util/zip/ZipFile.java
index 4f548a4..4c77de5 100644
--- a/ojluni/src/main/java/java/util/zip/ZipFile.java
+++ b/ojluni/src/main/java/java/util/zip/ZipFile.java
@@ -1,6 +1,6 @@
/*
* Copyright (C) 2014 The Android Open Source Project
- * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -32,70 +32,84 @@
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
+import java.io.RandomAccessFile;
+import java.io.UncheckedIOException;
+import java.lang.ref.Cleaner.Cleanable;
+import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
+import java.nio.file.InvalidPathException;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.Files;
import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
import java.util.Deque;
import java.util.Enumeration;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Iterator;
-import java.util.Map;
+import java.util.List;
+import java.util.Locale;
+import java.util.Objects;
import java.util.NoSuchElementException;
+import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
+import java.util.TreeSet;
import java.util.WeakHashMap;
+import java.util.function.Consumer;
+import java.util.function.IntFunction;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
+import jdk.internal.access.SharedSecrets;
+import jdk.internal.misc.VM;
+import jdk.internal.ref.CleanerFactory;
+import jdk.internal.vm.annotation.Stable;
+import sun.security.util.SignatureFileVerifier;
import dalvik.system.CloseGuard;
import dalvik.system.ZipPathValidator;
import static java.util.zip.ZipConstants64.*;
+import static java.util.zip.ZipUtils.*;
/**
* This class is used to read entries from a zip file.
*
- * <p> Unless otherwise noted, passing a <tt>null</tt> argument to a constructor
+ * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
*
+ * @apiNote
+ * To release resources used by this {@code ZipFile}, the {@link #close()} method
+ * should be called explicitly or by try-with-resources. Subclasses are responsible
+ * for the cleanup of resources acquired by the subclass. Subclasses that override
+ * {@link #finalize()} in order to perform cleanup should be modified to use alternative
+ * cleanup mechanisms such as {@link java.lang.ref.Cleaner} and remove the overriding
+ * {@code finalize} method.
+ *
* @author David Connelly
+ * @since 1.1
*/
-public
-class ZipFile implements ZipConstants, Closeable {
- // Android-note: jzfile does not require @ReachabilitySensitive annotation.
- // The @ReachabilitySensitive annotation is usually added to instance fields that references
- // native data that is cleaned up when the instance becomes unreachable. Its presence ensures
- // that the instance object is not finalized until the field is no longer used. Without it an
- // instance could be finalized during execution of an instance method iff that method's this
- // variable holds the last reference to the instance and the method had copied all the fields
- // it needs out of the instance. That would release the native data, invalidating its reference
- // and would cause serious problems if the method had taken a copy of that field and
- // then called a native method that would try to use it.
- //
- // This field does not require the annotation because all usages of this field are enclosed
- // within a synchronized(this) block and finalizing of the object referenced in a synchronized
- // block is not allowed as that would release its monitor that is currently in use.
- private long jzfile; // address of jzfile data
+public class ZipFile implements ZipConstants, Closeable {
+
private final String name; // zip file name
- private final int total; // total number of entries
- private final boolean locsig; // if zip file starts with LOCSIG (usually true)
- private volatile boolean closeRequested = false;
+ private volatile boolean closeRequested;
+
+ // The "resource" used by this zip file that needs to be
+ // cleaned after use.
+ // a) the input streams that need to be closed
+ // b) the list of cached Inflater objects
+ // c) the "native" source of this zip file.
+ private final @Stable CleanableResource res;
// Android-added: CloseGuard support.
private final CloseGuard guard = CloseGuard.get();
- // Android-added: Do not use unlink() to implement OPEN_DELETE.
- // Upstream uses unlink() to cause the file name to be removed from the filesystem after it is
- // opened but that does not work on fuse fs as it causes problems with lseek. Android simply
- // keeps a reference to the File so that it can explicitly delete it during close.
- //
- // OpenJDK 9+181 has a pure Java implementation of ZipFile that does not use unlink() and
- // instead does something very similar to what Android does. If Android adopts it then this
- // patch can be dropped.
- // See http://b/28950284 and http://b/28901232 for more details.
- private final File fileToRemoveOnClose;
-
private static final int STORED = ZipEntry.STORED;
private static final int DEFLATED = ZipEntry.DEFLATED;
@@ -108,44 +122,17 @@
* Mode flag to open a zip file and mark it for deletion. The file will be
* deleted some time between the moment that it is opened and the moment
* that it is closed, but its contents will remain accessible via the
- * <tt>ZipFile</tt> object until either the close method is invoked or the
+ * {@code ZipFile} object until either the close method is invoked or the
* virtual machine exits.
*/
public static final int OPEN_DELETE = 0x4;
- // Android-removed: initIDs() not used on Android.
- /*
- static {
- /* Zip library is loaded from System.initializeSystemClass *
- initIDs();
- }
-
- private static native void initIDs();
- */
-
- private static final boolean usemmap;
-
- // Android-added: An instance variable that determines if zip path validation should be enabled.
- private final boolean isZipPathValidatorEnabled;
-
- static {
- // Android-changed: Always use mmap.
- /*
- // A system prpperty to disable mmap use to avoid vm crash when
- // in-use zip file is accidently overwritten by others.
- String prop = sun.misc.VM.getSavedProperty("sun.zip.disableMemoryMapping");
- usemmap = (prop == null ||
- !(prop.length() == 0 || prop.equalsIgnoreCase("true")));
- */
- usemmap = true;
- }
-
// Android-changed: Additional ZipException throw scenario with ZipPathValidator.
/**
* Opens a zip file for reading.
*
- * <p>First, if there is a security manager, its <code>checkRead</code>
- * method is called with the <code>name</code> argument as its argument
+ * <p>First, if there is a security manager, its {@code checkRead}
+ * method is called with the {@code name} argument as its argument
* to ensure the read is allowed.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
@@ -161,7 +148,7 @@
* and (the <code>name</code> argument contains ".." or starts with "/").
* @throws IOException if an I/O error has occurred
* @throws SecurityException if a security manager exists and its
- * <code>checkRead</code> method doesn't allow read access to the file.
+ * {@code checkRead} method doesn't allow read access to the file.
*
* @see SecurityManager#checkRead(java.lang.String)
*/
@@ -170,12 +157,12 @@
}
/**
- * Opens a new <code>ZipFile</code> to read from the specified
- * <code>File</code> object in the specified mode. The mode argument
- * must be either <tt>OPEN_READ</tt> or <tt>OPEN_READ | OPEN_DELETE</tt>.
+ * Opens a new {@code ZipFile} to read from the specified
+ * {@code File} object in the specified mode. The mode argument
+ * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
*
- * <p>First, if there is a security manager, its <code>checkRead</code>
- * method is called with the <code>name</code> argument as its argument to
+ * <p>First, if there is a security manager, its {@code checkRead}
+ * method is called with the {@code name} argument as its argument to
* ensure the read is allowed.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
@@ -186,15 +173,17 @@
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws SecurityException if a security manager exists and
- * its <code>checkRead</code> method
+ * its {@code checkRead} method
* doesn't allow read access to the file,
- * or its <code>checkDelete</code> method doesn't allow deleting
- * the file when the <tt>OPEN_DELETE</tt> flag is set.
- * @throws IllegalArgumentException if the <tt>mode</tt> argument is invalid
+ * or its {@code checkDelete} method doesn't allow deleting
+ * the file when the {@code OPEN_DELETE} flag is set.
+ * @throws IllegalArgumentException if the {@code mode} argument is invalid
* @see SecurityManager#checkRead(java.lang.String)
* @since 1.3
*/
public ZipFile(File file, int mode) throws IOException {
+ // Android-changed: Use StandardCharsets.UTF_8.
+ // this(file, mode, UTF_8.INSTANCE);
this(file, mode, StandardCharsets.UTF_8);
}
@@ -212,16 +201,14 @@
this(file, OPEN_READ);
}
- private ZipCoder zc;
-
// Android-changed: Use of the hidden constructor with a new argument for zip path validation.
/**
- * Opens a new <code>ZipFile</code> to read from the specified
- * <code>File</code> object in the specified mode. The mode argument
- * must be either <tt>OPEN_READ</tt> or <tt>OPEN_READ | OPEN_DELETE</tt>.
+ * Opens a new {@code ZipFile} to read from the specified
+ * {@code File} object in the specified mode. The mode argument
+ * must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
*
- * <p>First, if there is a security manager, its <code>checkRead</code>
- * method is called with the <code>name</code> argument as its argument to
+ * <p>First, if there is a security manager, its {@code checkRead}
+ * method is called with the {@code name} argument as its argument to
* ensure the read is allowed.
*
* @param file the ZIP file to be opened for reading
@@ -236,12 +223,12 @@
* @throws IOException if an I/O error has occurred
*
* @throws SecurityException
- * if a security manager exists and its <code>checkRead</code>
+ * if a security manager exists and its {@code checkRead}
* method doesn't allow read access to the file,or its
- * <code>checkDelete</code> method doesn't allow deleting the
- * file when the <tt>OPEN_DELETE</tt> flag is set
+ * {@code checkDelete} method doesn't allow deleting the
+ * file when the {@code OPEN_DELETE} flag is set
*
- * @throws IllegalArgumentException if the <tt>mode</tt> argument is invalid
+ * @throws IllegalArgumentException if the {@code mode} argument is invalid
*
* @see SecurityManager#checkRead(java.lang.String)
*
@@ -264,15 +251,16 @@
/** @hide */
public ZipFile(File file, int mode, Charset charset, boolean enableZipPathValidator)
throws IOException {
- isZipPathValidatorEnabled = enableZipPathValidator && !ZipPathValidator.isClear();
if (((mode & OPEN_READ) == 0) ||
((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) {
throw new IllegalArgumentException("Illegal mode: 0x"+
Integer.toHexString(mode));
}
String name = file.getPath();
+ file = new File(name);
// Android-removed: SecurityManager is always null.
/*
+ @SuppressWarnings("removal")
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkRead(name);
@@ -282,30 +270,28 @@
}
*/
- // Android-added: Do not use unlink() to implement OPEN_DELETE.
- fileToRemoveOnClose = ((mode & OPEN_DELETE) != 0) ? file : null;
+ Objects.requireNonNull(charset, "charset");
- if (charset == null)
- throw new NullPointerException("charset is null");
- this.zc = ZipCoder.get(charset);
+ this.name = name;
// Android-removed: Skip perf counters.
// long t0 = System.nanoTime();
- jzfile = open(name, mode, file.lastModified(), usemmap);
+
+ // Android-changed: pass isZipPathValidatorEnabled flag.
+ // this.res = new CleanableResource(this, ZipCoder.get(charset), file, mode);
+ boolean isZipPathValidatorEnabled = enableZipPathValidator && !ZipPathValidator.isClear();
+ this.res = new CleanableResource(
+ this, ZipCoder.get(charset), file, mode, isZipPathValidatorEnabled);
+
// Android-removed: Skip perf counters.
- // sun.misc.PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0);
- // sun.misc.PerfCounter.getZipFileCount().increment();
- this.name = name;
- this.total = getTotal(jzfile);
- this.locsig = startsWithLOC(jzfile);
- // Android-added: CloseGuard support.
- guard.open("close");
+ // PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0);
+ // PerfCounter.getZipFileCount().increment();
}
/**
* Opens a zip file for reading.
*
- * <p>First, if there is a security manager, its <code>checkRead</code>
- * method is called with the <code>name</code> argument as its argument
+ * <p>First, if there is a security manager, its {@code checkRead}
+ * method is called with the {@code name} argument as its argument
* to ensure the read is allowed.
*
* @param name the name of the zip file
@@ -318,7 +304,7 @@
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws SecurityException
- * if a security manager exists and its <code>checkRead</code>
+ * if a security manager exists and its {@code checkRead}
* method doesn't allow read access to the file
*
* @see SecurityManager#checkRead(java.lang.String)
@@ -332,6 +318,7 @@
/**
* Opens a ZIP file for reading given the specified File object.
+ *
* @param file the ZIP file to be opened for reading
* @param charset
* The {@linkplain java.nio.charset.Charset charset} to be
@@ -357,15 +344,15 @@
*
* @throws IllegalStateException if the zip file has been closed
*
- * Since 1.7
+ * @since 1.7
*/
public String getComment() {
synchronized (this) {
ensureOpen();
- byte[] bcomm = getCommentBytes(jzfile);
- if (bcomm == null)
+ if (res.zsrc.comment == null) {
return null;
- return zc.toString(bcomm, bcomm.length);
+ }
+ return res.zsrc.zc.toString(res.zsrc.comment);
}
}
@@ -378,38 +365,24 @@
* @throws IllegalStateException if the zip file has been closed
*/
public ZipEntry getEntry(String name) {
- if (name == null) {
- throw new NullPointerException("name");
- }
- long jzentry = 0;
+ Objects.requireNonNull(name, "name");
+ ZipEntry entry = null;
synchronized (this) {
ensureOpen();
- jzentry = getEntry(jzfile, zc.getBytes(name), true);
- if (jzentry != 0) {
- ZipEntry ze = getZipEntry(name, jzentry);
- freeEntry(jzfile, jzentry);
- return ze;
+ int pos = res.zsrc.getEntryPos(name, true);
+ if (pos != -1) {
+ entry = getZipEntry(name, pos);
}
}
- return null;
+ return entry;
}
- private static native long getEntry(long jzfile, byte[] name,
- boolean addSlash);
-
- // freeEntry releases the C jzentry struct.
- private static native void freeEntry(long jzfile, long jzentry);
-
- // the outstanding inputstreams that need to be closed,
- // mapped to the inflater objects they use.
- private final Map<InputStream, Inflater> streams = new WeakHashMap<>();
-
/**
* Returns an input stream for reading the contents of the specified
* zip file entry.
- *
- * <p> Closing this ZIP file will, in turn, close all input
- * streams that have been returned by invocations of this method.
+ * <p>
+ * Closing this ZIP file will, in turn, close all input streams that
+ * have been returned by invocations of this method.
*
* @param entry the zip file entry
* @return the input stream for reading the contents of the specified
@@ -419,50 +392,44 @@
* @throws IllegalStateException if the zip file has been closed
*/
public InputStream getInputStream(ZipEntry entry) throws IOException {
- if (entry == null) {
- throw new NullPointerException("entry");
- }
- long jzentry = 0;
- ZipFileInputStream in = null;
+ Objects.requireNonNull(entry, "entry");
+ int pos;
+ ZipFileInputStream in;
+ Source zsrc = res.zsrc;
+ Set<InputStream> istreams = res.istreams;
synchronized (this) {
ensureOpen();
- if (!zc.isUTF8() && (entry.flag & USE_UTF8) != 0) {
- // Android-changed: Find entry by name, falling back to name/ if cannot be found.
- // Needed for ClassPathURLStreamHandler handling of URLs without trailing slashes.
- // This was added as part of the work to move StrictJarFile from libcore to
- // framework, see http://b/111293098 for more details.
- // It should be possible to revert this after upgrading to OpenJDK 8u144 or above.
- // jzentry = getEntry(jzfile, zc.getBytesUTF8(entry.name), false);
- jzentry = getEntry(jzfile, zc.getBytesUTF8(entry.name), true);
+ if (Objects.equals(lastEntryName, entry.name)) {
+ pos = lastEntryPos;
} else {
- // Android-changed: Find entry by name, falling back to name/ if cannot be found.
- // jzentry = getEntry(jzfile, zc.getBytes(entry.name), false);
- jzentry = getEntry(jzfile, zc.getBytes(entry.name), true);
+ pos = zsrc.getEntryPos(entry.name, false);
}
- if (jzentry == 0) {
+ if (pos == -1) {
return null;
}
- in = new ZipFileInputStream(jzentry);
-
- switch (getEntryMethod(jzentry)) {
+ in = new ZipFileInputStream(zsrc.cen, pos);
+ switch (CENHOW(zsrc.cen, pos)) {
case STORED:
- synchronized (streams) {
- streams.put(in, null);
+ synchronized (istreams) {
+ istreams.add(in);
}
return in;
case DEFLATED:
+ // Inflater likes a bit of slack
// MORE: Compute good size for inflater stream:
- long size = getEntrySize(jzentry) + 2; // Inflater likes a bit of slack
- // Android-changed: Use 64k buffer size, performs better than 8k.
- // See http://b/65491407.
- // if (size > 65536) size = 8192;
- if (size > 65536) size = 65536;
- if (size <= 0) size = 4096;
- Inflater inf = getInflater();
- InputStream is =
- new ZipFileInflaterInputStream(in, inf, (int)size);
- synchronized (streams) {
- streams.put(is, inf);
+ long size = CENLEN(zsrc.cen, pos) + 2;
+ if (size > 65536) {
+ // Android-changed: Use 64k buffer size, performs
+ // better than 8k. See http://b/65491407.
+ // size = 8192;
+ size = 65536;
+ }
+ if (size <= 0) {
+ size = 4096;
+ }
+ InputStream is = new ZipFileInflaterInputStream(in, res, (int)size);
+ synchronized (istreams) {
+ istreams.add(is);
}
return is;
default:
@@ -471,30 +438,51 @@
}
}
- private class ZipFileInflaterInputStream extends InflaterInputStream {
- private volatile boolean closeRequested = false;
- private boolean eof = false;
- private final ZipFileInputStream zfin;
+ private static class InflaterCleanupAction implements Runnable {
+ private final Inflater inf;
+ private final CleanableResource res;
- ZipFileInflaterInputStream(ZipFileInputStream zfin, Inflater inf,
- int size) {
- super(zfin, inf, size);
- this.zfin = zfin;
+ InflaterCleanupAction(Inflater inf, CleanableResource res) {
+ this.inf = inf;
+ this.res = res;
+ }
+
+ @Override
+ public void run() {
+ res.releaseInflater(inf);
+ }
+ }
+
+ private class ZipFileInflaterInputStream extends InflaterInputStream {
+ private volatile boolean closeRequested;
+ private boolean eof = false;
+ private final Cleanable cleanable;
+
+ ZipFileInflaterInputStream(ZipFileInputStream zfin,
+ CleanableResource res, int size) {
+ this(zfin, res, res.getInflater(), size);
+ }
+
+ private ZipFileInflaterInputStream(ZipFileInputStream zfin,
+ CleanableResource res,
+ Inflater inf, int size) {
+ // Android-changed: ZipFileInflaterInputStream does not control its inflater's lifetime
+ // and hence it shouldn't be closed when the stream is closed.
+ // super(zfin, inf, size);
+ super(zfin, inf, size, /* ownsInflater */ false);
+ this.cleanable = CleanerFactory.cleaner().register(this,
+ new InflaterCleanupAction(inf, res));
}
public void close() throws IOException {
if (closeRequested)
return;
closeRequested = true;
-
super.close();
- Inflater inf;
- synchronized (streams) {
- inf = streams.remove(this);
+ synchronized (res.istreams) {
+ res.istreams.remove(this);
}
- if (inf != null) {
- releaseInflater(inf);
- }
+ cleanable.clean();
}
// Override fill() method to provide an extra "dummy" byte
@@ -516,47 +504,12 @@
public int available() throws IOException {
if (closeRequested)
return 0;
- long avail = zfin.size() - inf.getBytesWritten();
+ long avail = ((ZipFileInputStream)in).size() - inf.getBytesWritten();
return (avail > (long) Integer.MAX_VALUE ?
Integer.MAX_VALUE : (int) avail);
}
-
- protected void finalize() throws Throwable {
- close();
- }
}
- /*
- * Gets an inflater from the list of available inflaters or allocates
- * a new one.
- */
- private Inflater getInflater() {
- Inflater inf;
- synchronized (inflaterCache) {
- while (null != (inf = inflaterCache.poll())) {
- if (false == inf.ended()) {
- return inf;
- }
- }
- }
- return new Inflater(true);
- }
-
- /*
- * Releases the specified inflater to the list of available inflaters.
- */
- private void releaseInflater(Inflater inf) {
- if (false == inf.ended()) {
- inf.reset();
- synchronized (inflaterCache) {
- inflaterCache.add(inf);
- }
- }
- }
-
- // List of available Inflater objects for decompression
- private Deque<Inflater> inflaterCache = new ArrayDeque<>();
-
/**
* Returns the path name of the ZIP file.
* @return the path name of the ZIP file
@@ -565,55 +518,53 @@
return name;
}
- private class ZipEntryIterator implements Enumeration<ZipEntry>, Iterator<ZipEntry> {
- private int i = 0;
+ private class ZipEntryIterator<T extends ZipEntry>
+ implements Enumeration<T>, Iterator<T> {
- public ZipEntryIterator() {
- ensureOpen();
+ private int i = 0;
+ private final int entryCount;
+
+ public ZipEntryIterator(int entryCount) {
+ this.entryCount = entryCount;
}
+ @Override
public boolean hasMoreElements() {
return hasNext();
}
+ @Override
public boolean hasNext() {
+ // Android-changed: check that file is open.
+ // return i < entryCount;
synchronized (ZipFile.this) {
ensureOpen();
- return i < total;
+ return i < entryCount;
}
}
- public ZipEntry nextElement() {
+ @Override
+ public T nextElement() {
return next();
}
- public ZipEntry next() {
+ @Override
+ @SuppressWarnings("unchecked")
+ public T next() {
synchronized (ZipFile.this) {
ensureOpen();
- if (i >= total) {
+ if (!hasNext()) {
throw new NoSuchElementException();
}
- long jzentry = getNextEntry(jzfile, i++);
- if (jzentry == 0) {
- String message;
- if (closeRequested) {
- message = "ZipFile concurrently closed";
- } else {
- message = getZipMessage(ZipFile.this.jzfile);
- }
- throw new ZipError("jzentry == 0" +
- ",\n jzfile = " + ZipFile.this.jzfile +
- ",\n total = " + ZipFile.this.total +
- ",\n name = " + ZipFile.this.name +
- ",\n i = " + i +
- ",\n message = " + message
- );
- }
- ZipEntry ze = getZipEntry(null, jzentry);
- freeEntry(jzfile, jzentry);
- return ze;
+ // each "entry" has 3 ints in table entries
+ return (T)getZipEntry(null, res.zsrc.getEntryPos(i++ * 3));
}
}
+
+ @Override
+ public Iterator<T> asIterator() {
+ return this;
+ }
}
/**
@@ -622,11 +573,51 @@
* @throws IllegalStateException if the zip file has been closed
*/
public Enumeration<? extends ZipEntry> entries() {
- return new ZipEntryIterator();
+ synchronized (this) {
+ ensureOpen();
+ return new ZipEntryIterator<ZipEntry>(res.zsrc.total);
+ }
+ }
+
+ private Enumeration<JarEntry> jarEntries() {
+ synchronized (this) {
+ ensureOpen();
+ return new ZipEntryIterator<JarEntry>(res.zsrc.total);
+ }
+ }
+
+ private class EntrySpliterator<T> extends Spliterators.AbstractSpliterator<T> {
+ private int index;
+ private final int fence;
+ private final IntFunction<T> gen;
+
+ EntrySpliterator(int index, int fence, IntFunction<T> gen) {
+ super((long)fence,
+ Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.IMMUTABLE |
+ Spliterator.NONNULL);
+ this.index = index;
+ this.fence = fence;
+ this.gen = gen;
+ }
+
+ @Override
+ public boolean tryAdvance(Consumer<? super T> action) {
+ if (action == null)
+ throw new NullPointerException();
+ if (index >= 0 && index < fence) {
+ synchronized (ZipFile.this) {
+ ensureOpen();
+ action.accept(gen.apply(res.zsrc.getEntryPos(index++ * 3)));
+ }
+ return true;
+ }
+ return false;
+ }
}
/**
- * Return an ordered {@code Stream} over the ZIP file entries.
+ * Returns an ordered {@code Stream} over the ZIP file entries.
+ *
* Entries appear in the {@code Stream} in the order they appear in
* the central directory of the ZIP file.
*
@@ -635,69 +626,243 @@
* @since 1.8
*/
public Stream<? extends ZipEntry> stream() {
- return StreamSupport.stream(Spliterators.spliterator(
- new ZipEntryIterator(), size(),
- Spliterator.ORDERED | Spliterator.DISTINCT |
- Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
+ synchronized (this) {
+ ensureOpen();
+ return StreamSupport.stream(new EntrySpliterator<>(0, res.zsrc.total,
+ pos -> getZipEntry(null, pos)), false);
+ }
}
- // Android-added: Hook to validate zip entry name by ZipPathValidator.
- private void onZipEntryAccess(byte[] bname, int flag) throws ZipException {
- String name;
- if (!zc.isUTF8() && (flag & USE_UTF8) != 0) {
- name = zc.toStringUTF8(bname, bname.length);
- } else {
- name = zc.toString(bname, bname.length);
+ private String getEntryName(int pos) {
+ byte[] cen = res.zsrc.cen;
+ int nlen = CENNAM(cen, pos);
+ ZipCoder zc = res.zsrc.zipCoderForPos(pos);
+ return zc.toString(cen, pos + CENHDR, nlen);
+ }
+
+ /*
+ * Returns an ordered {@code Stream} over the zip file entry names.
+ *
+ * Entry names appear in the {@code Stream} in the order they appear in
+ * the central directory of the ZIP file.
+ *
+ * @return an ordered {@code Stream} of entry names in this zip file
+ * @throws IllegalStateException if the zip file has been closed
+ * @since 10
+ */
+ private Stream<String> entryNameStream() {
+ synchronized (this) {
+ ensureOpen();
+ return StreamSupport.stream(
+ new EntrySpliterator<>(0, res.zsrc.total, this::getEntryName), false);
}
- ZipPathValidator.getInstance().onZipEntryAccess(name);
}
- private ZipEntry getZipEntry(String name, long jzentry) {
- ZipEntry e = new ZipEntry();
- e.flag = getEntryFlag(jzentry); // get the flag first
+ /*
+ * Returns an ordered {@code Stream} over the zip file entries.
+ *
+ * Entries appear in the {@code Stream} in the order they appear in
+ * the central directory of the jar file.
+ *
+ * @return an ordered {@code Stream} of entries in this zip file
+ * @throws IllegalStateException if the zip file has been closed
+ * @since 10
+ */
+ private Stream<JarEntry> jarStream() {
+ synchronized (this) {
+ ensureOpen();
+ return StreamSupport.stream(new EntrySpliterator<>(0, res.zsrc.total,
+ pos -> (JarEntry)getZipEntry(null, pos)), false);
+ }
+ }
+
+ private String lastEntryName;
+ private int lastEntryPos;
+
+ /* Check ensureOpen() before invoking this method */
+ private ZipEntry getZipEntry(String name, int pos) {
+ byte[] cen = res.zsrc.cen;
+ int nlen = CENNAM(cen, pos);
+ int elen = CENEXT(cen, pos);
+ int clen = CENCOM(cen, pos);
+
+ ZipCoder zc = res.zsrc.zipCoderForPos(pos);
if (name != null) {
- e.name = name;
- } else {
- byte[] bname = getEntryBytes(jzentry, JZENTRY_NAME);
- if (!zc.isUTF8() && (e.flag & USE_UTF8) != 0) {
- e.name = zc.toStringUTF8(bname, bname.length);
- } else {
- e.name = zc.toString(bname, bname.length);
+ // only need to check for mismatch of trailing slash
+ if (nlen > 0 &&
+ !name.isEmpty() &&
+ zc.hasTrailingSlash(cen, pos + CENHDR + nlen) &&
+ !name.endsWith("/"))
+ {
+ name += '/';
}
- }
- e.xdostime = getEntryTime(jzentry);
- e.crc = getEntryCrc(jzentry);
- e.size = getEntrySize(jzentry);
- e.csize = getEntryCSize(jzentry);
- e.method = getEntryMethod(jzentry);
- e.setExtra0(getEntryBytes(jzentry, JZENTRY_EXTRA), false, false);
- byte[] bcomm = getEntryBytes(jzentry, JZENTRY_COMMENT);
- if (bcomm == null) {
- e.comment = null;
} else {
- if (!zc.isUTF8() && (e.flag & USE_UTF8) != 0) {
- e.comment = zc.toStringUTF8(bcomm, bcomm.length);
- } else {
- e.comment = zc.toString(bcomm, bcomm.length);
- }
+ // invoked from iterator, use the entry name stored in cen
+ name = zc.toString(cen, pos + CENHDR, nlen);
}
+ ZipEntry e;
+ if (this instanceof JarFile) {
+ // Android-changed: access method directly.
+ // e = Source.JUJA.entryFor((JarFile)this, name);
+ e = ((JarFile) this).entryFor(name);
+ } else {
+ e = new ZipEntry(name);
+ }
+ e.flag = CENFLG(cen, pos);
+ e.xdostime = CENTIM(cen, pos);
+ e.crc = CENCRC(cen, pos);
+ e.size = CENLEN(cen, pos);
+ e.csize = CENSIZ(cen, pos);
+ e.method = CENHOW(cen, pos);
+ if (CENVEM_FA(cen, pos) == FILE_ATTRIBUTES_UNIX) {
+ // read all bits in this field, including sym link attributes
+ e.extraAttributes = CENATX_PERMS(cen, pos) & 0xFFFF;
+ }
+
+ if (elen != 0) {
+ int start = pos + CENHDR + nlen;
+ e.setExtra0(Arrays.copyOfRange(cen, start, start + elen), true, false);
+ }
+ if (clen != 0) {
+ int start = pos + CENHDR + nlen + elen;
+ e.comment = zc.toString(cen, start, clen);
+ }
+ lastEntryName = e.name;
+ lastEntryPos = pos;
return e;
}
- private static native long getNextEntry(long jzfile, int i);
-
/**
* Returns the number of entries in the ZIP file.
+ *
* @return the number of entries in the ZIP file
* @throws IllegalStateException if the zip file has been closed
*/
public int size() {
- ensureOpen();
- return total;
+ synchronized (this) {
+ ensureOpen();
+ return res.zsrc.total;
+ }
+ }
+
+ private static class CleanableResource implements Runnable {
+ // The outstanding inputstreams that need to be closed
+ final Set<InputStream> istreams;
+
+ // List of cached Inflater objects for decompression
+ Deque<Inflater> inflaterCache;
+
+ final Cleanable cleanable;
+
+ Source zsrc;
+
+ CleanableResource(ZipFile zf, ZipCoder zc, File file, int mode) throws IOException {
+ this(zf, zc, file, mode, false);
+ }
+
+ // Android-added: added extra enableZipPathValidator argument.
+ CleanableResource(ZipFile zf, ZipCoder zc, File file,
+ int mode, boolean enableZipPathValidator) throws IOException {
+ this.cleanable = CleanerFactory.cleaner().register(zf, this);
+ this.istreams = Collections.newSetFromMap(new WeakHashMap<>());
+ this.inflaterCache = new ArrayDeque<>();
+ this.zsrc = Source.get(file, (mode & OPEN_DELETE) != 0, zc, enableZipPathValidator);
+ }
+
+ void clean() {
+ cleanable.clean();
+ }
+
+ /*
+ * Gets an inflater from the list of available inflaters or allocates
+ * a new one.
+ */
+ Inflater getInflater() {
+ Inflater inf;
+ synchronized (inflaterCache) {
+ if ((inf = inflaterCache.poll()) != null) {
+ return inf;
+ }
+ }
+ return new Inflater(true);
+ }
+
+ /*
+ * Releases the specified inflater to the list of available inflaters.
+ */
+ void releaseInflater(Inflater inf) {
+ Deque<Inflater> inflaters = this.inflaterCache;
+ if (inflaters != null) {
+ synchronized (inflaters) {
+ // double checked!
+ if (inflaters == this.inflaterCache) {
+ inf.reset();
+ inflaters.add(inf);
+ return;
+ }
+ }
+ }
+ // inflaters cache already closed - just end it.
+ inf.end();
+ }
+
+ public void run() {
+ IOException ioe = null;
+
+ // Release cached inflaters and close the cache first
+ Deque<Inflater> inflaters = this.inflaterCache;
+ if (inflaters != null) {
+ synchronized (inflaters) {
+ // no need to double-check as only one thread gets a
+ // chance to execute run() (Cleaner guarantee)...
+ Inflater inf;
+ while ((inf = inflaters.poll()) != null) {
+ inf.end();
+ }
+ // close inflaters cache
+ this.inflaterCache = null;
+ }
+ }
+
+ // Close streams, release their inflaters
+ if (istreams != null) {
+ synchronized (istreams) {
+ if (!istreams.isEmpty()) {
+ InputStream[] copy = istreams.toArray(new InputStream[0]);
+ istreams.clear();
+ for (InputStream is : copy) {
+ try {
+ is.close();
+ } catch (IOException e) {
+ if (ioe == null) ioe = e;
+ else ioe.addSuppressed(e);
+ }
+ }
+ }
+ }
+ }
+
+ // Release zip src
+ if (zsrc != null) {
+ synchronized (zsrc) {
+ try {
+ Source.release(zsrc);
+ zsrc = null;
+ } catch (IOException e) {
+ if (ioe == null) ioe = e;
+ else ioe.addSuppressed(e);
+ }
+ }
+ }
+ if (ioe != null) {
+ throw new UncheckedIOException(ioe);
+ }
+ }
}
/**
* Closes the ZIP file.
+ *
* <p> Closing this ZIP file will close all of the input streams
* previously returned by invocations of the {@link #getInputStream
* getInputStream} method.
@@ -705,8 +870,9 @@
* @throws IOException if an I/O error has occurred
*/
public void close() throws IOException {
- if (closeRequested)
+ if (closeRequested) {
return;
+ }
// Android-added: CloseGuard support.
if (guard != null) {
guard.close();
@@ -714,85 +880,21 @@
closeRequested = true;
synchronized (this) {
- // Close streams, release their inflaters
- // BEGIN Android-added: null field check to avoid NullPointerException during finalize.
- // If the constructor threw an exception then the streams / inflaterCache fields can
- // be null and close() can be called by the finalizer.
- if (streams != null) {
- // END Android-added: null field check to avoid NullPointerException during finalize.
- synchronized (streams) {
- if (false == streams.isEmpty()) {
- Map<InputStream, Inflater> copy = new HashMap<>(streams);
- streams.clear();
- for (Map.Entry<InputStream, Inflater> e : copy.entrySet()) {
- e.getKey().close();
- Inflater inf = e.getValue();
- if (inf != null) {
- inf.end();
- }
- }
- }
- }
- // BEGIN Android-added: null field check to avoid NullPointerException during finalize.
- }
-
- if (inflaterCache != null) {
- // END Android-added: null field check to avoid NullPointerException during finalize.
- // Release cached inflaters
- Inflater inf;
- synchronized (inflaterCache) {
- while (null != (inf = inflaterCache.poll())) {
- inf.end();
- }
- }
- // BEGIN Android-added: null field check to avoid NullPointerException during finalize.
- }
- // END Android-added: null field check to avoid NullPointerException during finalize.
-
- if (jzfile != 0) {
- // Close the zip file
- long zf = this.jzfile;
- jzfile = 0;
-
- close(zf);
- }
- // Android-added: Do not use unlink() to implement OPEN_DELETE.
- if (fileToRemoveOnClose != null) {
- fileToRemoveOnClose.delete();
+ // Close streams, release their inflaters, release cached inflaters
+ // and release zip source
+ try {
+ res.clean();
+ } catch (UncheckedIOException ioe) {
+ throw ioe.getCause();
}
}
}
- /**
- * Ensures that the system resources held by this ZipFile object are
- * released when there are no more references to it.
- *
- * <p>
- * Since the time when GC would invoke this method is undetermined,
- * it is strongly recommended that applications invoke the <code>close</code>
- * method as soon they have finished accessing this <code>ZipFile</code>.
- * This will prevent holding up system resources for an undetermined
- * length of time.
- *
- * @throws IOException if an I/O error has occurred
- * @see java.util.zip.ZipFile#close()
- */
- protected void finalize() throws IOException {
- // Android-added: CloseGuard support.
- if (guard != null) {
- guard.warnIfOpen();
- }
- close();
- }
-
- private static native void close(long jzfile);
-
private void ensureOpen() {
if (closeRequested) {
throw new IllegalStateException("zip file closed");
}
-
- if (jzfile == 0) {
+ if (res.zsrc == null) {
throw new IllegalStateException("The object is not initialized.");
}
}
@@ -807,50 +909,103 @@
* Inner class implementing the input stream used to read a
* (possibly compressed) zip file entry.
*/
- private class ZipFileInputStream extends InputStream {
- private volatile boolean zfisCloseRequested = false;
- protected long jzentry; // address of jzentry data
+ private class ZipFileInputStream extends InputStream {
+ private volatile boolean closeRequested;
private long pos; // current position within entry data
+ private long startingPos; // Start position for the entry data
protected long rem; // number of remaining bytes within entry
protected long size; // uncompressed size of this entry
- ZipFileInputStream(long jzentry) {
- pos = 0;
- rem = getEntryCSize(jzentry);
- size = getEntrySize(jzentry);
- this.jzentry = jzentry;
+ ZipFileInputStream(byte[] cen, int cenpos) {
+ rem = CENSIZ(cen, cenpos);
+ size = CENLEN(cen, cenpos);
+ pos = CENOFF(cen, cenpos);
+ // zip64
+ if (rem == ZIP64_MAGICVAL || size == ZIP64_MAGICVAL ||
+ pos == ZIP64_MAGICVAL) {
+ checkZIP64(cen, cenpos);
+ }
+ // negative for lazy initialization, see getDataOffset();
+ pos = - (pos + ZipFile.this.res.zsrc.locpos);
+ }
+
+ private void checkZIP64(byte[] cen, int cenpos) {
+ int off = cenpos + CENHDR + CENNAM(cen, cenpos);
+ int end = off + CENEXT(cen, cenpos);
+ while (off + 4 < end) {
+ int tag = get16(cen, off);
+ int sz = get16(cen, off + 2);
+ off += 4;
+ if (off + sz > end) // invalid data
+ break;
+ if (tag == EXTID_ZIP64) {
+ if (size == ZIP64_MAGICVAL) {
+ if (sz < 8 || (off + 8) > end)
+ break;
+ size = get64(cen, off);
+ sz -= 8;
+ off += 8;
+ }
+ if (rem == ZIP64_MAGICVAL) {
+ if (sz < 8 || (off + 8) > end)
+ break;
+ rem = get64(cen, off);
+ sz -= 8;
+ off += 8;
+ }
+ if (pos == ZIP64_MAGICVAL) {
+ if (sz < 8 || (off + 8) > end)
+ break;
+ pos = get64(cen, off);
+ sz -= 8;
+ off += 8;
+ }
+ break;
+ }
+ off += sz;
+ }
+ }
+
+ /*
+ * The Zip file spec explicitly allows the LOC extra data size to
+ * be different from the CEN extra data size. Since we cannot trust
+ * the CEN extra data size, we need to read the LOC to determine
+ * the entry data offset.
+ */
+ private long initDataOffset() throws IOException {
+ if (pos <= 0) {
+ byte[] loc = new byte[LOCHDR];
+ pos = -pos;
+ int len = ZipFile.this.res.zsrc.readFullyAt(loc, 0, loc.length, pos);
+ if (len != LOCHDR) {
+ throw new ZipException("ZipFile error reading zip file");
+ }
+ if (LOCSIG(loc) != LOCSIG) {
+ throw new ZipException("ZipFile invalid LOC header (bad signature)");
+ }
+ pos += LOCHDR + LOCNAM(loc) + LOCEXT(loc);
+ startingPos = pos; // Save starting position for the entry
+ }
+ return pos;
}
public int read(byte b[], int off, int len) throws IOException {
- // Android-added: Always throw an exception when reading from closed zipfile.
- // Required by the JavaDoc for InputStream.read(byte[], int, int). Upstream version
- // 8u121-b13 is not compliant but that bug has been fixed in upstream version 9+181
- // as part of a major change to switch to a pure Java implementation.
- // See https://bugs.openjdk.java.net/browse/JDK-8145260 and
- // https://bugs.openjdk.java.net/browse/JDK-8142508.
- ensureOpenOrZipException();
-
synchronized (ZipFile.this) {
- long rem = this.rem;
- long pos = this.pos;
+ ensureOpenOrZipException();
+ initDataOffset();
if (rem == 0) {
return -1;
}
- if (len <= 0) {
- return 0;
- }
if (len > rem) {
len = (int) rem;
}
-
- // Android-removed: Always throw an exception when reading from closed zipfile.
- // Moved to the start of the method.
- //ensureOpenOrZipException();
- len = ZipFile.read(ZipFile.this.jzfile, jzentry, pos, b,
- off, len);
+ if (len <= 0) {
+ return 0;
+ }
+ len = ZipFile.this.res.zsrc.readAt(b, off, len, pos);
if (len > 0) {
- this.pos = (pos + len);
- this.rem = (rem - len);
+ pos += len;
+ rem -= len;
}
}
if (rem == 0) {
@@ -868,11 +1023,26 @@
}
}
- public long skip(long n) {
- if (n > rem)
- n = rem;
- pos += n;
- rem -= n;
+ public long skip(long n) throws IOException {
+ synchronized (ZipFile.this) {
+ initDataOffset();
+ long newPos = pos + n;
+ if (n > 0) {
+ // If we overflowed adding the skip value or are moving
+ // past EOF, set the skip value to number of bytes remaining
+ // to reach EOF
+ if (newPos < 0 || n > rem) {
+ n = rem;
+ }
+ } else if (newPos < startingPos) {
+ // Tried to position before BOF so set position to the
+ // BOF and return the number of bytes we moved backwards
+ // to reach BOF
+ n = startingPos - pos;
+ }
+ pos += n;
+ rem -= n;
+ }
if (rem == 0) {
close();
}
@@ -888,84 +1058,873 @@
}
public void close() {
- if (zfisCloseRequested)
+ if (closeRequested) {
return;
- zfisCloseRequested = true;
-
+ }
+ closeRequested = true;
rem = 0;
- synchronized (ZipFile.this) {
- if (jzentry != 0 && ZipFile.this.jzfile != 0) {
- freeEntry(ZipFile.this.jzfile, jzentry);
- jzentry = 0;
- }
- }
- synchronized (streams) {
- streams.remove(this);
+ synchronized (res.istreams) {
+ res.istreams.remove(this);
}
}
- protected void finalize() {
- close();
- }
}
- // Android-removed: Access startsWithLocHeader() directly.
- /*
- static {
- sun.misc.SharedSecrets.setJavaUtilZipFileAccess(
- new sun.misc.JavaUtilZipFileAccess() {
- public boolean startsWithLocHeader(ZipFile zip) {
- return zip.startsWithLocHeader();
- }
- }
- );
- }
- */
-
/**
* Returns {@code true} if, and only if, the zip file begins with {@code
* LOCSIG}.
* @hide
*/
- // Android-changed: Access startsWithLocHeader() directly.
+ // Android-added: Access startsWithLocHeader() directly.
// Make hidden public for use by sun.misc.URLClassPath
- // private boolean startsWithLocHeader() {
public boolean startsWithLocHeader() {
- return locsig;
+ return res.zsrc.startsWithLoc;
}
- // BEGIN Android-added: Provide access to underlying file descriptor for testing.
- // See http://b/111148957 for background information.
- /** @hide */
- // @VisibleForTesting
- public int getFileDescriptor() {
- return getFileDescriptor(jzfile);
+ // Android-changed: marked as protected so JarFile can access it.
+ /**
+ * Returns the names of the META-INF/MANIFEST.MF entry - if exists -
+ * and any signature-related files under META-INF. This method is used in
+ * JarFile, via SharedSecrets, as an optimization.
+ * @hide
+ */
+ protected List<String> getManifestAndSignatureRelatedFiles() {
+ synchronized (this) {
+ ensureOpen();
+ Source zsrc = res.zsrc;
+ int[] metanames = zsrc.signatureMetaNames;
+ List<String> files = null;
+ if (zsrc.manifestPos >= 0) {
+ files = new ArrayList<>();
+ files.add(getEntryName(zsrc.manifestPos));
+ }
+ if (metanames != null) {
+ if (files == null) {
+ files = new ArrayList<>();
+ }
+ for (int i = 0; i < metanames.length; i++) {
+ files.add(getEntryName(metanames[i]));
+ }
+ }
+ return files == null ? List.of() : files;
+ }
}
- private static native int getFileDescriptor(long jzfile);
- // END Android-added: Provide access to underlying file descriptor for testing.
+ /**
+ * Returns the number of the META-INF/MANIFEST.MF entries, case insensitive.
+ * When this number is greater than 1, JarVerifier will treat a file as
+ * unsigned.
+ */
+ private int getManifestNum() {
+ synchronized (this) {
+ ensureOpen();
+ return res.zsrc.manifestNum;
+ }
+ }
- // Android-changed: Make it as a non-static method, so it can access charset config.
- private native long open(String name, int mode, long lastModified,
- boolean usemmap) throws IOException;
- private static native int getTotal(long jzfile);
- private static native boolean startsWithLOC(long jzfile);
- private static native int read(long jzfile, long jzentry,
- long pos, byte[] b, int off, int len);
+ // Android-changed: marked public and @hide as alternative to JavaUtilZipFileAccess.getManifestName.
+ /**
+ * Returns the name of the META-INF/MANIFEST.MF entry, ignoring
+ * case. If {@code onlyIfSignatureRelatedFiles} is true, we only return the
+ * manifest if there is also at least one signature-related file.
+ * This method is used in JarFile, via SharedSecrets, as an optimization
+ * when looking up the manifest file.
+ * @hide
+ */
+ protected String getManifestName(boolean onlyIfSignatureRelatedFiles) {
+ synchronized (this) {
+ ensureOpen();
+ Source zsrc = res.zsrc;
+ int pos = zsrc.manifestPos;
+ if (pos >= 0 && (!onlyIfSignatureRelatedFiles || zsrc.signatureMetaNames != null)) {
+ return getEntryName(pos);
+ }
+ }
+ return null;
+ }
- // access to the native zentry object
- private static native long getEntryTime(long jzentry);
- private static native long getEntryCrc(long jzentry);
- private static native long getEntryCSize(long jzentry);
- private static native long getEntrySize(long jzentry);
- private static native int getEntryMethod(long jzentry);
- private static native int getEntryFlag(long jzentry);
- private static native byte[] getCommentBytes(long jzfile);
+ /**
+ * Returns the versions for which there exists a non-directory
+ * entry that begin with "META-INF/versions/" (case ignored).
+ * This method is used in JarFile, via SharedSecrets, as an
+ * optimization when looking up potentially versioned entries.
+ * Returns an empty array if no versioned entries exist.
+ */
+ private int[] getMetaInfVersions() {
+ synchronized (this) {
+ ensureOpen();
+ return res.zsrc.metaVersions;
+ }
+ }
- private static final int JZENTRY_NAME = 0;
- private static final int JZENTRY_EXTRA = 1;
- private static final int JZENTRY_COMMENT = 2;
- private static native byte[] getEntryBytes(long jzentry, int type);
+ // Android-removed: this code does not run on Windows and JavaUtilZipFileAccess is not imported.
+ /*
+ private static boolean isWindows;
- private static native String getZipMessage(long jzfile);
+ static {
+ SharedSecrets.setJavaUtilZipFileAccess(
+ new JavaUtilZipFileAccess() {
+ @Override
+ public boolean startsWithLocHeader(ZipFile zip) {
+ return zip.res.zsrc.startsWithLoc;
+ }
+ @Override
+ public List<String> getManifestAndSignatureRelatedFiles(JarFile jar) {
+ return ((ZipFile)jar).getManifestAndSignatureRelatedFiles();
+ }
+ @Override
+ public int getManifestNum(JarFile jar) {
+ return ((ZipFile)jar).getManifestNum();
+ }
+ @Override
+ public String getManifestName(JarFile jar, boolean onlyIfHasSignatureRelatedFiles) {
+ return ((ZipFile)jar).getManifestName(onlyIfHasSignatureRelatedFiles);
+ }
+ @Override
+ public int[] getMetaInfVersions(JarFile jar) {
+ return ((ZipFile)jar).getMetaInfVersions();
+ }
+ @Override
+ public Enumeration<JarEntry> entries(ZipFile zip) {
+ return zip.jarEntries();
+ }
+ @Override
+ public Stream<JarEntry> stream(ZipFile zip) {
+ return zip.jarStream();
+ }
+ @Override
+ public Stream<String> entryNameStream(ZipFile zip) {
+ return zip.entryNameStream();
+ }
+ @Override
+ public int getExtraAttributes(ZipEntry ze) {
+ return ze.extraAttributes;
+ }
+ @Override
+ public void setExtraAttributes(ZipEntry ze, int extraAttrs) {
+ ze.extraAttributes = extraAttrs;
+ }
+
+ }
+ );
+ isWindows = VM.getSavedProperty("os.name").contains("Windows");
+ }
+ */
+
+ private static class Source {
+ // While this is only used from ZipFile, defining it there would cause
+ // a bootstrap cycle that would leave this initialized as null
+ // Android-removed: JavaUtilJarAccess is not available.
+ // private static final JavaUtilJarAccess JUJA = SharedSecrets.javaUtilJarAccess();
+ // "META-INF/".length()
+ private static final int META_INF_LEN = 9;
+ private static final int[] EMPTY_META_VERSIONS = new int[0];
+
+ private final Key key; // the key in files
+ private final @Stable ZipCoder zc; // zip coder used to decode/encode
+
+ private int refs = 1;
+
+ private RandomAccessFile zfile; // zfile of the underlying zip file
+ private byte[] cen; // CEN & ENDHDR
+ private long locpos; // position of first LOC header (usually 0)
+ private byte[] comment; // zip file comment
+ // list of meta entries in META-INF dir
+ private int manifestPos = -1; // position of the META-INF/MANIFEST.MF, if exists
+ private int manifestNum = 0; // number of META-INF/MANIFEST.MF, case insensitive
+ private int[] signatureMetaNames; // positions of signature related entries, if such exist
+ private int[] metaVersions; // list of unique versions found in META-INF/versions/
+ private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true)
+
+ // A Hashmap for all entries.
+ //
+ // A cen entry of Zip/JAR file. As we have one for every entry in every active Zip/JAR,
+ // We might have a lot of these in a typical system. In order to save space we don't
+ // keep the name in memory, but merely remember a 32 bit {@code hash} value of the
+ // entry name and its offset {@code pos} in the central directory hdeader.
+ //
+ // private static class Entry {
+ // int hash; // 32 bit hashcode on name
+ // int next; // hash chain: index into entries
+ // int pos; // Offset of central directory file header
+ // }
+ // private Entry[] entries; // array of hashed cen entry
+ //
+ // To reduce the total size of entries further, we use a int[] here to store 3 "int"
+ // {@code hash}, {@code next} and {@code pos} for each entry. The entry can then be
+ // referred by their index of their positions in the {@code entries}.
+ //
+ private int[] entries; // array of hashed cen entry
+
+ // Checks the entry at offset pos in the CEN, calculates the Entry values as per above,
+ // then returns the length of the entry name.
+ private int checkAndAddEntry(int pos, int index)
+ throws ZipException
+ {
+ byte[] cen = this.cen;
+ if (CENSIG(cen, pos) != CENSIG) {
+ zerror("invalid CEN header (bad signature)");
+ }
+ int method = CENHOW(cen, pos);
+ int flag = CENFLG(cen, pos);
+ if ((flag & 1) != 0) {
+ zerror("invalid CEN header (encrypted entry)");
+ }
+ if (method != STORED && method != DEFLATED) {
+ zerror("invalid CEN header (bad compression method: " + method + ")");
+ }
+ int entryPos = pos + CENHDR;
+ int nlen = CENNAM(cen, pos);
+ if (entryPos + nlen > cen.length - ENDHDR) {
+ zerror("invalid CEN header (bad header size)");
+ }
+ try {
+ ZipCoder zcp = zipCoderForPos(pos);
+ int hash = zcp.checkedHash(cen, entryPos, nlen);
+ int hsh = (hash & 0x7fffffff) % tablelen;
+ int next = table[hsh];
+ table[hsh] = index;
+ // Record the CEN offset and the name hash in our hash cell.
+ entries[index++] = hash;
+ entries[index++] = next;
+ entries[index ] = pos;
+ } catch (Exception e) {
+ zerror("invalid CEN header (bad entry name)");
+ }
+ return nlen;
+ }
+
+ private int getEntryHash(int index) { return entries[index]; }
+ private int getEntryNext(int index) { return entries[index + 1]; }
+ private int getEntryPos(int index) { return entries[index + 2]; }
+ private static final int ZIP_ENDCHAIN = -1;
+ private int total; // total number of entries
+ private int[] table; // Hash chain heads: indexes into entries
+ private int tablelen; // number of hash heads
+
+ // Android-changed: isZipFilePathValidatorEnabled added as Key part. Key is used as key in
+ // files HashMap, so not including it could lead to opening ZipFile w/o entry names
+ // validation.
+ private static class Key {
+ final BasicFileAttributes attrs;
+ File file;
+ final boolean utf8;
+ // Android-added: isZipFilePathValidatorEnabled added as Key part.
+ final boolean isZipFilePathValidatorEnabled;
+
+ public Key(File file, BasicFileAttributes attrs, ZipCoder zc) {
+ this(file, attrs, zc, /* isZipFilePathValidatorEnabled= */ false);
+ }
+
+ // Android-added: added constructor with isZipFilePathValidatorEnabled argument.
+ public Key(File file, BasicFileAttributes attrs, ZipCoder zc,
+ boolean isZipFilePathValidatorEnabled) {
+ this.attrs = attrs;
+ this.file = file;
+ this.utf8 = zc.isUTF8();
+ this.isZipFilePathValidatorEnabled = isZipFilePathValidatorEnabled;
+ }
+
+ public int hashCode() {
+ long t = utf8 ? 0 : Long.MAX_VALUE;
+ t += attrs.lastModifiedTime().toMillis();
+ // Android-changed: include izZipFilePathValidatorEnabled in hash computation.
+ // return ((int)(t ^ (t >>> 32))) + file.hashCode();
+ return ((int)(t ^ (t >>> 32))) + file.hashCode()
+ + Boolean.hashCode(isZipFilePathValidatorEnabled);
+ }
+
+ public boolean equals(Object obj) {
+ if (obj instanceof Key key) {
+ if (key.utf8 != utf8) {
+ return false;
+ }
+ if (!attrs.lastModifiedTime().equals(key.attrs.lastModifiedTime())) {
+ return false;
+ }
+ // Android-added: include isZipFilePathValidatorEnabled as equality part.
+ if (key.isZipFilePathValidatorEnabled != isZipFilePathValidatorEnabled) {
+ return false;
+ }
+ Object fk = attrs.fileKey();
+ if (fk != null) {
+ return fk.equals(key.attrs.fileKey());
+ } else {
+ return file.equals(key.file);
+ }
+ }
+ return false;
+ }
+ }
+ private static final HashMap<Key, Source> files = new HashMap<>();
+
+
+ // Android-changed: pass izZipFilePathValidatorEnabled argument.
+ // static Source get(File file, boolean toDelete, ZipCoder zc) throws IOException {
+ static Source get(File file, boolean toDelete, ZipCoder zc,
+ boolean isZipPathValidatorEnabled) throws IOException {
+ final Key key;
+ try {
+ // BEGIN Android-changed: isZipFilePathValidatorEnabled passed as part of Key.
+ /*
+ key = new Key(file,
+ Files.readAttributes(file.toPath(), BasicFileAttributes.class),
+ zc);
+ */
+ key = new Key(file,
+ Files.readAttributes(file.toPath(), BasicFileAttributes.class),
+ zc, isZipPathValidatorEnabled);
+ // END Android-changed: isZipFilePathValidatorEnabled passed as part of Key.
+ } catch (InvalidPathException ipe) {
+ throw new IOException(ipe);
+ }
+ Source src;
+ synchronized (files) {
+ src = files.get(key);
+ if (src != null) {
+ src.refs++;
+ return src;
+ }
+ }
+ src = new Source(key, toDelete, zc);
+
+ synchronized (files) {
+ if (files.containsKey(key)) { // someone else put in first
+ src.close(); // close the newly created one
+ src = files.get(key);
+ src.refs++;
+ return src;
+ }
+ files.put(key, src);
+ return src;
+ }
+ }
+
+ static void release(Source src) throws IOException {
+ synchronized (files) {
+ if (src != null && --src.refs == 0) {
+ files.remove(src.key);
+ src.close();
+ }
+ }
+ }
+
+ private Source(Key key, boolean toDelete, ZipCoder zc) throws IOException {
+ this.zc = zc;
+ this.key = key;
+ if (toDelete) {
+ // BEGIN Android-changed: we are not targeting Windows, keep else branch only. Also
+ // open file with O_CLOEXEC flag set.
+ /*
+ if (isWindows) {
+ this.zfile = SharedSecrets.getJavaIORandomAccessFileAccess()
+ .openAndDelete(key.file, "r");
+ } else {
+ this.zfile = new RandomAccessFile(key.file, "r");
+ key.file.delete();
+ }
+ */
+ this.zfile = new RandomAccessFile(key.file, "r", /* setCloExecFlag= */ true);
+ key.file.delete();
+ // END Android-changed: we are not targeting Windows, keep else branch only.
+ } else {
+ // Android-changed: open with O_CLOEXEC flag set.
+ // this.zfile = new RandomAccessFile(key.file, "r");
+ this.zfile = new RandomAccessFile(key.file, "r", /* setCloExecFlag= */ true);
+ }
+ try {
+ initCEN(-1);
+ byte[] buf = new byte[4];
+ readFullyAt(buf, 0, 4, 0);
+ this.startsWithLoc = (LOCSIG(buf) == LOCSIG);
+ } catch (IOException x) {
+ try {
+ this.zfile.close();
+ } catch (IOException xx) {}
+ throw x;
+ }
+ }
+
+ private void close() throws IOException {
+ zfile.close();
+ zfile = null;
+ cen = null;
+ entries = null;
+ table = null;
+ manifestPos = -1;
+ manifestNum = 0;
+ signatureMetaNames = null;
+ metaVersions = EMPTY_META_VERSIONS;
+ }
+
+ private static final int BUF_SIZE = 8192;
+ private final int readFullyAt(byte[] buf, int off, int len, long pos)
+ throws IOException
+ {
+ synchronized (zfile) {
+ zfile.seek(pos);
+ int N = len;
+ while (N > 0) {
+ int n = Math.min(BUF_SIZE, N);
+ zfile.readFully(buf, off, n);
+ off += n;
+ N -= n;
+ }
+ return len;
+ }
+ }
+
+ private final int readAt(byte[] buf, int off, int len, long pos)
+ throws IOException
+ {
+ synchronized (zfile) {
+ zfile.seek(pos);
+ return zfile.read(buf, off, len);
+ }
+ }
+
+
+ private static class End {
+ int centot; // 4 bytes
+ long cenlen; // 4 bytes
+ long cenoff; // 4 bytes
+ long endpos; // 4 bytes
+ }
+
+ /*
+ * Searches for end of central directory (END) header. The contents of
+ * the END header will be read and placed in endbuf. Returns the file
+ * position of the END header, otherwise returns -1 if the END header
+ * was not found or an error occurred.
+ */
+ private End findEND() throws IOException {
+ long ziplen = zfile.length();
+ if (ziplen <= 0)
+ zerror("zip file is empty");
+ End end = new End();
+ byte[] buf = new byte[READBLOCKSZ];
+ long minHDR = (ziplen - END_MAXLEN) > 0 ? ziplen - END_MAXLEN : 0;
+ long minPos = minHDR - (buf.length - ENDHDR);
+ for (long pos = ziplen - buf.length; pos >= minPos; pos -= (buf.length - ENDHDR)) {
+ int off = 0;
+ if (pos < 0) {
+ // Pretend there are some NUL bytes before start of file
+ off = (int)-pos;
+ Arrays.fill(buf, 0, off, (byte)0);
+ }
+ int len = buf.length - off;
+ if (readFullyAt(buf, off, len, pos + off) != len ) {
+ zerror("zip END header not found");
+ }
+ // Now scan the block backwards for END header signature
+ for (int i = buf.length - ENDHDR; i >= 0; i--) {
+ if (buf[i+0] == (byte)'P' &&
+ buf[i+1] == (byte)'K' &&
+ buf[i+2] == (byte)'\005' &&
+ buf[i+3] == (byte)'\006') {
+ // Found ENDSIG header
+ byte[] endbuf = Arrays.copyOfRange(buf, i, i + ENDHDR);
+ end.centot = ENDTOT(endbuf);
+ end.cenlen = ENDSIZ(endbuf);
+ end.cenoff = ENDOFF(endbuf);
+ end.endpos = pos + i;
+ int comlen = ENDCOM(endbuf);
+ if (end.endpos + ENDHDR + comlen != ziplen) {
+ // ENDSIG matched, however the size of file comment in it does
+ // not match the real size. One "common" cause for this problem
+ // is some "extra" bytes are padded at the end of the zipfile.
+ // Let's do some extra verification, we don't care about the
+ // performance in this situation.
+ byte[] sbuf = new byte[4];
+ long cenpos = end.endpos - end.cenlen;
+ long locpos = cenpos - end.cenoff;
+ if (cenpos < 0 ||
+ locpos < 0 ||
+ readFullyAt(sbuf, 0, sbuf.length, cenpos) != 4 ||
+ GETSIG(sbuf) != CENSIG ||
+ readFullyAt(sbuf, 0, sbuf.length, locpos) != 4 ||
+ GETSIG(sbuf) != LOCSIG) {
+ continue;
+ }
+ }
+ if (comlen > 0) { // this zip file has comlen
+ comment = new byte[comlen];
+ if (readFullyAt(comment, 0, comlen, end.endpos + ENDHDR) != comlen) {
+ zerror("zip comment read failed");
+ }
+ }
+ // must check for a zip64 end record; it is always permitted to be present
+ try {
+ byte[] loc64 = new byte[ZIP64_LOCHDR];
+ if (end.endpos < ZIP64_LOCHDR ||
+ readFullyAt(loc64, 0, loc64.length, end.endpos - ZIP64_LOCHDR)
+ != loc64.length || GETSIG(loc64) != ZIP64_LOCSIG) {
+ return end;
+ }
+ long end64pos = ZIP64_LOCOFF(loc64);
+ byte[] end64buf = new byte[ZIP64_ENDHDR];
+ if (readFullyAt(end64buf, 0, end64buf.length, end64pos)
+ != end64buf.length || GETSIG(end64buf) != ZIP64_ENDSIG) {
+ return end;
+ }
+ // end64 candidate found,
+ long cenlen64 = ZIP64_ENDSIZ(end64buf);
+ long cenoff64 = ZIP64_ENDOFF(end64buf);
+ long centot64 = ZIP64_ENDTOT(end64buf);
+ // double-check
+ if (cenlen64 != end.cenlen && end.cenlen != ZIP64_MAGICVAL ||
+ cenoff64 != end.cenoff && end.cenoff != ZIP64_MAGICVAL ||
+ centot64 != end.centot && end.centot != ZIP64_MAGICCOUNT) {
+ return end;
+ }
+ // to use the end64 values
+ end.cenlen = cenlen64;
+ end.cenoff = cenoff64;
+ end.centot = (int)centot64; // assume total < 2g
+ end.endpos = end64pos;
+ } catch (IOException x) {} // no zip64 loc/end
+ return end;
+ }
+ }
+ }
+ throw new ZipException("zip END header not found");
+ }
+
+ // Reads zip file central directory.
+ private void initCEN(int knownTotal) throws IOException {
+ // Prefer locals for better performance during startup
+ byte[] cen;
+ if (knownTotal == -1) {
+ End end = findEND();
+ if (end.endpos == 0) {
+ locpos = 0;
+ total = 0;
+ entries = new int[0];
+ this.cen = null;
+ return; // only END header present
+ }
+ if (end.cenlen > end.endpos)
+ zerror("invalid END header (bad central directory size)");
+ long cenpos = end.endpos - end.cenlen; // position of CEN table
+ // Get position of first local file (LOC) header, taking into
+ // account that there may be a stub prefixed to the zip file.
+ locpos = cenpos - end.cenoff;
+ if (locpos < 0) {
+ zerror("invalid END header (bad central directory offset)");
+ }
+ // read in the CEN and END
+ cen = this.cen = new byte[(int)(end.cenlen + ENDHDR)];
+ if (readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) {
+ zerror("read CEN tables failed");
+ }
+ this.total = end.centot;
+ } else {
+ cen = this.cen;
+ this.total = knownTotal;
+ }
+ // hash table for entries
+ int entriesLength = this.total * 3;
+ entries = new int[entriesLength];
+
+ int tablelen = ((total/2) | 1); // Odd -> fewer collisions
+ this.tablelen = tablelen;
+
+ int[] table = new int[tablelen];
+ this.table = table;
+
+ Arrays.fill(table, ZIP_ENDCHAIN);
+
+ // list for all meta entries
+ ArrayList<Integer> signatureNames = null;
+ // Set of all version numbers seen in META-INF/versions/
+ Set<Integer> metaVersionsSet = null;
+
+ // Iterate through the entries in the central directory
+ int idx = 0; // Index into the entries array
+ int pos = 0;
+ int entryPos = CENHDR;
+ int limit = cen.length - ENDHDR;
+ manifestNum = 0;
+ // Android-added: duplicate entries are not allowed. See CVE-2013-4787 and b/8219321
+ Set<String> entriesNames = new HashSet<>();
+ while (entryPos <= limit) {
+ if (idx >= entriesLength) {
+ // This will only happen if the zip file has an incorrect
+ // ENDTOT field, which usually means it contains more than
+ // 65535 entries.
+ initCEN(countCENHeaders(cen, limit));
+ return;
+ }
+
+ // Checks the entry and adds values to entries[idx ... idx+2]
+ int nlen = checkAndAddEntry(pos, idx);
+
+ // BEGIN Android-added: duplicate entries are not allowed. See CVE-2013-4787
+ // and b/8219321.
+ // zipCoderForPos takes USE_UTF8 flag into account.
+ ZipCoder zcp = zipCoderForPos(entryPos);
+ String name = zcp.toString(cen, pos + CENHDR, nlen);
+ if (!entriesNames.add(name)) {
+ zerror("Duplicate entry name: " + name);
+ }
+ // END Android-added: duplicate entries are not allowed. See CVE-2013-4787
+ // and b/8219321
+ // BEGIN Android-added: don't allow NUL in entry names. We can handle it in Java fine,
+ // but it is of questionable utility as a valid pathname can't contain NUL.
+ for (int nameIdx = 0; nameIdx < nlen; ++nameIdx) {
+ byte b = cen[pos + CENHDR + nameIdx];
+
+ if (b == 0) {
+ zerror("Filename contains NUL byte: " + name);
+ }
+ }
+ // END Android-added: don't allow NUL in entry names.
+ // BEGIN Android-changed: validation of zip entry names.
+ if (key.isZipFilePathValidatorEnabled && !ZipPathValidator.isClear()) {
+ ZipPathValidator.getInstance().onZipEntryAccess(name);
+ }
+ // END Android-changed: validation of zip entry names.
+ idx += 3;
+
+ // Adds name to metanames.
+ if (isMetaName(cen, entryPos, nlen)) {
+ // nlen is at least META_INF_LENGTH
+ if (isManifestName(entryPos + META_INF_LEN, nlen - META_INF_LEN)) {
+ manifestPos = pos;
+ manifestNum++;
+ } else {
+ if (isSignatureRelated(entryPos, nlen)) {
+ if (signatureNames == null)
+ signatureNames = new ArrayList<>(4);
+ signatureNames.add(pos);
+ }
+
+ // If this is a versioned entry, parse the version
+ // and store it for later. This optimizes lookup
+ // performance in multi-release jar files
+ int version = getMetaVersion(entryPos + META_INF_LEN, nlen - META_INF_LEN);
+ if (version > 0) {
+ if (metaVersionsSet == null)
+ metaVersionsSet = new TreeSet<>();
+ metaVersionsSet.add(version);
+ }
+ }
+ }
+ // skip to the start of the next entry
+ pos = nextEntryPos(pos, entryPos, nlen);
+ entryPos = pos + CENHDR;
+ }
+
+ // Adjust the total entries
+ this.total = idx / 3;
+
+ if (signatureNames != null) {
+ int len = signatureNames.size();
+ signatureMetaNames = new int[len];
+ for (int j = 0; j < len; j++) {
+ signatureMetaNames[j] = signatureNames.get(j);
+ }
+ }
+ if (metaVersionsSet != null) {
+ metaVersions = new int[metaVersionsSet.size()];
+ int c = 0;
+ for (Integer version : metaVersionsSet) {
+ metaVersions[c++] = version;
+ }
+ } else {
+ metaVersions = EMPTY_META_VERSIONS;
+ }
+ if (pos + ENDHDR != cen.length) {
+ zerror("invalid CEN header (bad header size)");
+ }
+ }
+
+ private int nextEntryPos(int pos, int entryPos, int nlen) {
+ return entryPos + nlen + CENCOM(cen, pos) + CENEXT(cen, pos);
+ }
+
+ private static void zerror(String msg) throws ZipException {
+ throw new ZipException(msg);
+ }
+
+ /*
+ * Returns the {@code pos} of the zip cen entry corresponding to the
+ * specified entry name, or -1 if not found.
+ */
+ private int getEntryPos(String name, boolean addSlash) {
+ if (total == 0) {
+ return -1;
+ }
+
+ int hsh = ZipCoder.hash(name);
+ int idx = table[(hsh & 0x7fffffff) % tablelen];
+
+ // Search down the target hash chain for a entry whose
+ // 32 bit hash matches the hashed name.
+ while (idx != ZIP_ENDCHAIN) {
+ if (getEntryHash(idx) == hsh) {
+ // The CEN name must match the specfied one
+ int pos = getEntryPos(idx);
+
+ try {
+ ZipCoder zc = zipCoderForPos(pos);
+ String entry = zc.toString(cen, pos + CENHDR, CENNAM(cen, pos));
+
+ // If addSlash is true we'll test for name+/ in addition to
+ // name, unless name is the empty string or already ends with a
+ // slash
+ int entryLen = entry.length();
+ int nameLen = name.length();
+ if ((entryLen == nameLen && entry.equals(name)) ||
+ (addSlash &&
+ nameLen + 1 == entryLen &&
+ entry.startsWith(name) &&
+ entry.charAt(entryLen - 1) == '/')) {
+ return pos;
+ }
+ } catch (IllegalArgumentException iae) {
+ // Ignore
+ }
+ }
+ idx = getEntryNext(idx);
+ }
+ return -1;
+ }
+
+ private ZipCoder zipCoderForPos(int pos) {
+ if (zc.isUTF8()) {
+ return zc;
+ }
+ if ((CENFLG(cen, pos) & USE_UTF8) != 0) {
+ return ZipCoder.UTF8;
+ }
+ return zc;
+ }
+
+ /**
+ * Returns true if the bytes represent a non-directory name
+ * beginning with "META-INF/", disregarding ASCII case.
+ */
+ private static boolean isMetaName(byte[] name, int off, int len) {
+ // Use the "oldest ASCII trick in the book":
+ // ch | 0x20 == Character.toLowerCase(ch)
+ return len > META_INF_LEN // "META-INF/".length()
+ && name[off + len - 1] != '/' // non-directory
+ && (name[off++] | 0x20) == 'm'
+ && (name[off++] | 0x20) == 'e'
+ && (name[off++] | 0x20) == 't'
+ && (name[off++] | 0x20) == 'a'
+ && (name[off++] ) == '-'
+ && (name[off++] | 0x20) == 'i'
+ && (name[off++] | 0x20) == 'n'
+ && (name[off++] | 0x20) == 'f'
+ && (name[off] ) == '/';
+ }
+
+ /*
+ * Check if the bytes represents a name equals to MANIFEST.MF
+ */
+ private boolean isManifestName(int off, int len) {
+ byte[] name = cen;
+ return (len == 11 // "MANIFEST.MF".length()
+ && (name[off++] | 0x20) == 'm'
+ && (name[off++] | 0x20) == 'a'
+ && (name[off++] | 0x20) == 'n'
+ && (name[off++] | 0x20) == 'i'
+ && (name[off++] | 0x20) == 'f'
+ && (name[off++] | 0x20) == 'e'
+ && (name[off++] | 0x20) == 's'
+ && (name[off++] | 0x20) == 't'
+ && (name[off++] ) == '.'
+ && (name[off++] | 0x20) == 'm'
+ && (name[off] | 0x20) == 'f');
+ }
+
+ private boolean isSignatureRelated(int off, int len) {
+ // Only called when isMetaName(name, off, len) is true, which means
+ // len is at least META_INF_LENGTH
+ // assert isMetaName(name, off, len)
+ boolean signatureRelated = false;
+ byte[] name = cen;
+ if (name[off + len - 3] == '.') {
+ // Check if entry ends with .EC and .SF
+ int b1 = name[off + len - 2] | 0x20;
+ int b2 = name[off + len - 1] | 0x20;
+ if ((b1 == 'e' && b2 == 'c') || (b1 == 's' && b2 == 'f')) {
+ signatureRelated = true;
+ }
+ } else if (name[off + len - 4] == '.') {
+ // Check if entry ends with .DSA and .RSA
+ int b1 = name[off + len - 3] | 0x20;
+ int b2 = name[off + len - 2] | 0x20;
+ int b3 = name[off + len - 1] | 0x20;
+ if ((b1 == 'r' || b1 == 'd') && b2 == 's' && b3 == 'a') {
+ signatureRelated = true;
+ }
+ }
+ // Above logic must match SignatureFileVerifier.isBlockOrSF
+ assert(signatureRelated == SignatureFileVerifier
+ // Android-changed: use StandardCharsets.
+ // .isBlockOrSF(new String(name, off, len, UTF_8.INSTANCE)
+ .isBlockOrSF(new String(name, off, len, StandardCharsets.UTF_8)
+ .toUpperCase(Locale.ENGLISH)));
+ return signatureRelated;
+ }
+
+ /*
+ * If the bytes represents a non-directory name beginning
+ * with "versions/", continuing with a positive integer,
+ * followed by a '/', then return that integer value.
+ * Otherwise, return 0
+ */
+ private int getMetaVersion(int off, int len) {
+ byte[] name = cen;
+ int nend = off + len;
+ if (!(len > 10 // "versions//".length()
+ && name[off + len - 1] != '/' // non-directory
+ && (name[off++] | 0x20) == 'v'
+ && (name[off++] | 0x20) == 'e'
+ && (name[off++] | 0x20) == 'r'
+ && (name[off++] | 0x20) == 's'
+ && (name[off++] | 0x20) == 'i'
+ && (name[off++] | 0x20) == 'o'
+ && (name[off++] | 0x20) == 'n'
+ && (name[off++] | 0x20) == 's'
+ && (name[off++] ) == '/')) {
+ return 0;
+ }
+ int version = 0;
+ while (off < nend) {
+ final byte c = name[off++];
+ if (c == '/') {
+ return version;
+ }
+ if (c < '0' || c > '9') {
+ return 0;
+ }
+ version = version * 10 + c - '0';
+ // Check for overflow and leading zeros
+ if (version <= 0) {
+ return 0;
+ }
+ }
+ return 0;
+ }
+
+ /**
+ * Returns the number of CEN headers in a central directory.
+ * Will not throw, even if the zip file is corrupt.
+ *
+ * @param cen copy of the bytes in a zip file's central directory
+ * @param size number of bytes in central directory
+ */
+ private static int countCENHeaders(byte[] cen, int size) {
+ int count = 0;
+ for (int p = 0;
+ p + CENHDR <= size;
+ p += CENHDR + CENNAM(cen, p) + CENEXT(cen, p) + CENCOM(cen, p))
+ count++;
+ return count;
+ }
+ }
}
diff --git a/ojluni/src/main/native/Deflater.c b/ojluni/src/main/native/Deflater.c
index 9ee0326..9dfff0a 100644
--- a/ojluni/src/main/native/Deflater.c
+++ b/ojluni/src/main/native/Deflater.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -41,25 +41,6 @@
#define DEF_MEM_LEVEL 8
-static jfieldID levelID;
-static jfieldID strategyID;
-static jfieldID setParamsID;
-static jfieldID finishID;
-static jfieldID finishedID;
-static jfieldID bufID, offID, lenID;
-
-static void Deflater_initIDs(JNIEnv *env) {
- jclass cls = (*env)->FindClass(env, "java/util/zip/Deflater");
- levelID = (*env)->GetFieldID(env, cls, "level", "I");
- strategyID = (*env)->GetFieldID(env, cls, "strategy", "I");
- setParamsID = (*env)->GetFieldID(env, cls, "setParams", "Z");
- finishID = (*env)->GetFieldID(env, cls, "finish", "Z");
- finishedID = (*env)->GetFieldID(env, cls, "finished", "Z");
- bufID = (*env)->GetFieldID(env, cls, "buf", "[B");
- offID = (*env)->GetFieldID(env, cls, "off", "I");
- lenID = (*env)->GetFieldID(env, cls, "len", "I");
-}
-
JNIEXPORT jlong JNICALL
Deflater_init(JNIEnv *env, jclass cls, jint level,
jint strategy, jboolean nowrap)
@@ -98,17 +79,15 @@
}
}
-JNIEXPORT void JNICALL
-Deflater_setDictionary(JNIEnv *env, jclass cls, jlong addr,
- jarray b, jint off, jint len)
+static void throwInternalErrorHelper(JNIEnv *env, z_stream *strm, const char *fixmsg) {
+ const char *msg = NULL;
+ msg = (strm->msg != NULL) ? strm->msg : fixmsg;
+ JNU_ThrowInternalError(env, msg);
+}
+
+static void checkSetDictionaryResult(JNIEnv *env, jlong addr, jint res)
{
- Bytef *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
- int res;
- if (buf == 0) {/* out of memory */
- return;
- }
- res = deflateSetDictionary((z_stream *)jlong_to_ptr(addr), buf + off, len);
- (*env)->ReleasePrimitiveArrayCritical(env, b, buf, 0);
+ z_stream *strm = (z_stream *) jlong_to_ptr(addr);
switch (res) {
case Z_OK:
break;
@@ -116,104 +95,198 @@
JNU_ThrowIllegalArgumentException(env, 0);
break;
default:
- JNU_ThrowInternalError(env, ((z_stream *)jlong_to_ptr(addr))->msg);
+ throwInternalErrorHelper(env, strm, "unknown error in checkSetDictionaryResult");
break;
}
}
-JNIEXPORT jint JNICALL
-Deflater_deflateBytes(JNIEnv *env, jobject this, jlong addr,
- jarray b, jint off, jint len, jint flush)
+JNIEXPORT void JNICALL
+Deflater_setDictionary(JNIEnv *env, jclass cls, jlong addr,
+ jbyteArray b, jint off, jint len)
+{
+ int res;
+ Bytef *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
+ if (buf == NULL) /* out of memory */
+ return;
+ res = deflateSetDictionary(jlong_to_ptr(addr), buf + off, len);
+ (*env)->ReleasePrimitiveArrayCritical(env, b, buf, 0);
+ checkSetDictionaryResult(env, addr, res);
+}
+
+JNIEXPORT void JNICALL
+Deflater_setDictionaryBuffer(JNIEnv *env, jclass cls, jlong addr,
+ jlong bufferAddr, jint len)
+{
+ int res;
+ Bytef *buf = jlong_to_ptr(bufferAddr);
+ res = deflateSetDictionary(jlong_to_ptr(addr), buf, len);
+ checkSetDictionaryResult(env, addr, res);
+}
+
+static jint doDeflate(JNIEnv *env, jlong addr,
+ jbyte *input, jint inputLen,
+ jbyte *output, jint outputLen,
+ jint flush, jint params)
{
z_stream *strm = jlong_to_ptr(addr);
-
- jarray this_buf = (*env)->GetObjectField(env, this, bufID);
- jint this_off = (*env)->GetIntField(env, this, offID);
- jint this_len = (*env)->GetIntField(env, this, lenID);
- jbyte *in_buf;
- jbyte *out_buf;
+ int setParams = params & 1;
int res;
- if ((*env)->GetBooleanField(env, this, setParamsID)) {
- int level = (*env)->GetIntField(env, this, levelID);
- int strategy = (*env)->GetIntField(env, this, strategyID);
- in_buf = (*env)->GetPrimitiveArrayCritical(env, this_buf, 0);
- if (in_buf == NULL) {
- // Throw OOME only when length is not zero
- if (this_len != 0)
- JNU_ThrowOutOfMemoryError(env, 0);
- return 0;
- }
- out_buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
- if (out_buf == NULL) {
- (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
- if (len != 0)
- JNU_ThrowOutOfMemoryError(env, 0);
- return 0;
- }
- strm->next_in = (Bytef *) (in_buf + this_off);
- strm->next_out = (Bytef *) (out_buf + off);
- strm->avail_in = this_len;
- strm->avail_out = len;
+ strm->next_in = (Bytef *) input;
+ strm->next_out = (Bytef *) output;
+ strm->avail_in = inputLen;
+ strm->avail_out = outputLen;
+
+ if (setParams) {
+ int strategy = (params >> 1) & 3;
+ int level = params >> 3;
res = deflateParams(strm, level, strategy);
- (*env)->ReleasePrimitiveArrayCritical(env, b, out_buf, 0);
- (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
+ } else {
+ res = deflate(strm, flush);
+ }
+ return res;
+}
+static jlong checkDeflateStatus(JNIEnv *env, jlong addr,
+ jint inputLen,
+ jint outputLen,
+ jint params, int res)
+{
+ z_stream *strm = jlong_to_ptr(addr);
+ jint inputUsed = 0, outputUsed = 0;
+ int finished = 0;
+ int setParams = params & 1;
+
+ if (setParams) {
switch (res) {
case Z_OK:
- (*env)->SetBooleanField(env, this, setParamsID, JNI_FALSE);
- this_off += this_len - strm->avail_in;
- (*env)->SetIntField(env, this, offID, this_off);
- (*env)->SetIntField(env, this, lenID, strm->avail_in);
- return len - strm->avail_out;
+ setParams = 0;
+ /* fall through */
case Z_BUF_ERROR:
- (*env)->SetBooleanField(env, this, setParamsID, JNI_FALSE);
- return 0;
+ inputUsed = inputLen - strm->avail_in;
+ outputUsed = outputLen - strm->avail_out;
+ break;
default:
- JNU_ThrowInternalError(env, strm->msg);
+ throwInternalErrorHelper(env, strm, "unknown error in checkDeflateStatus, setParams case");
return 0;
}
} else {
- jboolean finish = (*env)->GetBooleanField(env, this, finishID);
- in_buf = (*env)->GetPrimitiveArrayCritical(env, this_buf, 0);
- if (in_buf == NULL) {
- if (this_len != 0)
- JNU_ThrowOutOfMemoryError(env, 0);
- return 0;
- }
- out_buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
- if (out_buf == NULL) {
- (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
- if (len != 0)
- JNU_ThrowOutOfMemoryError(env, 0);
-
- return 0;
- }
-
- strm->next_in = (Bytef *) (in_buf + this_off);
- strm->next_out = (Bytef *) (out_buf + off);
- strm->avail_in = this_len;
- strm->avail_out = len;
- res = deflate(strm, finish ? Z_FINISH : flush);
- (*env)->ReleasePrimitiveArrayCritical(env, b, out_buf, 0);
- (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
-
switch (res) {
case Z_STREAM_END:
- (*env)->SetBooleanField(env, this, finishedID, JNI_TRUE);
+ finished = 1;
/* fall through */
case Z_OK:
- this_off += this_len - strm->avail_in;
- (*env)->SetIntField(env, this, offID, this_off);
- (*env)->SetIntField(env, this, lenID, strm->avail_in);
- return len - strm->avail_out;
case Z_BUF_ERROR:
- return 0;
- default:
- JNU_ThrowInternalError(env, strm->msg);
+ inputUsed = inputLen - strm->avail_in;
+ outputUsed = outputLen - strm->avail_out;
+ break;
+ default:
+ throwInternalErrorHelper(env, strm, "unknown error in checkDeflateStatus");
return 0;
}
}
+ return ((jlong)inputUsed) | (((jlong)outputUsed) << 31) | (((jlong)finished) << 62) | (((jlong)setParams) << 63);
+}
+
+JNIEXPORT jlong JNICALL
+Deflater_deflateBytesBytes(JNIEnv *env, jobject this, jlong addr,
+ jbyteArray inputArray, jint inputOff, jint inputLen,
+ jbyteArray outputArray, jint outputOff, jint outputLen,
+ jint flush, jint params)
+{
+ jbyte *input = (*env)->GetPrimitiveArrayCritical(env, inputArray, 0);
+ jbyte *output;
+ jlong retVal;
+ jint res;
+
+ if (input == NULL) {
+ if (inputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return 0L;
+ }
+ output = (*env)->GetPrimitiveArrayCritical(env, outputArray, 0);
+ if (output == NULL) {
+ (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
+ if (outputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return 0L;
+ }
+
+ res = doDeflate(env, addr, input + inputOff, inputLen,output + outputOff,
+ outputLen, flush, params);
+
+ (*env)->ReleasePrimitiveArrayCritical(env, outputArray, output, 0);
+ (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
+
+ retVal = checkDeflateStatus(env, addr, inputLen, outputLen, params, res);
+ return retVal;
+}
+
+
+JNIEXPORT jlong JNICALL
+Deflater_deflateBytesBuffer(JNIEnv *env, jobject this, jlong addr,
+ jbyteArray inputArray, jint inputOff, jint inputLen,
+ jlong outputBuffer, jint outputLen,
+ jint flush, jint params)
+{
+ jbyte *input = (*env)->GetPrimitiveArrayCritical(env, inputArray, 0);
+ jbyte *output;
+ jlong retVal;
+ jint res;
+ if (input == NULL) {
+ if (inputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return 0L;
+ }
+ output = jlong_to_ptr(outputBuffer);
+
+ res = doDeflate(env, addr, input + inputOff, inputLen, output, outputLen,
+ flush, params);
+
+ (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
+
+ retVal = checkDeflateStatus(env, addr, inputLen, outputLen, params, res);
+ return retVal;
+}
+
+JNIEXPORT jlong JNICALL
+Deflater_deflateBufferBytes(JNIEnv *env, jobject this, jlong addr,
+ jlong inputBuffer, jint inputLen,
+ jbyteArray outputArray, jint outputOff, jint outputLen,
+ jint flush, jint params)
+{
+ jbyte *input = jlong_to_ptr(inputBuffer);
+ jbyte *output = (*env)->GetPrimitiveArrayCritical(env, outputArray, 0);
+ jlong retVal;
+ jint res;
+ if (output == NULL) {
+ if (outputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return 0L;
+ }
+
+ res = doDeflate(env, addr, input, inputLen, output + outputOff, outputLen,
+ flush, params);
+ (*env)->ReleasePrimitiveArrayCritical(env, outputArray, output, 0);
+
+ retVal = checkDeflateStatus(env, addr, inputLen, outputLen, params, res);
+ return retVal;
+}
+
+JNIEXPORT jlong JNICALL
+Deflater_deflateBufferBuffer(JNIEnv *env, jobject this, jlong addr,
+ jlong inputBuffer, jint inputLen,
+ jlong outputBuffer, jint outputLen,
+ jint flush, jint params)
+{
+ jbyte *input = jlong_to_ptr(inputBuffer);
+ jbyte *output = jlong_to_ptr(outputBuffer);
+ jlong retVal;
+ jint res;
+
+ res = doDeflate(env, addr, input, inputLen, output, outputLen, flush, params);
+ retVal = checkDeflateStatus(env, addr, inputLen, outputLen, params, res);
+ return retVal;
}
JNIEXPORT jint JNICALL
@@ -226,7 +299,7 @@
Deflater_reset(JNIEnv *env, jclass cls, jlong addr)
{
if (deflateReset((z_stream *)jlong_to_ptr(addr)) != Z_OK) {
- JNU_ThrowInternalError(env, 0);
+ JNU_ThrowInternalError(env, "deflateReset failed");
}
}
@@ -234,7 +307,7 @@
Deflater_end(JNIEnv *env, jclass cls, jlong addr)
{
if (deflateEnd((z_stream *)jlong_to_ptr(addr)) == Z_STREAM_ERROR) {
- JNU_ThrowInternalError(env, 0);
+ JNU_ThrowInternalError(env, "deflateEnd failed");
} else {
free((z_stream *)jlong_to_ptr(addr));
}
@@ -243,7 +316,11 @@
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Deflater, init, "(IIZ)J"),
NATIVE_METHOD(Deflater, setDictionary, "(J[BII)V"),
- NATIVE_METHOD(Deflater, deflateBytes, "(J[BIII)I"),
+ NATIVE_METHOD(Deflater, setDictionaryBuffer, "(JJI)V"),
+ NATIVE_METHOD(Deflater, deflateBytesBytes, "(J[BII[BIIII)J"),
+ NATIVE_METHOD(Deflater, deflateBytesBuffer, "(J[BIIJIII)J"),
+ NATIVE_METHOD(Deflater, deflateBufferBytes, "(JJI[BIIII)J"),
+ NATIVE_METHOD(Deflater, deflateBufferBuffer, "(JJIJIII)J"),
NATIVE_METHOD(Deflater, getAdler, "(J)I"),
NATIVE_METHOD(Deflater, reset, "(J)V"),
NATIVE_METHOD(Deflater, end, "(J)V"),
@@ -251,6 +328,4 @@
void register_java_util_zip_Deflater(JNIEnv* env) {
jniRegisterNativeMethods(env, "java/util/zip/Deflater", gMethods, NELEM(gMethods));
-
- Deflater_initIDs(env);
}
diff --git a/ojluni/src/main/native/Inflater.c b/ojluni/src/main/native/Inflater.c
index c4c24f0..2b664db 100644
--- a/ojluni/src/main/native/Inflater.c
+++ b/ojluni/src/main/native/Inflater.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -44,17 +44,17 @@
#define ThrowDataFormatException(env, msg) \
JNU_ThrowByName(env, "java/util/zip/DataFormatException", msg)
-static jfieldID needDictID;
-static jfieldID finishedID;
-static jfieldID bufID, offID, lenID;
+static jfieldID inputConsumedID;
+static jfieldID outputConsumedID;
-static void Inflater_initIDs(JNIEnv *env) {
+JNIEXPORT void JNICALL
+static Inflater_initIDs(JNIEnv *env)
+{
jclass cls = (*env)->FindClass(env, "java/util/zip/Inflater");
- needDictID = (*env)->GetFieldID(env, cls, "needDict", "Z");
- finishedID = (*env)->GetFieldID(env, cls, "finished", "Z");
- bufID = (*env)->GetFieldID(env, cls, "buf", "[B");
- offID = (*env)->GetFieldID(env, cls, "off", "I");
- lenID = (*env)->GetFieldID(env, cls, "len", "I");
+ inputConsumedID = (*env)->GetFieldID(env, cls, "inputConsumed", "I");
+ outputConsumedID = (*env)->GetFieldID(env, cls, "outputConsumed", "I");
+ CHECK_NULL(inputConsumedID);
+ CHECK_NULL(outputConsumedID);
}
JNIEXPORT jlong JNICALL
@@ -90,16 +90,8 @@
}
}
-JNIEXPORT void JNICALL
-Inflater_setDictionary(JNIEnv *env, jclass cls, jlong addr,
- jarray b, jint off, jint len)
+static void checkSetDictionaryResult(JNIEnv *env, jlong addr, int res)
{
- Bytef *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
- int res;
- if (buf == 0) /* out of memory */
- return;
- res = inflateSetDictionary(jlong_to_ptr(addr), buf + off, len);
- (*env)->ReleasePrimitiveArrayCritical(env, b, buf, 0);
switch (res) {
case Z_OK:
break;
@@ -113,68 +105,182 @@
}
}
-JNIEXPORT jint JNICALL
-Inflater_inflateBytes(JNIEnv *env, jobject this, jlong addr,
- jarray b, jint off, jint len)
+JNIEXPORT void JNICALL
+Inflater_setDictionary(JNIEnv *env, jclass cls, jlong addr,
+ jbyteArray b, jint off, jint len)
+{
+ jint res;
+ Bytef *buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
+ if (buf == NULL) /* out of memory */
+ return;
+ res = inflateSetDictionary(jlong_to_ptr(addr), buf + off, len);
+ (*env)->ReleasePrimitiveArrayCritical(env, b, buf, 0);
+ checkSetDictionaryResult(env, addr, res);
+}
+
+JNIEXPORT void JNICALL
+Inflater_setDictionaryBuffer(JNIEnv *env, jclass cls, jlong addr,
+ jlong bufferAddr, jint len)
+{
+ jint res;
+ Bytef *buf = jlong_to_ptr(bufferAddr);
+ res = inflateSetDictionary(jlong_to_ptr(addr), buf, len);
+ checkSetDictionaryResult(env, addr, res);
+}
+
+static jint doInflate(jlong addr,
+ jbyte *input, jint inputLen,
+ jbyte *output, jint outputLen)
+{
+ jint ret;
+ z_stream *strm = jlong_to_ptr(addr);
+
+ strm->next_in = (Bytef *) input;
+ strm->next_out = (Bytef *) output;
+ strm->avail_in = inputLen;
+ strm->avail_out = outputLen;
+
+ ret = inflate(strm, Z_PARTIAL_FLUSH);
+ return ret;
+}
+
+static jlong checkInflateStatus(JNIEnv *env, jobject this, jlong addr,
+ jint inputLen, jint outputLen, jint ret )
{
z_stream *strm = jlong_to_ptr(addr);
- jarray this_buf = (jarray)(*env)->GetObjectField(env, this, bufID);
- jint this_off = (*env)->GetIntField(env, this, offID);
- jint this_len = (*env)->GetIntField(env, this, lenID);
-
- jbyte *in_buf;
- jbyte *out_buf;
- int ret;
-
- in_buf = (*env)->GetPrimitiveArrayCritical(env, this_buf, 0);
- if (in_buf == NULL) {
- if (this_len != 0)
- JNU_ThrowOutOfMemoryError(env, 0);
- return 0;
- }
- out_buf = (*env)->GetPrimitiveArrayCritical(env, b, 0);
- if (out_buf == NULL) {
- (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
- if (len != 0)
- JNU_ThrowOutOfMemoryError(env, 0);
- return 0;
- }
- strm->next_in = (Bytef *) (in_buf + this_off);
- strm->next_out = (Bytef *) (out_buf + off);
- strm->avail_in = this_len;
- strm->avail_out = len;
- ret = inflate(strm, Z_PARTIAL_FLUSH);
- (*env)->ReleasePrimitiveArrayCritical(env, b, out_buf, 0);
- (*env)->ReleasePrimitiveArrayCritical(env, this_buf, in_buf, 0);
+ jint inputUsed = 0, outputUsed = 0;
+ int finished = 0;
+ int needDict = 0;
switch (ret) {
case Z_STREAM_END:
- (*env)->SetBooleanField(env, this, finishedID, JNI_TRUE);
+ finished = 1;
/* fall through */
case Z_OK:
- this_off += this_len - strm->avail_in;
- (*env)->SetIntField(env, this, offID, this_off);
- (*env)->SetIntField(env, this, lenID, strm->avail_in);
- return len - strm->avail_out;
+ inputUsed = inputLen - strm->avail_in;
+ outputUsed = outputLen - strm->avail_out;
+ break;
case Z_NEED_DICT:
- (*env)->SetBooleanField(env, this, needDictID, JNI_TRUE);
+ needDict = 1;
/* Might have consumed some input here! */
- this_off += this_len - strm->avail_in;
- (*env)->SetIntField(env, this, offID, this_off);
- (*env)->SetIntField(env, this, lenID, strm->avail_in);
- return 0;
+ inputUsed = inputLen - strm->avail_in;
+ /* zlib is unclear about whether output may be produced */
+ outputUsed = outputLen - strm->avail_out;
+ break;
case Z_BUF_ERROR:
- return 0;
+ break;
case Z_DATA_ERROR:
+ inputUsed = inputLen - strm->avail_in;
+ (*env)->SetIntField(env, this, inputConsumedID, inputUsed);
+ outputUsed = outputLen - strm->avail_out;
+ (*env)->SetIntField(env, this, outputConsumedID, outputUsed);
ThrowDataFormatException(env, strm->msg);
- return 0;
+ break;
case Z_MEM_ERROR:
JNU_ThrowOutOfMemoryError(env, 0);
- return 0;
+ break;
default:
JNU_ThrowInternalError(env, strm->msg);
- return 0;
+ break;
}
+ return ((jlong)inputUsed) | (((jlong)outputUsed) << 31) | (((jlong)finished) << 62) | (((jlong)needDict) << 63);
+}
+
+JNIEXPORT jlong JNICALL
+Inflater_inflateBytesBytes(JNIEnv *env, jobject this, jlong addr,
+ jbyteArray inputArray, jint inputOff, jint inputLen,
+ jbyteArray outputArray, jint outputOff, jint outputLen)
+{
+ jbyte *input = (*env)->GetPrimitiveArrayCritical(env, inputArray, 0);
+ jbyte *output;
+ jint ret;
+ jlong retVal;
+
+ if (input == NULL) {
+ if (inputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return 0L;
+ }
+ output = (*env)->GetPrimitiveArrayCritical(env, outputArray, 0);
+ if (output == NULL) {
+ (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
+ if (outputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return 0L;
+ }
+
+ ret = doInflate(addr, input + inputOff, inputLen, output + outputOff,
+ outputLen);
+
+ (*env)->ReleasePrimitiveArrayCritical(env, outputArray, output, 0);
+ (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
+
+ retVal = checkInflateStatus(env, this, addr, inputLen, outputLen, ret );
+ return retVal;
+}
+
+JNIEXPORT jlong JNICALL
+Inflater_inflateBytesBuffer(JNIEnv *env, jobject this, jlong addr,
+ jbyteArray inputArray, jint inputOff, jint inputLen,
+ jlong outputBuffer, jint outputLen)
+{
+ jbyte *input = (*env)->GetPrimitiveArrayCritical(env, inputArray, 0);
+ jbyte *output;
+ jint ret;
+ jlong retVal;
+
+ if (input == NULL) {
+ if (inputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return 0L;
+ }
+ output = jlong_to_ptr(outputBuffer);
+
+ ret = doInflate(addr, input + inputOff, inputLen, output, outputLen);
+
+ (*env)->ReleasePrimitiveArrayCritical(env, inputArray, input, 0);
+ retVal = checkInflateStatus(env, this, addr, inputLen, outputLen, ret );
+
+ return retVal;
+}
+
+JNIEXPORT jlong JNICALL
+Inflater_inflateBufferBytes(JNIEnv *env, jobject this, jlong addr,
+ jlong inputBuffer, jint inputLen,
+ jbyteArray outputArray, jint outputOff, jint outputLen)
+{
+ jbyte *input = jlong_to_ptr(inputBuffer);
+ jbyte *output = (*env)->GetPrimitiveArrayCritical(env, outputArray, 0);
+ jint ret;
+ jlong retVal;
+
+ if (output == NULL) {
+ if (outputLen != 0 && (*env)->ExceptionOccurred(env) == NULL)
+ JNU_ThrowOutOfMemoryError(env, 0);
+ return 0L;
+ }
+
+ ret = doInflate(addr, input, inputLen, output + outputOff, outputLen);
+
+ (*env)->ReleasePrimitiveArrayCritical(env, outputArray, output, 0);
+ retVal = checkInflateStatus(env, this, addr, inputLen, outputLen, ret );
+
+ return retVal;
+}
+
+JNIEXPORT jlong JNICALL
+Inflater_inflateBufferBuffer(JNIEnv *env, jobject this, jlong addr,
+ jlong inputBuffer, jint inputLen,
+ jlong outputBuffer, jint outputLen)
+{
+ jbyte *input = jlong_to_ptr(inputBuffer);
+ jbyte *output = jlong_to_ptr(outputBuffer);
+ jint ret;
+ jlong retVal;
+
+ ret = doInflate(addr, input, inputLen, output, outputLen);
+ retVal = checkInflateStatus(env, this, addr, inputLen, outputLen, ret);
+ return retVal;
}
JNIEXPORT jint JNICALL
@@ -204,7 +310,11 @@
static JNINativeMethod gMethods[] = {
NATIVE_METHOD(Inflater, init, "(Z)J"),
NATIVE_METHOD(Inflater, setDictionary, "(J[BII)V"),
- NATIVE_METHOD(Inflater, inflateBytes, "(J[BII)I"),
+ NATIVE_METHOD(Inflater, setDictionaryBuffer, "(JJI)V"),
+ NATIVE_METHOD(Inflater, inflateBytesBytes, "(J[BII[BII)J"),
+ NATIVE_METHOD(Inflater, inflateBytesBuffer, "(J[BIIJI)J"),
+ NATIVE_METHOD(Inflater, inflateBufferBytes, "(JJI[BII)J"),
+ NATIVE_METHOD(Inflater, inflateBufferBuffer, "(JJIJI)J"),
NATIVE_METHOD(Inflater, getAdler, "(J)I"),
NATIVE_METHOD(Inflater, reset, "(J)V"),
NATIVE_METHOD(Inflater, end, "(J)V"),
diff --git a/ojluni/src/main/native/ZipFile.c b/ojluni/src/main/native/ZipFile.c
index 314b6c7..fcdd41c 100644
--- a/ojluni/src/main/native/ZipFile.c
+++ b/ojluni/src/main/native/ZipFile.c
@@ -59,16 +59,6 @@
static int OPEN_READ = java_util_zip_ZipFile_OPEN_READ;
static int OPEN_DELETE = java_util_zip_ZipFile_OPEN_DELETE;
-static void ZipFile_initIDs(JNIEnv *env)
-{
- jclass cls = (*env)->FindClass(env, "java/util/zip/ZipFile");
- jzfileID = (*env)->GetFieldID(env, cls, "jzfile", "J");
- assert(jzfileID != 0);
- jzOnZipEntryAccessID = (*env)->GetMethodID(env, cls, "onZipEntryAccess", "([BI)V");
- assert(jzOnZipEntryAccessID != 0);
-}
-
-
static void
ThrowZipException(JNIEnv *env, const char *msg)
{
@@ -423,9 +413,4 @@
NATIVE_METHOD(JarFile, getMetaInfEntryNames, "()[Ljava/lang/String;"),
};
-void register_java_util_zip_ZipFile(JNIEnv* env) {
- jniRegisterNativeMethods(env, "java/util/zip/ZipFile", gMethods, NELEM(gMethods));
- ZipFile_initIDs(env);
-
- jniRegisterNativeMethods(env, "java/util/jar/JarFile", gJarFileMethods, NELEM(gJarFileMethods));
-}
+void register_java_util_zip_ZipFile(JNIEnv* env) {}
diff --git a/ojluni/src/test/java/security/cert/AKISerialNumberTest.java b/ojluni/src/test/java/security/cert/AKISerialNumberTest.java
index eff0762..1ad6787 100644
--- a/ojluni/src/test/java/security/cert/AKISerialNumberTest.java
+++ b/ojluni/src/test/java/security/cert/AKISerialNumberTest.java
@@ -109,7 +109,7 @@
private static CertificateFactory cf;
// Android-changed: Removed args & added @Test
- @Test(enabled = false)
+ @Test
public static void main() throws Exception {
cf = CertificateFactory.getInstance("X.509");
@@ -125,6 +125,8 @@
PKIXBuilderParameters params = new PKIXBuilderParameters
(Collections.singleton(anchor), sel);
params.setRevocationEnabled(false);
+ // Set date to 2024-01-01 to satisfy cert constraints
+ params.setDate(new java.util.Date(1704067200000l));
ArrayList<X509Certificate> certs = new ArrayList<>();
certs.add(intCert);