diff options
Diffstat (limited to 'luni/src')
74 files changed, 1842 insertions, 5653 deletions
diff --git a/luni/src/main/java/java/io/ObjectStreamClass.java b/luni/src/main/java/java/io/ObjectStreamClass.java index 0e3a4a1..deaa8af 100644 --- a/luni/src/main/java/java/io/ObjectStreamClass.java +++ b/luni/src/main/java/java/io/ObjectStreamClass.java @@ -73,11 +73,7 @@ public class ObjectStreamClass implements Serializable { static final Class<?>[] UNSHARED_PARAM_TYPES; - private static native void oneTimeInitialization(); - static { - oneTimeInitialization(); - CLASS_MODIFIERS_MASK = Modifier.PUBLIC | Modifier.FINAL | Modifier.INTERFACE | Modifier.ABSTRACT; FIELD_MODIFIERS_MASK = Modifier.PUBLIC | Modifier.PRIVATE diff --git a/luni/src/main/java/java/net/DatagramSocket.java b/luni/src/main/java/java/net/DatagramSocket.java index c90bcd4..2ea31cf 100644 --- a/luni/src/main/java/java/net/DatagramSocket.java +++ b/luni/src/main/java/java/net/DatagramSocket.java @@ -51,12 +51,6 @@ public class DatagramSocket { private static class Lock { } - // BEGIN android-removed: we do this statically, when we start the VM. - // static { - // Platform.getNetworkSystem().oneTimeInitialization(true); - // } - // END android-removed - private Object lock = new Lock(); /** diff --git a/luni/src/main/java/java/net/NetworkInterface.java b/luni/src/main/java/java/net/NetworkInterface.java index b3e242e..e9581f0 100644 --- a/luni/src/main/java/java/net/NetworkInterface.java +++ b/luni/src/main/java/java/net/NetworkInterface.java @@ -428,9 +428,9 @@ public final class NetworkInterface extends Object { if (addresses.isEmpty()) { return false; } - return isUpImpl(name, interfaceIndex); + return isUpImpl(name); } - private static native boolean isUpImpl(String n, int index) throws SocketException; + private static native boolean isUpImpl(String n) throws SocketException; /** * Returns true if this network interface is a loopback interface. @@ -444,9 +444,9 @@ public final class NetworkInterface extends Object { if (addresses.isEmpty()) { return false; } - return isLoopbackImpl(name, interfaceIndex); + return isLoopbackImpl(name); } - private static native boolean isLoopbackImpl(String n, int index) throws SocketException; + private static native boolean isLoopbackImpl(String n) throws SocketException; /** * Returns true if this network interface is a point-to-point interface. @@ -461,9 +461,9 @@ public final class NetworkInterface extends Object { if (addresses.isEmpty()) { return false; } - return isPointToPointImpl(name, interfaceIndex); + return isPointToPointImpl(name); } - private static native boolean isPointToPointImpl(String n, int index) throws SocketException; + private static native boolean isPointToPointImpl(String n) throws SocketException; /** * Returns true if this network interface supports multicast. @@ -476,9 +476,9 @@ public final class NetworkInterface extends Object { if (addresses.isEmpty()) { return false; } - return supportsMulticastImpl(name, interfaceIndex); + return supportsMulticastImpl(name); } - private static native boolean supportsMulticastImpl(String n, int index) throws SocketException; + private static native boolean supportsMulticastImpl(String n) throws SocketException; /** * Returns the hardware address of the interface, if it has one, and the @@ -494,9 +494,9 @@ public final class NetworkInterface extends Object { if (addresses.isEmpty()) { return new byte[0]; } - return getHardwareAddressImpl(name, interfaceIndex); + return getHardwareAddressImpl(name); } - private static native byte[] getHardwareAddressImpl(String n, int index) throws SocketException; + private static native byte[] getHardwareAddressImpl(String n) throws SocketException; /** * Returns the Maximum Transmission Unit (MTU) of this interface. @@ -510,9 +510,9 @@ public final class NetworkInterface extends Object { if (addresses.isEmpty()) { return 0; } - return getMTUImpl(name, interfaceIndex); + return getMTUImpl(name); } - private static native int getMTUImpl(String n, int index) throws SocketException; + private static native int getMTUImpl(String n) throws SocketException; /** * Returns true if this interface is a virtual interface (also called diff --git a/luni/src/main/java/java/net/ServerSocket.java b/luni/src/main/java/java/net/ServerSocket.java index ce7b84f..45dd49d 100644 --- a/luni/src/main/java/java/net/ServerSocket.java +++ b/luni/src/main/java/java/net/ServerSocket.java @@ -42,12 +42,6 @@ public class ServerSocket { private boolean isClosed; - // BEGIN android-removed: we do this statically, when we start the VM. - // static { - // Platform.getNetworkSystem().oneTimeInitialization(true); - // } - // END android-removed - /** * Constructs a new {@code ServerSocket} instance which is not bound to any * port. The default number of pending connections may be backlogged. diff --git a/luni/src/main/java/java/net/Socket.java b/luni/src/main/java/java/net/Socket.java index 208bc09..f380202 100644 --- a/luni/src/main/java/java/net/Socket.java +++ b/luni/src/main/java/java/net/Socket.java @@ -72,12 +72,6 @@ public class Socket { return logger; } - // BEGIN android-removed: we do this statically, when we start the VM. - // static { - // Platform.getNetworkSystem().oneTimeInitialization(true); - // } - // END android-removed - /** * Creates a new unconnected socket. When a SocketImplFactory is defined it * creates the internal socket implementation, otherwise the default socket diff --git a/luni/src/main/java/java/nio/channels/DatagramChannel.java b/luni/src/main/java/java/nio/channels/DatagramChannel.java index 3281cf4..fceb110 100644 --- a/luni/src/main/java/java/nio/channels/DatagramChannel.java +++ b/luni/src/main/java/java/nio/channels/DatagramChannel.java @@ -44,12 +44,6 @@ import org.apache.harmony.luni.platform.Platform; public abstract class DatagramChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel { - // BEGIN android-removed: we do this statically, when we start the VM. - // static { - // Platform.getNetworkSystem().oneTimeInitialization(true); - // } - // END android-removed - /** * Constructs a new {@code DatagramChannel}. * diff --git a/luni/src/main/java/java/nio/channels/SocketChannel.java b/luni/src/main/java/java/nio/channels/SocketChannel.java index ba03a2a..dcc9aa6 100644 --- a/luni/src/main/java/java/nio/channels/SocketChannel.java +++ b/luni/src/main/java/java/nio/channels/SocketChannel.java @@ -59,12 +59,6 @@ import org.apache.harmony.luni.platform.Platform; public abstract class SocketChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel { - // BEGIN android-removed: we do this statically, when we start the VM. - // static { - // Platform.getNetworkSystem().oneTimeInitialization(true); - // } - // END android-removed - /** * Constructs a new {@code SocketChannel}. * diff --git a/luni/src/main/java/java/text/SimpleDateFormat.java b/luni/src/main/java/java/text/SimpleDateFormat.java index 815a4dc..c910574 100644 --- a/luni/src/main/java/java/text/SimpleDateFormat.java +++ b/luni/src/main/java/java/text/SimpleDateFormat.java @@ -967,7 +967,7 @@ public class SimpleDateFormat extends DateFormat { * Returns the date which is the start of the one hundred year period for two-digit year values. */ public Date get2DigitYearStart() { - return defaultCenturyStart; + return (Date) defaultCenturyStart.clone(); } /** @@ -1332,9 +1332,9 @@ public class SimpleDateFormat extends DateFormat { * Sets the date which is the start of the one hundred year period for two-digit year values. */ public void set2DigitYearStart(Date date) { - defaultCenturyStart = date; + defaultCenturyStart = (Date) date.clone(); Calendar cal = new GregorianCalendar(); - cal.setTime(date); + cal.setTime(defaultCenturyStart); creationYear = cal.get(Calendar.YEAR); } diff --git a/luni/src/main/java/java/util/TreeMap.java b/luni/src/main/java/java/util/TreeMap.java index 64eeb38..a2362b9 100644 --- a/luni/src/main/java/java/util/TreeMap.java +++ b/luni/src/main/java/java/util/TreeMap.java @@ -255,10 +255,10 @@ public class TreeMap<K, V> extends AbstractMap<K, V> */ Node<K, V> find(K key, Relation relation) { if (root == null) { + if (comparator == NATURAL_ORDER && !(key instanceof Comparable)) { + throw new ClassCastException(key.getClass().getName()); // NullPointerException ok + } if (relation == Relation.CREATE) { - if (comparator == NATURAL_ORDER && key == null) { - throw new NullPointerException(); - } root = new Node<K, V>(null, key); size = 1; modCount++; diff --git a/luni/src/main/java/java/util/UnknownFormatConversionException.java b/luni/src/main/java/java/util/UnknownFormatConversionException.java index 8bb9441..efea9a5 100644 --- a/luni/src/main/java/java/util/UnknownFormatConversionException.java +++ b/luni/src/main/java/java/util/UnknownFormatConversionException.java @@ -36,6 +36,9 @@ public class UnknownFormatConversionException extends IllegalFormatException { * the unknown format conversion. */ public UnknownFormatConversionException(String s) { + if (s == null) { + throw new NullPointerException(); + } this.s = s; } diff --git a/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java b/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java index 1eb11e3..efb509b 100644 --- a/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java +++ b/luni/src/main/java/java/util/prefs/FilePreferencesImpl.java @@ -140,7 +140,8 @@ class FilePreferencesImpl extends AbstractPreferences { } }); if (null == names) {// file is not a directory, exception case - throw new BackingStoreException("Cannot get child names for " + toString()); + throw new BackingStoreException("Cannot get child names for " + toString() + + " (path is " + path + ")"); } return names; } diff --git a/luni/src/main/java/java/util/zip/Deflater.java b/luni/src/main/java/java/util/zip/Deflater.java index 41a337c..c0c62d9 100644 --- a/luni/src/main/java/java/util/zip/Deflater.java +++ b/luni/src/main/java/java/util/zip/Deflater.java @@ -108,17 +108,10 @@ public class Deflater { */ private static final int FINISH = 4; - // Fill in the JNI id caches - private static native void oneTimeInitialization(); - // A stub buffer used when deflate() called while inputBuffer has not been // set. private static final byte[] STUB_INPUT_BUFFER = new byte[0]; - static { - oneTimeInitialization(); - } - private int flushParm = NO_FLUSH; private boolean finished; diff --git a/luni/src/main/java/java/util/zip/Inflater.java b/luni/src/main/java/java/util/zip/Inflater.java index 4921d3d..03eed76 100644 --- a/luni/src/main/java/java/util/zip/Inflater.java +++ b/luni/src/main/java/java/util/zip/Inflater.java @@ -37,14 +37,6 @@ import java.io.FileDescriptor; // android-only * @see Deflater */ public class Inflater { - - static { - oneTimeInitialization(); - } - - // Fill in the JNI id caches - private static native void oneTimeInitialization(); - private boolean finished; // Set by the inflateImpl native int inLength; diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java b/luni/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java index b289f2c..b75b9db 100644 --- a/luni/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java +++ b/luni/src/main/java/org/apache/harmony/nio/internal/FileChannelImpl.java @@ -172,19 +172,12 @@ public abstract class FileChannelImpl extends FileChannel { lockManager.removeLock(lock); } - /* - * Flush the contents of the file to disk, and the metadata if asked. - */ - public void force(boolean metadata) throws IOException { + @Override public void force(boolean metadata) throws IOException { openCheck(); - // Forcing data-only on a read-only file is a no-op. - if (metadata) { - fileSystem.fflush(handle, metadata); - } + fileSystem.fflush(handle, metadata); } - public abstract MappedByteBuffer map(MapMode mode, long position, long size) - throws IOException; + public abstract MappedByteBuffer map(MapMode mode, long position, long size) throws IOException; protected final MappedByteBuffer mapImpl(int mapMode, long position, long size) throws IOException { diff --git a/luni/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java b/luni/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java index 359d108..f107150 100644 --- a/luni/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java +++ b/luni/src/main/java/org/apache/harmony/nio/internal/ReadOnlyFileChannel.java @@ -95,9 +95,8 @@ public final class ReadOnlyFileChannel extends FileChannelImpl { return super.mapImpl(IMemorySystem.MMAP_READ_ONLY, position, size); } - public final void force(boolean metadata) throws IOException { + @Override public final void force(boolean metadata) throws IOException { openCheck(); - return; } protected final FileLock basicLock(long position, long size, diff --git a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java index d3b4563..e649991 100644 --- a/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java +++ b/luni/src/main/java/org/apache/harmony/security/provider/cert/X509CertImpl.java @@ -54,7 +54,7 @@ import org.apache.harmony.security.x509.TBSCertificate; // BEGIN android-added import java.security.interfaces.RSAPublicKey; -import org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl; +import org.apache.harmony.xnet.provider.jsse.NativeCrypto; // END android-added /** @@ -597,7 +597,7 @@ public class X509CertImpl extends X509Certificate { } byte[] sig = certificate.getSignatureValue(); - if (!OpenSSLSocketImpl.verifySignature(tbsCertificate, sig, algorithm, rsaKey)) { + if (!NativeCrypto.verifySignature(tbsCertificate, sig, algorithm, rsaKey)) { throw new SignatureException(Messages.getString("security.15C")); //$NON-NLS-1$ } } diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java index dbc8282..6e38cf6 100644 --- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java +++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/NativeCrypto.java @@ -23,14 +23,14 @@ import java.net.Socket; import java.security.PrivateKey; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; +import java.security.interfaces.RSAPublicKey; import java.util.ArrayList; - import org.bouncycastle.openssl.PEMWriter; /** - * Provides the Java side of our JNI glue for OpenSSL. Currently only hashing - * and verifying are covered. Is expected to grow over time. Also needs to move - * into libcore/openssl at some point. + * Provides the Java side of our JNI glue for OpenSSL. Currently only + * hashing and verifying are covered. Is expected to grow over + * time. Also needs to move into libcore/openssl at some point. */ public class NativeCrypto { @@ -75,6 +75,30 @@ public class NativeCrypto { public static native int EVP_VerifyFinal(int ctx, byte[] signature, int offset, int length, int key); + // --- Legacy Signature handling ------------------------------------------- + // TODO rewrite/replace with EVP_Verify* + /** + * Verifies an RSA signature. Conceptually, this method doesn't really + * belong here, but due to its native code being closely tied to OpenSSL + * (just like the rest of this class), we put it here for the time being. + * This also solves potential problems with native library initialization. + * + * @param message The message to verify + * @param signature The signature to verify + * @param algorithm The hash/sign algorithm to use, i.e. "RSA-SHA1" + * @param key The RSA public key to use + * @return true if the verification succeeds, false otherwise + */ + public static boolean verifySignature(byte[] message, byte[] signature, String algorithm, RSAPublicKey key) { + byte[] modulus = key.getModulus().toByteArray(); + byte[] exponent = key.getPublicExponent().toByteArray(); + + return verifySignature(message, signature, algorithm, modulus, exponent) == 1; + } + + private static native int verifySignature(byte[] message, byte[] signature, + String algorithm, byte[] modulus, byte[] exponent); + // --- SSL handling -------------------------------------------------------- private static final String SUPPORTED_PROTOCOL_SSLV3 = "SSLv3"; @@ -305,6 +329,22 @@ public class NativeCrypto { public static native byte[][] SSL_get_certificate(int sslNativePointer); + /** + * Reads with the native SSL_read function from the encrypted data stream + * @return -1 if error or the end of the stream is reached. + */ + public static native int SSL_read_byte(int sslNativePointer, int timeout) throws IOException; + public static native int SSL_read(int sslNativePointer, byte[] b, int off, int len, int timeout) throws IOException; + + /** + * Writes with the native SSL_write function to the encrypted data stream. + */ + public static native void SSL_write_byte(int sslNativePointer, int b) throws IOException; + public static native void SSL_write(int sslNativePointer, byte[] b, int off, int len) throws IOException; + + public static native void SSL_interrupt(int sslNativePointer) throws IOException; + public static native void SSL_shutdown(int sslNativePointer) throws IOException; + public static native void SSL_free(int sslNativePointer); public static native byte[] SSL_SESSION_session_id(int sslSessionNativePointer); diff --git a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java index a813bf0..f643249 100644 --- a/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java +++ b/luni/src/main/java/org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl.java @@ -19,34 +19,25 @@ package org.apache.harmony.xnet.provider.jsse; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.OutputStreamWriter; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketException; -import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; -import java.security.interfaces.RSAPublicKey; import java.util.ArrayList; import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Level; import java.util.logging.Logger; - import javax.net.ssl.HandshakeCompletedEvent; import javax.net.ssl.HandshakeCompletedListener; import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSession; - import org.apache.harmony.security.provider.cert.X509CertImpl; /** * Implementation of the class OpenSSLSocketImpl - * based on OpenSSL. The JNI native interface for some methods - * of this this class are defined in the file: - * org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp + * based on OpenSSL. * * This class only supports SSLv3 and TLSv1. This should be documented elsewhere * later, for example in the package.html or a separate reference document. @@ -531,13 +522,6 @@ public class OpenSSLSocketImpl } /** - * Reads with the native SSL_read function from the encrypted data stream - * @return -1 if error or the end of the stream is reached. - */ - private native int nativeread(int sslNativePointer, int timeout) throws IOException; - private native int nativeread(int sslNativePointer, byte[] b, int off, int len, int timeout) throws IOException; - - /** * This inner class provides input data stream functionality * for the OpenSSL native implementation. It is used to * read data received via SSL protocol. @@ -560,7 +544,7 @@ public class OpenSSLSocketImpl */ public int read() throws IOException { synchronized(readLock) { - return OpenSSLSocketImpl.this.nativeread(sslNativePointer, timeout); + return NativeCrypto.SSL_read_byte(sslNativePointer, timeout); } } @@ -570,18 +554,12 @@ public class OpenSSLSocketImpl */ public int read(byte[] b, int off, int len) throws IOException { synchronized(readLock) { - return OpenSSLSocketImpl.this.nativeread(sslNativePointer, b, off, len, timeout); + return NativeCrypto.SSL_read(sslNativePointer, b, off, len, timeout); } } } /** - * Writes with the native SSL_write function to the encrypted data stream. - */ - private native void nativewrite(int sslNativePointer, int b) throws IOException; - private native void nativewrite(int sslNativePointer, byte[] b, int off, int len) throws IOException; - - /** * This inner class provides output data stream functionality * for the OpenSSL native implementation. It is used to * write data according to the encryption parameters given in SSL context. @@ -601,7 +579,7 @@ public class OpenSSLSocketImpl */ public void write(int b) throws IOException { synchronized(writeLock) { - OpenSSLSocketImpl.this.nativewrite(sslNativePointer, b); + NativeCrypto.SSL_write_byte(sslNativePointer, b); } } @@ -611,7 +589,7 @@ public class OpenSSLSocketImpl */ public void write(byte[] b, int start, int len) throws IOException { synchronized(writeLock) { - OpenSSLSocketImpl.this.nativewrite(sslNativePointer, b, start, len); + NativeCrypto.SSL_write(sslNativePointer, b, start, len); } } } @@ -870,9 +848,6 @@ public class OpenSSLSocketImpl } // END android-added - private native void nativeinterrupt(int sslNativePointer) throws IOException; - private native void nativeclose(int sslNativePointer) throws IOException; - /** * Closes the SSL socket. Once closed, a socket is not available for further * use anymore under any circumstance. A new socket must be created. @@ -903,7 +878,7 @@ public class OpenSSLSocketImpl } } - nativeinterrupt(sslNativePointer); + NativeCrypto.SSL_interrupt(sslNativePointer); synchronized (this) { synchronized (writeLock) { @@ -914,7 +889,7 @@ public class OpenSSLSocketImpl // Shut down the SSL connection, per se. try { if (handshakeStarted) { - nativeclose(sslNativePointer); + NativeCrypto.SSL_shutdown(sslNativePointer); } } catch (IOException ex) { /* @@ -975,26 +950,4 @@ public class OpenSSLSocketImpl updateInstanceCount(-1); free(); } - - /** - * Verifies an RSA signature. Conceptually, this method doesn't really - * belong here, but due to its native code being closely tied to OpenSSL - * (just like the rest of this class), we put it here for the time being. - * This also solves potential problems with native library initialization. - * - * @param message The message to verify - * @param signature The signature to verify - * @param algorithm The hash/sign algorithm to use, i.e. "RSA-SHA1" - * @param key The RSA public key to use - * @return true if the verification succeeds, false otherwise - */ - public static boolean verifySignature(byte[] message, byte[] signature, String algorithm, RSAPublicKey key) { - byte[] modulus = key.getModulus().toByteArray(); - byte[] exponent = key.getPublicExponent().toByteArray(); - - return nativeverifysignature(message, signature, algorithm, modulus, exponent) == 1; - } - - private static native int nativeverifysignature(byte[] message, byte[] signature, - String algorithm, byte[] modulus, byte[] exponent); } diff --git a/luni/src/main/native/BidiWrapper.cpp b/luni/src/main/native/BidiWrapper.cpp index 03efa92..3ec51cb 100644 --- a/luni/src/main/native/BidiWrapper.cpp +++ b/luni/src/main/native/BidiWrapper.cpp @@ -60,11 +60,11 @@ static UBiDi* uBiDi(jlong ptr) { return reinterpret_cast<BiDiData*>(static_cast<uintptr_t>(ptr))->uBiDi(); } -static jlong BidiWrapper_ubidi_open(JNIEnv* env, jclass) { +static jlong BidiWrapper_ubidi_open(JNIEnv*, jclass) { return reinterpret_cast<uintptr_t>(new BiDiData(ubidi_open())); } -static void BidiWrapper_ubidi_close(JNIEnv* env, jclass, jlong ptr) { +static void BidiWrapper_ubidi_close(JNIEnv*, jclass, jlong ptr) { delete biDiData(ptr); } @@ -97,15 +97,15 @@ static jlong BidiWrapper_ubidi_setLine(JNIEnv* env, jclass, jlong ptr, jint star return reinterpret_cast<uintptr_t>(lineData.release()); } -static jint BidiWrapper_ubidi_getDirection(JNIEnv * env, jclass clazz, jlong ptr) { +static jint BidiWrapper_ubidi_getDirection(JNIEnv*, jclass, jlong ptr) { return ubidi_getDirection(uBiDi(ptr)); } -static jint BidiWrapper_ubidi_getLength(JNIEnv* env, jclass, jlong ptr) { +static jint BidiWrapper_ubidi_getLength(JNIEnv*, jclass, jlong ptr) { return ubidi_getLength(uBiDi(ptr)); } -static jbyte BidiWrapper_ubidi_getParaLevel(JNIEnv* env, jclass, jlong ptr) { +static jbyte BidiWrapper_ubidi_getParaLevel(JNIEnv*, jclass, jlong ptr) { return ubidi_getParaLevel(uBiDi(ptr)); } diff --git a/luni/src/main/native/ICU.cpp b/luni/src/main/native/ICU.cpp index 4f08513..1945b69 100644 --- a/luni/src/main/native/ICU.cpp +++ b/luni/src/main/native/ICU.cpp @@ -358,7 +358,7 @@ static jstring getDisplayTimeZoneNative(JNIEnv* env, jclass, jstring zoneId, jbo return env->NewString(displayName.getBuffer(), displayName.length()); } -static bool getDayIntVector(JNIEnv* env, UResourceBundle* gregorian, int* values) { +static bool getDayIntVector(JNIEnv*, UResourceBundle* gregorian, int* values) { // get the First day of week and the minimal days in first week numbers UErrorCode status = U_ZERO_ERROR; ScopedResourceBundle gregorianElems(ures_getByKey(gregorian, "DateTimeElements", NULL, &status)); diff --git a/luni/src/main/native/NativeBreakIterator.cpp b/luni/src/main/native/NativeBreakIterator.cpp index 0be7630..e2db39a 100644 --- a/luni/src/main/native/NativeBreakIterator.cpp +++ b/luni/src/main/native/NativeBreakIterator.cpp @@ -34,7 +34,7 @@ static jint getIterator(JNIEnv* env, jstring locale, UBreakIteratorType type) { return reinterpret_cast<uintptr_t>(it); } -static jint getCharacterInstanceImpl(JNIEnv* env, jclass clazz, jstring locale) { +static jint getCharacterInstanceImpl(JNIEnv* env, jclass, jstring locale) { return getIterator(env, locale, UBRK_CHARACTER); } @@ -54,7 +54,7 @@ static UBreakIterator* breakIterator(jint address) { return reinterpret_cast<UBreakIterator*>(static_cast<uintptr_t>(address)); } -static void closeBreakIteratorImpl(JNIEnv* env, jclass, jint address) { +static void closeBreakIteratorImpl(JNIEnv*, jclass, jint address) { ubrk_close(breakIterator(address)); } @@ -78,7 +78,7 @@ static jboolean isBoundaryImpl(JNIEnv*, jclass, jint address, jint offset) { return ubrk_isBoundary(breakIterator(address), offset); } -static jint nextImpl(JNIEnv* env, jclass, jint address, jint n) { +static jint nextImpl(JNIEnv*, jclass, jint address, jint n) { UBreakIterator* bi = breakIterator(address); if (n < 0) { while (n++ < -1) { diff --git a/luni/src/main/native/NativeCollation.cpp b/luni/src/main/native/NativeCollation.cpp index 9a092e8..ce76786 100644 --- a/luni/src/main/native/NativeCollation.cpp +++ b/luni/src/main/native/NativeCollation.cpp @@ -26,11 +26,11 @@ static UCollationElements* toCollationElements(jint address) { return reinterpret_cast<UCollationElements*>(static_cast<uintptr_t>(address)); } -static void closeCollator(JNIEnv* env, jclass, jint address) { +static void closeCollator(JNIEnv*, jclass, jint address) { ucol_close(toCollator(address)); } -static void closeElements(JNIEnv* env, jclass, jint address) { +static void closeElements(JNIEnv*, jclass, jint address) { ucol_closeElements(toCollationElements(address)); } @@ -58,7 +58,7 @@ static jint getCollationElementIterator(JNIEnv* env, jclass, jint address, jstri return static_cast<jint>(reinterpret_cast<uintptr_t>(result)); } -static jint getMaxExpansion(JNIEnv* env, jclass, jint address, jint order) { +static jint getMaxExpansion(JNIEnv*, jclass, jint address, jint order) { return ucol_getMaxExpansion(toCollationElements(address), order); } @@ -75,7 +75,7 @@ static void setNormalization(JNIEnv* env, jclass, jint address, jint mode) { icu4jni_error(env, status); } -static jint getOffset(JNIEnv* env, jclass, jint address) { +static jint getOffset(JNIEnv*, jclass, jint address) { return ucol_getOffset(toCollationElements(address)); } @@ -139,7 +139,7 @@ static jint previous(JNIEnv* env, jclass, jint address) { return result; } -static void reset(JNIEnv* env, jclass, jint address) { +static void reset(JNIEnv*, jclass, jint address) { ucol_reset(toCollationElements(address)); } diff --git a/luni/src/main/native/NativeConverter.cpp b/luni/src/main/native/NativeConverter.cpp index 8b3952e..5ef5329 100644 --- a/luni/src/main/native/NativeConverter.cpp +++ b/luni/src/main/native/NativeConverter.cpp @@ -48,7 +48,7 @@ static jlong openConverter(JNIEnv* env, jclass, jstring converterName) { return (jlong) conv; } -static void closeConverter(JNIEnv* env, jclass, jlong handle) { +static void closeConverter(JNIEnv*, jclass, jlong handle) { UConverter* cnv = (UConverter*)(long)handle; if (cnv) { // BEGIN android-added @@ -87,7 +87,7 @@ static void closeConverter(JNIEnv* env, jclass, jlong handle) { * @param data buffer to recieve state of the current conversion * @param flush boolean that specifies end of source input */ -static jint convertCharToByte(JNIEnv *env, jclass, jlong handle, jcharArray source, jint sourceEnd, jbyteArray target, jint targetEnd, jintArray data, jboolean flush) { +static jint convertCharToByte(JNIEnv* env, jclass, jlong handle, jcharArray source, jint sourceEnd, jbyteArray target, jint targetEnd, jintArray data, jboolean flush) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; @@ -134,7 +134,7 @@ static jint convertCharToByte(JNIEnv *env, jclass, jlong handle, jcharArray sou return errorCode; } -static jint encode(JNIEnv *env, jclass, jlong handle, jcharArray source, jint sourceEnd, jbyteArray target, jint targetEnd, jintArray data, jboolean flush) { +static jint encode(JNIEnv* env, jclass, jlong handle, jcharArray source, jint sourceEnd, jbyteArray target, jint targetEnd, jintArray data, jboolean flush) { UErrorCode ec = UErrorCode(convertCharToByte(env, NULL,handle,source,sourceEnd, target,targetEnd,data,flush)); UConverter* cnv = (UConverter*)handle; @@ -171,7 +171,7 @@ static jint encode(JNIEnv *env, jclass, jlong handle, jcharArray source, jint so * @param data buffer to recieve state of the current conversion * @param flush boolean that specifies end of source input */ -static jint convertByteToChar(JNIEnv *env, jclass, jlong handle, jbyteArray source, jint sourceEnd, jcharArray target, jint targetEnd, jintArray data, jboolean flush) { +static jint convertByteToChar(JNIEnv* env, jclass, jlong handle, jbyteArray source, jint sourceEnd, jcharArray target, jint targetEnd, jintArray data, jboolean flush) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; @@ -219,7 +219,7 @@ static jint convertByteToChar(JNIEnv *env, jclass, jlong handle, jbyteArray sour return errorCode; } -static jint decode(JNIEnv *env, jclass, jlong handle, jbyteArray source, jint sourceEnd, jcharArray target, jint targetEnd, jintArray data, jboolean flush) { +static jint decode(JNIEnv* env, jclass, jlong handle, jbyteArray source, jint sourceEnd, jcharArray target, jint targetEnd, jintArray data, jboolean flush) { jint ec = convertByteToChar(env, NULL,handle,source,sourceEnd, target,targetEnd,data,flush); @@ -244,31 +244,31 @@ static jint decode(JNIEnv *env, jclass, jlong handle, jbyteArray source, jint so return ec; } -static void resetByteToChar(JNIEnv* env, jclass, jlong handle) { +static void resetByteToChar(JNIEnv*, jclass, jlong handle) { UConverter* cnv = (UConverter*)handle; if (cnv) { ucnv_resetToUnicode(cnv); } } -static void resetCharToByte(JNIEnv* env, jclass, jlong handle) { +static void resetCharToByte(JNIEnv*, jclass, jlong handle) { UConverter* cnv = (UConverter*)handle; if (cnv) { ucnv_resetFromUnicode(cnv); } } -static jint getMaxBytesPerChar(JNIEnv *env, jclass, jlong handle) { +static jint getMaxBytesPerChar(JNIEnv*, jclass, jlong handle) { UConverter* cnv = (UConverter*)handle; return (cnv != NULL) ? ucnv_getMaxCharSize(cnv) : -1; } -static jint getMinBytesPerChar(JNIEnv *env, jclass, jlong handle) { +static jint getMinBytesPerChar(JNIEnv*, jclass, jlong handle) { UConverter* cnv = (UConverter*)handle; return (cnv != NULL) ? ucnv_getMinCharSize(cnv) : -1; } -static jfloat getAveBytesPerChar(JNIEnv *env, jclass, jlong handle) { +static jfloat getAveBytesPerChar(JNIEnv*, jclass, jlong handle) { UConverter* cnv = (UConverter*)handle; if (cnv) { jfloat max = (jfloat)ucnv_getMaxCharSize(cnv); @@ -278,7 +278,7 @@ static jfloat getAveBytesPerChar(JNIEnv *env, jclass, jlong handle) { return -1; } -static jint flushByteToChar(JNIEnv *env, jclass,jlong handle, jcharArray target, jint targetEnd, jintArray data) { +static jint flushByteToChar(JNIEnv* env, jclass,jlong handle, jcharArray target, jint targetEnd, jintArray data) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; @@ -319,7 +319,7 @@ static jint flushByteToChar(JNIEnv *env, jclass,jlong handle, jcharArray target, return errorCode; } -static jint flushCharToByte (JNIEnv *env, jclass, jlong handle, jbyteArray target, jint targetEnd, jintArray data) { +static jint flushCharToByte (JNIEnv* env, jclass, jlong handle, jbyteArray target, jint targetEnd, jintArray data) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; @@ -367,7 +367,7 @@ static void toChars(const UChar* us, char* cs, int32_t length) { --length; } } -static jint setSubstitutionBytes(JNIEnv *env, jclass, jlong handle, jbyteArray subChars, jint length) { +static jint setSubstitutionBytes(JNIEnv* env, jclass, jlong handle, jbyteArray subChars, jint length) { UConverter* cnv = (UConverter*) handle; UErrorCode errorCode = U_ZERO_ERROR; if (cnv) { @@ -485,7 +485,7 @@ static void JNI_TO_U_CALLBACK_SUBSTITUTE( const void *context, UConverterToUnico return; } -static jboolean canEncode(JNIEnv *env, jclass, jlong handle, jint codeUnit) { +static jboolean canEncode(JNIEnv*, jclass, jlong handle, jint codeUnit) { UErrorCode errorCode =U_ZERO_ERROR; UConverter* cnv = (UConverter*)handle; @@ -504,10 +504,10 @@ static jboolean canEncode(JNIEnv *env, jclass, jlong handle, jint codeUnit) { sourceLimit,NULL, TRUE,&errorCode); if(U_SUCCESS(errorCode)) { - return (jboolean)TRUE; + return JNI_TRUE; } } - return (jboolean)FALSE; + return JNI_FALSE; } /* @@ -519,7 +519,7 @@ static jboolean canEncode(JNIEnv *env, jclass, jlong handle, jint codeUnit) { * the registry must be valid aliases. If a supported charset is not listed in the IANA * registry then its canonical name must begin with one of the strings "X-" or "x-". */ -static jstring getJavaCanonicalName(JNIEnv *env, const char* icuCanonicalName) { +static jstring getJavaCanonicalName(JNIEnv* env, const char* icuCanonicalName) { UErrorCode status = U_ZERO_ERROR; // Check to see if this is a well-known MIME or IANA name. @@ -556,7 +556,7 @@ static jstring getJavaCanonicalName(JNIEnv *env, const char* icuCanonicalName) { return env->NewStringUTF(&result[0]); } -static jobjectArray getAvailableCharsetNames(JNIEnv *env, jclass) { +static jobjectArray getAvailableCharsetNames(JNIEnv* env, jclass) { int32_t num = ucnv_countAvailable(); jobjectArray result = env->NewObjectArray(num, env->FindClass("java/lang/String"), NULL); for (int i = 0; i < num; ++i) { @@ -707,7 +707,7 @@ static UConverterFromUCallback getFromUCallback(int32_t mode) { } } -static jint setCallbackEncode(JNIEnv *env, jclass, jlong handle, jint onMalformedInput, jint onUnmappableInput, jbyteArray subChars, jint length) { +static jint setCallbackEncode(JNIEnv* env, jclass, jlong handle, jint onMalformedInput, jint onUnmappableInput, jbyteArray subChars, jint length) { UConverter* conv = (UConverter*)handle; UErrorCode errorCode =U_ZERO_ERROR; @@ -836,7 +836,7 @@ static void CHARSET_DECODER_CALLBACK(const void *context, } } -static jint setCallbackDecode(JNIEnv *env, jclass, jlong handle, jint onMalformedInput, jint onUnmappableInput, jcharArray subChars, jint length) { +static jint setCallbackDecode(JNIEnv* env, jclass, jlong handle, jint onMalformedInput, jint onUnmappableInput, jcharArray subChars, jint length) { UConverter* conv = (UConverter*)handle; UErrorCode errorCode =U_ZERO_ERROR; @@ -886,18 +886,18 @@ static jint setCallbackDecode(JNIEnv *env, jclass, jlong handle, jint onMalforme return U_ILLEGAL_ARGUMENT_ERROR; } -static jint getMaxCharsPerByte(JNIEnv *env, jclass, jlong handle) { +static jint getMaxCharsPerByte(JNIEnv*, jclass, jlong) { /* * currently we know that max number of chars per byte is 2 */ return 2; } -static jfloat getAveCharsPerByte(JNIEnv *env, jclass, jlong handle) { +static jfloat getAveCharsPerByte(JNIEnv* env, jclass, jlong handle) { return (1 / (jfloat) getMaxBytesPerChar(env, NULL, handle)); } -static jbyteArray getSubstitutionBytes(JNIEnv *env, jclass, jlong handle) { +static jbyteArray getSubstitutionBytes(JNIEnv* env, jclass, jlong handle) { const UConverter * cnv = (const UConverter *) handle; if (cnv) { UErrorCode status = U_ZERO_ERROR; @@ -915,7 +915,7 @@ static jbyteArray getSubstitutionBytes(JNIEnv *env, jclass, jlong handle) { return env->NewByteArray(0); } -static jboolean contains(JNIEnv* env, jclass, jlong handle1, jlong handle2) { +static jboolean contains(JNIEnv*, jclass, jlong handle1, jlong handle2) { UErrorCode status = U_ZERO_ERROR; const UConverter * cnv1 = (const UConverter *) handle1; const UConverter * cnv2 = (const UConverter *) handle2; diff --git a/luni/src/main/native/NativeDecimalFormat.cpp b/luni/src/main/native/NativeDecimalFormat.cpp index 8f39a39..606f2cc 100644 --- a/luni/src/main/native/NativeDecimalFormat.cpp +++ b/luni/src/main/native/NativeDecimalFormat.cpp @@ -77,7 +77,7 @@ static void setDecimalFormatSymbols(JNIEnv* env, jclass, jint addr, toDecimalFormat(addr)->adoptDecimalFormatSymbols(symbols); } -static jint openDecimalFormatImpl(JNIEnv* env, jclass clazz, jstring pattern0, +static jint openDecimalFormatImpl(JNIEnv* env, jclass, jstring pattern0, jstring currencySymbol, jchar decimalSeparator, jchar digit, jchar groupingSeparator, jstring infinity, jstring internationalCurrencySymbol, jchar minusSign, @@ -103,11 +103,11 @@ static jint openDecimalFormatImpl(JNIEnv* env, jclass clazz, jstring pattern0, return static_cast<jint>(reinterpret_cast<uintptr_t>(fmt)); } -static void closeDecimalFormatImpl(JNIEnv* env, jclass, jint addr) { +static void closeDecimalFormatImpl(JNIEnv*, jclass, jint addr) { delete toDecimalFormat(addr); } -static void setRoundingMode(JNIEnv* env, jclass, jint addr, jint mode, jdouble increment) { +static void setRoundingMode(JNIEnv*, jclass, jint addr, jint mode, jdouble increment) { DecimalFormat* fmt = toDecimalFormat(addr); fmt->setRoundingMode(static_cast<DecimalFormat::ERoundingMode>(mode)); fmt->setRoundingIncrement(increment); @@ -123,7 +123,7 @@ static void setSymbol(JNIEnv* env, jclass, jint addr, jint symbol, jstring s) { env->ReleaseStringChars(s, chars); } -static void setAttribute(JNIEnv *env, jclass clazz, jint addr, jint symbol, +static void setAttribute(JNIEnv*, jclass, jint addr, jint symbol, jint value) { UNumberFormat *fmt = (UNumberFormat *)(int)addr; @@ -131,7 +131,7 @@ static void setAttribute(JNIEnv *env, jclass clazz, jint addr, jint symbol, unum_setAttribute(fmt, (UNumberFormatAttribute) symbol, value); } -static jint getAttribute(JNIEnv *env, jclass clazz, jint addr, jint symbol) { +static jint getAttribute(JNIEnv*, jclass, jint addr, jint symbol) { UNumberFormat *fmt = (UNumberFormat *)(int)addr; @@ -140,7 +140,7 @@ static jint getAttribute(JNIEnv *env, jclass clazz, jint addr, jint symbol) { return res; } -static void setTextAttribute(JNIEnv *env, jclass clazz, jint addr, jint symbol, +static void setTextAttribute(JNIEnv* env, jclass, jint addr, jint symbol, jstring text) { // the errorcode returned by unum_setTextAttribute @@ -160,7 +160,7 @@ static void setTextAttribute(JNIEnv *env, jclass clazz, jint addr, jint symbol, icu4jni_error(env, status); } -static jstring getTextAttribute(JNIEnv *env, jclass clazz, jint addr, +static jstring getTextAttribute(JNIEnv* env, jclass, jint addr, jint symbol) { uint32_t resultlength, reslenneeded; @@ -198,7 +198,7 @@ static jstring getTextAttribute(JNIEnv *env, jclass clazz, jint addr, return res; } -static void applyPatternImpl(JNIEnv *env, jclass clazz, jint addr, jboolean localized, jstring pattern0) { +static void applyPatternImpl(JNIEnv* env, jclass, jint addr, jboolean localized, jstring pattern0) { if (pattern0 == NULL) { jniThrowNullPointerException(env, NULL); return; @@ -214,7 +214,7 @@ static void applyPatternImpl(JNIEnv *env, jclass clazz, jint addr, jboolean loca icu4jni_error(env, status); } -static jstring toPatternImpl(JNIEnv *env, jclass, jint addr, jboolean localized) { +static jstring toPatternImpl(JNIEnv* env, jclass, jint addr, jboolean localized) { DecimalFormat* fmt = toDecimalFormat(addr); UnicodeString pattern; if (localized) { @@ -226,9 +226,7 @@ static jstring toPatternImpl(JNIEnv *env, jclass, jint addr, jboolean localized) } template <typename T> -static jstring format(JNIEnv *env, jint addr, jobject field, jstring fieldType, jobject attributes, T val) { - UErrorCode status = U_ZERO_ERROR; - +static jstring format(JNIEnv* env, jint addr, jobject field, jstring fieldType, jobject attributes, T val) { DecimalFormat::AttributeBuffer attrBuffer; attrBuffer.buffer = NULL; DecimalFormat::AttributeBuffer* attrBufferPtr = NULL; @@ -302,7 +300,7 @@ static jstring formatDouble(JNIEnv* env, jclass, jint addr, jdouble value, return format(env, addr, field, fieldType, attributes, doubleValue); } -static jstring formatDigitList(JNIEnv *env, jclass clazz, jint addr, jstring value, +static jstring formatDigitList(JNIEnv* env, jclass, jint addr, jstring value, jobject field, jstring fieldType, jobject attributes, jint scale) { // const char * valueUTF = env->GetStringUTFChars(value, NULL); @@ -470,7 +468,7 @@ static jstring formatDigitList(JNIEnv *env, jclass clazz, jint addr, jstring val return resulting; } -static jobject parse(JNIEnv *env, jclass clazz, jint addr, jstring text, +static jobject parse(JNIEnv* env, jclass, jint addr, jstring text, jobject position) { // TODO: cache these? jclass parsePositionClass = env->FindClass("java/text/ParsePosition"); @@ -490,7 +488,6 @@ static jobject parse(JNIEnv *env, jclass clazz, jint addr, jstring text, jmethodID dblInitMethodID = env->GetMethodID(doubleClass, "<init>", "(D)V"); jmethodID bigDecimalInitMethodID = env->GetMethodID(bigDecimalClass, "<init>", "(Ljava/math/BigInteger;I)V"); jmethodID bigIntegerInitMethodID = env->GetMethodID(bigIntegerClass, "<init>", "(Ljava/lang/String;)V"); - jmethodID doubleValueMethodID = env->GetMethodID(bigDecimalClass, "doubleValue", "()D"); // make sure the ParsePosition is valid. Actually icu4c would parse a number // correctly even if the parsePosition is set to -1, but since the RI fails @@ -523,7 +520,6 @@ static jobject parse(JNIEnv *env, jclass clazz, jint addr, jstring text, } Formattable::Type numType = res.getType(); - UErrorCode fmtStatus; double resultDouble; long resultLong; @@ -579,7 +575,7 @@ static jobject parse(JNIEnv *env, jclass clazz, jint addr, jstring text, } } -static jint cloneDecimalFormatImpl(JNIEnv *env, jclass, jint addr) { +static jint cloneDecimalFormatImpl(JNIEnv*, jclass, jint addr) { DecimalFormat* fmt = toDecimalFormat(addr); return static_cast<jint>(reinterpret_cast<uintptr_t>(fmt->clone())); } diff --git a/luni/src/main/native/NativeRegEx.cpp b/luni/src/main/native/NativeRegEx.cpp index 511f1e4..513dc41 100644 --- a/luni/src/main/native/NativeRegEx.cpp +++ b/luni/src/main/native/NativeRegEx.cpp @@ -58,7 +58,7 @@ static void throwRuntimeException(JNIEnv* env, UErrorCode status) { jniThrowRuntimeException(env, u_errorName(status)); } -static void _close(JNIEnv* env, jclass clazz, RegExData* data) +static void _close(JNIEnv*, jclass, RegExData* data) { if (data->regex != NULL) { uregex_close(data->regex); @@ -81,7 +81,6 @@ static RegExData* open(JNIEnv* env, jclass clazz, jstring pattern, jint flags) UParseError error; error.offset = -1; - jchar const * patternRaw; int patternLen = env->GetStringLength(pattern); if (patternLen == 0) { data->regex = uregex_open(&EMPTY_STRING, -1, flags, &error, &status); @@ -101,7 +100,7 @@ static RegExData* open(JNIEnv* env, jclass clazz, jstring pattern, jint flags) return data; } -static RegExData* _clone(JNIEnv* env, jclass clazz, RegExData* data) +static RegExData* _clone(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; @@ -116,7 +115,7 @@ static RegExData* _clone(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static void setText(JNIEnv* env, jclass clazz, RegExData* data, jstring text) +static void setText(JNIEnv* env, jclass, RegExData* data, jstring text) { UErrorCode status = U_ZERO_ERROR; @@ -146,7 +145,7 @@ static void setText(JNIEnv* env, jclass clazz, RegExData* data, jstring text) } } -static jboolean matches(JNIEnv* env, jclass clazz, RegExData* data, +static jboolean matches(JNIEnv* env, jclass, RegExData* data, jint startIndex) { UErrorCode status = U_ZERO_ERROR; @@ -159,7 +158,7 @@ static jboolean matches(JNIEnv* env, jclass clazz, RegExData* data, return result; } -static jboolean lookingAt(JNIEnv* env, jclass clazz, RegExData* data, +static jboolean lookingAt(JNIEnv* env, jclass, RegExData* data, jint startIndex) { UErrorCode status = U_ZERO_ERROR; @@ -172,7 +171,7 @@ static jboolean lookingAt(JNIEnv* env, jclass clazz, RegExData* data, return result; } -static jboolean find(JNIEnv* env, jclass clazz, RegExData* data, +static jboolean find(JNIEnv* env, jclass, RegExData* data, jint startIndex) { UErrorCode status = U_ZERO_ERROR; @@ -185,7 +184,7 @@ static jboolean find(JNIEnv* env, jclass clazz, RegExData* data, return result; } -static jboolean findNext(JNIEnv* env, jclass clazz, RegExData* data) +static jboolean findNext(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; @@ -197,7 +196,7 @@ static jboolean findNext(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static jint groupCount(JNIEnv* env, jclass clazz, RegExData* data) +static jint groupCount(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; @@ -209,7 +208,7 @@ static jint groupCount(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static void startEnd(JNIEnv* env, jclass clazz, RegExData* data, +static void startEnd(JNIEnv* env, jclass, RegExData* data, jintArray offsets) { UErrorCode status = U_ZERO_ERROR; @@ -229,7 +228,7 @@ static void startEnd(JNIEnv* env, jclass clazz, RegExData* data, } } -static void setRegion(JNIEnv* env, jclass clazz, RegExData* data, jint start, +static void setRegion(JNIEnv* env, jclass, RegExData* data, jint start, jint end) { UErrorCode status = U_ZERO_ERROR; @@ -239,7 +238,7 @@ static void setRegion(JNIEnv* env, jclass clazz, RegExData* data, jint start, } } -static jint regionStart(JNIEnv* env, jclass clazz, RegExData* data) +static jint regionStart(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; int result = uregex_regionStart(data->regex, &status); @@ -249,7 +248,7 @@ static jint regionStart(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static jint regionEnd(JNIEnv* env, jclass clazz, RegExData* data) +static jint regionEnd(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; int result = uregex_regionEnd(data->regex, &status); @@ -259,7 +258,7 @@ static jint regionEnd(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static void useTransparentBounds(JNIEnv* env, jclass clazz, RegExData* data, +static void useTransparentBounds(JNIEnv* env, jclass, RegExData* data, jboolean value) { UErrorCode status = U_ZERO_ERROR; @@ -269,7 +268,7 @@ static void useTransparentBounds(JNIEnv* env, jclass clazz, RegExData* data, } } -static jboolean hasTransparentBounds(JNIEnv* env, jclass clazz, RegExData* data) +static jboolean hasTransparentBounds(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; jboolean result = uregex_hasTransparentBounds(data->regex, &status); @@ -279,7 +278,7 @@ static jboolean hasTransparentBounds(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static void useAnchoringBounds(JNIEnv* env, jclass clazz, RegExData* data, +static void useAnchoringBounds(JNIEnv* env, jclass, RegExData* data, jboolean value) { UErrorCode status = U_ZERO_ERROR; @@ -289,7 +288,7 @@ static void useAnchoringBounds(JNIEnv* env, jclass clazz, RegExData* data, } } -static jboolean hasAnchoringBounds(JNIEnv* env, jclass clazz, RegExData* data) +static jboolean hasAnchoringBounds(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; jboolean result = uregex_hasAnchoringBounds(data->regex, &status); @@ -299,7 +298,7 @@ static jboolean hasAnchoringBounds(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static jboolean hitEnd(JNIEnv* env, jclass clazz, RegExData* data) +static jboolean hitEnd(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; jboolean result = uregex_hitEnd(data->regex, &status); @@ -309,7 +308,7 @@ static jboolean hitEnd(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static jboolean requireEnd(JNIEnv* env, jclass clazz, RegExData* data) +static jboolean requireEnd(JNIEnv* env, jclass, RegExData* data) { UErrorCode status = U_ZERO_ERROR; jboolean result = uregex_requireEnd(data->regex, &status); @@ -319,7 +318,7 @@ static jboolean requireEnd(JNIEnv* env, jclass clazz, RegExData* data) return result; } -static void reset(JNIEnv* env, jclass clazz, RegExData* data, jint position) +static void reset(JNIEnv* env, jclass, RegExData* data, jint position) { UErrorCode status = U_ZERO_ERROR; uregex_reset(data->regex, position, &status); diff --git a/luni/src/main/native/Register.cpp b/luni/src/main/native/Register.cpp index 8980cc5..ee996c3 100644 --- a/luni/src/main/native/Register.cpp +++ b/luni/src/main/native/Register.cpp @@ -32,31 +32,31 @@ extern int register_com_ibm_icu4jni_util_Resources(JNIEnv* env); extern int register_java_io_Console(JNIEnv* env); extern int register_java_io_File(JNIEnv* env); extern "C" int register_java_io_FileDescriptor(JNIEnv* env); -extern "C" int register_java_io_ObjectInputStream(JNIEnv* env); -extern "C" int register_java_io_ObjectOutputStream(JNIEnv* env); -extern "C" int register_java_io_ObjectStreamClass(JNIEnv* env); -extern "C" int register_java_lang_Double(JNIEnv* env); -extern "C" int register_java_lang_Float(JNIEnv* env); -extern "C" int register_java_lang_Math(JNIEnv* env); +extern int register_java_io_ObjectInputStream(JNIEnv* env); +extern int register_java_io_ObjectOutputStream(JNIEnv* env); +extern int register_java_io_ObjectStreamClass(JNIEnv* env); +extern int register_java_lang_Double(JNIEnv* env); +extern int register_java_lang_Float(JNIEnv* env); +extern int register_java_lang_Math(JNIEnv* env); extern int register_java_lang_ProcessManager(JNIEnv* env); -extern "C" int register_java_lang_StrictMath(JNIEnv* env); +extern int register_java_lang_StrictMath(JNIEnv* env); extern int register_java_lang_System(JNIEnv* env); extern int register_java_net_InetAddress(JNIEnv* env); extern int register_java_net_NetworkInterface(JNIEnv* env); -extern "C" int register_java_util_zip_Adler32(JNIEnv* env); -extern "C" int register_java_util_zip_CRC32(JNIEnv* env); -extern "C" int register_java_util_zip_Deflater(JNIEnv* env); -extern "C" int register_java_util_zip_Inflater(JNIEnv* env); -extern "C" int register_org_apache_harmony_dalvik_NativeTestTarget(JNIEnv* env); +extern int register_java_util_zip_Adler32(JNIEnv* env); +extern int register_java_util_zip_CRC32(JNIEnv* env); +extern int register_java_util_zip_Deflater(JNIEnv* env); +extern int register_java_util_zip_Inflater(JNIEnv* env); +extern int register_org_apache_harmony_dalvik_NativeTestTarget(JNIEnv* env); extern int register_org_apache_harmony_luni_platform_OSFileSystem(JNIEnv* env); extern int register_org_apache_harmony_luni_platform_OSMemory(JNIEnv* env); extern int register_org_apache_harmony_luni_platform_OSNetworkSystem(JNIEnv* env); -extern "C" int register_org_apache_harmony_luni_util_NumberConvert(JNIEnv* env); -extern "C" int register_org_apache_harmony_luni_util_fltparse(JNIEnv* env); +extern int register_org_apache_harmony_luni_util_NumberConvert(JNIEnv* env); +extern int register_org_apache_harmony_luni_util_fltparse(JNIEnv* env); extern int register_org_apache_harmony_text_BidiWrapper(JNIEnv* env); extern int register_org_apache_harmony_xml_ExpatParser(JNIEnv* env); extern int register_org_apache_harmony_xnet_provider_jsse_NativeCrypto(JNIEnv* env); -extern "C" int register_org_openssl_NativeBN(JNIEnv* env); +extern int register_org_openssl_NativeBN(JNIEnv* env); // DalvikVM calls this on startup, so we can statically register all our native methods. extern "C" int registerCoreLibrariesJni(JNIEnv* env) { diff --git a/luni/src/main/native/ScopedJavaUnicodeString.h b/luni/src/main/native/ScopedJavaUnicodeString.h deleted file mode 100644 index b108a6b..0000000 --- a/luni/src/main/native/ScopedJavaUnicodeString.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2010 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef SCOPED_JAVA_UNICODE_STRING_H_included -#define SCOPED_JAVA_UNICODE_STRING_H_included - -#include "JNIHelp.h" -#include "unicode/unistr.h" - -// A smart pointer that provides access to an ICU UnicodeString given a JNI -// jstring. We give ICU a direct pointer to the characters on the Java heap. -// It's clever enough to copy-on-write if necessary. -class ScopedJavaUnicodeString { -public: - ScopedJavaUnicodeString(JNIEnv* env, jstring s) : mEnv(env), mString(s) { - mChars = env->GetStringChars(mString, NULL); - const int32_t charCount = env->GetStringLength(mString); - mUnicodeString.setTo(false, mChars, charCount); - } - - ~ScopedJavaUnicodeString() { - mEnv->ReleaseStringChars(mString, mChars); - } - - const UnicodeString& unicodeString() const { - return mUnicodeString; - } - - UnicodeString& unicodeString() { - return mUnicodeString; - } - -private: - JNIEnv* mEnv; - jstring mString; - const UChar* mChars; - UnicodeString mUnicodeString; - - // Disallow copy and assignment. - ScopedJavaUnicodeString(const ScopedJavaUnicodeString&); - void operator=(const ScopedJavaUnicodeString&); -}; - -#endif // SCOPED_JAVA_UNICODE_STRING_H_included diff --git a/luni/src/main/native/UCharacter.cpp b/luni/src/main/native/UCharacter.cpp index abad16a..136f58c 100644 --- a/luni/src/main/native/UCharacter.cpp +++ b/luni/src/main/native/UCharacter.cpp @@ -81,7 +81,7 @@ static jboolean isDigitImpl(JNIEnv*, jclass, jint codePoint) { } static jboolean isIdentifierIgnorableImpl(JNIEnv*, jclass, jint codePoint) { - // Java also returns TRUE for U+0085 Next Line (it omits U+0085 from whitespace ISO controls) + // Java also returns true for U+0085 Next Line (it omits U+0085 from whitespace ISO controls). if(codePoint == 0x0085) { return JNI_TRUE; } diff --git a/luni/src/main/native/cbigint.c b/luni/src/main/native/cbigint.cpp index 92b2992..92b2992 100644 --- a/luni/src/main/native/cbigint.c +++ b/luni/src/main/native/cbigint.cpp diff --git a/luni/src/main/native/cbigint.h b/luni/src/main/native/cbigint.h index 220aba8..b149053 100644 --- a/luni/src/main/native/cbigint.h +++ b/luni/src/main/native/cbigint.h @@ -17,8 +17,11 @@ #if !defined(cbigint_h) #define cbigint_h + +#include "hycomp.h" #include "fltconst.h" #include "JNIHelp.h" + #define LOW_U32_FROM_VAR(u64) LOW_U32_FROM_LONG64(u64) #define LOW_U32_FROM_PTR(u64ptr) LOW_U32_FROM_LONG64_PTR(u64ptr) #define HIGH_U32_FROM_VAR(u64) HIGH_U32_FROM_LONG64(u64) diff --git a/luni/src/main/native/commonDblParce.c b/luni/src/main/native/commonDblParce.cpp index 5d85645..a07690e 100644 --- a/luni/src/main/native/commonDblParce.c +++ b/luni/src/main/native/commonDblParce.cpp @@ -15,6 +15,7 @@ * limitations under the License. */ #include <stdlib.h> +#include <string.h> #include <math.h> #include "commonDblParce.h" @@ -135,10 +136,8 @@ static const jdouble tens[] = { /* *********************************************************** */ /* ************** private function declarations ************** */ -static U_64 dblparse_shiftRight64 (U_64 * lp, volatile int mbe); - -static jdouble createDouble1 (JNIEnv * env, U_64 * f, IDATA length, jint e); -static jdouble doubleAlgorithm (JNIEnv * env, U_64 * f, IDATA length, jint e, +static jdouble createDouble1 (JNIEnv* env, U_64 * f, IDATA length, jint e); +static jdouble doubleAlgorithm (JNIEnv* env, U_64 * f, IDATA length, jint e, jdouble z); /* *********************************************************** */ @@ -148,7 +147,7 @@ static jdouble doubleAlgorithm (JNIEnv * env, U_64 * f, IDATA length, jint e, #define sizeOfTenToTheE(e) (((e) / 19) + 1) jdouble -createDouble (JNIEnv * env, const char *s, jint e) +createDouble (JNIEnv* env, const char *s, jint e) { /* assumes s is a null terminated string with at least one * character in it */ @@ -253,7 +252,7 @@ createDouble (JNIEnv * env, const char *s, jint e) } jdouble -createDouble1 (JNIEnv * env, U_64 * f, IDATA length, jint e) +createDouble1 (JNIEnv* env, U_64 * f, IDATA length, jint e) { IDATA numBits; jdouble result; @@ -320,84 +319,6 @@ createDouble1 (JNIEnv * env, U_64 * f, IDATA length, jint e) return doubleAlgorithm (env, f, length, e, result); } -static U_64 -dblparse_shiftRight64 (U_64 * lp, volatile int mbe) -{ - U_64 b1Value = 0; - U_32 hi = HIGH_U32_FROM_LONG64_PTR (lp); - U_32 lo = LOW_U32_FROM_LONG64_PTR (lp); - int srAmt; - - if (mbe == 0) - return 0; - if (mbe >= 128) - { - HIGH_U32_FROM_LONG64_PTR (lp) = 0; - LOW_U32_FROM_LONG64_PTR (lp) = 0; - return 0; - } - - /* Certain platforms do not handle de-referencing a 64-bit value - * from a pointer on the stack correctly (e.g. MVL-hh/XScale) - * because the pointer may not be properly aligned, so we'll have - * to handle two 32-bit chunks. */ - if (mbe < 32) - { - LOW_U32_FROM_LONG64 (b1Value) = 0; - HIGH_U32_FROM_LONG64 (b1Value) = lo << (32 - mbe); - LOW_U32_FROM_LONG64_PTR (lp) = (hi << (32 - mbe)) | (lo >> mbe); - HIGH_U32_FROM_LONG64_PTR (lp) = hi >> mbe; - } - else if (mbe == 32) - { - LOW_U32_FROM_LONG64 (b1Value) = 0; - HIGH_U32_FROM_LONG64 (b1Value) = lo; - LOW_U32_FROM_LONG64_PTR (lp) = hi; - HIGH_U32_FROM_LONG64_PTR (lp) = 0; - } - else if (mbe < 64) - { - srAmt = mbe - 32; - LOW_U32_FROM_LONG64 (b1Value) = lo << (32 - srAmt); - HIGH_U32_FROM_LONG64 (b1Value) = (hi << (32 - srAmt)) | (lo >> srAmt); - LOW_U32_FROM_LONG64_PTR (lp) = hi >> srAmt; - HIGH_U32_FROM_LONG64_PTR (lp) = 0; - } - else if (mbe == 64) - { - LOW_U32_FROM_LONG64 (b1Value) = lo; - HIGH_U32_FROM_LONG64 (b1Value) = hi; - LOW_U32_FROM_LONG64_PTR (lp) = 0; - HIGH_U32_FROM_LONG64_PTR (lp) = 0; - } - else if (mbe < 96) - { - srAmt = mbe - 64; - b1Value = *lp; - HIGH_U32_FROM_LONG64_PTR (lp) = 0; - LOW_U32_FROM_LONG64_PTR (lp) = 0; - LOW_U32_FROM_LONG64 (b1Value) >>= srAmt; - LOW_U32_FROM_LONG64 (b1Value) |= (hi << (32 - srAmt)); - HIGH_U32_FROM_LONG64 (b1Value) >>= srAmt; - } - else if (mbe == 96) - { - LOW_U32_FROM_LONG64 (b1Value) = hi; - HIGH_U32_FROM_LONG64 (b1Value) = 0; - HIGH_U32_FROM_LONG64_PTR (lp) = 0; - LOW_U32_FROM_LONG64_PTR (lp) = 0; - } - else - { - LOW_U32_FROM_LONG64 (b1Value) = hi >> (mbe - 96); - HIGH_U32_FROM_LONG64 (b1Value) = 0; - HIGH_U32_FROM_LONG64_PTR (lp) = 0; - LOW_U32_FROM_LONG64_PTR (lp) = 0; - } - - return b1Value; -} - #if defined(WIN32) /* disable global optimizations on the microsoft compiler for the * doubleAlgorithm function otherwise it won't compile */ @@ -423,7 +344,7 @@ dblparse_shiftRight64 (U_64 * lp, volatile int mbe) * then return the original approximation. */ static jdouble -doubleAlgorithm (JNIEnv * env, U_64 * f, IDATA length, jint e, jdouble z) +doubleAlgorithm (JNIEnv*, U_64 * f, IDATA length, jint e, jdouble z) { U_64 m; IDATA k, comparison, comparison2; diff --git a/luni/src/main/native/fltconst.h b/luni/src/main/native/fltconst.h index 940d5fc..d96c5bb 100644 --- a/luni/src/main/native/fltconst.h +++ b/luni/src/main/native/fltconst.h @@ -31,9 +31,9 @@ positive == sign bit clear negative == sign bit set */ -#define MAX_U32_DOUBLE (ESDOUBLE) (4294967296.0) /* 2^32 */ -#define MAX_U32_SINGLE (ESSINGLE) (4294967296.0) /* 2^32 */ -#define HY_POS_PI (ESDOUBLE) (3.141592653589793) +#define MAX_U32_DOUBLE (double) (4294967296.0) /* 2^32 */ +#define MAX_U32_SINGLE (float) (4294967296.0) /* 2^32 */ +#define HY_POS_PI (double) (3.141592653589793) #ifdef HY_LITTLE_ENDIAN #ifdef HY_PLATFORM_DOUBLE_ORDER diff --git a/luni/src/main/native/hy2sie.h b/luni/src/main/native/hy2sie.h deleted file mode 100644 index d40d0e8..0000000 --- a/luni/src/main/native/hy2sie.h +++ /dev/null @@ -1,114 +0,0 @@ -#if !defined(hy2sie_h) -#define hy2sie_h - - -#include "JNIHelp.h" -#include "jni.h" -#include "sieb.h" - - -typedef int BOOLEAN; -#define TRUE 1 -#define FALSE 0 - - -// mc: Stuff adopted from hyport.h: - -/** HyMaxPath was chosen from unix MAXPATHLEN. Override in platform - * specific hyfile implementations if needed. - */ -#define HyMaxPath 1024 - - - -// Following definitions from hycomp.h: - -/** - * Define common types: - * <ul> - * <li><code>U_32 / I_32</code> - unsigned/signed 32 bits</li> - * <li><code>U_16 / I_16</code> - unsigned/signed 16 bits</li> - * <li><code>U_8 / I_8</code> - unsigned/signed 8 bits (bytes -- not to be - * confused with char)</li> - * </ul> - */ - -typedef int I_32; -typedef short I_16; -typedef signed char I_8; /* chars can be unsigned */ -typedef unsigned int U_32; -typedef unsigned short U_16; -typedef unsigned char U_8; - -typedef long long I_64; -typedef unsigned long long U_64; - -/** - * Define platform specific types: - * <ul> - * <li><code>UDATA</code> - unsigned data, can be used as an integer or - * pointer storage</li> - * <li><code>IDATA</code> - signed data, can be used as an integer or - * pointer storage</li> - * </ul> - */ -/* FIXME: POINTER64 */ - -typedef I_32 IDATA; -typedef U_32 UDATA; - - -// Further required definitions from Harmony: - -#define HYCONST64(x) x##L - - -#define HY_CFUNC -#define HY_CDATA -#define PROTOTYPE(x) x -#define VMCALL -#define PVMCALL * -#define NORETURN - -#define GLOBAL_DATA(symbol) ((void*)&(symbol)) - - -// Following definitions substitute the HyPortLibrary simply with the JNIEnv - -typedef JNIEnv HyPortLibrary; - -#define PORT_ACCESS_FROM_ENV(env) HyPortLibrary *privatePortLibrary = env -#define PORT_ACCESS_FROM_PORT(portLibrary) HyPortLibrary *privatePortLibrary = portLibrary -#define PORTLIB privatePortLibrary - - -// Following defintion is used to avoide quite a few signedness warnings: -#define mcSignednessBull void * - - -// Following the substitution of hyfile: - -#include <fcntl.h> - -#define HyOpenRead O_RDONLY -#define hyfile_open(a, b, c) open(a, b, c) - -#define HySeekEnd SEEK_END -#define HySeekSet SEEK_SET -#define HySeekCur SEEK_CUR -#define hyfile_seek(a, b, c) lseek(a, b, c) - -#define hyfile_read(a, b, c) read(a, b, c) - -#define hyfile_close(a) close(a) - - -// And further substitutions: - -#define hymem_allocate_memory(byteCount) sieb_malloc(privatePortLibrary, byteCount) -#define hymem_free_memory(pointer) sieb_free(privatePortLibrary, pointer) - -#define ioh_convertToPlatform(path) sieb_convertToPlatform (path) - - -#endif /* hy2sie_h */ diff --git a/luni/src/main/native/hycomp.h b/luni/src/main/native/hycomp.h index cd8ce73..9670f8f 100644 --- a/luni/src/main/native/hycomp.h +++ b/luni/src/main/native/hycomp.h @@ -23,43 +23,10 @@ #endif /** - * USE_PROTOTYPES: Use full ANSI prototypes. - * - * CLOCK_PRIMS: We want the timer/clock prims to be used - * * LITTLE_ENDIAN: This is for the intel machines or other * little endian processors. Defaults to big endian. * - * NO_LVALUE_CASTING: This is for compilers that don't like the left side - * of assigns to be cast. It hacks around to do the - * right thing. - * * ATOMIC_FLOAT_ACCESS: So that float operations will work. - * - * LINKED_USER_PRIMITIVES: Indicates that user primitives are statically linked - * with the VM executeable. - * - * OLD_SPACE_SIZE_DIFF: The 68k uses a different amount of old space. - * This "legitimizes" the change. - * - * SIMPLE_SIGNAL: For machines that don't use real signals in C. - * (eg: PC, 68k) - * - * OS_NAME_LOOKUP: Use nlist to lookup user primitive addresses. - * - * VMCALL: Tag for all functions called by the VM. - * - * VMAPICALL: Tag for all functions called via the PlatformFunction - * callWith: mechanism. - * - * SYS_FLOAT: For some math functions where extended types (80 or 96 bits) are returned - * Most platforms return as a double - * - * FLOAT_EXTENDED: If defined, the type name for extended precision floats. - * - * PLATFORM_IS_ASCII: Must be defined if the platform is ASCII - * - * EXE_EXTENSION_CHAR: the executable has a delimiter that we want to stop at as part of argv[0]. */ /** @@ -72,18 +39,11 @@ * Define common types: * <ul> * <li><code>U_32 / I_32</code> - unsigned/signed 32 bits</li> - * <li><code>U_16 / I_16</code> - unsigned/signed 16 bits</li> - * <li><code>U_8 / I_8</code> - unsigned/signed 8 bits (bytes -- not to be - * confused with char)</li> * </ul> */ typedef int I_32; -typedef short I_16; -typedef signed char I_8; /* chars can be unsigned */ typedef unsigned int U_32; -typedef unsigned short U_16; -typedef unsigned char U_8; /** * Define platform specific types: @@ -96,357 +56,25 @@ typedef unsigned char U_8; #define DATA_TYPES_DEFINED -/* NOTE: Linux supports different processors -- do not assume 386 */ - #if defined(HYX86_64) || defined(HYIA64) || defined(HYPPC64) || defined(HYS390X) - - typedef unsigned long int U_64; /* 64bits */ - typedef long int I_64; - #define TOC_UNWRAP_ADDRESS(wrappedPointer) ((void *) (wrappedPointer)[0]) - #define TOC_STORE_TOC(dest,wrappedPointer) (dest = ((UDATA*)wrappedPointer)[1]) - - #define HY_WORD64 - - #else - typedef unsigned long long U_64; typedef long long I_64; - #endif - - #if defined(HYS390X) || defined(HYS390) || defined(HYPPC64) || defined(HYPPC32) - #define HY_BIG_ENDIAN - #else - #define HY_LITTLE_ENDIAN - #endif - - #if defined(HYPPC32) - #define VA_PTR(valist) (&valist[0]) - #endif - - typedef double SYS_FLOAT; - #define HYCONST64(x) x##LL - #define NO_LVALUE_CASTING - #define FLOAT_EXTENDED long double - #define PLATFORM_IS_ASCII - #define PLATFORM_LINE_DELIMITER "\012" - #define DIR_SEPARATOR '/' - #define DIR_SEPARATOR_STR "/" - -/** - * No priorities on Linux - */ - - #define HY_PRIORITY_MAP {0,0,0,0,0,0,0,0,0,0,0,0} - - typedef U_32 BOOLEAN; - -#endif - -/* Win32 - Windows 3.1 & NT using Win32 */ -#if defined(WIN32) - - #define HY_LITTLE_ENDIAN - -/* Define 64-bit integers for Windows */ - typedef __int64 I_64; - typedef unsigned __int64 U_64; - - typedef double SYS_FLOAT; - #define NO_LVALUE_CASTING - #define VMAPICALL _stdcall - #define VMCALL _cdecl - #define EXE_EXTENSION_CHAR '.' - - #define DIR_SEPARATOR '\\' - #define DIR_SEPARATOR_STR "\\" - -/* Modifications for the Alpha running WIN-NT */ - #if defined(_ALPHA_) - #undef small /* defined as char in rpcndr.h */ - typedef double FLOAT_EXTENDED; - #endif - - #define HY_PRIORITY_MAP { \ - THREAD_PRIORITY_IDLE, /* 0 */\ - THREAD_PRIORITY_LOWEST, /* 1 */\ - THREAD_PRIORITY_BELOW_NORMAL, /* 2 */\ - THREAD_PRIORITY_BELOW_NORMAL, /* 3 */\ - THREAD_PRIORITY_BELOW_NORMAL, /* 4 */\ - THREAD_PRIORITY_NORMAL, /* 5 */\ - THREAD_PRIORITY_ABOVE_NORMAL, /* 6 */\ - THREAD_PRIORITY_ABOVE_NORMAL, /* 7 */\ - THREAD_PRIORITY_ABOVE_NORMAL, /* 8 */\ - THREAD_PRIORITY_ABOVE_NORMAL, /* 9 */\ - THREAD_PRIORITY_HIGHEST, /*10 */\ - THREAD_PRIORITY_TIME_CRITICAL /*11 */} - -#endif /* defined(WIN32) */ - -#if !defined(VMCALL) - #define VMCALL - #define VMAPICALL #endif -#define PVMCALL VMCALL * - -#define GLOBAL_DATA(symbol) ((void*)&(symbol)) -#define GLOBAL_TABLE(symbol) GLOBAL_DATA(symbol) - -/** - * Define platform specific types: - * <ul> - * <li><code>UDATA</code> - unsigned data, can be used as an integer or - * pointer storage</li> - * <li><code>IDATA</code> - signed data, can be used as an integer or - * pointer storage</li> - * </ul> - */ -/* FIXME: POINTER64 */ -#if defined(HYX86_64) || defined(HYIA64) || defined(HYPPC64) || defined(HYS390X) || defined(POINTER64) - -typedef I_64 IDATA; -typedef U_64 UDATA; - -#else /* this is default for non-64bit systems */ typedef I_32 IDATA; typedef U_32 UDATA; -#endif /* defined(HYX86_64) */ - #if !defined(DATA_TYPES_DEFINED) /* no generic U_64 or I_64 */ -/* don't typedef BOOLEAN since it's already def'ed on Win32 */ -#define BOOLEAN UDATA - #ifndef HY_BIG_ENDIAN #define HY_LITTLE_ENDIAN #endif #endif -#if !defined(HYCONST64) -#define HYCONST64(x) x##L -#endif - -#if !defined(HY_DEFAULT_SCHED) - -/** - * By default, pthreads platforms use the <code>SCHED_OTHER</code> thread - * scheduling policy. - */ - -#define HY_DEFAULT_SCHED SCHED_OTHER -#endif - -#if !defined(HY_PRIORITY_MAP) - -/** - * If no priority map if provided, priorities will be determined - * algorithmically. - */ - -#endif - -#if !defined(FALSE) -#define FALSE ((BOOLEAN) 0) -#if !defined(TRUE) -#define TRUE ((BOOLEAN) (!FALSE)) -#endif -#endif - -#if !defined(NULL) -#if defined(__cplusplus) -#define NULL (0) -#else -#define NULL ((void *)0) -#endif -#endif -#define USE_PROTOTYPES -#if defined(USE_PROTOTYPES) -#define PROTOTYPE(x) x -#define VARARGS , ... -#else -#define PROTOTYPE(x) () -#define VARARGS -#endif - -/** - * Assign the default line delimiter, if it was not set. - */ - -#if !defined(PLATFORM_LINE_DELIMITER) -#define PLATFORM_LINE_DELIMITER "\015\012" -#endif - -/** - * Set the max path length, if it was not set. - */ - -#if !defined(MAX_IMAGE_PATH_LENGTH) -#define MAX_IMAGE_PATH_LENGTH (2048) -#endif -typedef double ESDOUBLE; -typedef float ESSINGLE; - -/** - * Helpers for U_64s. - */ - -#define CLEAR_U64(u64) (u64 = (U_64)0) -#define LOW_LONG(l) (*((U_32 *) &(l))) -#define HIGH_LONG(l) (*(((U_32 *) &(l)) + 1)) -#define I8(x) ((I_8) (x)) -#define I8P(x) ((I_8 *) (x)) -#define U16(x) ((U_16) (x)) -#define I16(x) ((I_16) (x)) -#define I16P(x) ((I_16 *) (x)) #define U32(x) ((U_32) (x)) #define I32(x) ((I_32) (x)) -#define I32P(x) ((I_32 *) (x)) -#define U16P(x) ((U_16 *) (x)) #define U32P(x) ((U_32 *) (x)) -#define OBJP(x) ((HyObject *) (x)) -#define OBJPP(x) ((HyObject **) (x)) -#define OBJPPP(x) ((HyObject ***) (x)) -#define CLASSP(x) ((Class *) (x)) -#define CLASSPP(x) ((Class **) (x)) -#define BYTEP(x) ((BYTE *) (x)) - -/** - * Test - was conflicting with OS2.h - */ - -#define ESCHAR(x) ((CHARACTER) (x)) -#define FLT(x) ((FLOAT) x) -#define FLTP(x) ((FLOAT *) (x)) -#if defined(NO_LVALUE_CASTING) -#define LI8(x) (*((I_8 *) &(x))) -#define LI8P(x) (*((I_8 **) &(x))) -#define LU16(x) (*((U_16 *) &(x))) -#define LI16(x) (*((I_16 *) &(x))) -#define LU32(x) (*((U_32 *) &(x))) -#define LI32(x) (*((I_32 *) &(x))) -#define LI32P(x) (*((I_32 **) &(x))) -#define LU16P(x) (*((U_16 **) &(x))) -#define LU32P(x) (*((U_32 **) &(x))) -#define LOBJP(x) (*((HyObject **) &(x))) -#define LOBJPP(x) (*((HyObject ***) &(x))) -#define LOBJPPP(x) (*((HyObject ****) &(x)) -#define LCLASSP(x) (*((Class **) &(x))) -#define LBYTEP(x) (*((BYTE **) &(x))) -#define LCHAR(x) (*((CHARACTER) &(x))) -#define LFLT(x) (*((FLOAT) &x)) -#define LFLTP(x) (*((FLOAT *) &(x))) -#else -#define LI8(x) I8((x)) -#define LI8P(x) I8P((x)) -#define LU16(x) U16((x)) -#define LI16(x) I16((x)) -#define LU32(x) U32((x)) -#define LI32(x) I32((x)) -#define LI32P(x) I32P((x)) -#define LU16P(x) U16P((x)) -#define LU32P(x) U32P((x)) -#define LOBJP(x) OBJP((x)) -#define LOBJPP(x) OBJPP((x)) -#define LOBJPPP(x) OBJPPP((x)) -#define LIOBJP(x) IOBJP((x)) -#define LCLASSP(x) CLASSP((x)) -#define LBYTEP(x) BYTEP((x)) -#define LCHAR(x) CHAR((x)) -#define LFLT(x) FLT((x)) -#define LFLTP(x) FLTP((x)) -#endif - -/** - * Macros for converting between words and longs and accessing bits. - */ - -#define HIGH_WORD(x) U16(U32((x)) >> 16) -#define LOW_WORD(x) U16(U32((x)) & 0xFFFF) -#define LOW_BIT(o) (U32((o)) & 1) -#define LOW_2_BITS(o) (U32((o)) & 3) -#define LOW_3_BITS(o) (U32((o)) & 7) -#define LOW_4_BITS(o) (U32((o)) & 15) -#define MAKE_32(h, l) ((U32((h)) << 16) | U32((l))) -#define MAKE_64(h, l) ((((I_64)(h)) << 32) | (l)) -#if defined(__cplusplus) -#define HY_CFUNC "C" -#define HY_CDATA "C" -#else -#define HY_CFUNC -#define HY_CDATA -#endif - -/** - * Macros for tagging functions which read/write the vm thread. - */ - -#define READSVMTHREAD -#define WRITESVMTHREAD -#define REQUIRESSTACKFRAME - -/** - * Macro for tagging functions, which never return. - */ - -#if defined(__GNUC__) - -/** - * On GCC, we can actually pass this information on to the compiler. - */ - -#define NORETURN __attribute__((noreturn)) -#else -#define NORETURN -#endif - -/** - * On some systems va_list is an array type. This is probably in - * violation of the ANSI C spec, but it's not entirely clear. Because of - * this, we end up with an undesired extra level of indirection if we take - * the address of a va_list argument. - * - * To get it right, always use the VA_PTR macro - */ - -#if !defined(VA_PTR) -#define VA_PTR(valist) (&valist) -#endif -#if !defined(TOC_UNWRAP_ADDRESS) -#define TOC_UNWRAP_ADDRESS(wrappedPointer) (wrappedPointer) -#endif - -#if !defined(TOC_STORE_TOC) -#define TOC_STORE_TOC(dest,wrappedPointer) -#endif -/** - * Macros for accessing I_64 values. - */ - -#if defined(ATOMIC_LONG_ACCESS) -#define PTR_LONG_STORE(dstPtr, aLongPtr) ((*U32P(dstPtr) = *U32P(aLongPtr)), (*(U32P(dstPtr)+1) = *(U32P(aLongPtr)+1))) -#define PTR_LONG_VALUE(dstPtr, aLongPtr) ((*U32P(aLongPtr) = *U32P(dstPtr)), (*(U32P(aLongPtr)+1) = *(U32P(dstPtr)+1))) -#else -#define PTR_LONG_STORE(dstPtr, aLongPtr) (*(dstPtr) = *(aLongPtr)) -#define PTR_LONG_VALUE(dstPtr, aLongPtr) (*(aLongPtr) = *(dstPtr)) -#endif - -/** - * Macro used when declaring tables which require relocations. - */ - -#if !defined(HYCONST_TABLE) -#define HYCONST_TABLE const -#endif - -/** - * ANSI qsort is not always available. - */ - -#if !defined(HY_SORT) -#define HY_SORT(base, nmemb, size, compare) qsort((base), (nmemb), (size), (compare)) -#endif #endif /* hycomp_h */ diff --git a/luni/src/main/native/hymutex.h b/luni/src/main/native/hymutex.h deleted file mode 100644 index 5c98ebd..0000000 --- a/luni/src/main/native/hymutex.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if !defined(hymutex_h) -#define hymutex_h - -#include <pthread.h> -#include <stdlib.h> - -typedef pthread_mutex_t MUTEX; - -/* MUTEX_INIT */ -#define MUTEX_INIT(mutex) (pthread_mutex_init(&(mutex), NULL) == 0) - -/* MUTEX_DESTROY */ -#define MUTEX_DESTROY(mutex) pthread_mutex_destroy(&(mutex)) - -/* MUTEX_ENTER */ -#define MUTEX_ENTER(mutex) pthread_mutex_lock(&(mutex)) - -/* - * MUTEX_TRY_ENTER - * returns 0 on success - */ -#define MUTEX_TRY_ENTER(mutex) pthread_mutex_trylock(&(mutex)) - -/* MUTEX_EXIT */ -#define MUTEX_EXIT(mutex) pthread_mutex_unlock(&(mutex)) - -#endif /* hymutex_h */ diff --git a/luni/src/main/native/hyport.h b/luni/src/main/native/hyport.h deleted file mode 100644 index 029d4fe..0000000 --- a/luni/src/main/native/hyport.h +++ /dev/null @@ -1 +0,0 @@ -#include "hy2sie.h" diff --git a/luni/src/main/native/ifaddrs-android.h b/luni/src/main/native/ifaddrs-android.h index b66bf69..f2fa98f 100644 --- a/luni/src/main/native/ifaddrs-android.h +++ b/luni/src/main/native/ifaddrs-android.h @@ -186,7 +186,7 @@ inline int getifaddrs(ifaddrs** result) { ssize_t bytesRead; while ((bytesRead = recvNetlinkMessage(fd.get(), &buf[0], buf.size())) > 0) { nlmsghdr* hdr = reinterpret_cast<nlmsghdr*>(&buf[0]); - for (; NLMSG_OK(hdr, bytesRead); hdr = NLMSG_NEXT(hdr, bytesRead)) { + for (; NLMSG_OK(hdr, (size_t)bytesRead); hdr = NLMSG_NEXT(hdr, bytesRead)) { switch (hdr->nlmsg_type) { case NLMSG_DONE: return 0; diff --git a/luni/src/main/native/java_io_Console.cpp b/luni/src/main/native/java_io_Console.cpp index fdaafaf..f6c69e7 100644 --- a/luni/src/main/native/java_io_Console.cpp +++ b/luni/src/main/native/java_io_Console.cpp @@ -21,7 +21,7 @@ #include <termios.h> #include <unistd.h> -static jboolean java_io_Console_isatty(JNIEnv* env, jclass, jint fd) { +static jboolean java_io_Console_isatty(JNIEnv*, jclass, jint fd) { return TEMP_FAILURE_RETRY(isatty(fd)); } diff --git a/luni/src/main/native/java_io_File.cpp b/luni/src/main/native/java_io_File.cpp index dc25057..1d5ec51 100644 --- a/luni/src/main/native/java_io_File.cpp +++ b/luni/src/main/native/java_io_File.cpp @@ -115,7 +115,7 @@ static jboolean java_io_File_canReadImpl(JNIEnv* env, jobject, jbyteArray pathBy return (access(&path[0], R_OK) == 0); } -static jboolean java_io_File_canWriteImpl(JNIEnv* env, jobject recv, jbyteArray pathBytes) { +static jboolean java_io_File_canWriteImpl(JNIEnv* env, jobject, jbyteArray pathBytes) { ScopedByteArray path(env, pathBytes); return (access(&path[0], W_OK) == 0); } diff --git a/luni/src/main/native/java_io_ObjectInputStream.c b/luni/src/main/native/java_io_ObjectInputStream.cpp index 0aa56b0..57f8afe 100644 --- a/luni/src/main/native/java_io_ObjectInputStream.c +++ b/luni/src/main/native/java_io_ObjectInputStream.cpp @@ -17,7 +17,7 @@ #include "JNIHelp.h" -static void java_setFieldBool (JNIEnv * env, jclass clazz, +static void java_setFieldBool (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -27,20 +27,20 @@ static void java_setFieldBool (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "Z"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, "Z"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, * or maybe it returned the real value */ if(fid != 0) { - (*env)->SetBooleanField(env, targetObject, fid, newValue); + env->SetBooleanField(targetObject, fid, newValue); } } -static void java_setFieldChar (JNIEnv * env, jclass clazz, +static void java_setFieldChar (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -50,20 +50,20 @@ static void java_setFieldChar (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "C"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, "C"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, * or maybe it returned the real value */ if(fid != 0) { - (*env)->SetCharField(env, targetObject, fid, newValue); + env->SetCharField(targetObject, fid, newValue); } } -static void java_setFieldInt (JNIEnv * env, jclass clazz, +static void java_setFieldInt (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -73,20 +73,20 @@ static void java_setFieldInt (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "I"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, "I"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, * or maybe it returned the real value */ if(fid != 0) { - (*env)->SetIntField(env, targetObject, fid, newValue); + env->SetIntField(targetObject, fid, newValue); } } -static void java_setFieldFloat (JNIEnv * env, jclass clazz, +static void java_setFieldFloat (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -96,20 +96,20 @@ static void java_setFieldFloat (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "F"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, "F"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, * or maybe it returned the real value */ if(fid != 0) { - (*env)->SetFloatField(env, targetObject, fid, newValue); + env->SetFloatField(targetObject, fid, newValue); } } -static void java_setFieldDouble (JNIEnv * env, jclass clazz, +static void java_setFieldDouble (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -119,21 +119,21 @@ static void java_setFieldDouble (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "D"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, "D"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, * or maybe it returned the real value */ if(fid != 0) { - (*env)->SetDoubleField(env, targetObject, fid, newValue); + env->SetDoubleField(targetObject, fid, newValue); } } -static void java_setFieldShort (JNIEnv * env, jclass clazz, +static void java_setFieldShort (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -143,21 +143,21 @@ static void java_setFieldShort (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "S"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, "S"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, * or maybe it returned the real value */ if(fid != 0) { - (*env)->SetShortField(env, targetObject, fid, newValue); + env->SetShortField(targetObject, fid, newValue); } } -static void java_setFieldLong (JNIEnv * env, jclass clazz, +static void java_setFieldLong (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -167,36 +167,36 @@ static void java_setFieldLong (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "J"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, "J"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, * or maybe it returned the real value */ if(fid != 0) { - (*env)->SetLongField(env, targetObject, fid, newValue); + env->SetLongField(targetObject, fid, newValue); } } -static jobject java_newInstance (JNIEnv * env, jclass clazz, +static jobject java_newInstance (JNIEnv* env, jclass, jclass instantiationClass, jclass constructorClass) { jmethodID mid = - (*env)->GetMethodID(env, constructorClass, "<init>", "()V"); + env->GetMethodID(constructorClass, "<init>", "()V"); if(mid == 0) { /* Cant newInstance,No empty constructor... */ return (jobject) 0; } else { /* Instantiate an object of a given class */ - return (jobject) (*env)->NewObject(env, instantiationClass, mid); + return (jobject) env->NewObject(instantiationClass, mid); } } -static void java_setFieldByte (JNIEnv * env, jclass clazz, +static void java_setFieldByte (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -206,17 +206,17 @@ static void java_setFieldByte (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "B"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, "B"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* Two options now. Maybe getFieldID caused an exception, or maybe it returned the real value */ if(fid != 0) { - (*env)->SetByteField(env, targetObject, fid, newValue); + env->SetByteField(targetObject, fid, newValue); } } -static void java_setFieldObj (JNIEnv * env, jclass clazz, +static void java_setFieldObj (JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, @@ -227,19 +227,19 @@ static void java_setFieldObj (JNIEnv * env, jclass clazz, if(targetObject == NULL) { return; } - fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - fieldTypeNameInC = (*env)->GetStringUTFChars(env, fieldTypeName, NULL); - fid = (*env)->GetFieldID(env, declaringClass, + fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + fieldTypeNameInC = env->GetStringUTFChars(fieldTypeName, NULL); + fid = env->GetFieldID(declaringClass, fieldNameInC, fieldTypeNameInC); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); - (*env)->ReleaseStringUTFChars(env, fieldTypeName, fieldTypeNameInC); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); + env->ReleaseStringUTFChars(fieldTypeName, fieldTypeNameInC); /* * Two options now. Maybe getFieldID caused an exception, * or maybe it returned the real value */ if(fid != 0) { - (*env)->SetObjectField(env, targetObject, fid, newValue); + env->SetObjectField(targetObject, fid, newValue); } } diff --git a/luni/src/main/native/java_io_ObjectOutputStream.c b/luni/src/main/native/java_io_ObjectOutputStream.cpp index d6432c7..791e041 100644 --- a/luni/src/main/native/java_io_ObjectOutputStream.c +++ b/luni/src/main/native/java_io_ObjectOutputStream.cpp @@ -17,13 +17,13 @@ #include "JNIHelp.h" -static jlong java_getFieldLong(JNIEnv * env, jclass clazz, +static jlong java_getFieldLong(JNIEnv * env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "J"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, "J"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, @@ -33,17 +33,17 @@ static jlong java_getFieldLong(JNIEnv * env, jclass clazz, // Field not found. I believe we must throw an exception here return (jlong) 0L; } else { - return (*env)->GetLongField (env, targetObject, fid); + return env->GetLongField(targetObject, fid); } } -static jshort java_getFieldShort(JNIEnv * env, jclass clazz, +static jshort java_getFieldShort(JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "S"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, "S"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, @@ -53,17 +53,17 @@ static jshort java_getFieldShort(JNIEnv * env, jclass clazz, // Field not found. I believe we must throw an exception here return (jshort) 0; } else { - return (*env)->GetShortField (env, targetObject, fid); + return env->GetShortField(targetObject, fid); } } -static jdouble java_getFieldDouble(JNIEnv * env, jclass clazz, +static jdouble java_getFieldDouble(JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "D"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, "D"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, @@ -73,17 +73,17 @@ static jdouble java_getFieldDouble(JNIEnv * env, jclass clazz, // Field not found. I believe we must throw an exception here return (jdouble) 0.0; } else { - return (*env)->GetDoubleField (env, targetObject, fid); + return env->GetDoubleField(targetObject, fid); } } -static jboolean java_getFieldBool(JNIEnv * env, jclass clazz, +static jboolean java_getFieldBool(JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "Z"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, "Z"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, @@ -93,17 +93,17 @@ static jboolean java_getFieldBool(JNIEnv * env, jclass clazz, // Field not found. I believe we must throw an exception here return (jboolean) 0; } else { - return (*env)->GetBooleanField (env, targetObject, fid); + return env->GetBooleanField(targetObject, fid); } } -static jbyte java_getFieldByte(JNIEnv * env, jclass clazz, +static jbyte java_getFieldByte(JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "B"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, "B"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, @@ -113,17 +113,17 @@ static jbyte java_getFieldByte(JNIEnv * env, jclass clazz, // Field not found. I believe we must throw an exception here return (jbyte) 0; } else { - return (*env)->GetByteField (env, targetObject, fid); + return env->GetByteField(targetObject, fid); } } -static jfloat java_getFieldFloat(JNIEnv * env, jclass clazz, +static jfloat java_getFieldFloat(JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "F"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, "F"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, @@ -134,18 +134,18 @@ static jfloat java_getFieldFloat(JNIEnv * env, jclass clazz, return (jfloat) 0.0f; } else { - return (*env)->GetFloatField (env, targetObject, fid); + return env->GetFloatField(targetObject, fid); } } -static jchar java_getFieldChar(JNIEnv * env, jclass clazz, +static jchar java_getFieldChar(JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "C"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, "C"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused an exception, @@ -155,22 +155,22 @@ static jchar java_getFieldChar(JNIEnv * env, jclass clazz, // Field not found. I believe we must throw an exception here return (jchar) 0; } else { - return (*env)->GetCharField(env, targetObject, fid); + return env->GetCharField(targetObject, fid); } } -static jobject java_getFieldObj(JNIEnv * env, jclass clazz, +static jobject java_getFieldObj(JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName, jstring fieldTypeName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); const char *fieldTypeNameInC = - (*env)->GetStringUTFChars(env, fieldTypeName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, + env->GetStringUTFChars(fieldTypeName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, fieldTypeNameInC); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); - (*env)->ReleaseStringUTFChars(env, fieldTypeName, fieldTypeNameInC); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); + env->ReleaseStringUTFChars(fieldTypeName, fieldTypeNameInC); /* * Two options now. Maybe getFieldID caused an exception, @@ -180,17 +180,17 @@ static jobject java_getFieldObj(JNIEnv * env, jclass clazz, // Field not found. I believe we must throw an exception here return (jobject) 0; } else { - return (*env)->GetObjectField (env, targetObject, fid); + return env->GetObjectField(targetObject, fid); } } -static jint java_getFieldInt(JNIEnv * env, jclass clazz, +static jint java_getFieldInt(JNIEnv* env, jclass, jobject targetObject, jclass declaringClass, jstring fieldName) { - const char *fieldNameInC = (*env)->GetStringUTFChars(env, fieldName, NULL); - jfieldID fid = (*env)->GetFieldID(env, declaringClass, fieldNameInC, "I"); - (*env)->ReleaseStringUTFChars(env, fieldName, fieldNameInC); + const char *fieldNameInC = env->GetStringUTFChars(fieldName, NULL); + jfieldID fid = env->GetFieldID(declaringClass, fieldNameInC, "I"); + env->ReleaseStringUTFChars(fieldName, fieldNameInC); /* * Two options now. Maybe getFieldID caused @@ -200,7 +200,7 @@ static jint java_getFieldInt(JNIEnv * env, jclass clazz, // Field not found. I believe we must throw an exception here return (jint) 0; } else { - return (*env)->GetIntField(env, targetObject, fid); + return env->GetIntField(targetObject, fid); } } diff --git a/luni/src/main/native/java_io_ObjectStreamClass.c b/luni/src/main/native/java_io_ObjectStreamClass.c deleted file mode 100644 index 935ff37..0000000 --- a/luni/src/main/native/java_io_ObjectStreamClass.c +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "JNIHelp.h" - -static jobject java_io_osc_getFieldSignature(JNIEnv * env, jclass clazz, - jobject reflectField) { - jclass lookupClass; - jmethodID mid; - - lookupClass = (*env)->FindClass(env, "java/lang/reflect/Field"); - if(!lookupClass) { - return NULL; - } - - mid = (*env)->GetMethodID(env, lookupClass, "getSignature", - "()Ljava/lang/String;"); - if(!mid) - { - return NULL; - } - - jclass fieldClass = (*env)->GetObjectClass(env, reflectField); - - return (*env)->CallNonvirtualObjectMethod(env, reflectField, - fieldClass, mid); -} - -static jobject java_io_osc_getMethodSignature(JNIEnv * env, jclass clazz, - jobject reflectMethod) -{ - jclass lookupClass; - jmethodID mid; - - lookupClass = (*env)->FindClass(env, "java/lang/reflect/Method"); - if(!lookupClass) { - return NULL; - } - - mid = (*env)->GetMethodID(env, lookupClass, "getSignature", - "()Ljava/lang/String;"); - if(!mid) { - return NULL; - } - - jclass methodClass = (*env)->GetObjectClass(env, reflectMethod); - return (*env)->CallNonvirtualObjectMethod(env, reflectMethod, - methodClass, mid); -} - -static jobject java_io_osc_getConstructorSignature(JNIEnv * env, - jclass clazz, - jobject - reflectConstructor) -{ - jclass lookupClass; - jmethodID mid; - - lookupClass = (*env)->FindClass(env, "java/lang/reflect/Constructor"); - if(!lookupClass) { - return NULL; - } - - mid = (*env)->GetMethodID(env, lookupClass, "getSignature", - "()Ljava/lang/String;"); - if(!mid) { - return NULL; - } - - jclass constructorClass = (*env)->GetObjectClass(env, reflectConstructor); - return (*env)->CallNonvirtualObjectMethod(env, reflectConstructor, - constructorClass, mid); -} - -static jboolean java_io_osc_hasClinit(JNIEnv * env, jclass clazz, - jobject targetClass) { - jmethodID mid = (*env)->GetStaticMethodID(env, targetClass, - "<clinit>", "()V"); - (*env)->ExceptionClear(env); - - /* - * Can I just return mid and rely on typecast to convert to jboolean ? - * Safe implementation for now - */ - if(mid == 0) { - /* No <clinit>... */ - return (jboolean) 0; - } else { - return (jboolean) 1; - } -} - -static void java_io_osc_oneTimeInitialization(JNIEnv * env, jclass clazz) { - // dummy to stay compatible to harmony -} - -static JNINativeMethod gMethods[] = { - { "getFieldSignature", - "(Ljava/lang/reflect/Field;)Ljava/lang/String;", - (void*) java_io_osc_getFieldSignature }, - { "getMethodSignature", - "(Ljava/lang/reflect/Method;)Ljava/lang/String;", - (void*) java_io_osc_getMethodSignature }, - { "getConstructorSignature", - "(Ljava/lang/reflect/Constructor;)Ljava/lang/String;", - (void*) java_io_osc_getConstructorSignature }, - { "hasClinit", "(Ljava/lang/Class;)Z", - (void*) java_io_osc_hasClinit }, - { "oneTimeInitialization", "()V", - (void*) java_io_osc_oneTimeInitialization } -}; -int register_java_io_ObjectStreamClass(JNIEnv* env) { - return jniRegisterNativeMethods(env, "java/io/ObjectStreamClass", gMethods, NELEM(gMethods)); -} diff --git a/luni/src/main/native/java_io_ObjectStreamClass.cpp b/luni/src/main/native/java_io_ObjectStreamClass.cpp new file mode 100644 index 0000000..666692d --- /dev/null +++ b/luni/src/main/native/java_io_ObjectStreamClass.cpp @@ -0,0 +1,103 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "JNIHelp.h" + +static jobject java_io_osc_getFieldSignature(JNIEnv* env, jclass, + jobject reflectField) { + jclass lookupClass; + jmethodID mid; + + lookupClass = env->FindClass("java/lang/reflect/Field"); + if(!lookupClass) { + return NULL; + } + + mid = env->GetMethodID(lookupClass, "getSignature", + "()Ljava/lang/String;"); + if(!mid) + { + return NULL; + } + + jclass fieldClass = env->GetObjectClass(reflectField); + + return env->CallNonvirtualObjectMethod(reflectField, + fieldClass, mid); +} + +static jobject java_io_osc_getMethodSignature(JNIEnv* env, jclass, + jobject reflectMethod) +{ + jclass lookupClass; + jmethodID mid; + + lookupClass = env->FindClass("java/lang/reflect/Method"); + if(!lookupClass) { + return NULL; + } + + mid = env->GetMethodID(lookupClass, "getSignature", + "()Ljava/lang/String;"); + if(!mid) { + return NULL; + } + + jclass methodClass = env->GetObjectClass(reflectMethod); + return env->CallNonvirtualObjectMethod(reflectMethod, + methodClass, mid); +} + +static jobject java_io_osc_getConstructorSignature(JNIEnv* env, + jclass, + jobject + reflectConstructor) +{ + jclass lookupClass; + jmethodID mid; + + lookupClass = env->FindClass("java/lang/reflect/Constructor"); + if(!lookupClass) { + return NULL; + } + + mid = env->GetMethodID(lookupClass, "getSignature", + "()Ljava/lang/String;"); + if(!mid) { + return NULL; + } + + jclass constructorClass = env->GetObjectClass(reflectConstructor); + return env->CallNonvirtualObjectMethod(reflectConstructor, + constructorClass, mid); +} + +static jboolean java_io_osc_hasClinit(JNIEnv * env, jclass, jclass targetClass) { + jmethodID mid = env->GetStaticMethodID(targetClass, "<clinit>", "()V"); + env->ExceptionClear(); + return (mid != 0); +} + +static JNINativeMethod gMethods[] = { + { "getConstructorSignature", "(Ljava/lang/reflect/Constructor;)Ljava/lang/String;", (void*) java_io_osc_getConstructorSignature }, + { "getFieldSignature", "(Ljava/lang/reflect/Field;)Ljava/lang/String;", (void*) java_io_osc_getFieldSignature }, + { "getMethodSignature", "(Ljava/lang/reflect/Method;)Ljava/lang/String;", (void*) java_io_osc_getMethodSignature }, + { "hasClinit", "(Ljava/lang/Class;)Z", (void*) java_io_osc_hasClinit }, +}; +int register_java_io_ObjectStreamClass(JNIEnv* env) { + return jniRegisterNativeMethods(env, "java/io/ObjectStreamClass", gMethods, NELEM(gMethods)); +} diff --git a/luni/src/main/native/java_lang_Double.c b/luni/src/main/native/java_lang_Double.cpp index 9cc0869..65576f7 100644 --- a/luni/src/main/native/java_lang_Double.c +++ b/luni/src/main/native/java_lang_Double.cpp @@ -21,7 +21,7 @@ typedef union { /* * public static native long doubleToLongBits(double value) */ -static jlong doubleToLongBits(JNIEnv* env, jclass clazz, jdouble val) +static jlong doubleToLongBits(JNIEnv*, jclass, jdouble val) { Double d; @@ -39,7 +39,7 @@ static jlong doubleToLongBits(JNIEnv* env, jclass clazz, jdouble val) /* * public static native long doubleToRawLongBits(double value) */ -static jlong doubleToRawLongBits(JNIEnv* env, jclass clazz, jdouble val) +static jlong doubleToRawLongBits(JNIEnv*, jclass, jdouble val) { Double d; @@ -51,7 +51,7 @@ static jlong doubleToRawLongBits(JNIEnv* env, jclass clazz, jdouble val) /* * public static native double longBitsToDouble(long bits) */ -static jdouble longBitsToDouble(JNIEnv* env, jclass clazz, jlong val) +static jdouble longBitsToDouble(JNIEnv*, jclass, jlong val) { Double d; @@ -61,9 +61,9 @@ static jdouble longBitsToDouble(JNIEnv* env, jclass clazz, jlong val) } static JNINativeMethod gMethods[] = { - { "doubleToLongBits", "(D)J", doubleToLongBits }, - { "doubleToRawLongBits", "(D)J", doubleToRawLongBits }, - { "longBitsToDouble", "(J)D", longBitsToDouble }, + { "doubleToLongBits", "(D)J", (void*)doubleToLongBits }, + { "doubleToRawLongBits", "(D)J", (void*)doubleToRawLongBits }, + { "longBitsToDouble", "(J)D", (void*)longBitsToDouble }, }; int register_java_lang_Double(JNIEnv* env) { return jniRegisterNativeMethods(env, "java/lang/Double", gMethods, NELEM(gMethods)); diff --git a/luni/src/main/native/java_lang_Float.c b/luni/src/main/native/java_lang_Float.cpp index 6426495..08f5464 100644 --- a/luni/src/main/native/java_lang_Float.c +++ b/luni/src/main/native/java_lang_Float.cpp @@ -29,7 +29,7 @@ static int IsNaN(unsigned bits) /* * public static native int floatToIntBits(float value) */ -static jint floatToIntBits(JNIEnv* env, jclass clazz, jfloat val) +static jint floatToIntBits(JNIEnv*, jclass, jfloat val) { Float f; @@ -47,7 +47,7 @@ static jint floatToIntBits(JNIEnv* env, jclass clazz, jfloat val) /* * public static native int floatToRawBits(float value) */ -static jint floatToRawBits(JNIEnv* env, jclass clazz, jfloat val) +static jint floatToRawBits(JNIEnv*, jclass, jfloat val) { Float f; @@ -59,7 +59,7 @@ static jint floatToRawBits(JNIEnv* env, jclass clazz, jfloat val) /* * public static native float intBitsToFloat(int bits) */ -static jfloat intBitsToFloat(JNIEnv* env, jclass clazz, jint val) +static jfloat intBitsToFloat(JNIEnv*, jclass, jint val) { Float f; @@ -69,9 +69,9 @@ static jfloat intBitsToFloat(JNIEnv* env, jclass clazz, jint val) } static JNINativeMethod gMethods[] = { - { "floatToIntBits", "(F)I", floatToIntBits }, - { "floatToRawIntBits", "(F)I", floatToRawBits }, - { "intBitsToFloat", "(I)F", intBitsToFloat }, + { "floatToIntBits", "(F)I", (void*)floatToIntBits }, + { "floatToRawIntBits", "(F)I", (void*)floatToRawBits }, + { "intBitsToFloat", "(I)F", (void*)intBitsToFloat }, }; int register_java_lang_Float(JNIEnv* env) { return jniRegisterNativeMethods(env, "java/lang/Float", gMethods, NELEM(gMethods)); diff --git a/luni/src/main/native/java_lang_Math.c b/luni/src/main/native/java_lang_Math.c deleted file mode 100644 index 2092c2d..0000000 --- a/luni/src/main/native/java_lang_Math.c +++ /dev/null @@ -1,204 +0,0 @@ -/* - * Copyright 2006 The Android Open Source Project - * - * Native functions for java.lang.Math. - */ -#include "jni.h" -#include "JNIHelp.h" - -#include <stdlib.h> -#include <math.h> - -/* native public static double sin(double a); */ -static jdouble jsin(JNIEnv* env, jclass clazz, jdouble a) -{ - return sin(a); -} - -/* native public static double cos(double a); */ -static jdouble jcos(JNIEnv* env, jclass clazz, jdouble a) -{ - return cos(a); -} - -/* native public static double tan(double a); */ -static jdouble jtan(JNIEnv* env, jclass clazz, jdouble a) -{ - return tan(a); -} - -/* native public static double asin(double a); */ -static jdouble jasin(JNIEnv* env, jclass clazz, jdouble a) -{ - return asin(a); -} - -/* native public static double acos(double a); */ -static jdouble jacos(JNIEnv* env, jclass clazz, jdouble a) -{ - return acos(a); -} - -/* native public static double atan(double a); */ -static jdouble jatan(JNIEnv* env, jclass clazz, jdouble a) -{ - return atan(a); -} - -/* native public static double exp(double a); */ -static jdouble jexp(JNIEnv* env, jclass clazz, jdouble a) -{ - return exp(a); -} - -/* native public static double log(double a); */ -static jdouble jlog(JNIEnv* env, jclass clazz, jdouble a) -{ - return log(a); -} - -/* native public static double sqrt(double a); */ -static jdouble jsqrt(JNIEnv* env, jclass clazz, jdouble a) -{ - return sqrt(a); -} - -/* native public static double IEEEremainder(double a, double b); */ -static jdouble jieee_remainder(JNIEnv* env, jclass clazz, jdouble a, jdouble b) -{ - return remainder(a, b); -} - -/* native public static double floor(double a); */ -static jdouble jfloor(JNIEnv* env, jclass clazz, jdouble a) -{ - return floor(a); -} - -/* native public static double ceil(double a); */ -static jdouble jceil(JNIEnv* env, jclass clazz, jdouble a) -{ - return ceil(a); -} - -/* native public static double rint(double a); */ -static jdouble jrint(JNIEnv* env, jclass clazz, jdouble a) -{ - return rint(a); -} - -/* native public static double atan2(double a, double b); */ -static jdouble jatan2(JNIEnv* env, jclass clazz, jdouble a, jdouble b) -{ - return atan2(a, b); -} - -/* native public static double pow(double a, double b); */ -static jdouble jpow(JNIEnv* env, jclass clazz, jdouble a, jdouble b) -{ - return pow(a, b); -} - -/* native public static double sinh(double a); */ -static jdouble jsinh(JNIEnv* env, jclass clazz, jdouble a) -{ - return sinh(a); -} - -/* native public static double tanh(double a); */ -static jdouble jtanh(JNIEnv* env, jclass clazz, jdouble a) -{ - return tanh(a); -} - -/* native public static double cosh(double a); */ -static jdouble jcosh(JNIEnv* env, jclass clazz, jdouble a) -{ - return cosh(a); -} - -/* native public static double log10(double a); */ -static jdouble jlog10(JNIEnv* env, jclass clazz, jdouble a) -{ - return log10(a); -} - -/* native public static double cbrt(double a); */ -static jdouble jcbrt(JNIEnv* env, jclass clazz, jdouble a) -{ - return cbrt(a); -} - -/* native public static double expm1(double a); */ -static jdouble jexpm1(JNIEnv* env, jclass clazz, jdouble a) -{ - return expm1(a); -} - -/* native public static double hypot(double a, double b); */ -static jdouble jhypot(JNIEnv* env, jclass clazz, jdouble a, jdouble b) -{ - return hypot(a, b); -} - -/* native public static double log1p(double a); */ -static jdouble jlog1p(JNIEnv* env, jclass clazz, jdouble a) -{ - return log1p(a); -} - -/* native public static double nextafter(double a, double b); */ -static jdouble jnextafter(JNIEnv* env, jclass clazz, jdouble a, jdouble b) -{ - return nextafter(a, b); -} - -/* native public static float nextafterf(float a, float b); */ -static jfloat jnextafterf(JNIEnv* env, jclass clazz, jfloat a, jfloat b) -{ - return nextafterf(a, b); -} - -static jdouble copySign(JNIEnv* env, jclass clazz, jdouble a, jdouble b) { - // Our StrictMath.copySign delegates to Math.copySign, so we need to treat NaN as positive. - return copysign(a, isnan(b) ? 1.0 : b); -} - -static jfloat copySign_f(JNIEnv* env, jclass clazz, jfloat a, jfloat b) { - // Our StrictMath.copySign delegates to Math.copySign, so we need to treat NaN as positive. - return copysignf(a, isnan(b) ? 1.0 : b); -} - -static JNINativeMethod gMethods[] = { - { "IEEEremainder", "(DD)D", jieee_remainder }, - { "acos", "(D)D", jacos }, - { "asin", "(D)D", jasin }, - { "atan", "(D)D", jatan }, - { "atan2", "(DD)D", jatan2 }, - { "cbrt", "(D)D", jcbrt }, - { "ceil", "(D)D", jceil }, - { "copySign", "(DD)D", copySign }, - { "copySign", "(FF)F", copySign_f }, - { "cos", "(D)D", jcos }, - { "cosh", "(D)D", jcosh }, - { "exp", "(D)D", jexp }, - { "expm1", "(D)D", jexpm1 }, - { "floor", "(D)D", jfloor }, - { "hypot", "(DD)D", jhypot }, - { "log", "(D)D", jlog }, - { "log10", "(D)D", jlog10 }, - { "log1p", "(D)D", jlog1p }, - { "nextafter", "(DD)D", jnextafter }, - { "nextafterf", "(FF)F", jnextafterf }, - { "pow", "(DD)D", jpow }, - { "rint", "(D)D", jrint }, - { "sin", "(D)D", jsin }, - { "sinh", "(D)D", jsinh }, - { "sqrt", "(D)D", jsqrt }, - { "tan", "(D)D", jtan }, - { "tanh", "(D)D", jtanh }, -}; - -int register_java_lang_Math(JNIEnv* env) { - return jniRegisterNativeMethods(env, "java/lang/Math", gMethods, NELEM(gMethods)); -} diff --git a/luni/src/main/native/java_lang_Math.cpp b/luni/src/main/native/java_lang_Math.cpp new file mode 100644 index 0000000..7fdce6f --- /dev/null +++ b/luni/src/main/native/java_lang_Math.cpp @@ -0,0 +1,204 @@ +/* + * Copyright 2006 The Android Open Source Project + * + * Native functions for java.lang.Math. + */ +#include "jni.h" +#include "JNIHelp.h" + +#include <stdlib.h> +#include <math.h> + +/* native public static double sin(double a); */ +static jdouble jsin(JNIEnv*, jclass, jdouble a) +{ + return sin(a); +} + +/* native public static double cos(double a); */ +static jdouble jcos(JNIEnv*, jclass, jdouble a) +{ + return cos(a); +} + +/* native public static double tan(double a); */ +static jdouble jtan(JNIEnv*, jclass, jdouble a) +{ + return tan(a); +} + +/* native public static double asin(double a); */ +static jdouble jasin(JNIEnv*, jclass, jdouble a) +{ + return asin(a); +} + +/* native public static double acos(double a); */ +static jdouble jacos(JNIEnv*, jclass, jdouble a) +{ + return acos(a); +} + +/* native public static double atan(double a); */ +static jdouble jatan(JNIEnv*, jclass, jdouble a) +{ + return atan(a); +} + +/* native public static double exp(double a); */ +static jdouble jexp(JNIEnv*, jclass, jdouble a) +{ + return exp(a); +} + +/* native public static double log(double a); */ +static jdouble jlog(JNIEnv*, jclass, jdouble a) +{ + return log(a); +} + +/* native public static double sqrt(double a); */ +static jdouble jsqrt(JNIEnv*, jclass, jdouble a) +{ + return sqrt(a); +} + +/* native public static double IEEEremainder(double a, double b); */ +static jdouble jieee_remainder(JNIEnv*, jclass, jdouble a, jdouble b) +{ + return remainder(a, b); +} + +/* native public static double floor(double a); */ +static jdouble jfloor(JNIEnv*, jclass, jdouble a) +{ + return floor(a); +} + +/* native public static double ceil(double a); */ +static jdouble jceil(JNIEnv*, jclass, jdouble a) +{ + return ceil(a); +} + +/* native public static double rint(double a); */ +static jdouble jrint(JNIEnv*, jclass, jdouble a) +{ + return rint(a); +} + +/* native public static double atan2(double a, double b); */ +static jdouble jatan2(JNIEnv*, jclass, jdouble a, jdouble b) +{ + return atan2(a, b); +} + +/* native public static double pow(double a, double b); */ +static jdouble jpow(JNIEnv*, jclass, jdouble a, jdouble b) +{ + return pow(a, b); +} + +/* native public static double sinh(double a); */ +static jdouble jsinh(JNIEnv*, jclass, jdouble a) +{ + return sinh(a); +} + +/* native public static double tanh(double a); */ +static jdouble jtanh(JNIEnv*, jclass, jdouble a) +{ + return tanh(a); +} + +/* native public static double cosh(double a); */ +static jdouble jcosh(JNIEnv*, jclass, jdouble a) +{ + return cosh(a); +} + +/* native public static double log10(double a); */ +static jdouble jlog10(JNIEnv*, jclass, jdouble a) +{ + return log10(a); +} + +/* native public static double cbrt(double a); */ +static jdouble jcbrt(JNIEnv*, jclass, jdouble a) +{ + return cbrt(a); +} + +/* native public static double expm1(double a); */ +static jdouble jexpm1(JNIEnv*, jclass, jdouble a) +{ + return expm1(a); +} + +/* native public static double hypot(double a, double b); */ +static jdouble jhypot(JNIEnv*, jclass, jdouble a, jdouble b) +{ + return hypot(a, b); +} + +/* native public static double log1p(double a); */ +static jdouble jlog1p(JNIEnv*, jclass, jdouble a) +{ + return log1p(a); +} + +/* native public static double nextafter(double a, double b); */ +static jdouble jnextafter(JNIEnv*, jclass, jdouble a, jdouble b) +{ + return nextafter(a, b); +} + +/* native public static float nextafterf(float a, float b); */ +static jfloat jnextafterf(JNIEnv*, jclass, jfloat a, jfloat b) +{ + return nextafterf(a, b); +} + +static jdouble copySign(JNIEnv*, jclass, jdouble a, jdouble b) { + // Our StrictMath.copySign delegates to Math.copySign, so we need to treat NaN as positive. + return copysign(a, isnan(b) ? 1.0 : b); +} + +static jfloat copySign_f(JNIEnv*, jclass, jfloat a, jfloat b) { + // Our StrictMath.copySign delegates to Math.copySign, so we need to treat NaN as positive. + return copysignf(a, isnan(b) ? 1.0 : b); +} + +static JNINativeMethod gMethods[] = { + { "IEEEremainder", "(DD)D", (void*)jieee_remainder }, + { "acos", "(D)D", (void*)jacos }, + { "asin", "(D)D", (void*)jasin }, + { "atan", "(D)D", (void*)jatan }, + { "atan2", "(DD)D", (void*)jatan2 }, + { "cbrt", "(D)D", (void*)jcbrt }, + { "ceil", "(D)D", (void*)jceil }, + { "copySign", "(DD)D", (void*)copySign }, + { "copySign", "(FF)F", (void*)copySign_f }, + { "cos", "(D)D", (void*)jcos }, + { "cosh", "(D)D", (void*)jcosh }, + { "exp", "(D)D", (void*)jexp }, + { "expm1", "(D)D", (void*)jexpm1 }, + { "floor", "(D)D", (void*)jfloor }, + { "hypot", "(DD)D", (void*)jhypot }, + { "log", "(D)D", (void*)jlog }, + { "log10", "(D)D", (void*)jlog10 }, + { "log1p", "(D)D", (void*)jlog1p }, + { "nextafter", "(DD)D", (void*)jnextafter }, + { "nextafterf", "(FF)F", (void*)jnextafterf }, + { "pow", "(DD)D", (void*)jpow }, + { "rint", "(D)D", (void*)jrint }, + { "sin", "(D)D", (void*)jsin }, + { "sinh", "(D)D", (void*)jsinh }, + { "sqrt", "(D)D", (void*)jsqrt }, + { "tan", "(D)D", (void*)jtan }, + { "tanh", "(D)D", (void*)jtanh }, +}; + +int register_java_lang_Math(JNIEnv* env) { + return jniRegisterNativeMethods(env, "java/lang/Math", gMethods, NELEM(gMethods)); +} diff --git a/luni/src/main/native/java_lang_ProcessManager.cpp b/luni/src/main/native/java_lang_ProcessManager.cpp index 666a8c7..c113c0f 100644 --- a/luni/src/main/native/java_lang_ProcessManager.cpp +++ b/luni/src/main/native/java_lang_ProcessManager.cpp @@ -61,7 +61,7 @@ static void java_lang_ProcessManager_close(JNIEnv* env, /** * Kills process with the given ID. */ -static void java_lang_ProcessManager_kill(JNIEnv* env, jclass clazz, jint pid) { +static void java_lang_ProcessManager_kill(JNIEnv* env, jclass, jint pid) { int result = kill((pid_t) pid, SIGKILL); if (result == -1) { jniThrowIOException(env, errno); @@ -335,7 +335,7 @@ static void freeStrings(JNIEnv* env, jobjectArray javaArray, char** array) { * Converts Java String[] to char** and delegates to executeProcess(). */ static pid_t java_lang_ProcessManager_exec( - JNIEnv* env, jclass clazz, jobjectArray javaCommands, + JNIEnv* env, jclass, jobjectArray javaCommands, jobjectArray javaEnvironment, jstring javaWorkingDirectory, jobject inDescriptor, jobject outDescriptor, jobject errDescriptor, jboolean redirectErrorStream) { diff --git a/luni/src/main/native/java_lang_StrictMath.c b/luni/src/main/native/java_lang_StrictMath.cpp index 651e2dd..0077d45 100644 --- a/luni/src/main/native/java_lang_StrictMath.c +++ b/luni/src/main/native/java_lang_StrictMath.cpp @@ -11,161 +11,161 @@ * into the android environment. */ -/* #include "fltconst.h" */ - #if defined(__P) #undef __P #endif /* defined(__P) */ +extern "C" { #include "../../external/fdlibm/fdlibm.h" +} _LIB_VERSION_TYPE _LIB_VERSION = _IEEE_; /* native public static double sin(double a); */ -static jdouble jsin(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jsin(JNIEnv*, jclass, jdouble a) { return ieee_sin(a); } /* native public static double cos(double a); */ -static jdouble jcos(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jcos(JNIEnv*, jclass, jdouble a) { return ieee_cos(a); } /* native public static double tan(double a); */ -static jdouble jtan(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jtan(JNIEnv*, jclass, jdouble a) { return ieee_tan(a); } /* native public static double asin(double a); */ -static jdouble jasin(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jasin(JNIEnv*, jclass, jdouble a) { return ieee_asin(a); } /* native public static double acos(double a); */ -static jdouble jacos(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jacos(JNIEnv*, jclass, jdouble a) { return ieee_acos(a); } /* native public static double atan(double a); */ -static jdouble jatan(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jatan(JNIEnv*, jclass, jdouble a) { return ieee_atan(a); } /* native public static double exp(double a); */ -static jdouble jexp(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jexp(JNIEnv*, jclass, jdouble a) { return ieee_exp(a); } /* native public static double log(double a); */ -static jdouble jlog(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jlog(JNIEnv*, jclass, jdouble a) { return ieee_log(a); } /* native public static double sqrt(double a); */ -static jdouble jsqrt2(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jsqrt2(JNIEnv*, jclass, jdouble a) { return ieee_sqrt(a); } /* native public static double IEEEremainder(double a, double b); */ -static jdouble jieee_remainder(JNIEnv* env, jclass clazz, jdouble a, jdouble b) +static jdouble jieee_remainder(JNIEnv*, jclass, jdouble a, jdouble b) { return ieee_remainder(a, b); } /* native public static double floor(double a); */ -static jdouble jfloor(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jfloor(JNIEnv*, jclass, jdouble a) { return ieee_floor(a); } /* native public static double ceil(double a); */ -static jdouble jceil(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jceil(JNIEnv*, jclass, jdouble a) { return ieee_ceil(a); } /* native public static double rint(double a); */ -static jdouble jrint(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jrint(JNIEnv*, jclass, jdouble a) { return ieee_rint(a); } /* native public static double atan2(double a, double b); */ -static jdouble jatan2(JNIEnv* env, jclass clazz, jdouble a, jdouble b) +static jdouble jatan2(JNIEnv*, jclass, jdouble a, jdouble b) { return ieee_atan2(a, b); } /* native public static double pow(double a, double b); */ -static jdouble jpow(JNIEnv* env, jclass clazz, jdouble a, jdouble b) +static jdouble jpow(JNIEnv*, jclass, jdouble a, jdouble b) { return ieee_pow(a,b); } /* native public static double sinh(double a); */ -static jdouble jsinh(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jsinh(JNIEnv*, jclass, jdouble a) { return ieee_sinh(a); } /* native public static double tanh(double a); */ -static jdouble jtanh(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jtanh(JNIEnv*, jclass, jdouble a) { return ieee_tanh(a); } /* native public static double cosh(double a); */ -static jdouble jcosh(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jcosh(JNIEnv*, jclass, jdouble a) { return ieee_cosh(a); } /* native public static double log10(double a); */ -static jdouble jlog10(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jlog10(JNIEnv*, jclass, jdouble a) { return ieee_log10(a); } /* native public static double cbrt(double a); */ -static jdouble jcbrt(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jcbrt(JNIEnv*, jclass, jdouble a) { return ieee_cbrt(a); } /* native public static double expm1(double a); */ -static jdouble jexpm1(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jexpm1(JNIEnv*, jclass, jdouble a) { return ieee_expm1(a); } /* native public static double hypot(double a, double b); */ -static jdouble jhypot(JNIEnv* env, jclass clazz, jdouble a, jdouble b) +static jdouble jhypot(JNIEnv*, jclass, jdouble a, jdouble b) { return ieee_hypot(a, b); } /* native public static double log1p(double a); */ -static jdouble jlog1p(JNIEnv* env, jclass clazz, jdouble a) +static jdouble jlog1p(JNIEnv*, jclass, jdouble a) { return ieee_log1p(a); } /* native public static double nextafter(double a, double b); */ -static jdouble jnextafter(JNIEnv* env, jclass clazz, jdouble a, jdouble b) +static jdouble jnextafter(JNIEnv*, jclass, jdouble a, jdouble b) { return ieee_nextafter(a, b); } /* native public static float nextafterf(float a, float b); */ -static jfloat jnextafterf(JNIEnv* env, jclass clazz, jfloat arg1, jfloat arg2) +static jfloat jnextafterf(JNIEnv*, jclass, jfloat arg1, jfloat arg2) { jint hx = *(jint*)&arg1; jint hy = *(jint*)&arg2; @@ -185,31 +185,31 @@ static jfloat jnextafterf(JNIEnv* env, jclass clazz, jfloat arg1, jfloat arg2) } static JNINativeMethod gMethods[] = { - { "IEEEremainder", "(DD)D", jieee_remainder }, - { "acos", "(D)D", jacos }, - { "asin", "(D)D", jasin }, - { "atan", "(D)D", jatan }, - { "atan2", "(DD)D", jatan2 }, - { "cbrt", "(D)D", jcbrt }, - { "ceil", "(D)D", jceil }, - { "cos", "(D)D", jcos }, - { "cosh", "(D)D", jcosh }, - { "exp", "(D)D", jexp }, - { "expm1", "(D)D", jexpm1 }, - { "floor", "(D)D", jfloor }, - { "hypot", "(DD)D", jhypot }, - { "log", "(D)D", jlog }, - { "log10", "(D)D", jlog10 }, - { "log1p", "(D)D", jlog1p }, - { "nextafter", "(DD)D", jnextafter }, - { "nextafterf", "(FF)F", jnextafterf }, - { "pow", "(DD)D", jpow }, - { "rint", "(D)D", jrint }, - { "sin", "(D)D", jsin }, - { "sinh", "(D)D", jsinh }, - { "sqrt", "(D)D", jsqrt2 }, - { "tan", "(D)D", jtan }, - { "tanh", "(D)D", jtanh }, + { "IEEEremainder", "(DD)D", (void*)jieee_remainder }, + { "acos", "(D)D", (void*)jacos }, + { "asin", "(D)D", (void*)jasin }, + { "atan", "(D)D", (void*)jatan }, + { "atan2", "(DD)D", (void*)jatan2 }, + { "cbrt", "(D)D", (void*)jcbrt }, + { "ceil", "(D)D", (void*)jceil }, + { "cos", "(D)D", (void*)jcos }, + { "cosh", "(D)D", (void*)jcosh }, + { "exp", "(D)D", (void*)jexp }, + { "expm1", "(D)D", (void*)jexpm1 }, + { "floor", "(D)D", (void*)jfloor }, + { "hypot", "(DD)D", (void*)jhypot }, + { "log", "(D)D", (void*)jlog }, + { "log10", "(D)D", (void*)jlog10 }, + { "log1p", "(D)D", (void*)jlog1p }, + { "nextafter", "(DD)D", (void*)jnextafter }, + { "nextafterf", "(FF)F", (void*)jnextafterf }, + { "pow", "(DD)D", (void*)jpow }, + { "rint", "(D)D", (void*)jrint }, + { "sin", "(D)D", (void*)jsin }, + { "sinh", "(D)D", (void*)jsinh }, + { "sqrt", "(D)D", (void*)jsqrt2 }, + { "tan", "(D)D", (void*)jtan }, + { "tanh", "(D)D", (void*)jtanh }, }; int register_java_lang_StrictMath(JNIEnv* env) { diff --git a/luni/src/main/native/java_net_InetAddress.cpp b/luni/src/main/native/java_net_InetAddress.cpp index 2fc575a..0bfe895 100644 --- a/luni/src/main/native/java_net_InetAddress.cpp +++ b/luni/src/main/native/java_net_InetAddress.cpp @@ -34,7 +34,7 @@ static jclass byteArrayClass = NULL; -static jstring InetAddress_gethostname(JNIEnv* env, jobject obj) +static jstring InetAddress_gethostname(JNIEnv* env, jclass) { char name[256]; int r = gethostname(name, 256); @@ -59,7 +59,7 @@ static void logIpString(struct addrinfo* ai, const char* name) } } #else -static inline void logIpString(struct addrinfo* ai, const char* name) +static inline void logIpString(struct addrinfo*, const char*) { } #endif @@ -150,7 +150,7 @@ static jobjectArray InetAddress_getaddrinfoImpl(JNIEnv* env, const char* name) { return addressArray; } -jobjectArray InetAddress_getaddrinfo(JNIEnv* env, jobject obj, jstring javaName) { +jobjectArray InetAddress_getaddrinfo(JNIEnv* env, jclass, jstring javaName) { if (javaName == NULL) { jniThrowNullPointerException(env, NULL); return NULL; @@ -170,7 +170,7 @@ jobjectArray InetAddress_getaddrinfo(JNIEnv* env, jobject obj, jstring javaName) * @return the hostname. * @throws UnknownHostException: the IP address has no associated hostname. */ -static jstring InetAddress_getnameinfo(JNIEnv* env, jobject obj, +static jstring InetAddress_getnameinfo(JNIEnv* env, jclass, jbyteArray javaAddress) { if (javaAddress == NULL) { diff --git a/luni/src/main/native/java_net_NetworkInterface.cpp b/luni/src/main/native/java_net_NetworkInterface.cpp index 16b4619..8abc846 100644 --- a/luni/src/main/native/java_net_NetworkInterface.cpp +++ b/luni/src/main/native/java_net_NetworkInterface.cpp @@ -184,7 +184,7 @@ static jboolean hasFlag(JNIEnv* env, jstring name, int flag) { return (ifr.ifr_flags & flag) != 0; } -static jbyteArray getHardwareAddressImpl(JNIEnv* env, jclass, jstring name, jint index) { +static jbyteArray getHardwareAddressImpl(JNIEnv* env, jclass, jstring name) { ifreq ifr; if (!doIoctl(env, name, SIOCGIFHWADDR, ifr)) { return NULL; @@ -205,36 +205,36 @@ static jbyteArray getHardwareAddressImpl(JNIEnv* env, jclass, jstring name, jint return result; } -static jint getMTUImpl(JNIEnv* env, jclass, jstring name, jint index) { +static jint getMTUImpl(JNIEnv* env, jclass, jstring name) { ifreq ifr; doIoctl(env, name, SIOCGIFMTU, ifr); // May throw. return ifr.ifr_mtu; } -static jboolean isLoopbackImpl(JNIEnv* env, jclass, jstring name, jint index) { +static jboolean isLoopbackImpl(JNIEnv* env, jclass, jstring name) { return hasFlag(env, name, IFF_LOOPBACK); } -static jboolean isPointToPointImpl(JNIEnv* env, jclass, jstring name, jint index) { +static jboolean isPointToPointImpl(JNIEnv* env, jclass, jstring name) { return hasFlag(env, name, IFF_POINTOPOINT); // Unix API typo! } -static jboolean isUpImpl(JNIEnv* env, jclass, jstring name, jint index) { +static jboolean isUpImpl(JNIEnv* env, jclass, jstring name) { return hasFlag(env, name, IFF_UP); } -static jboolean supportsMulticastImpl(JNIEnv* env, jclass, jstring name, jint index) { +static jboolean supportsMulticastImpl(JNIEnv* env, jclass, jstring name) { return hasFlag(env, name, IFF_MULTICAST); } static JNINativeMethod gMethods[] = { { "getAllInterfaceAddressesImpl", "()[Ljava/net/InterfaceAddress;", (void*) getAllInterfaceAddressesImpl }, - { "getHardwareAddressImpl", "(Ljava/lang/String;I)[B", (void*) getHardwareAddressImpl }, - { "getMTUImpl", "(Ljava/lang/String;I)I", (void*) getMTUImpl }, - { "isLoopbackImpl", "(Ljava/lang/String;I)Z", (void*) isLoopbackImpl }, - { "isPointToPointImpl", "(Ljava/lang/String;I)Z", (void*) isPointToPointImpl }, - { "isUpImpl", "(Ljava/lang/String;I)Z", (void*) isUpImpl }, - { "supportsMulticastImpl", "(Ljava/lang/String;I)Z", (void*) supportsMulticastImpl }, + { "getHardwareAddressImpl", "(Ljava/lang/String;)[B", (void*) getHardwareAddressImpl }, + { "getMTUImpl", "(Ljava/lang/String;)I", (void*) getMTUImpl }, + { "isLoopbackImpl", "(Ljava/lang/String;)Z", (void*) isLoopbackImpl }, + { "isPointToPointImpl", "(Ljava/lang/String;)Z", (void*) isPointToPointImpl }, + { "isUpImpl", "(Ljava/lang/String;)Z", (void*) isUpImpl }, + { "supportsMulticastImpl", "(Ljava/lang/String;)Z", (void*) supportsMulticastImpl }, }; int register_java_net_NetworkInterface(JNIEnv* env) { return jniRegisterNativeMethods(env, "java/net/NetworkInterface", gMethods, NELEM(gMethods)); diff --git a/luni/src/main/native/java_util_zip_Adler32.c b/luni/src/main/native/java_util_zip_Adler32.cpp index 4410e5b..3dc1802 100644 --- a/luni/src/main/native/java_util_zip_Adler32.c +++ b/luni/src/main/native/java_util_zip_Adler32.cpp @@ -15,37 +15,29 @@ * limitations under the License. */ +#include "JNIHelp.h" #include "jni.h" -#include "hy2sie.h" #include "zlib.h" -#include "sieb.h" -JNIEXPORT jlong JNICALL -Java_java_util_zip_Adler32_updateImpl (JNIEnv * env, jobject recv, - jbyteArray buf, int off, int len, - jlong crc) -{ - jbyte* b = (*env)->GetPrimitiveArrayCritical (env, buf, NULL); - if (b == NULL) { - return 0; - } - jlong result = (jlong) adler32 ((uLong) crc, (Bytef *) (b + off), (uInt) len); - (*env)->ReleasePrimitiveArrayCritical (env, buf, b, JNI_ABORT); - - return result; +static jlong Adler32_updateImpl(JNIEnv* env, jobject, jbyteArray buf, int off, int len, jlong crc) { + jbyte* b = (jbyte*) env->GetPrimitiveArrayCritical(buf, NULL); + if (b == NULL) { + jniThrowNullPointerException(env, NULL); + return 0; + } + jlong result = (jlong) adler32((uLong) crc, (Bytef *) (b + off), (uInt) len); + env->ReleasePrimitiveArrayCritical(buf, b, JNI_ABORT); + return result; } -JNIEXPORT jlong JNICALL -Java_java_util_zip_Adler32_updateByteImpl (JNIEnv * env, jobject recv, - jint val, jlong crc) -{ - Bytef bytefVal = val; - return adler32 ((uLong) crc, (Bytef *) (&bytefVal), 1); +static jlong Adler32_updateByteImpl(JNIEnv*, jobject, jint val, jlong crc) { + Bytef bytefVal = val; + return adler32((uLong) crc, (Bytef *) (&bytefVal), 1); } static JNINativeMethod gMethods[] = { - { "updateImpl", "([BIIJ)J", Java_java_util_zip_Adler32_updateImpl }, - { "updateByteImpl", "(IJ)J", Java_java_util_zip_Adler32_updateByteImpl }, + { "updateImpl", "([BIIJ)J", (void*) Adler32_updateImpl }, + { "updateByteImpl", "(IJ)J", (void*) Adler32_updateByteImpl }, }; int register_java_util_zip_Adler32(JNIEnv* env) { return jniRegisterNativeMethods(env, "java/util/zip/Adler32", gMethods, NELEM(gMethods)); diff --git a/luni/src/main/native/java_util_zip_CRC32.c b/luni/src/main/native/java_util_zip_CRC32.cpp index 95369a2..7b1bd29 100644 --- a/luni/src/main/native/java_util_zip_CRC32.c +++ b/luni/src/main/native/java_util_zip_CRC32.cpp @@ -15,35 +15,28 @@ * limitations under the License. */ -#include "hy2sie.h" -#include "sieb.h" - +#include "JNIHelp.h" +#include "jni.h" #include "zlib.h" -JNIEXPORT jlong JNICALL -Java_java_util_zip_CRC32_updateImpl (JNIEnv * env, jobject recv, - jbyteArray buf, int off, int len, - jlong crc) -{ - jbyte* b = ((*env)->GetPrimitiveArrayCritical (env, buf, 0)); - if (b == NULL) { - return -1; - } - jlong result = crc32 ((uLong) crc, (Bytef *) (b + off), (uInt) len); - ((*env)->ReleasePrimitiveArrayCritical (env, buf, b, JNI_ABORT)); - return result; +static jlong CRC32_updateImpl(JNIEnv* env, jobject, jbyteArray buf, int off, int len, jlong crc) { + jbyte* b = (jbyte*) env->GetPrimitiveArrayCritical(buf, NULL); + if (b == NULL) { + jniThrowNullPointerException(env, NULL); + return 0; + } + jlong result = crc32((uLong) crc, (Bytef *) (b + off), (uInt) len); + env->ReleasePrimitiveArrayCritical(buf, b, JNI_ABORT); + return result; } -JNIEXPORT jlong JNICALL -Java_java_util_zip_CRC32_updateByteImpl (JNIEnv * env, jobject recv, - jbyte val, jlong crc) -{ - return crc32 ((uLong) crc, (Bytef *) (&val), 1); +static jlong CRC32_updateByteImpl(JNIEnv*, jobject, jbyte val, jlong crc) { + return crc32((uLong) crc, (Bytef *) (&val), 1); } static JNINativeMethod gMethods[] = { - { "updateImpl", "([BIIJ)J", Java_java_util_zip_CRC32_updateImpl }, - { "updateByteImpl", "(BJ)J", Java_java_util_zip_CRC32_updateByteImpl }, + { "updateImpl", "([BIIJ)J", (void*) CRC32_updateImpl }, + { "updateByteImpl", "(BJ)J", (void*) CRC32_updateByteImpl }, }; int register_java_util_zip_CRC32(JNIEnv* env) { return jniRegisterNativeMethods(env, "java/util/zip/CRC32", gMethods, NELEM(gMethods)); diff --git a/luni/src/main/native/java_util_zip_Deflater.c b/luni/src/main/native/java_util_zip_Deflater.c deleted file mode 100644 index 59c7433..0000000 --- a/luni/src/main/native/java_util_zip_Deflater.c +++ /dev/null @@ -1,304 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "hy2sie.h" - -#include "zlib.h" -#include "zip.h" -#include "jni.h" - -#ifndef HY_ZIP_API -void zfree PROTOTYPE ((void *opaque, void *address)); -void *zalloc PROTOTYPE ((void *opaque, U_32 items, U_32 size)); -#endif - - -static struct { - jfieldID inRead; - jfieldID finished; -} gCachedFields; - - -JNIEXPORT void JNICALL -Java_java_util_zip_Deflater_setDictionaryImpl (JNIEnv * env, jobject recv, - jbyteArray dict, int off, - int len, jlong handle) -{ - PORT_ACCESS_FROM_ENV (env); - int err = 0; - unsigned char *dBytes; - JCLZipStream *stream = (JCLZipStream *) ((IDATA) handle); - - dBytes = jclmem_allocate_memory (env, len); - if (dBytes == NULL) - { - throwNewOutOfMemoryError (env, ""); - return; - } - (*env)->GetByteArrayRegion (env, dict, off, len, (mcSignednessBull)dBytes); - err = deflateSetDictionary (stream->stream, (Bytef *) dBytes, len); - if (err != Z_OK) - { - jclmem_free_memory (env, dBytes); - THROW_ZIP_EXCEPTION(env, err, IllegalArgumentException); - return; - } - stream->dict = (U_8*) dBytes; -} - -JNIEXPORT jlong JNICALL -Java_java_util_zip_Deflater_getTotalInImpl (JNIEnv * env, jobject recv, - jlong handle) -{ - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - return stream->stream->total_in; -} - -JNIEXPORT jlong JNICALL -Java_java_util_zip_Deflater_getTotalOutImpl (JNIEnv * env, jobject recv, - jlong handle) -{ - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - return stream->stream->total_out; -} - -JNIEXPORT jint JNICALL -Java_java_util_zip_Deflater_getAdlerImpl (JNIEnv * env, jobject recv, - jlong handle) -{ - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - - return stream->stream->adler; -} - -/* Create a new stream . This stream cannot be used until it has been properly initialized. */ -JNIEXPORT jlong JNICALL -Java_java_util_zip_Deflater_createStream (JNIEnv * env, jobject recv, - jint level, jint strategy, - jboolean noHeader) -{ - PORT_ACCESS_FROM_ENV (env); - JCLZipStream *jstream; - z_stream *stream; - int err = 0; - // BEGIN android-changed - int wbits = 12; // Was 15, made it 12 to reduce memory consumption. Use MAX - // for fastest. - int mlevel = 5; // Was 9, made it 5 to reduce memory consumption. Might result - // in out-of-memory problems according to some web pages. The - // ZLIB docs are a bit vague, unfortunately. The default - // results in 2 x 128K being allocated per Deflater, which is - // not acceptable. - // END android-changed -#ifdef HY_ZIP_API - VMI_ACCESS_FROM_ENV (env); - VMIZipFunctionTable *zipFuncs; - zipFuncs = (*VMI)->GetZipFunctions(VMI); -#endif - - /*Allocate mem for wrapped struct */ - jstream = jclmem_allocate_memory (env, sizeof (JCLZipStream)); - if (jstream == NULL) - { - throwNewOutOfMemoryError (env, ""); - return -1; - } - /*Allocate the z_stream */ - stream = jclmem_allocate_memory (env, sizeof (z_stream)); - if (stream == NULL) - { - jclmem_free_memory (env, jstream); - throwNewOutOfMemoryError (env, ""); - return -1; - } - stream->opaque = (void *) privatePortLibrary; - stream->zalloc = zalloc; - stream->zfree = zfree; - jstream->stream = stream; - jstream->dict = NULL; - jstream->inaddr = NULL; - - /*Unable to find official doc that this is the way to avoid zlib header use. However doc in zipsup.c claims it is so */ - if (noHeader) - wbits = wbits / -1; - err = deflateInit2 (stream, level, Z_DEFLATED, /*Only supported ZLIB method */ - wbits, /*Window bits to use. 15 is fastest but consumes the most memory */ - // BEGIN android-changed - mlevel, /*Memory allocation for internal compression state. 9 uses the most. */ - // END android-changed - strategy); - if (err != Z_OK) { - THROW_ZIP_EXCEPTION(env, err, IllegalArgumentException); - return -1; - } - - return (jlong) ((IDATA) jstream); -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Deflater_setInputImpl (JNIEnv * env, jobject recv, - jbyteArray buf, jint off, jint len, - jlong handle) -{ - PORT_ACCESS_FROM_ENV (env); - - JCLZipStream* stream = (JCLZipStream *) ((IDATA) handle); - if (stream->inaddr != NULL) { - /* Input has already been provided, free the old buffer. */ - jclmem_free_memory (env, stream->inaddr); - } - stream->inaddr = jclmem_allocate_memory (env, len); - if (stream->inaddr == NULL) { - throwNewOutOfMemoryError (env, ""); - return; - } - (*env)->GetByteArrayRegion(env, buf, off, len, (jbyte*) stream->inaddr); - stream->stream->next_in = (Bytef *) stream->inaddr; - stream->stream->avail_in = len; -} - -JNIEXPORT jint JNICALL -Java_java_util_zip_Deflater_deflateImpl (JNIEnv * env, jobject recv, - jbyteArray buf, int off, int len, - jlong handle, int flushParm) -{ - jbyte *out; - JCLZipStream *stream; - jint err = 0; - jint sin, sout, inBytes = 0; - - /* We need to get the number of bytes already read */ - inBytes = - ((*env)-> - GetIntField (env, recv, - gCachedFields.inRead)); - - stream = (JCLZipStream *) ((IDATA) handle); - stream->stream->avail_out = len; - sin = stream->stream->total_in; - sout = stream->stream->total_out; - out = ((*env)->GetPrimitiveArrayCritical (env, buf, 0)); - if (out == NULL) { - return -1; - } - stream->stream->next_out = (Bytef *) out + off; - err = deflate (stream->stream, flushParm); - ((*env)->ReleasePrimitiveArrayCritical (env, buf, out, 0)); - if (err != Z_OK) { - if (err == Z_MEM_ERROR) { - throwNewOutOfMemoryError(env, ""); - return 0; - } - if (err == Z_STREAM_END) - { - ((*env)-> - SetBooleanField (env, recv, - gCachedFields.finished, - JNI_TRUE)); - return stream->stream->total_out - sout; - } - } - if (flushParm != Z_FINISH) - { - /* Need to update the number of input bytes read. */ - ((*env)-> - SetIntField (env, recv, - gCachedFields.inRead, - (jint) stream->stream->total_in - sin + inBytes)); - } - return stream->stream->total_out - sout; -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Deflater_endImpl (JNIEnv * env, jobject recv, jlong handle) -{ - PORT_ACCESS_FROM_ENV (env); - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - - deflateEnd (stream->stream); - if (stream->inaddr != NULL) - jclmem_free_memory (env, stream->inaddr); - if (stream->dict != NULL) - jclmem_free_memory (env, stream->dict); - jclmem_free_memory (env, stream->stream); - jclmem_free_memory (env, stream); -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Deflater_resetImpl (JNIEnv * env, jobject recv, - jlong handle) -{ - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - deflateReset (stream->stream); -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Deflater_setLevelsImpl (JNIEnv * env, jobject recv, - int level, int strategy, - jlong handle) -{ - JCLZipStream *stream; - jbyte b = 0; - int err = 0; - - if (handle == -1) - { - throwNewIllegalStateException (env, ""); - return; - } - stream = (JCLZipStream *) ((IDATA) handle); - stream->stream->next_out = (Bytef *) & b; - err = deflateParams (stream->stream, level, strategy); - if (err != Z_OK) { - THROW_ZIP_EXCEPTION(env, err, IllegalStateException); - } -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Deflater_oneTimeInitialization (JNIEnv * env, jclass clazz) -{ - memset(&gCachedFields, 0, sizeof(gCachedFields)); - gCachedFields.inRead = (*env)->GetFieldID (env, clazz, "inRead", "I"); - gCachedFields.finished = (*env)->GetFieldID (env, clazz, "finished", "Z"); -} - -static JNINativeMethod gMethods[] = { - { "setDictionaryImpl", "([BIIJ)V", Java_java_util_zip_Deflater_setDictionaryImpl }, - { "getTotalInImpl", "(J)J", Java_java_util_zip_Deflater_getTotalInImpl }, - { "getTotalOutImpl", "(J)J", Java_java_util_zip_Deflater_getTotalOutImpl }, - { "getAdlerImpl", "(J)I", Java_java_util_zip_Deflater_getAdlerImpl }, - { "createStream", "(IIZ)J", Java_java_util_zip_Deflater_createStream }, - { "setInputImpl", "([BIIJ)V", Java_java_util_zip_Deflater_setInputImpl }, - { "deflateImpl", "([BIIJI)I", Java_java_util_zip_Deflater_deflateImpl }, - { "endImpl", "(J)V", Java_java_util_zip_Deflater_endImpl }, - { "resetImpl", "(J)V", Java_java_util_zip_Deflater_resetImpl }, - { "setLevelsImpl", "(IIJ)V", Java_java_util_zip_Deflater_setLevelsImpl }, - { "oneTimeInitialization", "()V", Java_java_util_zip_Deflater_oneTimeInitialization }, -}; -int register_java_util_zip_Deflater(JNIEnv* env) { - return jniRegisterNativeMethods(env, "java/util/zip/Deflater", gMethods, NELEM(gMethods)); -} diff --git a/luni/src/main/native/java_util_zip_Deflater.cpp b/luni/src/main/native/java_util_zip_Deflater.cpp new file mode 100644 index 0000000..c449087 --- /dev/null +++ b/luni/src/main/native/java_util_zip_Deflater.cpp @@ -0,0 +1,148 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "zip.h" + +static struct { + jfieldID inRead; + jfieldID finished; +} gCachedFields; + +static void Deflater_setDictionaryImpl(JNIEnv* env, jobject, jbyteArray dict, int off, int len, jlong handle) { + toNativeZipStream(handle)->setDictionary(env, dict, off, len, false); +} + +static jlong Deflater_getTotalInImpl(JNIEnv*, jobject, jlong handle) { + return toNativeZipStream(handle)->stream.total_in; +} + +static jlong Deflater_getTotalOutImpl(JNIEnv*, jobject, jlong handle) { + return toNativeZipStream(handle)->stream.total_out; +} + +static jint Deflater_getAdlerImpl(JNIEnv*, jobject, jlong handle) { + return toNativeZipStream(handle)->stream.adler; +} + +/* Create a new stream . This stream cannot be used until it has been properly initialized. */ +static jlong Deflater_createStream(JNIEnv * env, jobject, jint level, jint strategy, jboolean noHeader) { + UniquePtr<NativeZipStream> jstream(new NativeZipStream); + if (jstream.get() == NULL) { + jniThrowOutOfMemoryError(env, NULL); + return -1; + } + + int wbits = 12; // Was 15, made it 12 to reduce memory consumption. Use MAX for fastest. + int mlevel = 5; // Was 9, made it 5 to reduce memory consumption. Might result + // in out-of-memory problems according to some web pages. The + // ZLIB docs are a bit vague, unfortunately. The default + // results in 2 x 128K being allocated per Deflater, which is + // not acceptable. + /*Unable to find official doc that this is the way to avoid zlib header use. However doc in zipsup.c claims it is so */ + if (noHeader) { + wbits = wbits / -1; + } + int err = deflateInit2(&jstream->stream, level, Z_DEFLATED, wbits, mlevel, strategy); + if (err != Z_OK) { + throwExceptionForZlibError(env, "java/lang/IllegalArgumentException", err); + return -1; + } + return reinterpret_cast<uintptr_t>(jstream.release()); +} + +static void Deflater_setInputImpl(JNIEnv* env, jobject, jbyteArray buf, jint off, jint len, jlong handle) { + toNativeZipStream(handle)->setInput(env, buf, off, len); +} + +static jint Deflater_deflateImpl(JNIEnv* env, jobject recv, jbyteArray buf, int off, int len, jlong handle, int flushParm) { + /* We need to get the number of bytes already read */ + jint inBytes = env->GetIntField(recv, gCachedFields.inRead); + + NativeZipStream* stream = toNativeZipStream(handle); + stream->stream.avail_out = len; + jint sin = stream->stream.total_in; + jint sout = stream->stream.total_out; + jbyte* out = (jbyte*) env->GetPrimitiveArrayCritical(buf, NULL); + if (out == NULL) { + return -1; + } + stream->stream.next_out = (Bytef *) out + off; + int err = deflate(&stream->stream, flushParm); + env->ReleasePrimitiveArrayCritical(buf, out, 0); + if (err != Z_OK) { + if (err == Z_MEM_ERROR) { + jniThrowOutOfMemoryError(env, NULL); + return 0; + } + if (err == Z_STREAM_END) { + env->SetBooleanField(recv, gCachedFields.finished, JNI_TRUE); + return stream->stream.total_out - sout; + } + } + if (flushParm != Z_FINISH) { + /* Need to update the number of input bytes read. */ + env->SetIntField(recv, gCachedFields.inRead, (jint) stream->stream.total_in - sin + inBytes); + } + return stream->stream.total_out - sout; +} + +static void Deflater_endImpl(JNIEnv*, jobject, jlong handle) { + NativeZipStream* stream = toNativeZipStream(handle); + deflateEnd(&stream->stream); + delete stream; +} + +static void Deflater_resetImpl(JNIEnv* env, jobject, jlong handle) { + NativeZipStream* stream = toNativeZipStream(handle); + int err = deflateReset(&stream->stream); + if (err != Z_OK) { + throwExceptionForZlibError(env, "java/lang/IllegalArgumentException", err); + } +} + +static void Deflater_setLevelsImpl(JNIEnv* env, jobject, int level, int strategy, jlong handle) { + if (handle == -1) { + jniThrowException(env, "java/lang/IllegalStateException", NULL); + return; + } + NativeZipStream* stream = toNativeZipStream(handle); + jbyte b = 0; + stream->stream.next_out = (Bytef*) &b; + int err = deflateParams(&stream->stream, level, strategy); + if (err != Z_OK) { + throwExceptionForZlibError(env, "java/lang/IllegalStateException", err); + } +} + +static JNINativeMethod gMethods[] = { + { "createStream", "(IIZ)J", (void*) Deflater_createStream }, + { "deflateImpl", "([BIIJI)I", (void*) Deflater_deflateImpl }, + { "endImpl", "(J)V", (void*) Deflater_endImpl }, + { "getAdlerImpl", "(J)I", (void*) Deflater_getAdlerImpl }, + { "getTotalInImpl", "(J)J", (void*) Deflater_getTotalInImpl }, + { "getTotalOutImpl", "(J)J", (void*) Deflater_getTotalOutImpl }, + { "resetImpl", "(J)V", (void*) Deflater_resetImpl }, + { "setDictionaryImpl", "([BIIJ)V", (void*) Deflater_setDictionaryImpl }, + { "setInputImpl", "([BIIJ)V", (void*) Deflater_setInputImpl }, + { "setLevelsImpl", "(IIJ)V", (void*) Deflater_setLevelsImpl }, +}; +int register_java_util_zip_Deflater(JNIEnv* env) { + jclass deflaterClass = env->FindClass("java/util/zip/Deflater"); + gCachedFields.finished = env->GetFieldID(deflaterClass, "finished", "Z"); + gCachedFields.inRead = env->GetFieldID(deflaterClass, "inRead", "I"); + return jniRegisterNativeMethods(env, "java/util/zip/Deflater", gMethods, NELEM(gMethods)); +} diff --git a/luni/src/main/native/java_util_zip_Inflater.c b/luni/src/main/native/java_util_zip_Inflater.c deleted file mode 100644 index 6281081..0000000 --- a/luni/src/main/native/java_util_zip_Inflater.c +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "hy2sie.h" -#include "zip.h" - -#include "zlib.h" -#include <memory.h> -#define jclmem_allocate_memory(env, byteCount) sieb_malloc(env, byteCount) -#define jclmem_free_memory(env, pointer) sieb_free(env, pointer) - -#include <fcntl.h> - -void throwNewDataFormatException (JNIEnv * env, const char *message); - -void zfree PROTOTYPE ((void *opaque, void *address)); -void *zalloc PROTOTYPE ((void *opaque, U_32 items, U_32 size)); - - -static struct { - jfieldID inRead; - jfieldID finished; - jfieldID needsDictionary; -} gCachedFields; - - - -/* Create a new stream . This stream cannot be used until it has been properly initialized. */ -JNIEXPORT jlong JNICALL -Java_java_util_zip_Inflater_createStream (JNIEnv * env, jobject recv, - jboolean noHeader) -{ - PORT_ACCESS_FROM_ENV (env); - - JCLZipStream *jstream; - z_stream *stream; - int err = 0; - int wbits = 15; /*Use MAX for fastest */ -#ifdef HY_ZIP_API - VMI_ACCESS_FROM_ENV (env); - VMIZipFunctionTable *zipFuncs; - zipFuncs = (*VMI)->GetZipFunctions(VMI); -#endif - - /*Allocate mem for wrapped struct */ - jstream = jclmem_allocate_memory (env, sizeof (JCLZipStream)); - if (jstream == NULL) - { - throwNewOutOfMemoryError (env, ""); - return -1; - } - - /*Allocate the z_stream */ - stream = jclmem_allocate_memory (env, sizeof (z_stream)); - if (stream == NULL) - { - jclmem_free_memory (env, jstream); - throwNewOutOfMemoryError (env, ""); - return -1; - } - stream->opaque = (void *) privatePortLibrary; - stream->zalloc = zalloc; - stream->zfree = zfree; - stream->adler = 1; - jstream->stream = stream; - jstream->dict = NULL; - jstream->inaddr = NULL; - jstream->inCap = 0; - - /* - * In the range 8..15 for checked, or -8..-15 for unchecked inflate. Unchecked - * is appropriate for formats like zip that do their own validity checking. - */ - if (noHeader) - wbits = wbits / -1; - err = inflateInit2 (stream, wbits); /*Window bits to use. 15 is fastest but consumes the most memory */ - - if (err != Z_OK) - { - jclmem_free_memory (env, stream); - jclmem_free_memory (env, jstream); - THROW_ZIP_EXCEPTION(env, err, IllegalArgumentException); - return -1; - } - - return (jlong) ((IDATA) jstream); -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Inflater_setInputImpl (JNIEnv * env, jobject recv, - jbyteArray buf, jint off, jint len, - jlong handle) -{ - PORT_ACCESS_FROM_ENV (env); - - JCLZipStream *stream = (JCLZipStream *) ((IDATA) handle); - if (stream->inaddr != NULL) { - /* Input has already been provided, free the old buffer. */ - jclmem_free_memory (env, stream->inaddr); - } - U_8* baseAddr = jclmem_allocate_memory (env, len); - if (baseAddr == NULL) { - throwNewOutOfMemoryError (env, ""); - return; - } - stream->inaddr = baseAddr; - stream->stream->next_in = (Bytef *) baseAddr; - stream->stream->avail_in = len; - (*env)->GetByteArrayRegion(env, buf, off, len, (jbyte*) baseAddr); -} - -JNIEXPORT jint JNICALL -Java_java_util_zip_Inflater_setFileInputImpl (JNIEnv * env, jobject recv, - jobject javaFileDescriptor, jlong off, jint len, jlong handle) -{ - PORT_ACCESS_FROM_ENV (env); - - U_8 * baseAddr; - JCLZipStream * stream = (JCLZipStream *) ((IDATA) handle); - - if (stream->inCap < len) { - // No input buffer as yet (or one that is too small). - jclmem_free_memory(env, stream->inaddr); - baseAddr = jclmem_allocate_memory(env, len); - if (baseAddr == NULL) - { - throwNewOutOfMemoryError(env, ""); - return -1; - } - stream->inaddr = baseAddr; - } - stream->stream->next_in = (Bytef *) stream->inaddr; - stream->stream->avail_in = len; - - int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor); - lseek(fd, off, SEEK_SET); - int cnt = read(fd, stream->inaddr, len); - - return cnt; -} - -JNIEXPORT jint JNICALL -Java_java_util_zip_Inflater_inflateImpl (JNIEnv * env, jobject recv, - jbyteArray buf, int off, int len, - jlong handle) -{ - jbyte *out; - JCLZipStream *stream = (JCLZipStream *) ((IDATA) handle); - jint err = 0; - jfieldID fid = 0, fid2 = 0; - jint sin, sout, inBytes = 0; - - /* We need to get the number of bytes already read */ - fid = gCachedFields.inRead; - inBytes = ((*env)->GetIntField (env, recv, fid)); - - stream->stream->avail_out = len; - sin = stream->stream->total_in; - sout = stream->stream->total_out; - out = ((*env)->GetPrimitiveArrayCritical (env, buf, 0)); - if (out == NULL) { - throwNewOutOfMemoryError(env, ""); - return -1; - } - stream->stream->next_out = (Bytef *) out + off; - err = inflate (stream->stream, Z_SYNC_FLUSH); - ((*env)->ReleasePrimitiveArrayCritical (env, buf, out, 0)); - - if (err != Z_OK) - { - if(err == Z_STREAM_ERROR) { - return 0; - } - if (err == Z_STREAM_END || err == Z_NEED_DICT) - { - ((*env)->SetIntField (env, recv, fid, (jint) stream->stream->total_in - sin + inBytes)); /* Update inRead */ - if (err == Z_STREAM_END) - fid2 = gCachedFields.finished; - else - fid2 = gCachedFields.needsDictionary; - - ((*env)->SetBooleanField (env, recv, fid2, JNI_TRUE)); - return stream->stream->total_out - sout; - } - else - { - THROW_ZIP_EXCEPTION(env, err, DataFormatException); - return -1; - } - } - - /* Need to update the number of input bytes read. Is there a better way - * (Maybe global the fid then delete when end is called)? - */ - ((*env)-> - SetIntField (env, recv, fid, - (jint) stream->stream->total_in - sin + inBytes)); - - return stream->stream->total_out - sout; -} - -JNIEXPORT jint JNICALL -Java_java_util_zip_Inflater_getAdlerImpl (JNIEnv * env, jobject recv, - jlong handle) -{ - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - - return stream->stream->adler; -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Inflater_endImpl (JNIEnv * env, jobject recv, jlong handle) -{ - PORT_ACCESS_FROM_ENV (env); - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - inflateEnd (stream->stream); - if (stream->inaddr != NULL) /*Input has been provided, free the buffer */ - jclmem_free_memory (env, stream->inaddr); - if (stream->dict != NULL) - jclmem_free_memory (env, stream->dict); - jclmem_free_memory (env, stream->stream); - jclmem_free_memory (env, stream); -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Inflater_setDictionaryImpl (JNIEnv * env, jobject recv, - jbyteArray dict, int off, - int len, jlong handle) -{ - PORT_ACCESS_FROM_ENV (env); - int err = 0; - U_8 *dBytes; - JCLZipStream *stream = (JCLZipStream *) ((IDATA) handle); - - dBytes = jclmem_allocate_memory (env, len); - if (dBytes == NULL) - { - throwNewOutOfMemoryError (env, ""); - return; - } - (*env)->GetByteArrayRegion (env, dict, off, len, (mcSignednessBull)dBytes); - err = inflateSetDictionary (stream->stream, (Bytef *) dBytes, len); - if (err != Z_OK) - { - jclmem_free_memory (env, dBytes); - THROW_ZIP_EXCEPTION(env, err, IllegalArgumentException); - return; - } - stream->dict = dBytes; -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Inflater_resetImpl (JNIEnv * env, jobject recv, - jlong handle) -{ - JCLZipStream *stream; - int err = 0; - stream = (JCLZipStream *) ((IDATA) handle); - - err = inflateReset (stream->stream); - if (err != Z_OK) - { - THROW_ZIP_EXCEPTION(env, err, IllegalArgumentException); - return; - } -} - -/** - * Throw java.util.zip.DataFormatException - */ -void -throwNewDataFormatException (JNIEnv * env, const char *message) -{ - jniThrowException(env, "java/util/zip/DataFormatException", message); -} - -JNIEXPORT jlong JNICALL -Java_java_util_zip_Inflater_getTotalOutImpl (JNIEnv * env, jobject recv, - jlong handle) -{ - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - return stream->stream->total_out; - -} - -JNIEXPORT jlong JNICALL -Java_java_util_zip_Inflater_getTotalInImpl (JNIEnv * env, jobject recv, - jlong handle) -{ - JCLZipStream *stream; - - stream = (JCLZipStream *) ((IDATA) handle); - return stream->stream->total_in; -} - -JNIEXPORT void JNICALL -Java_java_util_zip_Inflater_oneTimeInitialization (JNIEnv * env, jclass clazz) -{ - memset(&gCachedFields, 0, sizeof(gCachedFields)); - gCachedFields.inRead = (*env)->GetFieldID (env, clazz, "inRead", "I"); - gCachedFields.finished = (*env)->GetFieldID (env, clazz, "finished", "Z"); - gCachedFields.needsDictionary = (*env)->GetFieldID (env, clazz, "needsDictionary", "Z"); -} - -static JNINativeMethod gMethods[] = { - { "createStream", "(Z)J", Java_java_util_zip_Inflater_createStream }, - { "setInputImpl", "([BIIJ)V", Java_java_util_zip_Inflater_setInputImpl }, - { "setFileInputImpl", "(Ljava/io/FileDescriptor;JIJ)I", Java_java_util_zip_Inflater_setFileInputImpl }, - { "inflateImpl", "([BIIJ)I", Java_java_util_zip_Inflater_inflateImpl }, - { "getAdlerImpl", "(J)I", Java_java_util_zip_Inflater_getAdlerImpl }, - { "endImpl", "(J)V", Java_java_util_zip_Inflater_endImpl }, - { "setDictionaryImpl", "([BIIJ)V", Java_java_util_zip_Inflater_setDictionaryImpl }, - { "resetImpl", "(J)V", Java_java_util_zip_Inflater_resetImpl }, - { "getTotalOutImpl", "(J)J", Java_java_util_zip_Inflater_getTotalOutImpl }, - { "getTotalInImpl", "(J)J", Java_java_util_zip_Inflater_getTotalInImpl }, - { "oneTimeInitialization", "()V", Java_java_util_zip_Inflater_oneTimeInitialization }, -}; -int register_java_util_zip_Inflater(JNIEnv* env) { - return jniRegisterNativeMethods(env, "java/util/zip/Inflater", gMethods, NELEM(gMethods)); -} diff --git a/luni/src/main/native/java_util_zip_Inflater.cpp b/luni/src/main/native/java_util_zip_Inflater.cpp new file mode 100644 index 0000000..e07de72 --- /dev/null +++ b/luni/src/main/native/java_util_zip_Inflater.cpp @@ -0,0 +1,160 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "zip.h" + +static struct { + jfieldID inRead; + jfieldID finished; + jfieldID needsDictionary; +} gCachedFields; + +/* Create a new stream . This stream cannot be used until it has been properly initialized. */ +static jlong Inflater_createStream(JNIEnv* env, jobject, jboolean noHeader) { + UniquePtr<NativeZipStream> jstream(new NativeZipStream); + if (jstream.get() == NULL) { + jniThrowOutOfMemoryError(env, NULL); + return -1; + } + jstream->stream.adler = 1; + + /* + * In the range 8..15 for checked, or -8..-15 for unchecked inflate. Unchecked + * is appropriate for formats like zip that do their own validity checking. + */ + /* Window bits to use. 15 is fastest but consumes the most memory */ + int wbits = 15; /*Use MAX for fastest */ + if (noHeader) { + wbits = wbits / -1; + } + int err = inflateInit2(&jstream->stream, wbits); + if (err != Z_OK) { + throwExceptionForZlibError(env, "java/lang/IllegalArgumentException", err); + return -1; + } + return reinterpret_cast<uintptr_t>(jstream.release()); +} + +static void Inflater_setInputImpl(JNIEnv* env, jobject, jbyteArray buf, jint off, jint len, jlong handle) { + toNativeZipStream(handle)->setInput(env, buf, off, len); +} + +static jint Inflater_setFileInputImpl(JNIEnv* env, jobject, jobject javaFileDescriptor, jlong off, jint len, jlong handle) { + NativeZipStream* stream = toNativeZipStream(handle); + if (stream->inCap < len) { + stream->setInput(env, NULL, 0, len); + } + // TODO: is it okay to be this sloppy about errors? + int fd = jniGetFDFromFileDescriptor(env, javaFileDescriptor); + lseek(fd, off, SEEK_SET); + return read(fd, &stream->input[0], len); +} + +static jint Inflater_inflateImpl(JNIEnv* env, jobject recv, jbyteArray buf, int off, int len, jlong handle) { + jfieldID fid2 = 0; + + /* We need to get the number of bytes already read */ + jfieldID fid = gCachedFields.inRead; + jint inBytes = env->GetIntField(recv, fid); + + NativeZipStream* stream = toNativeZipStream(handle); + stream->stream.avail_out = len; + jint sin = stream->stream.total_in; + jint sout = stream->stream.total_out; + jbyte* out = (jbyte*) env->GetPrimitiveArrayCritical(buf, 0); + if (out == NULL) { + jniThrowOutOfMemoryError(env, NULL); + return -1; + } + stream->stream.next_out = (Bytef *) out + off; + int err = inflate(&stream->stream, Z_SYNC_FLUSH); + env->ReleasePrimitiveArrayCritical(buf, out, 0); + + if (err != Z_OK) { + if (err == Z_STREAM_ERROR) { + return 0; + } + if (err == Z_STREAM_END || err == Z_NEED_DICT) { + env->SetIntField(recv, fid, (jint) stream->stream.total_in - sin + inBytes); + if (err == Z_STREAM_END) { + fid2 = gCachedFields.finished; + } else { + fid2 = gCachedFields.needsDictionary; + } + env->SetBooleanField(recv, fid2, JNI_TRUE); + return stream->stream.total_out - sout; + } else { + throwExceptionForZlibError(env, "java/util/zip/DataFormatException", err); + return -1; + } + } + + /* Need to update the number of input bytes read. Is there a better way + * (Maybe global the fid then delete when end is called)? + */ + env->SetIntField(recv, fid, (jint) stream->stream.total_in - sin + inBytes); + return stream->stream.total_out - sout; +} + +static jint Inflater_getAdlerImpl(JNIEnv*, jobject, jlong handle) { + return toNativeZipStream(handle)->stream.adler; +} + +static void Inflater_endImpl(JNIEnv*, jobject, jlong handle) { + NativeZipStream* stream = toNativeZipStream(handle); + inflateEnd(&stream->stream); + delete stream; +} + +static void Inflater_setDictionaryImpl(JNIEnv* env, jobject, jbyteArray dict, int off, int len, jlong handle) { + toNativeZipStream(handle)->setDictionary(env, dict, off, len, true); +} + +static void Inflater_resetImpl(JNIEnv* env, jobject, jlong handle) { + int err = inflateReset(&toNativeZipStream(handle)->stream); + if (err != Z_OK) { + throwExceptionForZlibError(env, "java/lang/IllegalArgumentException", err); + } +} + +static jlong Inflater_getTotalOutImpl(JNIEnv*, jobject, jlong handle) { + return toNativeZipStream(handle)->stream.total_out; +} + +static jlong Inflater_getTotalInImpl(JNIEnv*, jobject, jlong handle) { + return toNativeZipStream(handle)->stream.total_in; +} + +static JNINativeMethod gMethods[] = { + { "createStream", "(Z)J", (void*) Inflater_createStream }, + { "endImpl", "(J)V", (void*) Inflater_endImpl }, + { "getAdlerImpl", "(J)I", (void*) Inflater_getAdlerImpl }, + { "getTotalInImpl", "(J)J", (void*) Inflater_getTotalInImpl }, + { "getTotalOutImpl", "(J)J", (void*) Inflater_getTotalOutImpl }, + { "inflateImpl", "([BIIJ)I", (void*) Inflater_inflateImpl }, + { "resetImpl", "(J)V", (void*) Inflater_resetImpl }, + { "setDictionaryImpl", "([BIIJ)V", (void*) Inflater_setDictionaryImpl }, + { "setFileInputImpl", "(Ljava/io/FileDescriptor;JIJ)I", (void*) Inflater_setFileInputImpl }, + { "setInputImpl", "([BIIJ)V", (void*) Inflater_setInputImpl }, +}; +int register_java_util_zip_Inflater(JNIEnv* env) { + jclass inflaterClass = env->FindClass("java/util/zip/Inflater"); + gCachedFields.finished = env->GetFieldID(inflaterClass, "finished", "Z"); + gCachedFields.inRead = env->GetFieldID(inflaterClass, "inRead", "I"); + gCachedFields.needsDictionary = env->GetFieldID(inflaterClass, "needsDictionary", "Z"); + return jniRegisterNativeMethods(env, "java/util/zip/Inflater", gMethods, NELEM(gMethods)); +} diff --git a/luni/src/main/native/org_apache_harmony_luni_platform_OSFileSystem.cpp b/luni/src/main/native/org_apache_harmony_luni_platform_OSFileSystem.cpp index af82efc..f0367a8 100644 --- a/luni/src/main/native/org_apache_harmony_luni_platform_OSFileSystem.cpp +++ b/luni/src/main/native/org_apache_harmony_luni_platform_OSFileSystem.cpp @@ -15,16 +15,6 @@ * limitations under the License. */ -// BEGIN android-note -// This file corresponds to harmony's OSFileSystem.c and OSFileSystemLinux32.c. -// It has been greatly simplified by the assumption that the underlying -// platform is always Linux. -// END android-note - -/* - * Common natives supporting the file system interface. - */ - /* Values for HyFileOpen */ #define HyOpenRead 1 #define HyOpenWrite 2 @@ -49,6 +39,7 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> +#include <unistd.h> #include <sys/ioctl.h> #include <sys/uio.h> @@ -191,7 +182,7 @@ static void harmony_io_unlockImpl(JNIEnv* env, jobject, jint handle, * Returns the granularity of the starting address for virtual memory allocation. * (It's the same as the page size.) */ -static jint harmony_io_getAllocGranularity(JNIEnv* env, jobject) { +static jint harmony_io_getAllocGranularity(JNIEnv*, jobject) { static int allocGranularity = getpagesize(); return allocGranularity; } @@ -367,10 +358,10 @@ static jlong harmony_io_seek(JNIEnv* env, jobject, jint fd, jlong offset, return result; } -// TODO: are we supposed to support the 'metadata' flag? (false => fdatasync.) -static void harmony_io_fflush(JNIEnv* env, jobject, jint fd, - jboolean metadata) { +static void harmony_io_fflush(JNIEnv* env, jobject, jint fd, jboolean metadataToo) { + LOGW("fdatasync unimplemented on Android"); // http://b/2667481 int rc = fsync(fd); + // int rc = metadataToo ? fsync(fd) : fdatasync(fd); if (rc == -1) { jniThrowIOException(env, errno); } diff --git a/luni/src/main/native/org_apache_harmony_luni_platform_OSMemory.cpp b/luni/src/main/native/org_apache_harmony_luni_platform_OSMemory.cpp index d1dafdb..8c8a864 100644 --- a/luni/src/main/native/org_apache_harmony_luni_platform_OSMemory.cpp +++ b/luni/src/main/native/org_apache_harmony_luni_platform_OSMemory.cpp @@ -43,7 +43,7 @@ static const int MMAP_WRITE_COPY = 4; * Method: littleEndian * Signature: ()Z */ -static jboolean harmony_nio_littleEndian(JNIEnv *_env, jclass _this) { +static jboolean harmony_nio_littleEndian(JNIEnv*, jclass) { long l = 0x01020304; unsigned char* c = (unsigned char*)&l; return (*c == 0x04) ? JNI_TRUE : JNI_FALSE; @@ -54,7 +54,7 @@ static jboolean harmony_nio_littleEndian(JNIEnv *_env, jclass _this) { * Method: getPointerSizeImpl * Signature: ()I */ -static jint harmony_nio_getPointerSizeImpl(JNIEnv *_env, jclass _this) { +static jint harmony_nio_getPointerSizeImpl(JNIEnv*, jclass) { return sizeof(void *); } @@ -63,7 +63,7 @@ static jint harmony_nio_getPointerSizeImpl(JNIEnv *_env, jclass _this) { * Method: mallocImpl * Signature: (I)I */ -static jint harmony_nio_mallocImpl(JNIEnv *_env, jobject _this, jint size) { +static jint harmony_nio_mallocImpl(JNIEnv* _env, jobject, jint size) { jboolean allowed = _env->CallBooleanMethod(gIDCache.runtimeInstance, gIDCache.method_trackExternalAllocation, (jlong) size); if (!allowed) { @@ -93,7 +93,7 @@ static jint harmony_nio_mallocImpl(JNIEnv *_env, jobject _this, jint size) { * Method: freeImpl * Signature: (I)V */ -static void harmony_nio_freeImpl(JNIEnv *_env, jobject _this, jint pointer) { +static void harmony_nio_freeImpl(JNIEnv* _env, jobject, jint pointer) { jlong* adjptr = (jlong*) pointer; jint size = *--adjptr; LOGV("OSMemory free %d\n", size); @@ -107,7 +107,7 @@ static void harmony_nio_freeImpl(JNIEnv *_env, jobject _this, jint pointer) { * Method: memset * Signature: (IBJ)V */ -static void harmony_nio_memset(JNIEnv *_env, jobject _this, jint address, +static void harmony_nio_memset(JNIEnv*, jobject, jint address, jbyte value, jlong length) { memset ((void *) ((jint) address), (jbyte) value, (jlong) length); } @@ -117,7 +117,7 @@ static void harmony_nio_memset(JNIEnv *_env, jobject _this, jint address, * Method: memmove * Signature: (IIJ)V */ -static void harmony_nio_memmove(JNIEnv *_env, jobject _this, jint destAddress, +static void harmony_nio_memmove(JNIEnv*, jobject, jint destAddress, jint srcAddress, jlong length) { memmove ((void *) ((jint) destAddress), (const void *) ((jint) srcAddress), (jlong) length); @@ -128,7 +128,7 @@ static void harmony_nio_memmove(JNIEnv *_env, jobject _this, jint destAddress, * Method: getByteImpl * Signature: (I)B */ -static jbyte harmony_nio_getByteImpl(JNIEnv *_env, jobject _this, +static jbyte harmony_nio_getByteImpl(JNIEnv*, jobject, jint pointer) { jbyte returnValue = *((jbyte *)pointer); return returnValue; @@ -139,7 +139,7 @@ static jbyte harmony_nio_getByteImpl(JNIEnv *_env, jobject _this, * Method: getBytesImpl * Signature: (I[BII)V */ -static void harmony_nio_getBytesImpl(JNIEnv *_env, jobject _this, jint pointer, +static void harmony_nio_getBytesImpl(JNIEnv* _env, jobject, jint pointer, jbyteArray dst, jint offset, jint length) { jbyte* src = reinterpret_cast<jbyte*>(static_cast<uintptr_t>(pointer)); _env->SetByteArrayRegion(dst, offset, length, src); @@ -150,7 +150,7 @@ static void harmony_nio_getBytesImpl(JNIEnv *_env, jobject _this, jint pointer, * Method: putByteImpl * Signature: (IB)V */ -static void harmony_nio_putByteImpl(JNIEnv *_env, jobject _this, jint pointer, +static void harmony_nio_putByteImpl(JNIEnv*, jobject, jint pointer, jbyte val) { *((jbyte *)pointer) = val; } @@ -160,7 +160,7 @@ static void harmony_nio_putByteImpl(JNIEnv *_env, jobject _this, jint pointer, * Method: putBytesImpl * Signature: (I[BII)V */ -static void harmony_nio_putBytesImpl(JNIEnv *_env, jobject _this, +static void harmony_nio_putBytesImpl(JNIEnv* _env, jobject, jint pointer, jbyteArray src, jint offset, jint length) { jbyte* dst = reinterpret_cast<jbyte*>(static_cast<uintptr_t>(pointer)); _env->GetByteArrayRegion(src, offset, length, dst); @@ -199,7 +199,7 @@ swapInts(jint *ints, int count) { * Method: setShortArrayImpl * Signature: (I[SIIZ)V */ -static void harmony_nio_setShortArrayImpl(JNIEnv *_env, jobject _this, +static void harmony_nio_setShortArrayImpl(JNIEnv* _env, jobject, jint pointer, jshortArray src, jint offset, jint length, jboolean swap) { jshort* dst = reinterpret_cast<jshort*>(static_cast<uintptr_t>(pointer)); _env->GetShortArrayRegion(src, offset, length, dst); @@ -213,7 +213,7 @@ static void harmony_nio_setShortArrayImpl(JNIEnv *_env, jobject _this, * Method: setIntArrayImpl * Signature: (I[IIIZ)V */ -static void harmony_nio_setIntArrayImpl(JNIEnv *_env, jobject _this, +static void harmony_nio_setIntArrayImpl(JNIEnv* _env, jobject, jint pointer, jintArray src, jint offset, jint length, jboolean swap) { jint* dst = reinterpret_cast<jint*>(static_cast<uintptr_t>(pointer)); _env->GetIntArrayRegion(src, offset, length, dst); @@ -227,7 +227,7 @@ static void harmony_nio_setIntArrayImpl(JNIEnv *_env, jobject _this, * Method: getShortImpl * Signature: (I)S */ -static jshort harmony_nio_getShortImpl(JNIEnv *_env, jobject _this, +static jshort harmony_nio_getShortImpl(JNIEnv*, jobject, jint pointer) { if ((pointer & 0x1) == 0) { jshort returnValue = *((jshort *)pointer); @@ -248,7 +248,7 @@ static jshort harmony_nio_getShortImpl(JNIEnv *_env, jobject _this, * Method: petShortImpl * Signature: (IS)V */ -static void harmony_nio_putShortImpl(JNIEnv *_env, jobject _this, jint pointer, +static void harmony_nio_putShortImpl(JNIEnv*, jobject, jint pointer, jshort value) { if ((pointer & 0x1) == 0) { *((jshort *)pointer) = value; @@ -266,7 +266,7 @@ static void harmony_nio_putShortImpl(JNIEnv *_env, jobject _this, jint pointer, * Method: getIntImpl * Signature: (I)I */ -static jint harmony_nio_getIntImpl(JNIEnv *_env, jobject _this, jint pointer) { +static jint harmony_nio_getIntImpl(JNIEnv*, jobject, jint pointer) { if ((pointer & 0x3) == 0) { jint returnValue = *((jint *)pointer); return returnValue; @@ -288,7 +288,7 @@ static jint harmony_nio_getIntImpl(JNIEnv *_env, jobject _this, jint pointer) { * Method: putIntImpl * Signature: (II)V */ -static void harmony_nio_putIntImpl(JNIEnv *_env, jobject _this, jint pointer, +static void harmony_nio_putIntImpl(JNIEnv*, jobject, jint pointer, jint value) { if ((pointer & 0x3) == 0) { *((jint *)pointer) = value; @@ -308,7 +308,7 @@ static void harmony_nio_putIntImpl(JNIEnv *_env, jobject _this, jint pointer, * Method: getLongImpl * Signature: (I)Ljava/lang/Long; */ -static jlong harmony_nio_getLongImpl(JNIEnv *_env, jobject _this, +static jlong harmony_nio_getLongImpl(JNIEnv*, jobject, jint pointer) { if ((pointer & 0x7) == 0) { jlong returnValue = *((jlong *)pointer); @@ -326,7 +326,7 @@ static jlong harmony_nio_getLongImpl(JNIEnv *_env, jobject _this, * Method: putLongImpl * Signature: (IJ)V */ -static void harmony_nio_putLongImpl(JNIEnv *_env, jobject _this, jint pointer, +static void harmony_nio_putLongImpl(JNIEnv*, jobject, jint pointer, jlong value) { if ((pointer & 0x7) == 0) { *((jlong *)pointer) = value; @@ -341,7 +341,7 @@ static void harmony_nio_putLongImpl(JNIEnv *_env, jobject _this, jint pointer, * Method: getFloatImpl * Signature: (I)F */ -static jfloat harmony_nio_getFloatImpl(JNIEnv *_env, jobject _this, +static jfloat harmony_nio_getFloatImpl(JNIEnv*, jobject, jint pointer) { if ((pointer & 0x3) == 0) { jfloat returnValue = *((jfloat *)pointer); @@ -359,7 +359,7 @@ static jfloat harmony_nio_getFloatImpl(JNIEnv *_env, jobject _this, * Method: setFloatImpl * Signature: (IF)V */ -static void harmony_nio_putFloatImpl(JNIEnv *_env, jobject _this, jint pointer, +static void harmony_nio_putFloatImpl(JNIEnv*, jobject, jint pointer, jfloat value) { if ((pointer & 0x3) == 0) { *((jfloat *)pointer) = value; @@ -374,7 +374,7 @@ static void harmony_nio_putFloatImpl(JNIEnv *_env, jobject _this, jint pointer, * Method: getDoubleImpl * Signature: (I)D */ -static jdouble harmony_nio_getDoubleImpl(JNIEnv *_env, jobject _this, +static jdouble harmony_nio_getDoubleImpl(JNIEnv*, jobject, jint pointer) { if ((pointer & 0x7) == 0) { jdouble returnValue = *((jdouble *)pointer); @@ -392,7 +392,7 @@ static jdouble harmony_nio_getDoubleImpl(JNIEnv *_env, jobject _this, * Method: putDoubleImpl * Signature: (ID)V */ -static void harmony_nio_putDoubleImpl(JNIEnv *_env, jobject _this, jint pointer, +static void harmony_nio_putDoubleImpl(JNIEnv*, jobject, jint pointer, jdouble value) { if ((pointer & 0x7) == 0) { *((jdouble *)pointer) = value; @@ -407,7 +407,7 @@ static void harmony_nio_putDoubleImpl(JNIEnv *_env, jobject _this, jint pointer, * Method: getAddress * Signature: (I)I */ -static jint harmony_nio_getAddress(JNIEnv *_env, jobject _this, jint pointer) { +static jint harmony_nio_getAddress(JNIEnv*, jobject, jint pointer) { return (jint) * (int *) pointer; } @@ -416,7 +416,7 @@ static jint harmony_nio_getAddress(JNIEnv *_env, jobject _this, jint pointer) { * Method: setAddress * Signature: (II)V */ -static void harmony_nio_setAddress(JNIEnv *_env, jobject _this, jint pointer, +static void harmony_nio_setAddress(JNIEnv*, jobject, jint pointer, jint value) { *(int *) pointer = (int) value; } @@ -460,7 +460,7 @@ static jint harmony_nio_mmapImpl(JNIEnv* env, jobject, jint fd, * Method: unmapImpl * Signature: (IJ)V */ -static void harmony_nio_unmapImpl(JNIEnv *_env, jobject _this, jint address, +static void harmony_nio_unmapImpl(JNIEnv*, jobject, jint address, jlong size) { munmap((void *)address, (size_t)size); } @@ -470,7 +470,7 @@ static void harmony_nio_unmapImpl(JNIEnv *_env, jobject _this, jint address, * Method: loadImpl * Signature: (IJ)I */ -static jint harmony_nio_loadImpl(JNIEnv *_env, jobject _this, jint address, +static jint harmony_nio_loadImpl(JNIEnv*, jobject, jint address, jlong size) { if(mlock((void *)address, (size_t)size)!=-1) { @@ -493,7 +493,7 @@ static jint harmony_nio_loadImpl(JNIEnv *_env, jobject _this, jint address, * Method: isLoadedImpl * Signature: (IJ)Z */ -static jboolean harmony_nio_isLoadedImpl(JNIEnv *_env, jobject _this, +static jboolean harmony_nio_isLoadedImpl(JNIEnv*, jobject, jint address, jlong size) { static int page_size = getpagesize(); @@ -530,8 +530,7 @@ static jboolean harmony_nio_isLoadedImpl(JNIEnv *_env, jobject _this, * Method: flushImpl * Signature: (IJ)I */ -static jint harmony_nio_flushImpl(JNIEnv *_env, jobject _this, jint address, - jlong size) { +static jint harmony_nio_flushImpl(JNIEnv *, jobject, jint address, jlong size) { return msync((void *)address, size, MS_SYNC); } diff --git a/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp b/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp index 7ef36f0..afad49d 100644 --- a/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp +++ b/luni/src/main/native/org_apache_harmony_luni_platform_OSNetworkSystem.cpp @@ -1115,7 +1115,7 @@ static jint osNetworkSystem_readDirect(JNIEnv* env, jobject, return bytesReceived; } -static jint osNetworkSystem_readSocketImpl(JNIEnv* env, jclass clazz, +static jint osNetworkSystem_readSocketImpl(JNIEnv* env, jclass, jobject fileDescriptor, jbyteArray byteArray, jint offset, jint count, jint timeout) { // LOGD("ENTER readSocketImpl"); @@ -1242,7 +1242,6 @@ static void osNetworkSystem_connectStreamWithTimeoutSocket(JNIEnv* env, int remainingTimeout = timeout; int passedTimeout = 0; int finishTime = 0; - int blocking = 0; bool hasTimeout = timeout > 0; /* if a timeout was specified calculate the finish time value */ diff --git a/luni/src/main/native/org_apache_harmony_luni_util_NumberConvert.c b/luni/src/main/native/org_apache_harmony_luni_util_NumberConvert.cpp index 496fe6f..3ea8bdc 100644 --- a/luni/src/main/native/org_apache_harmony_luni_util_NumberConvert.c +++ b/luni/src/main/native/org_apache_harmony_luni_util_NumberConvert.cpp @@ -26,20 +26,6 @@ #define USE_LL #endif -JNIEXPORT void JNICALL -Java_org_apache_harmony_luni_util_NumberConverter_bigIntDigitGeneratorInstImpl (JNIEnv * - env, - jobject - inst, - jlong f, - jint e, - jboolean - isDenormalized, - jboolean - mantissaIsZero, - jint p); - - #define INV_LOG_OF_TEN_BASE_2 (0.30102999566398114) /* Local */ #define ERROR_OCCURED(x) (HIGH_I32_FROM_VAR(x) < 0) /* Local */ @@ -80,18 +66,14 @@ Java_org_apache_harmony_luni_util_NumberConverter_bigIntDigitGeneratorInstImpl ( * */ JNIEXPORT void JNICALL -Java_org_apache_harmony_luni_util_NumberConverter_bigIntDigitGeneratorInstImpl (JNIEnv * - env, - jobject - inst, - jlong f, - jint e, - jboolean - isDenormalized, - jboolean - mantissaIsZero, - jint p) -{ +Java_org_apache_harmony_luni_util_NumberConverter_bigIntDigitGeneratorInstImpl ( + JNIEnv* env, + jobject inst, + jlong f, + jint e, + jboolean isDenormalized, + jboolean mantissaIsZero, + jint p) { int RLength, SLength, TempLength, mplus_Length, mminus_Length; int high, low, i; jint k, firstK, U; @@ -204,10 +186,10 @@ Java_org_apache_harmony_luni_util_NumberConverter_bigIntDigitGeneratorInstImpl ( --mminus_Length; } - clazz = (*env)->GetObjectClass (env, inst); - fid = (*env)->GetFieldID (env, clazz, "uArray", "[I"); - uArrayObject = (jintArray) (*env)->GetObjectField (env, inst, fid); - uArray = (*env)->GetIntArrayElements (env, uArrayObject, 0); + clazz = env->GetObjectClass(inst); + fid = env->GetFieldID(clazz, "uArray", "[I"); + uArrayObject = (jintArray) env->GetObjectField(inst, fid); + uArray = env->GetIntArrayElements(uArrayObject, 0); getCount = setCount = 0; do @@ -261,21 +243,21 @@ Java_org_apache_harmony_luni_util_NumberConverter_bigIntDigitGeneratorInstImpl ( else uArray[setCount++] = U + 1; - (*env)->ReleaseIntArrayElements (env, uArrayObject, uArray, 0); + env->ReleaseIntArrayElements(uArrayObject, uArray, 0); - fid = (*env)->GetFieldID (env, clazz, "setCount", "I"); - (*env)->SetIntField (env, inst, fid, setCount); + fid = env->GetFieldID(clazz, "setCount", "I"); + env->SetIntField(inst, fid, setCount); - fid = (*env)->GetFieldID (env, clazz, "getCount", "I"); - (*env)->SetIntField (env, inst, fid, getCount); + fid = env->GetFieldID(clazz, "getCount", "I"); + env->SetIntField(inst, fid, getCount); - fid = (*env)->GetFieldID (env, clazz, "firstK", "I"); - (*env)->SetIntField (env, inst, fid, firstK); + fid = env->GetFieldID(clazz, "firstK", "I"); + env->SetIntField(inst, fid, firstK); } static JNINativeMethod gMethods[] = { { "bigIntDigitGeneratorInstImpl", "(JIZZI)V" , - Java_org_apache_harmony_luni_util_NumberConverter_bigIntDigitGeneratorInstImpl }, + (void*)Java_org_apache_harmony_luni_util_NumberConverter_bigIntDigitGeneratorInstImpl }, }; int register_org_apache_harmony_luni_util_NumberConvert(JNIEnv *env) { return jniRegisterNativeMethods(env, "org/apache/harmony/luni/util/NumberConverter", diff --git a/luni/src/main/native/org_apache_harmony_luni_util_fltparse.c b/luni/src/main/native/org_apache_harmony_luni_util_fltparse.cpp index daef934..e7f3c5b 100644 --- a/luni/src/main/native/org_apache_harmony_luni_util_fltparse.c +++ b/luni/src/main/native/org_apache_harmony_luni_util_fltparse.cpp @@ -40,18 +40,18 @@ #define DEFAULT_WIDTH MAX_ACCURACY_WIDTH JNIEXPORT jfloat JNICALL -Java_org_apache_harmony_luni_util_FloatingPointParser_parseFltImpl (JNIEnv * env, +Java_org_apache_harmony_luni_util_FloatingPointParser_parseFltImpl (JNIEnv* env, jclass clazz, jstring s, jint e); JNIEXPORT jdouble JNICALL -Java_org_apache_harmony_luni_util_FloatingPointParser_parseDblImpl (JNIEnv * env, +Java_org_apache_harmony_luni_util_FloatingPointParser_parseDblImpl (JNIEnv* env, jclass clazz, jstring s, jint e); -jfloat createFloat1 (JNIEnv * env, U_64 * f, IDATA length, jint e); -jfloat floatAlgorithm (JNIEnv * env, U_64 * f, IDATA length, jint e, +jfloat createFloat1 (JNIEnv* env, U_64 * f, IDATA length, jint e); +jfloat floatAlgorithm (JNIEnv* env, U_64 * f, IDATA length, jint e, jfloat z); -jfloat createFloat (JNIEnv * env, const char *s, jint e); +jfloat createFloat (JNIEnv* env, const char *s, jint e); static const U_32 tens[] = { 0x3f800000, @@ -121,7 +121,7 @@ static const U_32 tens[] = { #define release(r) if ((r)) free((r)); jfloat -createFloat (JNIEnv * env, const char *s, jint e) +createFloat (JNIEnv* env, const char *s, jint e) { /* assumes s is a null terminated string with at least one * character in it */ @@ -222,7 +222,7 @@ createFloat (JNIEnv * env, const char *s, jint e) } jfloat -createFloat1 (JNIEnv * env, U_64 * f, IDATA length, jint e) +createFloat1 (JNIEnv* env, U_64 * f, IDATA length, jint e) { IDATA numBits; jdouble dresult; @@ -351,7 +351,7 @@ createFloat1 (JNIEnv * env, U_64 * f, IDATA length, jint e) * then return the original approximation. */ jfloat -floatAlgorithm (JNIEnv * env, U_64 * f, IDATA length, jint e, jfloat z) +floatAlgorithm (JNIEnv*, U_64 * f, IDATA length, jint e, jfloat z) { U_64 m; IDATA k, comparison, comparison2; @@ -538,14 +538,14 @@ OutOfMemory: #endif JNIEXPORT jfloat JNICALL -Java_org_apache_harmony_luni_util_FloatingPointParser_parseFltImpl (JNIEnv * env, - jclass clazz, +Java_org_apache_harmony_luni_util_FloatingPointParser_parseFltImpl (JNIEnv* env, + jclass, jstring s, jint e) { jfloat flt; - const char *str = (*env)->GetStringUTFChars (env, s, 0); + const char *str = env->GetStringUTFChars(s, 0); flt = createFloat (env, str, e); - (*env)->ReleaseStringUTFChars (env, s, str); + env->ReleaseStringUTFChars(s, str); if (((I_32) FLOAT_TO_INTBITS (flt)) >= 0) { @@ -564,14 +564,14 @@ Java_org_apache_harmony_luni_util_FloatingPointParser_parseFltImpl (JNIEnv * env } JNIEXPORT jdouble JNICALL -Java_org_apache_harmony_luni_util_FloatingPointParser_parseDblImpl (JNIEnv * env, - jclass clazz, +Java_org_apache_harmony_luni_util_FloatingPointParser_parseDblImpl (JNIEnv* env, + jclass, jstring s, jint e) { jdouble dbl; - const char *str = (*env)->GetStringUTFChars (env, s, 0); - dbl = createDouble (env, str, e); - (*env)->ReleaseStringUTFChars (env, s, str); + const char *str = env->GetStringUTFChars(s, 0); + dbl = createDouble(env, str, e); + env->ReleaseStringUTFChars(s, str); if (!ERROR_OCCURED (dbl)) { @@ -591,9 +591,9 @@ Java_org_apache_harmony_luni_util_FloatingPointParser_parseDblImpl (JNIEnv * env static JNINativeMethod gMethods[] = { { "parseFltImpl", "(Ljava/lang/String;I)F", - Java_org_apache_harmony_luni_util_FloatingPointParser_parseFltImpl }, + (void*)Java_org_apache_harmony_luni_util_FloatingPointParser_parseFltImpl }, { "parseDblImpl", "(Ljava/lang/String;I)D", - Java_org_apache_harmony_luni_util_FloatingPointParser_parseDblImpl }, + (void*)Java_org_apache_harmony_luni_util_FloatingPointParser_parseDblImpl }, }; int register_org_apache_harmony_luni_util_fltparse(JNIEnv *env) { return jniRegisterNativeMethods(env, "org/apache/harmony/luni/util/FloatingPointParser", diff --git a/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp index c684708..78c29f9 100644 --- a/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp +++ b/luni/src/main/native/org_apache_harmony_xml_ExpatParser.cpp @@ -780,8 +780,6 @@ static void endCdata(void* data) { /** * Called by Expat at the beginning of a DOCTYPE section. - * - * @param data parsing context */ static void startDtd(void* data, const char* name, const char* systemId, const char* publicId, int hasInternalSubset) { @@ -858,7 +856,7 @@ static void processingInstruction(void* data, const char* target, * @param javaContext that was provided to handleExternalEntity * @returns the pointer to the C Expat entity parser */ -static jint createEntityParser(JNIEnv* env, jobject object, jint parentParser, +static jint createEntityParser(JNIEnv* env, jobject, jint parentParser, jstring javaEncoding, jstring javaContext) { const char* encoding = env->GetStringUTFChars(javaEncoding, NULL); if (encoding == NULL) { @@ -889,7 +887,7 @@ static jint createEntityParser(JNIEnv* env, jobject object, jint parentParser, * ourselves. */ static int handleExternalEntity(XML_Parser parser, const char* context, - const char* ignored, const char* systemId, const char* publicId) { + const char*, const char* systemId, const char* publicId) { ParsingContext* parsingContext = (ParsingContext*) XML_GetUserData(parser); jobject javaParser = parsingContext->object; JNIEnv* env = parsingContext->env; @@ -1161,7 +1159,7 @@ static void appendBytes(JNIEnv* env, jobject object, jint pointer, * @param object the Java ExpatParser instance * @param i pointer to the C expat parser */ -static void releaseParser(JNIEnv* env, jobject object, jint i) { +static void releaseParser(JNIEnv*, jobject, jint i) { XML_Parser parser = (XML_Parser) i; XML_ParserFree(parser); } @@ -1172,7 +1170,7 @@ static void releaseParser(JNIEnv* env, jobject object, jint i) { * @param object the Java ExpatParser instance * @param i pointer to the C expat parser */ -static void release(JNIEnv* env, jobject object, jint i) { +static void release(JNIEnv* env, jobject, jint i) { XML_Parser parser = (XML_Parser) i; ParsingContext* context = (ParsingContext*) XML_GetUserData(parser); @@ -1188,7 +1186,7 @@ static void release(JNIEnv* env, jobject object, jint i) { * @param pointer to the C expat parser * @returns current line number */ -static int line(JNIEnv* env, jobject clazz, jint pointer) { +static int line(JNIEnv*, jobject, jint pointer) { XML_Parser parser = (XML_Parser) pointer; return XML_GetCurrentLineNumber(parser); } @@ -1200,7 +1198,7 @@ static int line(JNIEnv* env, jobject clazz, jint pointer) { * @param pointer to the C expat parser * @returns current column number */ -static int column(JNIEnv* env, jobject clazz, jint pointer) { +static int column(JNIEnv*, jobject, jint pointer) { XML_Parser parser = (XML_Parser) pointer; return XML_GetCurrentColumnNumber(parser); } @@ -1214,7 +1212,7 @@ static int column(JNIEnv* env, jobject clazz, jint pointer) { * @param index of the attribute * @returns interned Java string containing attribute's URI */ -static jstring getAttributeURI(JNIEnv* env, jobject clazz, jint pointer, +static jstring getAttributeURI(JNIEnv* env, jobject, jint pointer, jint attributePointer, jint index) { XML_Parser parser = (XML_Parser) pointer; ParsingContext* context = (ParsingContext*) XML_GetUserData(parser); @@ -1230,7 +1228,7 @@ static jstring getAttributeURI(JNIEnv* env, jobject clazz, jint pointer, * @param index of the attribute * @returns interned Java string containing attribute's local name */ -static jstring getAttributeLocalName(JNIEnv* env, jobject clazz, jint pointer, +static jstring getAttributeLocalName(JNIEnv* env, jobject, jint pointer, jint attributePointer, jint index) { XML_Parser parser = (XML_Parser) pointer; ParsingContext* context = (ParsingContext*) XML_GetUserData(parser); @@ -1246,7 +1244,7 @@ static jstring getAttributeLocalName(JNIEnv* env, jobject clazz, jint pointer, * @param index of the attribute * @returns interned Java string containing attribute's local name */ -static jstring getAttributeQName(JNIEnv* env, jobject clazz, jint pointer, +static jstring getAttributeQName(JNIEnv* env, jobject, jint pointer, jint attributePointer, jint index) { XML_Parser parser = (XML_Parser) pointer; ParsingContext* context = (ParsingContext*) XML_GetUserData(parser); @@ -1261,7 +1259,7 @@ static jstring getAttributeQName(JNIEnv* env, jobject clazz, jint pointer, * @param index of the attribute * @returns Java string containing attribute's value */ -static jstring getAttributeValueByIndex(JNIEnv* env, jobject clazz, +static jstring getAttributeValueByIndex(JNIEnv* env, jobject, jint attributePointer, jint index) { const char** attributes = (const char**) attributePointer; const char* value = attributes[(index << 1) + 1]; @@ -1276,7 +1274,7 @@ static jstring getAttributeValueByIndex(JNIEnv* env, jobject clazz, * @returns index of attribute with the given uri and local name or -1 if not * found */ -static jint getAttributeIndexForQName(JNIEnv* env, jobject clazz, +static jint getAttributeIndexForQName(JNIEnv* env, jobject, jint attributePointer, jstring qName) { const char** attributes = (const char**) attributePointer; @@ -1306,7 +1304,7 @@ static jint getAttributeIndexForQName(JNIEnv* env, jobject clazz, * @returns index of attribute with the given uri and local name or -1 if not * found */ -static jint getAttributeIndex(JNIEnv* env, jobject clazz, +static jint getAttributeIndex(JNIEnv* env, jobject, jint attributePointer, jstring uri, jstring localName) { const char** attributes = (const char**) attributePointer; @@ -1413,7 +1411,7 @@ static char** cloneStrings(const char** source, int count) { * @param pointer to char** to clone * @param count number of attributes */ -static jint cloneAttributes(JNIEnv* env, jobject clazz, +static jint cloneAttributes(JNIEnv*, jobject, jint pointer, jint count) { return (int) cloneStrings((const char**) pointer, count << 1); } @@ -1421,7 +1419,7 @@ static jint cloneAttributes(JNIEnv* env, jobject clazz, /** * Frees cloned attributes. */ -static void freeAttributes(JNIEnv* env, jobject clazz, jint pointer) { +static void freeAttributes(JNIEnv*, jobject, jint pointer) { free((void*) pointer); } diff --git a/luni/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp b/luni/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp index 5e2aaf6..2c8a02a 100644 --- a/luni/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp +++ b/luni/src/main/native/org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp @@ -36,13 +36,20 @@ #include <openssl/rsa.h> #include <openssl/ssl.h> +#include "ScopedByteArray.h" +#include "ScopedGlobalRef.h" +#include "ScopedUtfChars.h" +#include "UniquePtr.h" + #undef WITH_JNI_TRACE #ifdef WITH_JNI_TRACE #define JNI_TRACE(...) \ ((void)LOG(LOG_INFO, LOG_TAG "-jni", __VA_ARGS__)); \ - ((void)printf("I/" LOG_TAG "-jni:")); \ - ((void)printf(__VA_ARGS__)); \ +/* + ((void)printf("I/" LOG_TAG "-jni:")); \ + ((void)printf(__VA_ARGS__)); \ ((void)printf("\n")) +*/ #else #define JNI_TRACE(...) ((void)0) #endif @@ -65,7 +72,7 @@ static void freeSslErrorState(void) { * * @return 1 if an exception was thrown, 0 if not. */ -static int throwExceptionIfNecessary(JNIEnv* env, const char* location) { +static int throwExceptionIfNecessary(JNIEnv* env, const char* /*location*/) { int error = ERR_get_error(); int result = 0; @@ -105,12 +112,10 @@ static void throwSSLExceptionStr(JNIEnv* env, const char* message) { * SSL errors. This will also log the errors. * * @param env the JNI environment - * @param sslReturnCode return code from failing SSL function * @param sslErrorCode error code returned from SSL_get_error() * @param message null-ok; general error message */ -static void throwSSLExceptionWithSslErrors(JNIEnv* env, int sslReturnCode, - int sslErrorCode, const char* message) { +static void throwSSLExceptionWithSslErrors(JNIEnv* env, int sslErrorCode, const char* message) { const char* messageStr = NULL; char* str; int ret; @@ -226,7 +231,7 @@ static void throwSSLExceptionWithSslErrors(JNIEnv* env, int sslReturnCode, * @param throwIfNull whether to throw if the SSL pointer is NULL * @returns the pointer, which may be NULL */ -static SSL* getSslPointer(JNIEnv* env, int ssl_address, bool throwIfNull) { +static SSL* to_SSL(JNIEnv* env, int ssl_address, bool throwIfNull) { SSL* ssl = reinterpret_cast<SSL*>(static_cast<uintptr_t>(ssl_address)); if ((ssl == NULL) && throwIfNull) { throwSSLExceptionStr(env, "null SSL pointer"); @@ -235,6 +240,14 @@ static SSL* getSslPointer(JNIEnv* env, int ssl_address, bool throwIfNull) { return ssl; } +static SSL_CTX* to_SSL_CTX(int ssl_ctx_address) { + return reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address)); +} + +static SSL_SESSION* to_SSL_SESSION(int ssl_session_address) { + return reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address)); +} + /** * Converts a Java byte[] to an OpenSSL BIGNUM, allocating the BIGNUM on the * fly. @@ -242,10 +255,9 @@ static SSL* getSslPointer(JNIEnv* env, int ssl_address, bool throwIfNull) { static BIGNUM* arrayToBignum(JNIEnv* env, jbyteArray source) { // LOGD("Entering arrayToBignum()"); - jbyte* sourceBytes = env->GetByteArrayElements(source, NULL); + ScopedByteArray sourceBytes(env, source); int sourceLength = env->GetArrayLength(source); - BIGNUM* bignum = BN_bin2bn((unsigned char*) sourceBytes, sourceLength, NULL); - env->ReleaseByteArrayElements(source, sourceBytes, JNI_ABORT); + BIGNUM* bignum = BN_bin2bn((unsigned char*) sourceBytes.bytes(), sourceLength, NULL); return bignum; } @@ -265,7 +277,7 @@ static BIGNUM* arrayToBignum(JNIEnv* env, jbyteArray source) { static MUTEX_TYPE *mutex_buf = NULL; -static void locking_function(int mode, int n, const char * file, int line) { +static void locking_function(int mode, int n, const char*, int) { if (mode & CRYPTO_LOCK) { MUTEX_LOCK(mutex_buf[n]); } else { @@ -320,7 +332,7 @@ int THREAD_cleanup(void) { * Initialization phase for every OpenSSL job: Loads the Error strings, the * crypto algorithms and reset the OpenSSL library */ -static void NativeCrypto_clinit(JNIEnv* env, jclass) +static void NativeCrypto_clinit(JNIEnv*, jclass) { SSL_load_error_strings(); ERR_load_crypto_strings(); @@ -332,10 +344,14 @@ static void NativeCrypto_clinit(JNIEnv* env, jclass) /** * public static native int EVP_PKEY_new_DSA(byte[] p, byte[] q, byte[] g, byte[] pub_key, byte[] priv_key); */ -static EVP_PKEY* NativeCrypto_EVP_PKEY_new_DSA(JNIEnv* env, jclass clazz, jbyteArray p, jbyteArray q, jbyteArray g, jbyteArray pub_key, jbyteArray priv_key) { +static EVP_PKEY* NativeCrypto_EVP_PKEY_new_DSA(JNIEnv* env, jclass, jbyteArray p, jbyteArray q, jbyteArray g, jbyteArray pub_key, jbyteArray priv_key) { // LOGD("Entering EVP_PKEY_new_DSA()"); DSA* dsa = DSA_new(); + if (dsa == NULL) { + jniThrowRuntimeException(env, "DSA_new failed"); + return NULL; + } dsa->p = arrayToBignum(env, p); dsa->q = arrayToBignum(env, q); @@ -353,6 +369,10 @@ static EVP_PKEY* NativeCrypto_EVP_PKEY_new_DSA(JNIEnv* env, jclass clazz, jbyteA } EVP_PKEY* pkey = EVP_PKEY_new(); + if (pkey == NULL) { + jniThrowRuntimeException(env, "EVP_PKEY_new failed"); + return NULL; + } EVP_PKEY_assign_DSA(pkey, dsa); return pkey; @@ -361,10 +381,14 @@ static EVP_PKEY* NativeCrypto_EVP_PKEY_new_DSA(JNIEnv* env, jclass clazz, jbyteA /** * private static native int EVP_PKEY_new_RSA(byte[] n, byte[] e, byte[] d, byte[] p, byte[] q); */ -static EVP_PKEY* NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass clazz, jbyteArray n, jbyteArray e, jbyteArray d, jbyteArray p, jbyteArray q) { +static EVP_PKEY* NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass, jbyteArray n, jbyteArray e, jbyteArray d, jbyteArray p, jbyteArray q) { // LOGD("Entering EVP_PKEY_new_RSA()"); RSA* rsa = RSA_new(); + if (rsa == NULL) { + jniThrowRuntimeException(env, "RSA_new failed"); + return NULL; + } rsa->n = arrayToBignum(env, n); rsa->e = arrayToBignum(env, e); @@ -391,6 +415,11 @@ static EVP_PKEY* NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass clazz, jbyteA } EVP_PKEY* pkey = EVP_PKEY_new(); + if (pkey == NULL) { + RSA_free(rsa); + jniThrowRuntimeException(env, "EVP_PKEY_new failed"); + return NULL; + } EVP_PKEY_assign_RSA(pkey, rsa); return pkey; @@ -399,7 +428,7 @@ static EVP_PKEY* NativeCrypto_EVP_PKEY_new_RSA(JNIEnv* env, jclass clazz, jbyteA /** * private static native void EVP_PKEY_free(int pkey); */ -static void NativeCrypto_EVP_PKEY_free(JNIEnv* env, jclass clazz, EVP_PKEY* pkey) { +static void NativeCrypto_EVP_PKEY_free(JNIEnv*, jclass, EVP_PKEY* pkey) { // LOGD("Entering EVP_PKEY_free()"); if (pkey != NULL) { @@ -410,7 +439,7 @@ static void NativeCrypto_EVP_PKEY_free(JNIEnv* env, jclass clazz, EVP_PKEY* pkey /* * public static native int EVP_new() */ -static jint NativeCrypto_EVP_new(JNIEnv* env, jclass clazz) { +static jint NativeCrypto_EVP_new(JNIEnv*, jclass) { // LOGI("NativeCrypto_EVP_DigestNew"); return (jint)EVP_MD_CTX_create(); @@ -419,7 +448,7 @@ static jint NativeCrypto_EVP_new(JNIEnv* env, jclass clazz) { /* * public static native void EVP_free(int) */ -static void NativeCrypto_EVP_free(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx) { +static void NativeCrypto_EVP_free(JNIEnv*, jclass, EVP_MD_CTX* ctx) { // LOGI("NativeCrypto_EVP_DigestFree"); if (ctx != NULL) { @@ -430,7 +459,7 @@ static void NativeCrypto_EVP_free(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx) { /* * public static native int EVP_DigestFinal(int, byte[], int) */ -static jint NativeCrypto_EVP_DigestFinal(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jbyteArray hash, jint offset) { +static jint NativeCrypto_EVP_DigestFinal(JNIEnv* env, jclass, EVP_MD_CTX* ctx, jbyteArray hash, jint offset) { // LOGI("NativeCrypto_EVP_DigestFinal%x, %x, %d, %d", ctx, hash, offset); if (ctx == NULL || hash == NULL) { @@ -452,7 +481,7 @@ static jint NativeCrypto_EVP_DigestFinal(JNIEnv* env, jclass clazz, EVP_MD_CTX* /* * public static native void EVP_DigestInit(int, java.lang.String) */ -static void NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jstring algorithm) { +static void NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass, EVP_MD_CTX* ctx, jstring algorithm) { // LOGI("NativeCrypto_EVP_DigestInit"); if (ctx == NULL || algorithm == NULL) { @@ -460,10 +489,9 @@ static void NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass clazz, EVP_MD_CTX* c return; } - const char* algorithmChars = env->GetStringUTFChars(algorithm, NULL); + ScopedUtfChars algorithmChars(env, algorithm); - const EVP_MD *digest = EVP_get_digestbynid(OBJ_txt2nid(algorithmChars)); - env->ReleaseStringUTFChars(algorithm, algorithmChars); + const EVP_MD *digest = EVP_get_digestbynid(OBJ_txt2nid(algorithmChars.c_str())); if (digest == NULL) { jniThrowRuntimeException(env, "Hash algorithm not found"); @@ -478,7 +506,7 @@ static void NativeCrypto_EVP_DigestInit(JNIEnv* env, jclass clazz, EVP_MD_CTX* c /* * public static native void EVP_DigestSize(int) */ -static jint NativeCrypto_EVP_DigestSize(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx) { +static jint NativeCrypto_EVP_DigestSize(JNIEnv* env, jclass, EVP_MD_CTX* ctx) { // LOGI("NativeCrypto_EVP_DigestSize"); if (ctx == NULL) { @@ -496,7 +524,7 @@ static jint NativeCrypto_EVP_DigestSize(JNIEnv* env, jclass clazz, EVP_MD_CTX* c /* * public static native void EVP_DigestBlockSize(int) */ -static jint NativeCrypto_EVP_DigestBlockSize(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx) { +static jint NativeCrypto_EVP_DigestBlockSize(JNIEnv* env, jclass, EVP_MD_CTX* ctx) { // LOGI("NativeCrypto_EVP_DigestBlockSize"); if (ctx == NULL) { @@ -514,7 +542,7 @@ static jint NativeCrypto_EVP_DigestBlockSize(JNIEnv* env, jclass clazz, EVP_MD_C /* * public static native void EVP_DigestUpdate(int, byte[], int, int) */ -static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length) { +static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length) { // LOGI("NativeCrypto_EVP_DigestUpdate %x, %x, %d, %d", ctx, buffer, offset, length); if (ctx == NULL || buffer == NULL) { @@ -522,9 +550,8 @@ static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass clazz, EVP_MD_CTX* return; } - jbyte* bufferBytes = env->GetByteArrayElements(buffer, NULL); - EVP_DigestUpdate(ctx, (unsigned char*) (bufferBytes + offset), length); - env->ReleaseByteArrayElements(buffer, bufferBytes, JNI_ABORT); + ScopedByteArray bufferBytes(env, buffer); + EVP_DigestUpdate(ctx, (unsigned char*) (bufferBytes.bytes() + offset), length); throwExceptionIfNecessary(env, "NativeCrypto_EVP_DigestUpdate"); } @@ -532,7 +559,7 @@ static void NativeCrypto_EVP_DigestUpdate(JNIEnv* env, jclass clazz, EVP_MD_CTX* /* * public static native void EVP_VerifyInit(int, java.lang.String) */ -static void NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jstring algorithm) { +static void NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass, EVP_MD_CTX* ctx, jstring algorithm) { // LOGI("NativeCrypto_EVP_VerifyInit"); if (ctx == NULL || algorithm == NULL) { @@ -540,10 +567,9 @@ static void NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass clazz, EVP_MD_CTX* c return; } - const char* algorithmChars = env->GetStringUTFChars(algorithm, NULL); + ScopedUtfChars algorithmChars(env, algorithm); - const EVP_MD *digest = EVP_get_digestbynid(OBJ_txt2nid(algorithmChars)); - env->ReleaseStringUTFChars(algorithm, algorithmChars); + const EVP_MD *digest = EVP_get_digestbynid(OBJ_txt2nid(algorithmChars.c_str())); if (digest == NULL) { jniThrowRuntimeException(env, "Hash algorithm not found"); @@ -558,7 +584,7 @@ static void NativeCrypto_EVP_VerifyInit(JNIEnv* env, jclass clazz, EVP_MD_CTX* c /* * public static native void EVP_VerifyUpdate(int, byte[], int, int) */ -static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length) { +static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length) { // LOGI("NativeCrypto_EVP_VerifyUpdate %x, %x, %d, %d", ctx, buffer, offset, length); if (ctx == NULL || buffer == NULL) { @@ -566,9 +592,8 @@ static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass clazz, EVP_MD_CTX* return; } - jbyte* bufferBytes = env->GetByteArrayElements(buffer, NULL); - EVP_VerifyUpdate(ctx, (unsigned char*) (bufferBytes + offset), length); - env->ReleaseByteArrayElements(buffer, bufferBytes, JNI_ABORT); + ScopedByteArray bufferBytes(env, buffer); + EVP_VerifyUpdate(ctx, (unsigned char*) (bufferBytes.bytes() + offset), length); throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyUpdate"); } @@ -576,7 +601,7 @@ static void NativeCrypto_EVP_VerifyUpdate(JNIEnv* env, jclass clazz, EVP_MD_CTX* /* * public static native void EVP_VerifyFinal(int, byte[], int, int, int) */ -static int NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass clazz, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length, EVP_PKEY* pkey) { +static int NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass, EVP_MD_CTX* ctx, jbyteArray buffer, jint offset, jint length, EVP_PKEY* pkey) { // LOGI("NativeCrypto_EVP_VerifyFinal %x, %x, %d, %d %x", ctx, buffer, offset, length, pkey); if (ctx == NULL || buffer == NULL || pkey == NULL) { @@ -584,9 +609,8 @@ static int NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass clazz, EVP_MD_CTX* c return -1; } - jbyte* bufferBytes = env->GetByteArrayElements(buffer, NULL); - int result = EVP_VerifyFinal(ctx, (unsigned char*) (bufferBytes + offset), length, pkey); - env->ReleaseByteArrayElements(buffer, bufferBytes, JNI_ABORT); + ScopedByteArray bufferBytes(env, buffer); + int result = EVP_VerifyFinal(ctx, (unsigned char*) (bufferBytes.bytes() + offset), length, pkey); throwExceptionIfNecessary(env, "NativeCrypto_EVP_VerifyFinal"); @@ -594,6 +618,129 @@ static int NativeCrypto_EVP_VerifyFinal(JNIEnv* env, jclass clazz, EVP_MD_CTX* c } /** + * Helper function that creates an RSA public key from two buffers containing + * the big-endian bit representation of the modulus and the public exponent. + * + * @param mod The data of the modulus + * @param modLen The length of the modulus data + * @param exp The data of the exponent + * @param expLen The length of the exponent data + * + * @return A pointer to the new RSA structure, or NULL on error + */ +static RSA* rsaCreateKey(unsigned char* mod, int modLen, unsigned char* exp, int expLen) { + // LOGD("Entering rsaCreateKey()"); + + RSA* rsa = RSA_new(); + if (rsa == NULL) { + return NULL; + } + + rsa->n = BN_bin2bn(mod, modLen, NULL); + rsa->e = BN_bin2bn(exp, expLen, NULL); + + if (rsa->n == NULL || rsa->e == NULL) { + RSA_free(rsa); + return NULL; + } + + return rsa; +} + +/** + * Helper function that verifies a given RSA signature for a given message. + * + * @param msg The message to verify + * @param msgLen The length of the message + * @param sig The signature to verify + * @param sigLen The length of the signature + * @param algorithm The name of the hash/sign algorithm to use, e.g. "RSA-SHA1" + * @param rsa The RSA public key to use + * + * @return 1 on success, 0 on failure, -1 on error (check SSL errors then) + * + */ +static int rsaVerify(unsigned char* msg, unsigned int msgLen, unsigned char* sig, + unsigned int sigLen, char* algorithm, RSA* rsa) { + + // LOGD("Entering rsaVerify(%x, %d, %x, %d, %s, %x)", msg, msgLen, sig, sigLen, algorithm, rsa); + + EVP_PKEY* pkey = EVP_PKEY_new(); + if (pkey == NULL) { + return -1; + } + EVP_PKEY_set1_RSA(pkey, rsa); + + const EVP_MD *type = EVP_get_digestbyname(algorithm); + if (type == NULL) { + EVP_PKEY_free(pkey); + return -1; + } + + EVP_MD_CTX ctx; + EVP_MD_CTX_init(&ctx); + if (EVP_VerifyInit_ex(&ctx, type, NULL) == 0) { + EVP_PKEY_free(pkey); + return -1; + } + + EVP_VerifyUpdate(&ctx, msg, msgLen); + int result = EVP_VerifyFinal(&ctx, sig, sigLen, pkey); + EVP_MD_CTX_cleanup(&ctx); + EVP_PKEY_free(pkey); + return result; +} + +/** + * Verifies an RSA signature. + */ +static int NativeCrypto_verifysignature(JNIEnv* env, jclass, + jbyteArray msg, jbyteArray sig, jstring algorithm, jbyteArray mod, jbyteArray exp) { + + JNI_TRACE("NativeCrypto_verifysignature msg=%p sig=%p algorithm=%p mod=%p exp%p", + msg, sig, algorithm, mod, exp); + + if (msg == NULL || sig == NULL || algorithm == NULL || mod == NULL || exp == NULL) { + jniThrowNullPointerException(env, NULL); + JNI_TRACE("NativeCrypto_verifysignature => -1"); + return -1; + } + + int result = -1; + + ScopedByteArray msgBytes(env, msg); + jint msgLength = env->GetArrayLength(msg); + + ScopedByteArray sigBytes(env, sig); + jint sigLength = env->GetArrayLength(sig); + + ScopedByteArray modBytes(env, mod); + jint modLength = env->GetArrayLength(mod); + + ScopedByteArray expBytes(env, exp); + jint expLength = env->GetArrayLength(exp); + + ScopedUtfChars algorithmChars(env, algorithm); + JNI_TRACE("NativeCrypto_verifysignature algorithmChars=%s", algorithmChars.c_str()); + + RSA* rsa = rsaCreateKey((unsigned char*) modBytes.bytes(), modLength, (unsigned char*) expBytes.bytes(), expLength); + if (rsa != NULL) { + result = rsaVerify((unsigned char*) msgBytes.bytes(), msgLength, (unsigned char*) sigBytes.bytes(), sigLength, + (char*) algorithmChars.c_str(), rsa); + RSA_free(rsa); + } + + if (result == -1) { + if (!throwExceptionIfNecessary(env, "NativeCrypto_verifysignature")) { + jniThrowRuntimeException(env, "Internal error during verification"); + } + } + + JNI_TRACE("NativeCrypto_verifysignature => %d", result); + return result; +} + +/** * Convert ssl version constant to string. Based on SSL_get_version */ // TODO move to jsse.patch @@ -615,6 +762,7 @@ static const char* get_ssl_version(int ssl_version) { } } +#ifdef WITH_JNI_TRACE /** * Convert content type constant to string. */ @@ -639,7 +787,9 @@ static const char* get_content_type(int content_type) { } } } +#endif +#ifdef WITH_JNI_TRACE /** * Simple logging call back to show hand shake messages */ @@ -654,11 +804,13 @@ static void ssl_msg_callback_LOG(int write_p, int ssl_version, int content_type, len, arg); } +#endif +#ifdef WITH_JNI_TRACE /** * Based on example logging call back from SSL_CTX_set_info_callback man page */ -static void info_callback_LOG(const SSL *s, int where, int ret) +static void info_callback_LOG(const SSL* s __attribute__ ((unused)), int where, int ret) { int w = where & ~SSL_ST_MASK; const char* str; @@ -706,6 +858,7 @@ static void info_callback_LOG(const SSL *s, int where, int ret) s, str, where, SSL_state_string(s), SSL_state_string_long(s)); } } +#endif /** * Returns an array containing all the X509 certificate's bytes. @@ -720,7 +873,7 @@ static jobjectArray getCertificateBytes(JNIEnv* env, int count = sk_X509_num(chain); if (count <= 0) { - NULL; + return NULL; } jobjectArray joa = env->NewObjectArray(count, env->FindClass("[B"), NULL); @@ -729,6 +882,10 @@ static jobjectArray getCertificateBytes(JNIEnv* env, } BIO* bio = BIO_new(BIO_s_mem()); + if (bio == NULL) { + jniThrowRuntimeException(env, "BIO_new failed"); + return NULL; + } // LOGD("Start fetching the certificates"); for (int i = 0; i < count; i++) { @@ -829,8 +986,8 @@ class AppData { int fdsEmergency[2]; MUTEX_TYPE mutex; JNIEnv* env; - jobject certificateChainVerifier; - jobject handshakeCompletedCallback; + ScopedGlobalRef certificateChainVerifier; + ScopedGlobalRef handshakeCompletedCallback; /** * Creates our application data and attaches it to a given SSL connection. @@ -841,17 +998,29 @@ class AppData { * @param hcc The HandshakeCompletedCallback */ public: - static AppData* create(JNIEnv* e, jobject ccv, jobject hcc) { - AppData* appData = new AppData(e, ccv, hcc); - appData->fdsEmergency[0] = -1; - appData->fdsEmergency[1] = -1; + static AppData* create(JNIEnv* e, + jobject certificateChainVerifier, + jobject handshakeCompletedCallback) { + if (certificateChainVerifier == NULL) { + return NULL; + } + if (handshakeCompletedCallback == NULL) { + return NULL; + } + UniquePtr<AppData> appData(new AppData(e, certificateChainVerifier, handshakeCompletedCallback)); + if (appData->certificateChainVerifier.get() == NULL) { + return NULL; + } + if (appData->handshakeCompletedCallback.get() == NULL) { + return NULL; + } if (pipe(appData->fdsEmergency) == -1) { return NULL; } if (MUTEX_SETUP(appData->mutex) == -1) { - return NULL; + return NULL; } - return appData; + return appData.release(); } private: @@ -859,8 +1028,11 @@ class AppData { aliveAndKicking(1), waitingThreads(0), env(e), - certificateChainVerifier(ccv), - handshakeCompletedCallback(hcc) {} + certificateChainVerifier(e, ccv), + handshakeCompletedCallback(e, hcc) { + fdsEmergency[0] = -1; + fdsEmergency[1] = -1; + } /** * Destroys our application data, cleaning up everything in the process. @@ -878,7 +1050,7 @@ class AppData { } void setEnv(JNIEnv* e) { - if (handshakeCompletedCallback == NULL) { + if (handshakeCompletedCallback.get() == NULL) { return; } env = e; @@ -886,6 +1058,12 @@ class AppData { void clearEnv() { env = NULL; } + + void handshakeCompleted() { + certificateChainVerifier.reset(); + handshakeCompletedCallback.reset(); + clearEnv(); + } }; /** @@ -1038,7 +1216,7 @@ static const char* SSL_CIPHER_authentication_method(const SSL_CIPHER* cipher) /** * Verify the X509 certificate via SSL_CTX_set_cert_verify_callback */ -static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg) +static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg __attribute__ ((unused))) { /* Get the correct index to the SSLobject stored into X509_STORE_CTX. */ SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data(x509_store_ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); @@ -1048,10 +1226,10 @@ static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg) JNIEnv* env = appData->env; if (env == NULL) { LOGE("AppData->env missing in cert_verify_callback"); - JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl, result); + JNI_TRACE("ssl=%p cert_verify_callback => 0", ssl); return 0; } - jobject certificateChainVerifier = appData->certificateChainVerifier; + jobject certificateChainVerifier = appData->certificateChainVerifier.get(); jclass cls = env->GetObjectClass(certificateChainVerifier); jmethodID methodID = env->GetMethodID(cls, "verifyCertificateChain", "([[BLjava/lang/String;)V"); @@ -1086,7 +1264,7 @@ static int cert_verify_callback(X509_STORE_CTX* x509_store_ctx, void* arg) * for SSL_MODE_HANDSHAKE_CUTTHROUGH support, since SSL_do_handshake * returns before the handshake is completed in this case. */ -static void info_callback(const SSL *ssl, int where, int ret) { +static void info_callback(const SSL *ssl, int where, int ret __attribute__ ((unused))) { JNI_TRACE("ssl=%p info_callback where=0x%x ret=%d", ssl, where, ret); #ifdef WITH_JNI_TRACE info_callback_LOG(ssl, where, ret); @@ -1100,10 +1278,10 @@ static void info_callback(const SSL *ssl, int where, int ret) { JNIEnv* env = appData->env; if (env == NULL) { LOGE("AppData->env missing in info_callback"); - JNI_TRACE("ssl=%p info_callback env error", ssl, result); + JNI_TRACE("ssl=%p info_callback env error", ssl); return; } - jobject handshakeCompletedCallback = appData->handshakeCompletedCallback; + jobject handshakeCompletedCallback = appData->handshakeCompletedCallback.get(); jclass cls = env->GetObjectClass(handshakeCompletedCallback); jmethodID methodID = env->GetMethodID(cls, "handshakeCompleted", "()V"); @@ -1115,18 +1293,19 @@ static void info_callback(const SSL *ssl, int where, int ret) { JNI_TRACE("ssl=%p info_callback exception", ssl); } - // no longer needed after handshake is complete - appData->clearEnv(); - appData->certificateChainVerifier = NULL; - appData->handshakeCompletedCallback = NULL; + appData->handshakeCompleted(); JNI_TRACE("ssl=%p info_callback completed", ssl); } /* * public static native int SSL_CTX_new(); */ -static int NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass clazz) { +static int NativeCrypto_SSL_CTX_new(JNIEnv* env, jclass) { SSL_CTX* sslCtx = SSL_CTX_new(SSLv23_method()); + if (sslCtx == NULL) { + jniThrowRuntimeException(env, "SSL_CTX_new"); + return NULL; + } // Note: We explicitly do not allow SSLv2 to be used. SSL_CTX_set_options(sslCtx, SSL_OP_ALL | SSL_OP_NO_SSLv2); @@ -1189,7 +1368,7 @@ static jobjectArray makeCipherList(JNIEnv* env, STACK_OF(SSL_CIPHER)* cipher_lis static jobjectArray NativeCrypto_SSL_CTX_get_ciphers(JNIEnv* env, jclass, jint ssl_ctx_address) { - SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address)); + SSL_CTX* ssl_ctx = to_SSL_CTX(ssl_ctx_address); JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_get_ciphers", ssl_ctx); if (ssl_ctx == NULL) { jniThrowNullPointerException(env, "SSL_CTX is null"); @@ -1204,7 +1383,7 @@ static jobjectArray NativeCrypto_SSL_CTX_get_ciphers(JNIEnv* env, static void NativeCrypto_SSL_CTX_free(JNIEnv* env, jclass, jint ssl_ctx_address) { - SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address)); + SSL_CTX* ssl_ctx = to_SSL_CTX(ssl_ctx_address); JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_CTX_free", ssl_ctx); if (ssl_ctx == NULL) { jniThrowNullPointerException(env, "SSL_CTX is null"); @@ -1223,9 +1402,13 @@ static BIO* stringToMemBuf(JNIEnv* env, jstring string) { LocalArray<1024> buf(byteCount + 1); env->GetStringUTFRegion(string, 0, env->GetStringLength(string), &buf[0]); - BIO* result = BIO_new(BIO_s_mem()); - BIO_puts(result, &buf[0]); - return result; + BIO* bio = BIO_new(BIO_s_mem()); + if (bio == NULL) { + jniThrowRuntimeException(env, "BIO_new failed"); + return NULL; + } + BIO_puts(bio, &buf[0]); + return bio; } /** @@ -1233,11 +1416,11 @@ static BIO* stringToMemBuf(JNIEnv* env, jstring string) { * CertificateChainVerifier ccv) throws SSLException; */ static jint NativeCrypto_SSL_new(JNIEnv* env, jclass, - jint ssl_ctx_address, jstring privatekey, jstring certificates, jbyteArray seed, jobject ccv) + jint ssl_ctx_address, jstring privatekey, jstring certificates, jbyteArray seed) { - SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address)); - JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new privatekey=%p certificates=%p seed=%p ccv=%p", - ssl_ctx, privatekey, certificates, seed, ccv); + SSL_CTX* ssl_ctx = to_SSL_CTX(ssl_ctx_address); + JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new privatekey=%p certificates=%p seed=%p", + ssl_ctx, privatekey, certificates, seed); if (ssl_ctx == NULL) { jniThrowNullPointerException(env, "SSL_CTX is null"); JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx); @@ -1256,7 +1439,7 @@ static jint NativeCrypto_SSL_new(JNIEnv* env, jclass, SSL* ssl = SSL_new(ssl_ctx); if (ssl == NULL) { - throwSSLExceptionWithSslErrors(env, 0, 0, + throwSSLExceptionWithSslErrors(env, 0, "Unable to create SSL structure"); JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx); return NULL; @@ -1280,7 +1463,7 @@ static jint NativeCrypto_SSL_new(JNIEnv* env, jclass, if (privatekeyevp == NULL) { LOGE(ERR_error_string(ERR_get_error(), NULL)); - throwSSLExceptionWithSslErrors(env, 0, 0, + throwSSLExceptionWithSslErrors(env, 0, "Error parsing the private key"); SSL_free(ssl); JNI_TRACE("ssl_ctx=%p NativeCrypto_SSL_new => NULL", ssl_ctx); @@ -1294,7 +1477,7 @@ static jint NativeCrypto_SSL_new(JNIEnv* env, jclass, if (certificatesx509 == NULL) { LOGE(ERR_error_string(ERR_get_error(), NULL)); - throwSSLExceptionWithSslErrors(env, 0, 0, + throwSSLExceptionWithSslErrors(env, 0, "Error parsing the certificates"); EVP_PKEY_free(privatekeyevp); SSL_free(ssl); @@ -1305,7 +1488,7 @@ static jint NativeCrypto_SSL_new(JNIEnv* env, jclass, int ret = SSL_use_certificate(ssl, certificatesx509); if (ret != 1) { LOGE(ERR_error_string(ERR_get_error(), NULL)); - throwSSLExceptionWithSslErrors(env, ret, 0, + throwSSLExceptionWithSslErrors(env, 0, "Error setting the certificates"); X509_free(certificatesx509); EVP_PKEY_free(privatekeyevp); @@ -1317,7 +1500,7 @@ static jint NativeCrypto_SSL_new(JNIEnv* env, jclass, ret = SSL_use_PrivateKey(ssl, privatekeyevp); if (ret != 1) { LOGE(ERR_error_string(ERR_get_error(), NULL)); - throwSSLExceptionWithSslErrors(env, ret, 0, + throwSSLExceptionWithSslErrors(env, 0, "Error setting the private key"); X509_free(certificatesx509); EVP_PKEY_free(privatekeyevp); @@ -1328,7 +1511,7 @@ static jint NativeCrypto_SSL_new(JNIEnv* env, jclass, ret = SSL_check_private_key(ssl); if (ret != 1) { - throwSSLExceptionWithSslErrors(env, ret, 0, + throwSSLExceptionWithSslErrors(env, 0, "Error checking the private key"); X509_free(certificatesx509); EVP_PKEY_free(privatekeyevp); @@ -1346,7 +1529,7 @@ static jint NativeCrypto_SSL_new(JNIEnv* env, jclass, */ static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass, jint ssl_address) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode", ssl); if (ssl == NULL) { JNI_TRACE("ssl=%p NativeCrypto_SSL_get_mode => 0", ssl); @@ -1362,7 +1545,7 @@ static jlong NativeCrypto_SSL_get_mode(JNIEnv* env, jclass, */ static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass, jint ssl_address, jlong mode) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_set_mode mode=0x%llx", ssl, mode); if (ssl == NULL) { return 0; @@ -1377,7 +1560,7 @@ static jlong NativeCrypto_SSL_set_mode(JNIEnv* env, jclass, */ static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass, jint ssl_address, jlong mode) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_mode mode=0x%llx", ssl, mode); if (ssl == NULL) { return 0; @@ -1392,7 +1575,7 @@ static jlong NativeCrypto_SSL_clear_mode(JNIEnv* env, jclass, */ static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass, jint ssl_address) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options", ssl); if (ssl == NULL) { JNI_TRACE("ssl=%p NativeCrypto_SSL_get_options => 0", ssl); @@ -1408,7 +1591,7 @@ static jlong NativeCrypto_SSL_get_options(JNIEnv* env, jclass, */ static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass, jint ssl_address, jlong options) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_set_options options=0x%llx", ssl, options); if (ssl == NULL) { return 0; @@ -1423,7 +1606,7 @@ static jlong NativeCrypto_SSL_set_options(JNIEnv* env, jclass, */ static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass, jint ssl_address, jlong options) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_clear_options options=0x%llx", ssl, options); if (ssl == NULL) { return 0; @@ -1440,7 +1623,7 @@ static jlong NativeCrypto_SSL_clear_options(JNIEnv* env, jclass, static jobjectArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, jclass, jint ssl_address) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_get_ciphers", ssl); if (ssl == NULL) { return NULL; @@ -1454,15 +1637,14 @@ static jobjectArray NativeCrypto_SSL_get_ciphers(JNIEnv* env, static void NativeCrypto_SSL_set_cipher_list(JNIEnv* env, jclass, jint ssl_address, jstring controlString) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_set_cipher_list controlString=%p", ssl, controlString); if (ssl == NULL) { return; } - const char* str = env->GetStringUTFChars(controlString, NULL); - JNI_TRACE("ssl=%p NativeCrypto_SSL_controlString str=%s", ssl, str); - int rc = SSL_set_cipher_list(ssl, str); - env->ReleaseStringUTFChars(controlString, str); + ScopedUtfChars str(env, controlString); + JNI_TRACE("ssl=%p NativeCrypto_SSL_controlString str=%s", ssl, str.c_str()); + int rc = SSL_set_cipher_list(ssl, str.c_str()); if (rc == 0) { freeSslErrorState(); jniThrowException(env, "java/lang/IllegalArgumentException", @@ -1476,7 +1658,7 @@ static void NativeCrypto_SSL_set_cipher_list(JNIEnv* env, jclass, static void NativeCrypto_SSL_set_verify(JNIEnv* env, jclass, jint ssl_address, jint mode) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_set_verify", ssl); if (ssl == NULL) { return; @@ -1490,8 +1672,8 @@ static void NativeCrypto_SSL_set_verify(JNIEnv* env, static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass, jint ssl_address, jint ssl_session_address) { - SSL* ssl = getSslPointer(env, ssl_address, true); - SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address)); + SSL* ssl = to_SSL(env, ssl_address, true); + SSL_SESSION* ssl_session = to_SSL_SESSION(ssl_session_address); JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session ssl_session=%p", ssl, ssl_session); if (ssl == NULL) { return; @@ -1505,7 +1687,7 @@ static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass, */ int sslErrorCode = SSL_get_error(ssl, ret); if (sslErrorCode != SSL_ERROR_ZERO_RETURN) { - throwSSLExceptionWithSslErrors(env, ret, sslErrorCode, + throwSSLExceptionWithSslErrors(env, sslErrorCode, "SSL session set"); SSL_clear(ssl); } @@ -1518,7 +1700,7 @@ static void NativeCrypto_SSL_set_session(JNIEnv* env, jclass, static void NativeCrypto_SSL_set_session_creation_enabled(JNIEnv* env, jclass, jint ssl_address, jboolean creation_enabled) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_set_session_creation_enabled creation_enabled=%d", ssl, creation_enabled); if (ssl == NULL) { return; @@ -1538,7 +1720,7 @@ static jfieldID field_Socket_mFD; static jint NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, jint ssl_address, jobject socketObject, jobject ccv, jobject hcc, jint timeout, jboolean client_mode) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake socketObject=%p ccv=%p timeout=%d client_mode=%d", ssl, socketObject, ccv, timeout, client_mode); if (ssl == NULL) { @@ -1585,7 +1767,7 @@ static jint NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake s=%d", ssl, fd); if (ret != 1) { - throwSSLExceptionWithSslErrors(env, ret, 0, + throwSSLExceptionWithSslErrors(env, 0, "Error setting the file descriptor"); SSL_clear(ssl); JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl); @@ -1654,8 +1836,7 @@ static jint NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, int selectResult = sslSelect(error, fd, appData, timeout); if (selectResult == -1) { - throwSSLExceptionWithSslErrors(env, -1, error, - "handshake error"); + throwSSLExceptionWithSslErrors(env, error, "handshake error"); SSL_clear(ssl); JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl); return 0; @@ -1667,7 +1848,7 @@ static jint NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, return 0; } } else { - LOGE("Unknown error %d during handshake", error); + // LOGE("Unknown error %d during handshake", error); break; } } @@ -1684,7 +1865,7 @@ static jint NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, (sslErrorCode == SSL_ERROR_SYSCALL && errno == 0)) { throwSSLExceptionStr(env, "Connection closed by peer"); } else { - throwSSLExceptionWithSslErrors(env, ret, sslErrorCode, + throwSSLExceptionWithSslErrors(env, sslErrorCode, "Trouble accepting connection"); } SSL_clear(ssl); @@ -1697,7 +1878,7 @@ static jint NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, * at this point. */ int sslErrorCode = SSL_get_error(ssl, ret); - throwSSLExceptionWithSslErrors(env, ret, sslErrorCode, + throwSSLExceptionWithSslErrors(env, sslErrorCode, "Trouble accepting connection"); SSL_clear(ssl); JNI_TRACE("ssl=%p NativeCrypto_SSL_do_handshake => 0", ssl); @@ -1713,7 +1894,7 @@ static jint NativeCrypto_SSL_do_handshake(JNIEnv* env, jclass, */ static jobjectArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jint ssl_address) { - SSL* ssl = getSslPointer(env, ssl_address, true); + SSL* ssl = to_SSL(env, ssl_address, true); JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate", ssl); if (ssl == NULL) { JNI_TRACE("ssl=%p NativeCrypto_SSL_get_certificate => NULL", ssl); @@ -1743,231 +1924,6 @@ static jobjectArray NativeCrypto_SSL_get_certificate(JNIEnv* env, jclass, jint s /** - * public static native void SSL_free(int ssl); - */ -static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jint ssl_address) -{ - SSL* ssl = getSslPointer(env, ssl_address, true); - JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl); - if (ssl == NULL) { - return; - } - AppData* appData = (AppData*) SSL_get_app_data(ssl); - SSL_set_app_data(ssl, NULL); - delete appData; - SSL_free(ssl); -} - -/** - * Gets and returns in a byte array the ID of the actual SSL session. - */ -static jbyteArray NativeCrypto_SSL_SESSION_session_id(JNIEnv* env, jclass, jint ssl_session_address) { - SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address)); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id", ssl_session); - jbyteArray result = env->NewByteArray(ssl_session->session_id_length); - if (result != NULL) { - jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id); - env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src); - } - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id => %p session_id_length=%d", - ssl_session, result, ssl_session->session_id_length); - return result; -} - -/** - * Our implementation of what might be considered - * SSL_SESSION_get_peer_cert_chain - * - */ -// TODO move to jsse.patch -static STACK_OF(X509)* SSL_SESSION_get_peer_cert_chain(SSL_CTX* ssl_ctx, SSL_SESSION* ssl_session) { - SSL* ssl = SSL_new(ssl_ctx); - SSL_set_session(ssl, ssl_session); - STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl); - SSL_free(ssl); - return chain; -} - -// Fills a byte[][] with the peer certificates in the chain. -static jobjectArray NativeCrypto_SSL_SESSION_get_peer_cert_chain(JNIEnv* env, - jclass, jint ssl_ctx_address, jint ssl_session_address) -{ - SSL_CTX* ssl_ctx = reinterpret_cast<SSL_CTX*>(static_cast<uintptr_t>(ssl_ctx_address)); - SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address)); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_peer_cert_chain ssl_ctx=%p", ssl_session, ssl_ctx); - if (ssl_ctx == NULL) { - jniThrowNullPointerException(env, "SSL_CTX is null"); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_peer_cert_chain => NULL", ssl_session); - return NULL; - } - STACK_OF(X509)* chain = SSL_SESSION_get_peer_cert_chain(ssl_ctx, ssl_session); - jobjectArray objectArray = getCertificateBytes(env, chain); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_peer_cert_chain => %p", ssl_session, objectArray); - return objectArray; -} - -/** - * Gets and returns in a long integer the creation's time of the - * actual SSL session. - */ -static jlong NativeCrypto_SSL_SESSION_get_time(JNIEnv* env, jclass, jint ssl_session_address) { - SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address)); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time", ssl_session); - jlong result = SSL_SESSION_get_time(ssl_session); // must be jlong, not long or *1000 will overflow - result *= 1000; // OpenSSL uses seconds, Java uses milliseconds. - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time => %lld", ssl_session, result); - return result; -} - -/** - * Our implementation of what might be considered - * SSL_SESSION_get_version, based on SSL_get_version. - * See get_ssl_version above. - */ -// TODO move to jsse.patch -static const char* SSL_SESSION_get_version(SSL_SESSION* ssl_session) { - return get_ssl_version(ssl_session->ssl_version); -} - -/** - * Gets and returns in a string the version of the SSL protocol. If it - * returns the string "unknown" it means that no connection is established. - */ -static jstring NativeCrypto_SSL_SESSION_get_version(JNIEnv* env, jclass, jint ssl_session_address) { - SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address)); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version", ssl_session); - const char* protocol = SSL_SESSION_get_version(ssl_session); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version => %s", ssl_session, protocol); - jstring result = env->NewStringUTF(protocol); - return result; -} - -/** - * Gets and returns in a string the set of ciphers the actual SSL session uses. - */ -static jstring NativeCrypto_SSL_SESSION_cipher(JNIEnv* env, jclass, jint ssl_session_address) { - SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address)); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher", ssl_session); - const SSL_CIPHER* cipher = ssl_session->cipher; - const char* name = SSL_CIPHER_get_name(cipher); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher => %s", ssl_session, name); - return env->NewStringUTF(name); -} - -/** - * Frees the SSL session. - */ -static void NativeCrypto_SSL_SESSION_free(JNIEnv* env, jclass, jint session) { - SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(session); - JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_free", ssl_session); - SSL_SESSION_free(ssl_session); -} - - -/** - * Serializes the native state of the session (ID, cipher, and keys but - * not certificates). Returns a byte[] containing the DER-encoded state. - * See apache mod_ssl. - */ -static jbyteArray NativeCrypto_i2d_SSL_SESSION(JNIEnv* env, jclass, jint ssl_session_address) { - SSL_SESSION* ssl_session = reinterpret_cast<SSL_SESSION*>(static_cast<uintptr_t>(ssl_session_address)); - JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION", ssl_session); - if (ssl_session == NULL) { - JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION => NULL", ssl_session); - return NULL; - } - - // Compute the size of the DER data - int size = i2d_SSL_SESSION(ssl_session, NULL); - if (size == 0) { - JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION => NULL", ssl_session); - return NULL; - } - - jbyteArray bytes = env->NewByteArray(size); - if (bytes != NULL) { - jbyte* tmp = env->GetByteArrayElements(bytes, NULL); - unsigned char* ucp = reinterpret_cast<unsigned char*>(tmp); - i2d_SSL_SESSION(ssl_session, &ucp); - env->ReleaseByteArrayElements(bytes, tmp, 0); - } - - JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION => size=%d", ssl_session, size); - return bytes; -} - -/** - * Deserialize the session. - */ -static jint NativeCrypto_d2i_SSL_SESSION(JNIEnv* env, jclass, jbyteArray bytes, jint size) { - JNI_TRACE("NativeCrypto_d2i_SSL_SESSION bytes=%p size=%d", bytes, size); - if (bytes == NULL) { - JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => 0"); - return 0; - } - - jbyte* tmp = env->GetByteArrayElements(bytes, NULL); - const unsigned char* ucp = reinterpret_cast<const unsigned char*>(tmp); - SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, size); - env->ReleaseByteArrayElements(bytes, tmp, 0); - - JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => %p", ssl_session); - return static_cast<jint>(reinterpret_cast<uintptr_t>(ssl_session)); -} - -/* - * Defines the mapping from Java methods and their signatures - * to native functions. Order is (1) Java name, (2) signature, - * (3) pointer to C function. - */ -static JNINativeMethod sNativeCryptoMethods[] = { - { "clinit", "()V", (void*)NativeCrypto_clinit}, - { "EVP_PKEY_new_DSA", "([B[B[B[B[B)I", (void*)NativeCrypto_EVP_PKEY_new_DSA }, - { "EVP_PKEY_new_RSA", "([B[B[B[B[B)I", (void*)NativeCrypto_EVP_PKEY_new_RSA }, - { "EVP_PKEY_free", "(I)V", (void*)NativeCrypto_EVP_PKEY_free }, - { "EVP_new", "()I", (void*)NativeCrypto_EVP_new }, - { "EVP_free", "(I)V", (void*)NativeCrypto_EVP_free }, - { "EVP_DigestFinal", "(I[BI)I", (void*)NativeCrypto_EVP_DigestFinal }, - { "EVP_DigestInit", "(ILjava/lang/String;)V", (void*)NativeCrypto_EVP_DigestInit }, - { "EVP_DigestBlockSize", "(I)I", (void*)NativeCrypto_EVP_DigestBlockSize }, - { "EVP_DigestSize", "(I)I", (void*)NativeCrypto_EVP_DigestSize }, - { "EVP_DigestUpdate", "(I[BII)V", (void*)NativeCrypto_EVP_DigestUpdate }, - { "EVP_VerifyInit", "(ILjava/lang/String;)V", (void*)NativeCrypto_EVP_VerifyInit }, - { "EVP_VerifyUpdate", "(I[BII)V", (void*)NativeCrypto_EVP_VerifyUpdate }, - { "EVP_VerifyFinal", "(I[BIII)I", (void*)NativeCrypto_EVP_VerifyFinal }, - { "SSL_CTX_new", "()I", (void*)NativeCrypto_SSL_CTX_new }, - { "SSL_CTX_get_ciphers", "(I)[Ljava/lang/String;", (void*)NativeCrypto_SSL_CTX_get_ciphers}, - { "SSL_CTX_free", "(I)V", (void*)NativeCrypto_SSL_CTX_free }, - { "SSL_new", "(ILjava/lang/String;Ljava/lang/String;[B)I", (void*)NativeCrypto_SSL_new}, - { "SSL_get_mode", "(I)J", (void*)NativeCrypto_SSL_get_mode }, - { "SSL_set_mode", "(IJ)J", (void*)NativeCrypto_SSL_set_mode }, - { "SSL_clear_mode", "(IJ)J", (void*)NativeCrypto_SSL_clear_mode }, - { "SSL_get_options", "(I)J", (void*)NativeCrypto_SSL_get_options }, - { "SSL_set_options", "(IJ)J", (void*)NativeCrypto_SSL_set_options }, - { "SSL_clear_options", "(IJ)J", (void*)NativeCrypto_SSL_clear_options }, - { "SSL_get_ciphers", "(I)[Ljava/lang/String;", (void*)NativeCrypto_SSL_get_ciphers }, - { "SSL_set_cipher_list", "(ILjava/lang/String;)V", (void*)NativeCrypto_SSL_set_cipher_list }, - { "SSL_set_verify", "(II)V", (void*)NativeCrypto_SSL_set_verify}, - { "SSL_set_session", "(II)V", (void*)NativeCrypto_SSL_set_session }, - { "SSL_set_session_creation_enabled", "(IZ)V", (void*)NativeCrypto_SSL_set_session_creation_enabled }, - { "SSL_do_handshake", "(ILjava/net/Socket;Lorg/apache/harmony/xnet/provider/jsse/NativeCrypto$CertificateChainVerifier;Lorg/apache/harmony/xnet/provider/jsse/NativeCrypto$HandshakeCompletedCallback;IZ)I",(void*)NativeCrypto_SSL_do_handshake}, - { "SSL_get_certificate", "(I)[[B", (void*)NativeCrypto_SSL_get_certificate}, - { "SSL_free", "(I)V", (void*)NativeCrypto_SSL_free}, - { "SSL_SESSION_session_id", "(I)[B", (void*)NativeCrypto_SSL_SESSION_session_id }, - { "SSL_SESSION_get_peer_cert_chain", "(II)[[B", (void*)NativeCrypto_SSL_SESSION_get_peer_cert_chain }, - { "SSL_SESSION_get_time", "(I)J", (void*)NativeCrypto_SSL_SESSION_get_time }, - { "SSL_SESSION_get_version", "(I)Ljava/lang/String;", (void*)NativeCrypto_SSL_SESSION_get_version }, - { "SSL_SESSION_cipher", "(I)Ljava/lang/String;", (void*)NativeCrypto_SSL_SESSION_cipher }, - { "SSL_SESSION_free", "(I)V", (void*)NativeCrypto_SSL_SESSION_free }, - { "i2d_SSL_SESSION", "(I)[B", (void*)NativeCrypto_i2d_SSL_SESSION }, - { "d2i_SSL_SESSION", "([BI)I", (void*)NativeCrypto_d2i_SSL_SESSION }, -}; - -// ============================================================================ -// === OpenSSL-related helper stuff begins here. ============================== -// ============================================================================ - -/** * Helper function which does the actual reading. The Java layer guarantees that * at most one thread will enter this function at any given time. * @@ -2089,6 +2045,84 @@ static int sslRead(JNIEnv* env, SSL* ssl, char* buf, jint len, int* sslReturnCod } /** + * OpenSSL read function (1): only one chunk is read (returned as jint). + */ +static jint NativeCrypto_SSL_read_byte(JNIEnv* env, jclass, jint ssl_address, jint timeout) +{ + SSL* ssl = to_SSL(env, ssl_address, true); + JNI_TRACE("ssl=%p NativeCrypto_SSL_read_byte timeout=%d", ssl, timeout); + if (ssl == NULL) { + return 0; + } + + unsigned char byteRead; + int returnCode = 0; + int errorCode = 0; + + int ret = sslRead(env, ssl, (char *) &byteRead, 1, &returnCode, &errorCode, timeout); + + int result; + switch (ret) { + case THROW_EXCEPTION: + // See sslRead() regarding improper failure to handle normal cases. + throwSSLExceptionWithSslErrors(env, errorCode, "Read error"); + result = -1; + break; + case THROW_SOCKETTIMEOUTEXCEPTION: + throwSocketTimeoutException(env, "Read timed out"); + result = -1; + break; + case -1: + // Propagate EOF upwards. + result = -1; + break; + default: + // Return the actual char read, make sure it stays 8 bits wide. + result = ((jint) byteRead) & 0xFF; + break; + } + JNI_TRACE("ssl=%p NativeCrypto_SSL_read_byte => %d", ssl, result); + return result; +} + +/** + * OpenSSL read function (2): read into buffer at offset n chunks. + * Returns 1 (success) or value <= 0 (failure). + */ +static jint NativeCrypto_SSL_read(JNIEnv* env, jclass, jint ssl_address, jbyteArray dest, jint offset, jint len, jint timeout) +{ + SSL* ssl = to_SSL(env, ssl_address, true); + JNI_TRACE("ssl=%p NativeCrypto_SSL_read dest=%p offset=%d len=%d timeout=%d", ssl, dest, offset, len, timeout); + if (ssl == NULL) { + return 0; + } + + jbyte* bytes = env->GetByteArrayElements(dest, NULL); + int returnCode = 0; + int errorCode = 0; + + int ret = sslRead(env, ssl, (char*) (bytes + offset), len, &returnCode, &errorCode, timeout); + + env->ReleaseByteArrayElements(dest, bytes, 0); + + int result; + if (ret == THROW_EXCEPTION) { + // See sslRead() regarding improper failure to handle normal cases. + throwSSLExceptionWithSslErrors(env, errorCode, + "Read error"); + result = -1; + } else if(ret == THROW_SOCKETTIMEOUTEXCEPTION) { + throwSocketTimeoutException(env, "Read timed out"); + result = -1; + } else { + result = ret; + } + + JNI_TRACE("ssl=%p NativeCrypto_SSL_read => %d", ssl, result); + return result; +} + +/** * Helper function which does the actual writing. The Java layer guarantees that * at most one thread will enter this function at any given time. * @@ -2213,198 +2247,12 @@ static int sslWrite(JNIEnv* env, SSL* ssl, const char* buf, jint len, int* sslRe } /** - * Helper function that creates an RSA public key from two buffers containing - * the big-endian bit representation of the modulus and the public exponent. - * - * @param mod The data of the modulus - * @param modLen The length of the modulus data - * @param exp The data of the exponent - * @param expLen The length of the exponent data - * - * @return A pointer to the new RSA structure, or NULL on error - */ -static RSA* rsaCreateKey(unsigned char* mod, int modLen, unsigned char* exp, int expLen) { - // LOGD("Entering rsaCreateKey()"); - - RSA* rsa = RSA_new(); - - rsa->n = BN_bin2bn((unsigned char*) mod, modLen, NULL); - rsa->e = BN_bin2bn((unsigned char*) exp, expLen, NULL); - - if (rsa->n == NULL || rsa->e == NULL) { - RSA_free(rsa); - return NULL; - } - - return rsa; -} - -/** - * Helper function that frees an RSA key. Just calls the corresponding OpenSSL - * function. - * - * @param rsa The pointer to the new RSA structure to free. - */ -static void rsaFreeKey(RSA* rsa) { - // LOGD("Entering rsaFreeKey()"); - - if (rsa != NULL) { - RSA_free(rsa); - } -} - -/** - * Helper function that verifies a given RSA signature for a given message. - * - * @param msg The message to verify - * @param msgLen The length of the message - * @param sig The signature to verify - * @param sigLen The length of the signature - * @param algorithm The name of the hash/sign algorithm to use, e.g. "RSA-SHA1" - * @param rsa The RSA public key to use - * - * @return 1 on success, 0 on failure, -1 on error (check SSL errors then) - * - */ -static int rsaVerify(unsigned char* msg, unsigned int msgLen, unsigned char* sig, - unsigned int sigLen, char* algorithm, RSA* rsa) { - - // LOGD("Entering rsaVerify(%x, %d, %x, %d, %s, %x)", msg, msgLen, sig, sigLen, algorithm, rsa); - - int result = -1; - - EVP_PKEY* key = EVP_PKEY_new(); - EVP_PKEY_set1_RSA(key, rsa); - - const EVP_MD *type = EVP_get_digestbyname(algorithm); - if (type == NULL) { - goto cleanup; - } - - EVP_MD_CTX ctx; - - EVP_MD_CTX_init(&ctx); - if (EVP_VerifyInit_ex(&ctx, type, NULL) == 0) { - goto cleanup; - } - - EVP_VerifyUpdate(&ctx, msg, msgLen); - result = EVP_VerifyFinal(&ctx, sig, sigLen, key); - EVP_MD_CTX_cleanup(&ctx); - - cleanup: - - if (key != NULL) { - EVP_PKEY_free(key); - } - - return result; -} - -// ============================================================================ -// === OpenSSL-related helper stuff ends here. JNI glue follows. ============== -// ============================================================================ - -static jint org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_getsslsession(JNIEnv* env, jclass, - jint ssl_address) -{ - SSL* ssl = getSslPointer(env, ssl_address, true); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_getsslsession", ssl); - if (ssl == NULL) { - JNI_TRACE("ssl=%p OpenSSLSocketImpl_getsslsession => NULL", ssl); - return NULL; - } - SSL_SESSION* ssl_session = SSL_get1_session(ssl); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_getsslsession => ssl_session=%p", ssl, ssl_session); - return (jint) ssl_session; -} - -/** - * OpenSSL read function (1): only one chunk is read (returned as jint). - */ -static jint org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_read(JNIEnv* env, jclass, jint ssl_address, jint timeout) -{ - SSL* ssl = getSslPointer(env, ssl_address, true); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_readba timeout=%d", ssl, timeout); - if (ssl == NULL) { - return 0; - } - - unsigned char byteRead; - int returnCode = 0; - int errorCode = 0; - - int ret = sslRead(env, ssl, (char *) &byteRead, 1, &returnCode, &errorCode, timeout); - - int result; - switch (ret) { - case THROW_EXCEPTION: - // See sslRead() regarding improper failure to handle normal cases. - throwSSLExceptionWithSslErrors(env, returnCode, errorCode, - "Read error"); - result = -1; - break; - case THROW_SOCKETTIMEOUTEXCEPTION: - throwSocketTimeoutException(env, "Read timed out"); - result = -1; - break; - case -1: - // Propagate EOF upwards. - result = -1; - break; - default: - // Return the actual char read, make sure it stays 8 bits wide. - result = ((jint) byteRead) & 0xFF; - break; - } - JNI_TRACE("ssl=%p OpenSSLSocketImpl_read => %d", ssl, result); - return result; -} - -/** - * OpenSSL read function (2): read into buffer at offset n chunks. - * Returns 1 (success) or value <= 0 (failure). - */ -static jint org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_readba(JNIEnv* env, jclass, jint ssl_address, jbyteArray dest, jint offset, jint len, jint timeout) -{ - SSL* ssl = getSslPointer(env, ssl_address, true); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_readba dest=%p offset=%d len=%d timeout=%d", ssl, dest, offset, len, timeout); - if (ssl == NULL) { - return 0; - } - - jbyte* bytes = env->GetByteArrayElements(dest, NULL); - int returnCode = 0; - int errorCode = 0; - - int ret = sslRead(env, ssl, (char*) (bytes + offset), len, &returnCode, &errorCode, timeout); - - env->ReleaseByteArrayElements(dest, bytes, 0); - - int result; - if (ret == THROW_EXCEPTION) { - // See sslRead() regarding improper failure to handle normal cases. - throwSSLExceptionWithSslErrors(env, returnCode, errorCode, - "Read error"); - result = -1; - } else if(ret == THROW_SOCKETTIMEOUTEXCEPTION) { - throwSocketTimeoutException(env, "Read timed out"); - result = -1; - } else { - result = ret; - } - - JNI_TRACE("ssl=%p OpenSSLSocketImpl_readba => %d", ssl, result); - return result; -} - -/** * OpenSSL write function (1): only one chunk is written. */ -static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_write(JNIEnv* env, jclass, jint ssl_address, jint b) +static void NativeCrypto_SSL_write_byte(JNIEnv* env, jclass, jint ssl_address, jint b) { - SSL* ssl = getSslPointer(env, ssl_address, true); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_write b=%d", ssl, b); + SSL* ssl = to_SSL(env, ssl_address, true); + JNI_TRACE("ssl=%p NativeCrypto_SSL_write_byte b=%d", ssl, b); if (ssl == NULL) { return; } @@ -2416,7 +2264,7 @@ static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_write(JNIEnv if (ret == THROW_EXCEPTION) { // See sslWrite() regarding improper failure to handle normal cases. - throwSSLExceptionWithSslErrors(env, returnCode, errorCode, + throwSSLExceptionWithSslErrors(env, errorCode, "Write error"); } else if(ret == THROW_SOCKETTIMEOUTEXCEPTION) { throwSocketTimeoutException(env, "Write timed out"); @@ -2426,25 +2274,23 @@ static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_write(JNIEnv /** * OpenSSL write function (2): write into buffer at offset n chunks. */ -static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_writeba(JNIEnv* env, jclass, +static void NativeCrypto_SSL_write(JNIEnv* env, jclass, jint ssl_address, jbyteArray dest, jint offset, jint len) { - SSL* ssl = getSslPointer(env, ssl_address, true); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_writeba dest=%p offset=%d len=%d", ssl, dest, offset, len); + SSL* ssl = to_SSL(env, ssl_address, true); + JNI_TRACE("ssl=%p NativeCrypto_SSL_write dest=%p offset=%d len=%d", ssl, dest, offset, len); if (ssl == NULL) { return; } - jbyte* bytes = env->GetByteArrayElements(dest, NULL); + ScopedByteArray bytes(env, dest); int returnCode = 0; int errorCode = 0; - int ret = sslWrite(env, ssl, (const char *) (bytes + offset), len, &returnCode, &errorCode); - - env->ReleaseByteArrayElements(dest, bytes, 0); + int ret = sslWrite(env, ssl, (const char *) (bytes.bytes() + offset), len, &returnCode, &errorCode); if (ret == THROW_EXCEPTION) { // See sslWrite() regarding improper failure to handle normal cases. - throwSSLExceptionWithSslErrors(env, returnCode, errorCode, + throwSSLExceptionWithSslErrors(env, errorCode, "Write error"); } else if(ret == THROW_SOCKETTIMEOUTEXCEPTION) { throwSocketTimeoutException(env, "Write timed out"); @@ -2454,10 +2300,10 @@ static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_writeba(JNIE /** * Interrupt any pending IO before closing the socket. */ -static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_interrupt( +static void NativeCrypto_SSL_interrupt( JNIEnv* env, jclass, jint ssl_address) { - SSL* ssl = getSslPointer(env, ssl_address, false); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_interrupt", ssl); + SSL* ssl = to_SSL(env, ssl_address, false); + JNI_TRACE("ssl=%p NativeCrypto_SSL_interrupt", ssl); if (ssl == NULL) { return; } @@ -2479,10 +2325,10 @@ static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_interrupt( /** * OpenSSL close SSL socket function. */ -static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_close( +static void NativeCrypto_SSL_shutdown( JNIEnv* env, jclass, jint ssl_address) { - SSL* ssl = getSslPointer(env, ssl_address, false); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_close", ssl); + SSL* ssl = to_SSL(env, ssl_address, false); + JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown", ssl); if (ssl == NULL) { return; } @@ -2490,7 +2336,7 @@ static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_close( * Try to make socket blocking again. OpenSSL literature recommends this. */ int fd = SSL_get_fd(ssl); - JNI_TRACE("ssl=%p OpenSSLSocketImpl_close s=%d", ssl, fd); + JNI_TRACE("ssl=%p NativeCrypto_SSL_shutdown s=%d", ssl, fd); if (fd != -1) { int mode = fcntl(fd, F_GETFL); if (mode == -1 || fcntl(fd, F_SETFL, mode & ~O_NONBLOCK) == -1) { @@ -2527,7 +2373,7 @@ static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_close( * exception. */ int sslErrorCode = SSL_get_error(ssl, ret); - throwSSLExceptionWithSslErrors(env, ret, sslErrorCode, "SSL shutdown failed"); + throwSSLExceptionWithSslErrors(env, sslErrorCode, "SSL shutdown failed"); break; } @@ -2536,99 +2382,243 @@ static void org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_close( } /** - * Verifies an RSA signature. + * public static native void SSL_free(int ssl); */ -static int org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_verifysignature(JNIEnv* env, jclass clazz, - jbyteArray msg, jbyteArray sig, jstring algorithm, jbyteArray mod, jbyteArray exp) { +static void NativeCrypto_SSL_free(JNIEnv* env, jclass, jint ssl_address) +{ + SSL* ssl = to_SSL(env, ssl_address, true); + JNI_TRACE("ssl=%p NativeCrypto_SSL_free", ssl); + if (ssl == NULL) { + return; + } + AppData* appData = (AppData*) SSL_get_app_data(ssl); + SSL_set_app_data(ssl, NULL); + delete appData; + SSL_free(ssl); +} - JNI_TRACE("OpenSSLSocketImpl_verifysignature msg=%p sig=%p algorithm=%p mod=%p exp%p", - msg, sig, algorithm, mod, exp); +/** + * Gets and returns in a byte array the ID of the actual SSL session. + */ +static jbyteArray NativeCrypto_SSL_SESSION_session_id(JNIEnv* env, jclass, jint ssl_session_address) { + SSL_SESSION* ssl_session = to_SSL_SESSION(ssl_session_address); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id", ssl_session); + jbyteArray result = env->NewByteArray(ssl_session->session_id_length); + if (result != NULL) { + jbyte* src = reinterpret_cast<jbyte*>(ssl_session->session_id); + env->SetByteArrayRegion(result, 0, ssl_session->session_id_length, src); + } + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_session_id => %p session_id_length=%d", + ssl_session, result, ssl_session->session_id_length); + return result; +} - if (msg == NULL || sig == NULL || algorithm == NULL || mod == NULL || exp == NULL) { - jniThrowNullPointerException(env, NULL); - JNI_TRACE("OpenSSLSocketImpl_verifysignature => -1"); - return -1; +/** + * Our implementation of what might be considered + * SSL_SESSION_get_peer_cert_chain + * + */ +// TODO move to jsse.patch +static STACK_OF(X509)* SSL_SESSION_get_peer_cert_chain(SSL_CTX* ssl_ctx, SSL_SESSION* ssl_session) { + SSL* ssl = SSL_new(ssl_ctx); + if (ssl == NULL) { + return NULL; } + SSL_set_session(ssl, ssl_session); + STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl); + SSL_free(ssl); + return chain; +} - int result = -1; +// Fills a byte[][] with the peer certificates in the chain. +static jobjectArray NativeCrypto_SSL_SESSION_get_peer_cert_chain(JNIEnv* env, + jclass, jint ssl_ctx_address, jint ssl_session_address) +{ + SSL_CTX* ssl_ctx = to_SSL_CTX(ssl_ctx_address); + SSL_SESSION* ssl_session = to_SSL_SESSION(ssl_session_address); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_peer_cert_chain ssl_ctx=%p", ssl_session, ssl_ctx); + if (ssl_ctx == NULL) { + jniThrowNullPointerException(env, "SSL_CTX is null"); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_peer_cert_chain => NULL", ssl_session); + return NULL; + } + STACK_OF(X509)* chain = SSL_SESSION_get_peer_cert_chain(ssl_ctx, ssl_session); + jobjectArray objectArray = getCertificateBytes(env, chain); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_peer_cert_chain => %p", ssl_session, objectArray); + return objectArray; +} - jbyte* msgBytes = env->GetByteArrayElements(msg, NULL); - jint msgLength = env->GetArrayLength(msg); +/** + * Gets and returns in a long integer the creation's time of the + * actual SSL session. + */ +static jlong NativeCrypto_SSL_SESSION_get_time(JNIEnv*, jclass, jint ssl_session_address) { + SSL_SESSION* ssl_session = to_SSL_SESSION(ssl_session_address); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time", ssl_session); + jlong result = SSL_SESSION_get_time(ssl_session); // must be jlong, not long or *1000 will overflow + result *= 1000; // OpenSSL uses seconds, Java uses milliseconds. + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_time => %lld", ssl_session, result); + return result; +} - jbyte* sigBytes = env->GetByteArrayElements(sig, NULL); - jint sigLength = env->GetArrayLength(sig); +/** + * Our implementation of what might be considered + * SSL_SESSION_get_version, based on SSL_get_version. + * See get_ssl_version above. + */ +// TODO move to jsse.patch +static const char* SSL_SESSION_get_version(SSL_SESSION* ssl_session) { + return get_ssl_version(ssl_session->ssl_version); +} - jbyte* modBytes = env->GetByteArrayElements(mod, NULL); - jint modLength = env->GetArrayLength(mod); +/** + * Gets and returns in a string the version of the SSL protocol. If it + * returns the string "unknown" it means that no connection is established. + */ +static jstring NativeCrypto_SSL_SESSION_get_version(JNIEnv* env, jclass, jint ssl_session_address) { + SSL_SESSION* ssl_session = to_SSL_SESSION(ssl_session_address); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version", ssl_session); + const char* protocol = SSL_SESSION_get_version(ssl_session); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_get_version => %s", ssl_session, protocol); + return env->NewStringUTF(protocol); +} - jbyte* expBytes = env->GetByteArrayElements(exp, NULL); - jint expLength = env->GetArrayLength(exp); +/** + * Gets and returns in a string the set of ciphers the actual SSL session uses. + */ +static jstring NativeCrypto_SSL_SESSION_cipher(JNIEnv* env, jclass, jint ssl_session_address) { + SSL_SESSION* ssl_session = to_SSL_SESSION(ssl_session_address); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher", ssl_session); + const SSL_CIPHER* cipher = ssl_session->cipher; + const char* name = SSL_CIPHER_get_name(cipher); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_cipher => %s", ssl_session, name); + return env->NewStringUTF(name); +} - const char* algorithmChars = env->GetStringUTFChars(algorithm, NULL); - JNI_TRACE("OpenSSLSocketImpl_verifysignature algorithmChars=%s", algorithmChars); +/** + * Frees the SSL session. + */ +static void NativeCrypto_SSL_SESSION_free(JNIEnv*, jclass, jint ssl_session_address) { + SSL_SESSION* ssl_session = to_SSL_SESSION(ssl_session_address); + JNI_TRACE("ssl_session=%p NativeCrypto_SSL_SESSION_free", ssl_session); + SSL_SESSION_free(ssl_session); +} - RSA* rsa = rsaCreateKey((unsigned char*) modBytes, modLength, (unsigned char*) expBytes, expLength); - if (rsa != NULL) { - result = rsaVerify((unsigned char*) msgBytes, msgLength, (unsigned char*) sigBytes, sigLength, - (char*) algorithmChars, rsa); - rsaFreeKey(rsa); - } - env->ReleaseStringUTFChars(algorithm, algorithmChars); +/** + * Serializes the native state of the session (ID, cipher, and keys but + * not certificates). Returns a byte[] containing the DER-encoded state. + * See apache mod_ssl. + */ +static jbyteArray NativeCrypto_i2d_SSL_SESSION(JNIEnv* env, jclass, jint ssl_session_address) { + SSL_SESSION* ssl_session = to_SSL_SESSION(ssl_session_address); + JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION", ssl_session); + if (ssl_session == NULL) { + JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION => NULL", ssl_session); + return NULL; + } - env->ReleaseByteArrayElements(exp, expBytes, JNI_ABORT); - env->ReleaseByteArrayElements(mod, modBytes, JNI_ABORT); - env->ReleaseByteArrayElements(sig, sigBytes, JNI_ABORT); - env->ReleaseByteArrayElements(msg, msgBytes, JNI_ABORT); + // Compute the size of the DER data + int size = i2d_SSL_SESSION(ssl_session, NULL); + if (size == 0) { + JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION => NULL", ssl_session); + return NULL; + } - if (result == -1) { - int error = ERR_get_error(); - if (error != 0) { - char message[50]; - ERR_error_string_n(error, message, sizeof(message)); - jniThrowRuntimeException(env, message); - } else { - jniThrowRuntimeException(env, "Internal error during verification"); - } - freeSslErrorState(); + jbyteArray bytes = env->NewByteArray(size); + if (bytes != NULL) { + jbyte* tmp = env->GetByteArrayElements(bytes, NULL); + unsigned char* ucp = reinterpret_cast<unsigned char*>(tmp); + i2d_SSL_SESSION(ssl_session, &ucp); + env->ReleaseByteArrayElements(bytes, tmp, 0); } - JNI_TRACE("OpenSSLSocketImpl_verifysignature => %d", result); - return result; + JNI_TRACE("ssl_session=%p NativeCrypto_i2d_SSL_SESSION => size=%d", ssl_session, size); + return bytes; } -static JNINativeMethod sSocketImplMethods[] = -{ - {"nativeread", "(II)I", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_read}, - {"nativeread", "(I[BIII)I", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_readba}, - {"nativewrite", "(II)V", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_write}, - {"nativewrite", "(I[BII)V", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_writeba}, - {"nativeinterrupt", "(I)V", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_interrupt}, - {"nativeclose", "(I)V", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_close}, - {"nativeverifysignature", "([B[BLjava/lang/String;[B[B)I", (void*)org_apache_harmony_xnet_provider_jsse_OpenSSLSocketImpl_verifysignature}, -}; +/** + * Deserialize the session. + */ +static jint NativeCrypto_d2i_SSL_SESSION(JNIEnv* env, jclass, jbyteArray bytes, jint size) { + JNI_TRACE("NativeCrypto_d2i_SSL_SESSION bytes=%p size=%d", bytes, size); + if (bytes == NULL) { + JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => 0"); + return 0; + } -typedef struct { - const char* name; - const JNINativeMethod* methods; - jint nMethods; -} JNINativeClass; + ScopedByteArray tmp(env, bytes); + const unsigned char* ucp = reinterpret_cast<const unsigned char*>(tmp.bytes()); + SSL_SESSION* ssl_session = d2i_SSL_SESSION(NULL, &ucp, size); + + JNI_TRACE("NativeCrypto_d2i_SSL_SESSION => %p", ssl_session); + return static_cast<jint>(reinterpret_cast<uintptr_t>(ssl_session)); +} -static JNINativeClass sClasses[] = { - { "org/apache/harmony/xnet/provider/jsse/NativeCrypto", sNativeCryptoMethods, NELEM(sNativeCryptoMethods) }, - { "org/apache/harmony/xnet/provider/jsse/OpenSSLSocketImpl", sSocketImplMethods, NELEM(sSocketImplMethods) }, +/* + * Defines the mapping from Java methods and their signatures + * to native functions. Order is (1) Java name, (2) signature, + * (3) pointer to C function. + */ +static JNINativeMethod sNativeCryptoMethods[] = { + { "clinit", "()V", (void*)NativeCrypto_clinit}, + { "EVP_PKEY_new_DSA", "([B[B[B[B[B)I", (void*)NativeCrypto_EVP_PKEY_new_DSA }, + { "EVP_PKEY_new_RSA", "([B[B[B[B[B)I", (void*)NativeCrypto_EVP_PKEY_new_RSA }, + { "EVP_PKEY_free", "(I)V", (void*)NativeCrypto_EVP_PKEY_free }, + { "EVP_new", "()I", (void*)NativeCrypto_EVP_new }, + { "EVP_free", "(I)V", (void*)NativeCrypto_EVP_free }, + { "EVP_DigestFinal", "(I[BI)I", (void*)NativeCrypto_EVP_DigestFinal }, + { "EVP_DigestInit", "(ILjava/lang/String;)V", (void*)NativeCrypto_EVP_DigestInit }, + { "EVP_DigestBlockSize", "(I)I", (void*)NativeCrypto_EVP_DigestBlockSize }, + { "EVP_DigestSize", "(I)I", (void*)NativeCrypto_EVP_DigestSize }, + { "EVP_DigestUpdate", "(I[BII)V", (void*)NativeCrypto_EVP_DigestUpdate }, + { "EVP_VerifyInit", "(ILjava/lang/String;)V", (void*)NativeCrypto_EVP_VerifyInit }, + { "EVP_VerifyUpdate", "(I[BII)V", (void*)NativeCrypto_EVP_VerifyUpdate }, + { "EVP_VerifyFinal", "(I[BIII)I", (void*)NativeCrypto_EVP_VerifyFinal }, + { "verifySignature", "([B[BLjava/lang/String;[B[B)I", (void*)NativeCrypto_verifysignature}, + { "SSL_CTX_new", "()I", (void*)NativeCrypto_SSL_CTX_new }, + { "SSL_CTX_get_ciphers", "(I)[Ljava/lang/String;", (void*)NativeCrypto_SSL_CTX_get_ciphers}, + { "SSL_CTX_free", "(I)V", (void*)NativeCrypto_SSL_CTX_free }, + { "SSL_new", "(ILjava/lang/String;Ljava/lang/String;[B)I", (void*)NativeCrypto_SSL_new}, + { "SSL_get_mode", "(I)J", (void*)NativeCrypto_SSL_get_mode }, + { "SSL_set_mode", "(IJ)J", (void*)NativeCrypto_SSL_set_mode }, + { "SSL_clear_mode", "(IJ)J", (void*)NativeCrypto_SSL_clear_mode }, + { "SSL_get_options", "(I)J", (void*)NativeCrypto_SSL_get_options }, + { "SSL_set_options", "(IJ)J", (void*)NativeCrypto_SSL_set_options }, + { "SSL_clear_options", "(IJ)J", (void*)NativeCrypto_SSL_clear_options }, + { "SSL_get_ciphers", "(I)[Ljava/lang/String;", (void*)NativeCrypto_SSL_get_ciphers }, + { "SSL_set_cipher_list", "(ILjava/lang/String;)V", (void*)NativeCrypto_SSL_set_cipher_list }, + { "SSL_set_verify", "(II)V", (void*)NativeCrypto_SSL_set_verify}, + { "SSL_set_session", "(II)V", (void*)NativeCrypto_SSL_set_session }, + { "SSL_set_session_creation_enabled", "(IZ)V", (void*)NativeCrypto_SSL_set_session_creation_enabled }, + { "SSL_do_handshake", "(ILjava/net/Socket;Lorg/apache/harmony/xnet/provider/jsse/NativeCrypto$CertificateChainVerifier;Lorg/apache/harmony/xnet/provider/jsse/NativeCrypto$HandshakeCompletedCallback;IZ)I",(void*)NativeCrypto_SSL_do_handshake}, + { "SSL_get_certificate", "(I)[[B", (void*)NativeCrypto_SSL_get_certificate}, + { "SSL_read_byte", "(II)I", (void*)NativeCrypto_SSL_read_byte}, + { "SSL_read", "(I[BIII)I", (void*)NativeCrypto_SSL_read}, + { "SSL_write_byte", "(II)V", (void*)NativeCrypto_SSL_write_byte}, + { "SSL_write", "(I[BII)V", (void*)NativeCrypto_SSL_write}, + { "SSL_interrupt", "(I)V", (void*)NativeCrypto_SSL_interrupt}, + { "SSL_shutdown", "(I)V", (void*)NativeCrypto_SSL_shutdown}, + { "SSL_free", "(I)V", (void*)NativeCrypto_SSL_free}, + { "SSL_SESSION_session_id", "(I)[B", (void*)NativeCrypto_SSL_SESSION_session_id }, + { "SSL_SESSION_get_peer_cert_chain", "(II)[[B", (void*)NativeCrypto_SSL_SESSION_get_peer_cert_chain }, + { "SSL_SESSION_get_time", "(I)J", (void*)NativeCrypto_SSL_SESSION_get_time }, + { "SSL_SESSION_get_version", "(I)Ljava/lang/String;", (void*)NativeCrypto_SSL_SESSION_get_version }, + { "SSL_SESSION_cipher", "(I)Ljava/lang/String;", (void*)NativeCrypto_SSL_SESSION_cipher }, + { "SSL_SESSION_free", "(I)V", (void*)NativeCrypto_SSL_SESSION_free }, + { "i2d_SSL_SESSION", "(I)[B", (void*)NativeCrypto_i2d_SSL_SESSION }, + { "d2i_SSL_SESSION", "([BI)I", (void*)NativeCrypto_d2i_SSL_SESSION }, }; + int register_org_apache_harmony_xnet_provider_jsse_NativeCrypto(JNIEnv* env) { JNI_TRACE("register_org_apache_harmony_xnet_provider_jsse_NativeCrypto"); - // Register org.apache.harmony.xnet.provider.jsse.* methods - for (int i = 0; i < NELEM(sClasses); i++) { - int result = jniRegisterNativeMethods(env, - sClasses[i].name, - sClasses[i].methods, - sClasses[i].nMethods); - if (result == -1) { - return -1; - } + // Register org.apache.harmony.xnet.provider.jsse.NativeCrypto methods + int result = jniRegisterNativeMethods(env, + "org/apache/harmony/xnet/provider/jsse/NativeCrypto", + sNativeCryptoMethods, + NELEM(sNativeCryptoMethods)); + if (result == -1) { + return -1; } // java.net.Socket diff --git a/luni/src/main/native/sieb.c b/luni/src/main/native/sieb.c deleted file mode 100644 index 4529307..0000000 --- a/luni/src/main/native/sieb.c +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2009 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "sieb.h" -#include "JNIHelp.h" -#include "jni.h" - -#include <stdlib.h> - -// Throw java.lang.OutOfMemoryError -void throwNewOutOfMemoryError(JNIEnv *env, const char *message) { - jniThrowException(env, "java/lang/OutOfMemoryError", message); -} - -void *sieb_malloc(JNIEnv *env, size_t byteCnt) { - void *adr = malloc(byteCnt); - if (adr == 0) { - if (byteCnt == 0) { - throwNewOutOfMemoryError(env, "sieb_malloc(0) NOT ALLOWED"); - } else { - throwNewOutOfMemoryError(env, "sieb_malloc"); - } - } - return adr; -} - -void sieb_free(JNIEnv *env, void *adr) { - free(adr); -} - -void sieb_convertToPlatform(char *path) { - char *pathIndex; - - pathIndex = path; - while (*pathIndex != '\0') { - if (*pathIndex == '\\') { - *pathIndex = '/'; - } - pathIndex++; - } -} diff --git a/luni/src/main/native/sieb.h b/luni/src/main/native/sieb.h deleted file mode 100644 index c32da04..0000000 --- a/luni/src/main/native/sieb.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (C) 2009 The Android Open Source Project - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#if !defined(sieb_h) -#define sieb_h - -#include "JNIHelp.h" -#include "jni.h" - -void throwNewOutOfMemoryError(JNIEnv *env, const char *message); -void *sieb_malloc(JNIEnv *env, size_t byteCnt); -void sieb_free(JNIEnv *env, void *adr); -void sieb_convertToPlatform(char *path); - -#endif /* sieb_h */ diff --git a/luni/src/main/native/sub.mk b/luni/src/main/native/sub.mk index cf71bcf..59f82a7 100644 --- a/luni/src/main/native/sub.mk +++ b/luni/src/main/native/sub.mk @@ -3,54 +3,51 @@ # or BUILD_*_LIBRARY. LOCAL_SRC_FILES := \ + BidiWrapper.cpp \ + ErrorCode.cpp \ + ICU.cpp \ + NativeBreakIterator.cpp \ + NativeCollation.cpp \ + NativeConverter.cpp \ + NativeDecimalFormat.cpp \ + NativeIDN.cpp \ + NativeNormalizer.cpp \ + NativeRegEx.cpp \ + Register.cpp \ + UCharacter.cpp \ + cbigint.cpp \ + commonDblParce.cpp \ java_io_Console.cpp \ java_io_File.cpp \ java_io_FileDescriptor.c \ - java_io_ObjectInputStream.c \ - java_io_ObjectOutputStream.c \ - java_io_ObjectStreamClass.c \ - java_lang_Double.c \ - java_lang_Float.c \ - java_lang_Math.c \ - java_lang_ProcessManager.cpp \ - java_lang_StrictMath.c \ - java_lang_System.cpp \ + java_io_ObjectInputStream.cpp \ + java_io_ObjectOutputStream.cpp \ + java_io_ObjectStreamClass.cpp \ + java_lang_Double.cpp \ + java_lang_Float.cpp \ + java_lang_Math.cpp \ + java_lang_ProcessManager.cpp \ + java_lang_StrictMath.cpp \ + java_lang_System.cpp \ java_net_InetAddress.cpp \ java_net_NetworkInterface.cpp \ - java_util_zip_Adler32.c \ - java_util_zip_CRC32.c \ - java_util_zip_Deflater.c \ - java_util_zip_Inflater.c \ - cbigint.c \ - commonDblParce.c \ - org_apache_harmony_luni_util_fltparse.c \ - org_apache_harmony_luni_util_NumberConvert.c \ - org_apache_harmony_luni_platform_OSNetworkSystem.cpp \ + java_util_zip_Adler32.cpp \ + java_util_zip_CRC32.cpp \ + java_util_zip_Deflater.cpp \ + java_util_zip_Inflater.cpp \ org_apache_harmony_luni_platform_OSFileSystem.cpp \ org_apache_harmony_luni_platform_OSMemory.cpp \ + org_apache_harmony_luni_platform_OSNetworkSystem.cpp \ + org_apache_harmony_luni_util_NumberConvert.cpp \ + org_apache_harmony_luni_util_fltparse.cpp \ org_apache_harmony_xml_ExpatParser.cpp \ - org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp \ - zip.c \ - zipalloc.c \ - sieb.c \ - BidiWrapper.cpp \ - ErrorCode.cpp \ - ICU.cpp \ - NativeBreakIterator.cpp \ - NativeCollation.cpp \ - NativeConverter.cpp \ - NativeDecimalFormat.cpp \ - NativeIDN.cpp \ - NativeNormalizer.cpp \ - NativeRegEx.cpp \ - Register.cpp \ - UCharacter.cpp + org_apache_harmony_xnet_provider_jsse_NativeCrypto.cpp LOCAL_C_INCLUDES += \ external/expat/lib \ - external/icu4c/common \ - external/icu4c/i18n \ + external/icu4c/common \ + external/icu4c/i18n \ external/openssl/include \ external/zlib @@ -61,11 +58,11 @@ LOCAL_C_INCLUDES += \ LOCAL_SHARED_LIBRARIES += \ libcrypto \ libcutils \ - libexpat \ - libicudata \ - libicuuc \ - libicui18n \ - libssl \ + libexpat \ + libicudata \ + libicuuc \ + libicui18n \ + libssl \ libutils \ libz diff --git a/luni/src/main/native/zip.c b/luni/src/main/native/zip.c deleted file mode 100644 index 3d15d2a..0000000 --- a/luni/src/main/native/zip.c +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "zip.h" -#include "jni.h" - -/** - * Throw java.lang.IllegalStateException - */ -void -throwNewIllegalStateException (JNIEnv * env, const char *message) -{ - jniThrowException(env, "java/lang/IllegalStateException", message); -} - -/** - * Throw java.lang.IllegalArgumentException - */ -void -throwNewIllegalArgumentException (JNIEnv * env, const char *message) -{ - jniThrowException(env, "java/lang/IllegalArgumentException", message); -} diff --git a/luni/src/main/native/zip.h b/luni/src/main/native/zip.h index 1452073..6a4c201 100644 --- a/luni/src/main/native/zip.h +++ b/luni/src/main/native/zip.h @@ -1,13 +1,13 @@ -/* +/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,53 +18,85 @@ #if !defined(zip_h) #define zip_h -#ifndef HY_ZIP_API -#include "zipsup.h" -#else /* HY_ZIP_API */ -#include "vmizip.h" -#endif /* HY_ZIP_API */ +#include "JNIHelp.h" +#include "UniquePtr.h" +#include "jni.h" +#include "zlib.h" -#include "hymutex.h" +// FIXME: move to JNIHelp.h +static void jniThrowOutOfMemoryError(JNIEnv* env, const char* message) { + jniThrowException(env, "java/lang/OutOfMemoryError", message); +} -typedef struct JCLZipFile -{ - struct JCLZipFile *last; - struct JCLZipFile *next; -#ifndef HY_ZIP_API - HyZipFile hyZipFile; -#else - VMIZipFile hyZipFile; -#endif -} JCLZipFile; +static void throwExceptionForZlibError(JNIEnv* env, const char* exceptionClassName, int error) { + if (error == Z_MEM_ERROR) { + jniThrowOutOfMemoryError(env, NULL); + } else { + jniThrowException(env, exceptionClassName, zError(error)); + } +} -/* Fake JCLZipFile entry. last, next must be in the same position as JCLZipFile */ -typedef struct JCLZipFileLink -{ - JCLZipFile *last; - JCLZipFile *next; - MUTEX mutex; -} JCLZipFileLink; +class NativeZipStream { +public: + UniquePtr<jbyte[]> input; + int inCap; + z_stream stream; -// Contents from Harmony's inflater.h was put here: -// -typedef struct JCLZipStream -{ - U_8 *inaddr; - int inCap; - U_8 *dict; - z_stream *stream; -} JCLZipStream; + NativeZipStream() : input(NULL), inCap(0), mDict(NULL) { + // Let zlib use its default allocator. + stream.opaque = Z_NULL; + stream.zalloc = Z_NULL; + stream.zfree = Z_NULL; + } -#define THROW_ZIP_EXCEPTION(env, err, type) \ - if (err == Z_MEM_ERROR) { \ - throwNewOutOfMemoryError(env, ""); \ - } else { \ - throwNew##type(env, (const char*) zError(err)); \ - } + ~NativeZipStream() { + } -void throwNewIllegalStateException PROTOTYPE((JNIEnv* env, - const char* message)); -void throwNewIllegalArgumentException PROTOTYPE((JNIEnv* env, - const char* message)); + void setDictionary(JNIEnv* env, jbyteArray dict, int off, int len, bool inflate) { + UniquePtr<jbyte[]> dBytes(new jbyte[len]); + if (dBytes.get() == NULL) { + jniThrowOutOfMemoryError(env, NULL); + return; + } + env->GetByteArrayRegion(dict, off, len, &dBytes[0]); + int err; + if (inflate) { + err = inflateSetDictionary(&stream, (Bytef *) &dBytes[0], len); + } else { + err = deflateSetDictionary(&stream, (Bytef *) &dBytes[0], len); + } + if (err != Z_OK) { + throwExceptionForZlibError(env, "java/lang/IllegalArgumentException", err); + return; + } + mDict.reset(dBytes.release()); + } + + void setInput(JNIEnv* env, jbyteArray buf, jint off, jint len) { + input.reset(new jbyte[len]); + if (input.get() == NULL) { + inCap = 0; + jniThrowOutOfMemoryError(env, NULL); + return; + } + inCap = len; + if (buf != NULL) { + env->GetByteArrayRegion(buf, off, len, &input[0]); + } + stream.next_in = (Bytef *) &input[0]; + stream.avail_in = len; + } + +private: + UniquePtr<jbyte[]> mDict; + + // Disallow copy and assignment. + NativeZipStream(const NativeZipStream&); + void operator=(const NativeZipStream&); +}; + +static NativeZipStream* toNativeZipStream(jlong address) { + return reinterpret_cast<NativeZipStream*>(static_cast<uintptr_t>(address)); +} #endif /* zip_h */ diff --git a/luni/src/main/native/zipalloc.c b/luni/src/main/native/zipalloc.c deleted file mode 100644 index 2b4966b..0000000 --- a/luni/src/main/native/zipalloc.c +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "hyport.h" - -#include "zlib.h" - -#define CDEV_CURRENT_FUNCTION _prototypes_private - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION _prototypes_public -void *zalloc PROTOTYPE ((void *opaque, U_32 items, U_32 size)); -void zfree PROTOTYPE ((void *opaque, void *address)); - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zalloc - -/* - ZLib interface to hymem_allocate_memory. -*/ -void * -zalloc (void *opaque, U_32 items, U_32 size) -{ - PORT_ACCESS_FROM_PORT (((HyPortLibrary *) opaque)); - - return hymem_allocate_memory (items * size); -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zfree - -/* - ZLib interface to hymem_free_memory. -*/ -void -zfree (void *opaque, void *address) -{ - PORT_ACCESS_FROM_PORT ((HyPortLibrary *) opaque); - - hymem_free_memory (address); -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION - -#undef CDEV_CURRENT_FUNCTION diff --git a/luni/src/main/native/zipsup.c b/luni/src/main/native/zipsup.c deleted file mode 100644 index d6d07da..0000000 --- a/luni/src/main/native/zipsup.c +++ /dev/null @@ -1,2319 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @file - * @ingroup ZipSupport - * @brief Zip Support for Java VM -*/ - -#include <string.h> -#include <sys/stat.h> - -#include "hy2sie.h" -#include "zipsup.h" - -#include "zlib.h" - -// zlib is statically linked for Android: -#define checkZipLibrary(dummy) 0 -#ifdef checkZipLibrary -#define inflateInit2Func(a, b, c, d) inflateInit2_ (a, b, c, d) -#define inflateFunc(a, b) inflate (a, b) -#define inflateEndFunc(a) inflateEnd (a) -#else -/* Globals for the zip library */ -UDATA zipDLLDescriptor = 0; -int (*inflateInit2Func) (void *, int, const char *, int); -int (*inflateFunc) (void *, int); -int (*inflateEndFunc) (void *); -#endif - -#define ZIP_NEXT_U8(value, index) (value = *(index++)) -#define ZIP_NEXT_U16(value, index) ((value = (index[1] << 8) | index[0]), index += 2, value) -#define ZIP_NEXT_U32(value, index) ((value = ((U_32)index[3] << 24) | ((U_32)index[2] << 16) | ((U_32)index[1] << 8) | (U_32)index[0]), index += 4, value) - -#define WORK_BUFFER_SIZE 64000 - -#define SCAN_CHUNK_SIZE 1024 - -struct workBuffer -{ - HyPortLibrary *portLib; - UDATA *bufferStart; - UDATA *bufferEnd; - UDATA *currentAlloc; - UDATA cntr; -}; - -#define CDEV_CURRENT_FUNCTION _prototypes_private -I_32 zip_populateCache -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile)); - -static I_32 inflateData -PROTOTYPE ((struct workBuffer * workBuf, U_8 * inputBuffer, - U_32 inputBufferSize, U_8 * outputBuffer, U_32 outputBufferSize)); - -I_32 checkZipLibrary PROTOTYPE ((HyPortLibrary * portLib)); - -I_32 scanForDataDescriptor -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * zipEntry)); -void zdatafree PROTOTYPE ((void *opaque, void *address)); -static I_32 readZipEntry -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * zipEntry, const char *filename, - IDATA * enumerationPointer, IDATA * entryStart, - BOOLEAN findDirectory)); -I_32 scanForCentralEnd -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipCentralEnd * endEntry)); -void *zdataalloc PROTOTYPE ((void *opaque, U_32 items, U_32 size)); - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION _prototypes_public -I_32 zip_getZipEntryData -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, HyZipEntry * entry, - U_8 * buffer, U_32 bufferSize)); -I_32 zip_getZipEntryFromOffset -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, HyZipEntry * entry, - IDATA offset)); -I_32 zip_establishCache -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile)); -void zip_resetZipFile -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - IDATA * nextEntryPointer)); -I_32 zip_getNextZipEntry -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * zipEntry, IDATA * nextEntryPointer)); -I_32 zip_getZipEntry -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, HyZipEntry * entry, - const char *filename, BOOLEAN findDirectory)); -I_32 zip_getZipEntryExtraField -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, HyZipEntry * entry, - U_8 * buffer, U_32 bufferSize)); -void zip_initZipEntry -PROTOTYPE ((HyPortLibrary * portLib, HyZipEntry * entry)); -I_32 zip_openZipFile -PROTOTYPE ((HyPortLibrary * portLib, char *filename, HyZipFile * zipFile, - HyZipCachePool * cachePool)); -void zip_freeZipEntry -PROTOTYPE ((HyPortLibrary * portLib, HyZipEntry * entry)); -I_32 VMCALL zip_closeZipFile -PROTOTYPE ((HyPortLibrary * portLib, struct HyZipFile * zipFile)); -I_32 zip_getZipEntryComment -PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, HyZipEntry * entry, - U_8 * buffer, U_32 bufferSize)); - -#undef CDEV_CURRENT_FUNCTION - -//#include "hythread.h" -//#define ENTER() hythread_monitor_enter(hythread_global_monitor()) -//#define EXIT() hythread_monitor_exit(hythread_global_monitor()) - -#include "hymutex.h" -MUTEX zip_globalMutex; -static int initialized = 0; - -#define ENTER() \ - if (!initialized) { MUTEX_INIT(zip_globalMutex); initialized = 1; } \ - MUTEX_ENTER(zip_globalMutex); - -#define EXIT() MUTEX_EXIT(zip_globalMutex); - - -HyZipCachePool * -zipsup_GetZipCachePool(JNIEnv * env) -{ - static HyZipCachePool *pool = 0; - - if (pool == 0) { - pool = zipCachePool_new(env); - } - return pool; -} - - -#ifndef checkZipLibrary -#define CDEV_CURRENT_FUNCTION checkZipLibrary - -/* - Ensure that the zip library is loaded. - Return 0 on success, -1 on failure. -*/ -I_32 -checkZipLibrary (HyPortLibrary * portLib) -{ - PORT_ACCESS_FROM_PORT (portLib); - - /* if the library has already been loaded return success/failure */ - if (zipDLLDescriptor > 1) - return 0; - if (zipDLLDescriptor == 1) - return -1; - - /* open up the zip library by name */ - - if (hysl_open_shared_library (HY_ZIP_DLL_NAME, &zipDLLDescriptor, TRUE)) - goto openFailed; - - /* look up the functions */ - if (hysl_lookup_name - (zipDLLDescriptor, "inflateInit2_", (void *) &inflateInit2Func, - "ILILI")) - goto loadFailed; - if (hysl_lookup_name - (zipDLLDescriptor, "inflate", (void *) &inflateFunc, "IPI")) - goto loadFailed; - if (hysl_lookup_name - (zipDLLDescriptor, "inflateEnd", (void *) &inflateEndFunc, "IP")) - goto loadFailed; - - /* good to go */ - return 0; - -loadFailed: - hysl_close_shared_library (zipDLLDescriptor); - - /* mark the descriptor as a failed load. only report the error once */ - zipDLLDescriptor = 1; - - /* Unable to open %s (Missing export) */ - hynls_printf (PORTLIB, HYNLS_WARNING, HYNLS_ZIP_MISSING_EXPORT, - HY_ZIP_DLL_NAME); - - return -1; - -openFailed: - /* mark the descriptor as a failed load. only report the error once */ - zipDLLDescriptor = 1; - - /* Unable to open %s (%s) */ - hynls_printf (PORTLIB, HYNLS_WARNING, HYNLS_ZIP_UNABLE_TO_OPEN_ZIP_DLL, - HY_ZIP_DLL_NAME, hyerror_last_error_message ()); - return -1; -} - -#undef CDEV_CURRENT_FUNCTION -#endif - -#define CDEV_CURRENT_FUNCTION inflateData - -/* - Returns 0 on success or one of the following: - ZIP_ERR_UNSUPPORTED_FILE_TYPE - ZIP_ERR_FILE_CORRUPT - ZIP_ERR_OUT_OF_MEMORY - ZIP_ERR_INTERNAL_ERROR -*/ -static I_32 -inflateData (struct workBuffer *workBuf, U_8 * inputBuffer, - U_32 inputBufferSize, U_8 * outputBuffer, U_32 outputBufferSize) -{ - PORT_ACCESS_FROM_PORT (workBuf->portLib); - - z_stream stream; - I_32 err; - - stream.next_in = inputBuffer; - stream.avail_in = inputBufferSize; - stream.next_out = outputBuffer; - stream.avail_out = outputBufferSize; - - stream.opaque = workBuf; - stream.zalloc = zdataalloc; - stream.zfree = zdatafree; - - /* Initialize stream. Pass "-15" as max number of window bits, negated - to indicate that no zlib header is present in the data. */ - err = inflateInit2Func (&stream, -15, ZLIB_VERSION, sizeof (z_stream)); - if (err != Z_OK) - return -1; - - /* Inflate the data. */ - err = inflateFunc (&stream, Z_SYNC_FLUSH); - - /* Clean up the stream. */ - inflateEndFunc (&stream); - - /* Check the return code. Did we complete the inflate? */ - if ((err == Z_STREAM_END) || (err == Z_OK)) - { - if (stream.total_out == outputBufferSize) - { - return 0; - } - } - - switch (err) - { - case Z_OK: /* an error if file is incomplete */ - case Z_STREAM_END: /* an error if file is incomplete */ - case Z_ERRNO: /* a random error */ - case Z_STREAM_ERROR: /* stream inconsistent */ - case Z_DATA_ERROR: /* corrupted zip */ - return ZIP_ERR_FILE_CORRUPT; - - case Z_VERSION_ERROR: /* wrong zlib version */ - case Z_NEED_DICT: /* needs a preset dictionary that we can't provide */ - return ZIP_ERR_UNSUPPORTED_FILE_TYPE; - - case Z_MEM_ERROR: /* out of memory */ - return ZIP_ERR_OUT_OF_MEMORY; - - case Z_BUF_ERROR: /* no progress / out of output buffer */ - default: /* jic */ - return ZIP_ERR_INTERNAL_ERROR; - } -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION scanForCentralEnd -/* - Scan backward from end of file for a central end header. Read from zipFile and update the HyZipCentralEnd provided. - - Returns 0 on success or one of the following: - ZIP_ERR_FILE_READ_ERROR - ZIP_ERR_FILE_CORRUPT -*/ -I_32 -scanForCentralEnd (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipCentralEnd * endEntry) -{ - U_8 *current; - U_8 buffer[SCAN_CHUNK_SIZE]; - I_32 i, size, state; - U_32 dataSize = 0; - I_64 seekResult; - I_32 fileSize; - I_32 bytesAlreadyRead = 0; - - PORT_ACCESS_FROM_PORT (portLib); - - /* Haven't seen anything yet. */ - state = 0; - - seekResult = hyfile_seek (zipFile->fd, 0, HySeekEnd); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_READ_ERROR; - } - fileSize = (I_32) seekResult; - zipFile->pointer = fileSize; - - while (TRUE) - { - /* Fill the buffer. */ - if (bytesAlreadyRead == fileSize) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_CORRUPT; - } - - size = SCAN_CHUNK_SIZE; - if (size > fileSize - bytesAlreadyRead) - size = fileSize - bytesAlreadyRead; - bytesAlreadyRead += size; - seekResult = - hyfile_seek (zipFile->fd, fileSize - bytesAlreadyRead, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer = (I_32) seekResult; - - if (hyfile_read (zipFile->fd, buffer, size) != size) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer += size; - - /* Scan the buffer (backwards) for CentralEnd signature = PK^E^F. */ - for (i = size; i--; dataSize++) - { - switch (state) - { - case 0: - /* Nothing yet. */ - if (buffer[i] == 6) - state = 1; - break; - - case 1: - /* Seen ^F */ - if (buffer[i] == 5) - state = 2; - else - state = 0; - break; - - case 2: - /* Seen ^E^F */ - if (buffer[i] == 'K') - state = 3; - else - state = 0; - break; - - case 3: - /* Seen K^E^F */ - if (buffer[i] == 'P' && dataSize >= 21) - { - /* Found it. Read the data from the end-of-central-dir record. */ - current = buffer + i + 4; - (void) ZIP_NEXT_U16 (endEntry->diskNumber, current); - (void) ZIP_NEXT_U16 (endEntry->dirStartDisk, current); - (void) ZIP_NEXT_U16 (endEntry->thisDiskEntries, current); - (void) ZIP_NEXT_U16 (endEntry->totalEntries, current); - (void) ZIP_NEXT_U32 (endEntry->dirSize, current); - (void) ZIP_NEXT_U32 (endEntry->dirOffset, current); - (void) ZIP_NEXT_U16 (endEntry->commentLength, current); - - /* Quick test to ensure that the header isn't invalid. - Current dataSize is the number of bytes of data scanned, up to the ^H in the stream. */ - if (dataSize >= (U_32) (21 + endEntry->commentLength)) - return 0; - - /* Header looked invalid. Pretend we didn't see it and keep scanning.. */ - } - state = 0; - break; - } - } - } -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION scanForDataDescriptor -/* - Scan ahead for a data descriptor. Read from zipFile and update the HyZipLocalHeader provided. - - Returns 0 on success or one of the following: - ZIP_ERR_FILE_READ_ERROR - ZIP_ERR_FILE_CORRUPT -*/ -I_32 -scanForDataDescriptor (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * zipEntry) -{ - U_8 *current; - U_8 buffer[SCAN_CHUNK_SIZE], descriptor[16]; - I_32 i, size, state; - U_32 dataSize, blockPointer; - I_64 seekResult; - - PORT_ACCESS_FROM_PORT (portLib); - - /* Skip ahead and read the data descriptor. The compressed size should be 0. */ - if (zipFile->pointer != - (IDATA) (zipEntry->dataPointer + zipEntry->compressedSize)) - { - seekResult = - hyfile_seek (zipFile->fd, - zipEntry->dataPointer + zipEntry->compressedSize, - HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer = (I_32) seekResult; - } - - /* Haven't seen anything yet. */ - blockPointer = dataSize = zipEntry->compressedSize; - state = 0; - - /* Scan until we find PK^G^H (otherwise it's an error). */ - while (1) - { - /* Fill the buffer. */ - size = hyfile_read (zipFile->fd, buffer, SCAN_CHUNK_SIZE); - if (size == 0) - { - return ZIP_ERR_FILE_CORRUPT; - } - else if (size < 0) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer += size; - blockPointer += size; - - /* Scan the buffer. */ - for (i = 0; i < size; i++, dataSize++) - { - switch (state) - { - case 0: - /* Nothing yet. */ - if (buffer[i] == 'P') - { - state = 1; - } - break; - - case 1: - /* Seen P */ - if (buffer[i] == 'K') - { - state = 2; - } - else - state = 0; - break; - - case 2: - /* Seen PK */ - if (buffer[i] == 7) - { - state = 3; - } - else - { - state = 0; - } - break; - - case 3: - /* Seen PK^G */ - if (buffer[i] == 8) - { - /* Found it! Read the descriptor */ - if (i + 12 < size) - { - current = &buffer[i + 1]; - } - else - { - seekResult = - hyfile_seek (zipFile->fd, - zipEntry->dataPointer + dataSize + 1, - HySeekSet); - if ((seekResult < 0) - || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer = (I_32) seekResult; - if (hyfile_read (zipFile->fd, descriptor, 12) != 12) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer += 12; - current = descriptor; - } - - /* Read the data from the descriptor. */ - (void) ZIP_NEXT_U32 (zipEntry->crc32, current); - (void) ZIP_NEXT_U32 (zipEntry->compressedSize, current); - (void) ZIP_NEXT_U32 (zipEntry->uncompressedSize, current); - - /* Quick test to ensure that the header isn't invalid. - Current dataSize is the number of bytes of data scanned, up to the ^H in the stream. */ - if (dataSize - 3 == zipEntry->compressedSize) - { - return 0; - } - - /* Header looked invalid. Reset the pointer and continue scanning. */ - seekResult = - hyfile_seek (zipFile->fd, - zipEntry->dataPointer + blockPointer, - HySeekSet); - if ((seekResult < 0) - || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer = (I_32) seekResult; - } - else - state = 0; - break; - } - } - } -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_populateCache -/* - Fill in the cache of a given zip file. This should only be called once during zip_openZipFile! - - Returns 0 on success or one of the following: - ZIP_ERR_FILE_READ_ERROR - ZIP_ERR_FILE_OPEN_ERROR - ZIP_ERR_UNKNOWN_FILE_TYPE - ZIP_ERR_UNSUPPORTED_FILE_TYPE - ZIP_ERR_OUT_OF_MEMORY - ZIP_ERR_INTERNAL_ERROR -*/ -I_32 -zip_populateCache (HyPortLibrary * portLib, HyZipFile * zipFile) -{ - PORT_ACCESS_FROM_PORT (portLib); - - I_32 result = 0; - IDATA bufferSize = 65536; - IDATA unreadSize = 0; - IDATA bufferedSize = 0; - IDATA bytesToRead = 0; - IDATA filenameCopied; - HyZipEntry entry; - HyZipCentralEnd endEntry; - U_8 *buffer = NULL; - U_8 *filename = NULL; - IDATA filenameSize = 256; /* Should be sufficient for most filenames */ - U_8 *current; - U_32 sig; - U_32 localHeaderOffset; - IDATA startCentralDir; - I_64 seekResult; - - if (!zipFile->cache) - return ZIP_ERR_INTERNAL_ERROR; - - /* Find and read the end-of-central-dir record. */ - result = scanForCentralEnd (portLib, zipFile, &endEntry); - if (result != 0) - return result; - - unreadSize = endEntry.dirSize + 4 /* slop */ ; - zipFile->cache->startCentralDir = startCentralDir = - (IDATA) ((UDATA) endEntry.dirOffset); - - if (zipFile->pointer != startCentralDir) - { - seekResult = hyfile_seek (zipFile->fd, startCentralDir, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - - zipFile->pointer = (I_32) seekResult; - if (zipFile->pointer != startCentralDir) - { - result = ZIP_ERR_FILE_READ_ERROR; - zipFile->pointer = -1; - goto finished; - } - } - - /* No point in allocating more than we'll actually need.. */ - if (bufferSize > unreadSize) - bufferSize = unreadSize; - - filename = hymem_allocate_memory (filenameSize); - if (!filename) - { - result = ZIP_ERR_OUT_OF_MEMORY; - goto finished; - } - - /* Allocate some space to hold central directory goo as we eat through it */ - buffer = hymem_allocate_memory (bufferSize); - if (!buffer && (bufferSize > 4096)) - { - /* Not enough memory, fall back to a smaller buffer! */ - bufferSize = 4096; - buffer = hymem_allocate_memory (bufferSize); - } - if (!buffer) - { - result = ZIP_ERR_OUT_OF_MEMORY; - goto finished; - } - - while (unreadSize) - { - - /* Read as much as needed into buffer. */ - bytesToRead = bufferSize - bufferedSize; - if (bytesToRead > unreadSize) - bytesToRead = unreadSize; - result = hyfile_read (zipFile->fd, buffer + bufferedSize, bytesToRead); - if (result < 0) - { - result = ZIP_ERR_FILE_READ_ERROR; - zipFile->pointer = -1; - goto finished; - } - zipFile->pointer += result; - unreadSize -= result; - bufferedSize += result; - current = buffer; - - /* consume entries until we run out. */ - while (current + 46 < buffer + bufferedSize) - { - IDATA entryPointer; - - entryPointer = - zipFile->pointer + (current - (buffer + bufferedSize)); - - sig = 0; - (void) ZIP_NEXT_U32 (sig, current); - if (sig == ZIP_CentralEnd) - { - /* We're done here. */ - result = 0; - goto finished; - } - if (sig != ZIP_CentralHeader) - { - /* Umm...What the Hell? */ - result = ZIP_ERR_FILE_CORRUPT; - goto finished; - } - - /* Read ZIP_CentralHeader entry */ - (void) ZIP_NEXT_U16 (entry.versionCreated, current); - (void) ZIP_NEXT_U16 (entry.versionNeeded, current); - (void) ZIP_NEXT_U16 (entry.flags, current); - (void) ZIP_NEXT_U16 (entry.compressionMethod, current); - (void) ZIP_NEXT_U16 (entry.lastModTime, current); - (void) ZIP_NEXT_U16 (entry.lastModDate, current); - (void) ZIP_NEXT_U32 (entry.crc32, current); - (void) ZIP_NEXT_U32 (entry.compressedSize, current); - (void) ZIP_NEXT_U32 (entry.uncompressedSize, current); - (void) ZIP_NEXT_U16 (entry.filenameLength, current); - (void) ZIP_NEXT_U16 (entry.extraFieldLength, current); - (void) ZIP_NEXT_U16 (entry.fileCommentLength, current); - current += sizeof (U_16); /* skip disk number field */ - (void) ZIP_NEXT_U16 (entry.internalAttributes, current); - current += sizeof (U_32); /* skip external attributes field */ - (void) ZIP_NEXT_U32 (localHeaderOffset, current); - - /* Increase filename buffer size if necessary. */ - if (filenameSize < entry.filenameLength + 1) - { - hymem_free_memory (filename); - filenameSize = entry.filenameLength + 1; - filename = hymem_allocate_memory (filenameSize); - if (!filename) - { - result = ZIP_ERR_OUT_OF_MEMORY; - goto finished; - } - } - - filenameCopied = 0; - while (filenameCopied < entry.filenameLength) - { - IDATA size; - /* Copy as much of the filename as we can see in the buffer (probably the whole thing). */ - - size = entry.filenameLength - filenameCopied; - if (size > bufferedSize - (current - buffer)) - { - size = bufferedSize - (current - buffer); - } - memcpy (filename + filenameCopied, current, size); - filenameCopied += size; - current += size; - if (filenameCopied >= entry.filenameLength) - break; /* done */ - - /* Otherwise, we ran out of source string. Load another chunk.. */ - bufferedSize = 0; - if (!unreadSize) - { - /* Central header is supposedly done? Bak */ - result = ZIP_ERR_FILE_CORRUPT; - goto finished; - } - bytesToRead = bufferSize - bufferedSize; - if (bytesToRead > unreadSize) - bytesToRead = unreadSize; - result = - hyfile_read (zipFile->fd, buffer + bufferedSize, bytesToRead); - if (result < 0) - { - result = ZIP_ERR_FILE_READ_ERROR; - zipFile->pointer = -1; - goto finished; - } - zipFile->pointer += result; - unreadSize -= result; - bufferedSize += result; - current = buffer; - } - filename[entry.filenameLength] = '\0'; /* null-terminate */ - - if (((entry.compressionMethod == ZIP_CM_Deflated) - && (entry.flags & 0x8)) || (entry.fileCommentLength != 0)) - { - /* Either local header doesn't know the compressedSize, or this entry has a file - comment. In either case, cache the central header instead of the local header - so we can find the information we need later. */ - - result = - zipCache_addElement (zipFile->cache, (char *) filename, - entryPointer); - - } - else - { - result = - zipCache_addElement (zipFile->cache, (char *) filename, - localHeaderOffset); - } - - if (!result) - { - result = ZIP_ERR_OUT_OF_MEMORY; - goto finished; - } - - /* Skip the data and comment. */ - bytesToRead = entry.extraFieldLength + entry.fileCommentLength; - if (bufferedSize - (current - buffer) >= bytesToRead) - { - current += bytesToRead; - } - else - { - /* The rest of the buffer is uninteresting. Skip ahead to where the good stuff is */ - bytesToRead -= (bufferedSize - (current - buffer)); - current = buffer + bufferedSize; - unreadSize -= bytesToRead; - - seekResult = hyfile_seek (zipFile->fd, bytesToRead, HySeekCur); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer = (I_32) seekResult; - } - } - bufferedSize -= (current - buffer); - memmove (buffer, current, bufferedSize); - } - - result = 0; - -finished: - if (filename) - hymem_free_memory (filename); - if (buffer) - hymem_free_memory (buffer); - return result; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION readZipEntry -/* - Read the next zip entry for the zipFile into the zipEntry provided. If filename is non-NULL, it is expected to match - the filename read for the entry. If (cachePointer != -1) the filename of the entry will be looked up in the cache (assuming - there is one) to help detect use of an invalid cache. If enumerationPointer is non-NULL, sequential access is assumed and - either a local zip entry or a data descriptor will be accepted, but a central zip entry will cause ZIP_ERR_NO_MORE_ENTRIES - to be returned. If enumerationPointer is NULL, random access is assumed and either a local zip entry or a central zip - entry will be accepted. - - Returns 0 on success or one of the following: - ZIP_ERR_FILE_READ_ERROR - ZIP_ERR_FILE_CORRUPT - ZIP_ERR_OUT_OF_MEMORY - ZIP_ERR_NO_MORE_ENTRIES -*/ -static I_32 -readZipEntry (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * zipEntry, const char *filename, - IDATA * enumerationPointer, IDATA * entryStart, - BOOLEAN findDirectory) -{ - PORT_ACCESS_FROM_PORT (portLib); - - I_32 result; - U_8 buffer[46 + 128]; - U_8 *current; - U_32 sig; - IDATA readLength; - I_64 seekResult; - U_8 *readBuffer; - IDATA currentEntryPointer, localEntryPointer; - IDATA headerSize; - IDATA filenameLength = filename ? strlen (filename) : 0; - -retry: - if (entryStart) - *entryStart = zipFile->pointer; - readBuffer = NULL; - /* Guess how many bytes we'll need to read. If we guess correctly we will do fewer I/O operations */ - headerSize = 30; /* local zip header size */ - if (zipFile->cache && (zipFile->pointer >= zipFile->cache->startCentralDir)) - { - headerSize = 46; /* central zip header size */ - } - readLength = headerSize + (filename ? filenameLength : 128); - if (findDirectory) - { - /* Extra byte for possible trailing '/' */ - readLength++; - } - - /* Allocate some memory if necessary */ - if (readLength <= sizeof (buffer)) - { - current = buffer; - } - else - { - current = readBuffer = hymem_allocate_memory (readLength); - if (!readBuffer) - return ZIP_ERR_OUT_OF_MEMORY; - } - - currentEntryPointer = localEntryPointer = zipFile->pointer; - - result = hyfile_read (zipFile->fd, current, readLength); - if ((result < 22) - || (filename - && !(result == readLength - || (findDirectory && result == (readLength - 1))))) - { - /* We clearly didn't get enough bytes */ - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer += result; - readLength = result; /* If it's not enough, we'll catch that later */ - (void) ZIP_NEXT_U32 (sig, current); - - if (enumerationPointer) - { - if ((sig == ZIP_CentralEnd)) - { - result = ZIP_ERR_NO_MORE_ENTRIES; - goto finished; - } - } - if ((enumerationPointer || (!zipFile->cache)) - && (sig == ZIP_DataDescriptor)) - { - /* We failed to predict a data descriptor here. This should be an error (i.e. only happens in malformed zips?) - but, but we will silently skip over it */ - seekResult = - hyfile_seek (zipFile->fd, currentEntryPointer + 16, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer = (I_32) seekResult; - - if (zipFile->pointer == currentEntryPointer + 16) - { - if (readBuffer) - { - hymem_free_memory (readBuffer); - } - goto retry; - } - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - - if ((sig != ZIP_CentralHeader) && (sig != ZIP_LocalHeader)) - { - /* Unexpected. */ - result = ZIP_ERR_FILE_CORRUPT; - goto finished; - } - headerSize = ((sig == ZIP_CentralHeader) ? 46 : 30); - if (readLength < headerSize) - { - /* We didn't get the whole header (and none of the filename).. */ - /* NOTE: this could happen in normal use if the assumed filename length above is <16. Since it's 128, we don't - handle the impossible case where we would have to read more header. It could also happen if the caller - supplied a filename of length <16 but that only happens when we have a cache (so we'll know the header size) - */ - result = ZIP_ERR_FILE_READ_ERROR; - } - readLength -= headerSize; - - if (sig == ZIP_CentralHeader) - { - current += 2; /* skip versionCreated field */ - } - (void) ZIP_NEXT_U16 (zipEntry->versionNeeded, current); - (void) ZIP_NEXT_U16 (zipEntry->flags, current); - (void) ZIP_NEXT_U16 (zipEntry->compressionMethod, current); - (void) ZIP_NEXT_U16 (zipEntry->lastModTime, current); - (void) ZIP_NEXT_U16 (zipEntry->lastModDate, current); - (void) ZIP_NEXT_U32 (zipEntry->crc32, current); - (void) ZIP_NEXT_U32 (zipEntry->compressedSize, current); - (void) ZIP_NEXT_U32 (zipEntry->uncompressedSize, current); - (void) ZIP_NEXT_U16 (zipEntry->filenameLength, current); - (void) ZIP_NEXT_U16 (zipEntry->extraFieldLength, current); - zipEntry->fileCommentLength = 0; - - if (sig == ZIP_CentralHeader) - { - (void) ZIP_NEXT_U16 (zipEntry->fileCommentLength, current); - current += 8; /* skip disk number start + internal attrs + external attrs */ - (void) ZIP_NEXT_U32 (localEntryPointer, current); - } - - if (filename) - { - if (zipFile->cache) - { - if (! - (readLength == zipEntry->filenameLength - || (findDirectory - && (readLength - 1) == zipEntry->filenameLength))) - { - /* We knew exactly how much we were supposed to read, and this wasn't it */ - result = ZIP_ERR_FILE_CORRUPT; - goto finished; - } - } - } - - /* Allocate space for filename */ - if (zipEntry->filenameLength >= ZIP_INTERNAL_MAX) - { - zipEntry->filename = - hymem_allocate_memory (zipEntry->filenameLength + 1); - if (!zipEntry->filename) - { - result = ZIP_ERR_OUT_OF_MEMORY; - goto finished; - } - } - else - { - zipEntry->filename = zipEntry->internalFilename; - } - if (readLength > zipEntry->filenameLength) - { - readLength = zipEntry->filenameLength; - } - memcpy (zipEntry->filename, current, readLength); - - /* Read the rest of the filename if necessary. Allocate space in HyZipEntry for it! */ - if (readLength < zipEntry->filenameLength) - { - result = - hyfile_read (zipFile->fd, zipEntry->filename + readLength, - zipEntry->filenameLength - readLength); - if (result != (zipEntry->filenameLength - readLength)) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer += result; - } - zipEntry->filename[zipEntry->filenameLength] = '\0'; - - /* If we know what filename is supposed to be, compare it and make sure it matches */ - /* Note: CASE-SENSITIVE COMPARE because filenames in zips are case sensitive (even on platforms with - case-insensitive file systems) */ - if (filename) - { - if (! - ((findDirectory && zipEntry->filenameLength == (filenameLength + 1) - && zipEntry->filename[filenameLength] == '/' - && !strncmp ((char *) zipEntry->filename, (const char *) filename, - filenameLength)) - || !strcmp ((const char *) zipEntry->filename, - (const char *) filename))) - { - /* We seem to have read something totally invalid.. */ - result = ZIP_ERR_FILE_CORRUPT; - goto finished; - } - } - - zipEntry->filenamePointer = currentEntryPointer + headerSize; - zipEntry->extraFieldPointer = - localEntryPointer + 30 + zipEntry->filenameLength; - zipEntry->dataPointer = - zipEntry->extraFieldPointer + zipEntry->extraFieldLength; - zipEntry->extraField = NULL; - zipEntry->fileCommentPointer = 0; - zipEntry->fileComment = NULL; - zipEntry->data = NULL; - - if (sig == ZIP_CentralHeader) - { - U_8 buf[2]; - U_8 *buf2 = buf; - U_16 lost; - /* Also, we know where the comment is */ - zipEntry->fileCommentPointer = currentEntryPointer + headerSize + - zipEntry->filenameLength + zipEntry->extraFieldLength; - if (hyfile_seek (zipFile->fd, localEntryPointer + 28, HySeekSet) == - localEntryPointer + 28) - { - if (hyfile_read (zipFile->fd, buf, 2) == 2) - { - (void) ZIP_NEXT_U16 (lost, buf2); - zipEntry->dataPointer = zipEntry->extraFieldPointer + lost; - zipFile->pointer = localEntryPointer + 30; - } - } - } - - if ((sig == ZIP_LocalHeader) - && (zipEntry->compressionMethod == ZIP_CM_Deflated) - && (zipEntry->flags & 0x8)) - { - /* What we just read doesn't tell us how big the compressed data is. We have to do a heuristic search for a - valid data descriptor at the end of the compressed text */ - result = scanForDataDescriptor (portLib, zipFile, zipEntry); - if (result < 0) - goto finished; - } - - /* Entry read successfully */ - - if (enumerationPointer) - { - /* Work out where the next entry is supposed to be */ - *enumerationPointer = - zipEntry->fileCommentPointer + zipEntry->fileCommentLength; - } - - if (readBuffer) - hymem_free_memory (readBuffer); - return 0; - -finished: - if (readBuffer) - { - hymem_free_memory (readBuffer); - } - if ((zipEntry->filename) - && (zipEntry->filename != zipEntry->internalFilename)) - { - hymem_free_memory (zipEntry->filename); - } - zipEntry->filename = NULL; - if (result == ZIP_ERR_FILE_READ_ERROR) - { - zipFile->pointer = -1; - } - return result; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_closeZipFile -/** - * Attempt to close the zipfile. - * - * @param[in] portLib the port library - * @param[in] zipFile The zip file to be closed - * - * @return 0 on success - * @return ZIP_ERR_FILE_CLOSE_ERROR if there is an error closing the file - * @return ZIP_ERR_INTERNAL_ERROR if there is an internal error - * -*/ -I_32 VMCALL -zip_closeZipFile (HyPortLibrary * portLib, struct HyZipFile * zipFile) -{ - PORT_ACCESS_FROM_PORT (portLib); -#if defined(HY_NO_THR) - THREAD_ACCESS_FROM_PORT(portLib); -#endif /* HY_NO_THR */ - IDATA fd; - - ENTER (); - - fd = zipFile->fd; - zipFile->fd = -1; - - if (zipFile->cache && zipFile->cachePool) - { - zipCachePool_release (zipFile->cachePool, zipFile->cache); - zipFile->cache = NULL; - } - if ((zipFile->filename) && (zipFile->filename != zipFile->internalFilename)) - { - hymem_free_memory (zipFile->filename); - } - zipFile->filename = NULL; - - if (fd == -1) - { - EXIT (); - return ZIP_ERR_INTERNAL_ERROR; - } - if (hyfile_close (fd)) - { - EXIT (); - return ZIP_ERR_FILE_CLOSE_ERROR; - } - EXIT (); - return 0; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_establishCache -/** - * Called to set up a cache when a zip file is opened with a cachePool but without a cache, or when the - * current cache is found to be invalid in some way. - * - * @param[in] portLib the port library - * @param[in] zipFile the zip file for which we want to establish a cache - * - * The current cache is marked as invalid such that new instances of zip files - * won't try to use it and an attempt is made to establish a new cache. - * - * @return 0 on success - * @return ZIP_ERR_FILE_READ_ERROR if there is an error reading from zipFile - * @return ZIP_ERR_FILE_OPEN_ERROR if is there is an error opening the file - * @return ZIP_ERR_UNKNOWN_FILE_TYPE if the file type is unknown - * @return ZIP_ERR_UNSUPPORTED_FILE_TYPE if the file type is unsupported - * @return ZIP_ERR_OUT_OF_MEMORY if there is not enough memory to complete this call - * @return ZIP_ERR_INTERNAL_ERROR if there was an internal error -*/ - -I_32 -zip_establishCache (HyPortLibrary * portLib, HyZipFile * zipFile) -{ - PORT_ACCESS_FROM_PORT (portLib); - I_32 result; - I_64 timeStamp, actualFileSize; - IDATA fileSize, filenameLength; - - if (zipFile->cache) - { - if (zipFile->cachePool) - { - /* Whack cache timestamp to keep other people from starting to use it (we will create a new one for them - to start to use instead). Once all the current users of the cache have stopped using it, it will go away */ - zipFile->cache->zipTimeStamp = -2; - zipCachePool_release (zipFile->cachePool, zipFile->cache); - } - zipFile->cache = NULL; - } - if (!zipFile->cachePool) - { - return ZIP_ERR_INTERNAL_ERROR; - } - - /* Check the cachePool for a suitable cache. */ - filenameLength = strlen ((const char *) zipFile->filename); - -// timeStamp = hyfile_lastmod ((const char *) zipFile->filename); -// actualFileSize = hyfile_length ((const char *) zipFile->filename); - { - struct stat st; - tzset (); - stat ((mcSignednessBull)zipFile->filename, &st); - timeStamp = (U_64)st.st_mtime * 1000; - actualFileSize = (I_64) st.st_size; - } - - if ((actualFileSize < 0) || (actualFileSize > HYCONST64 (0x7FFFFFFF))) - { - return ZIP_ERR_INTERNAL_ERROR; - } - fileSize = (IDATA) actualFileSize; - - zipFile->cache = - zipCachePool_findCache (zipFile->cachePool, - (const char *) zipFile->filename, filenameLength, - fileSize, timeStamp); - if (!zipFile->cache) - { - /* Build a new cache. Because caller asked for a cache, fail if we can't provide one */ - zipFile->cache = - zipCache_new (portLib, (char *) zipFile->filename, filenameLength); - if (!zipFile->cache) - return ZIP_ERR_OUT_OF_MEMORY; - - zipFile->cache->zipFileSize = fileSize; - zipFile->cache->zipTimeStamp = timeStamp; - - result = zip_populateCache (portLib, zipFile); - if (result != 0) - { - zipCache_kill (zipFile->cache); - zipFile->cache = NULL; - return result; - } - if (!zipCachePool_addCache (zipFile->cachePool, zipFile->cache)) - { - zipCache_kill (zipFile->cache); - zipFile->cache = NULL; - return ZIP_ERR_OUT_OF_MEMORY; - } - } - return 0; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_initZipEntry -/** - * Initialize a zip entry. - * - * Should be called before the entry is passed to any other zip support functions - * - * @param[in] portLib the port library - * @param[in] entry the zip entry to init - * - * @return none -*/ - -void -zip_initZipEntry (HyPortLibrary * portLib, HyZipEntry * entry) -{ - memset (entry, 0, sizeof (*entry)); -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_freeZipEntry -/** - * Free any memory associated with a zip entry. - * - * @param[in] portLib the port library - * @param[in] entry the zip entry we are freeing - * - * @return none - * - * @note This does not free the entry itself. -*/ - -void -zip_freeZipEntry (HyPortLibrary * portLib, HyZipEntry * entry) -{ - PORT_ACCESS_FROM_PORT (portLib); - - if ((entry->filename) && (entry->filename != entry->internalFilename)) - { - hymem_free_memory (entry->filename); - } - entry->filename = NULL; - if (entry->extraField) - { - hymem_free_memory (entry->extraField); - entry->extraField = NULL; - } - if (entry->data) - { - hymem_free_memory (entry->data); - entry->data = NULL; - } - if (entry->fileComment) - { - hymem_free_memory (entry->fileComment); - entry->fileComment = NULL; - } -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_getNextZipEntry -/** - * Read the next zip entry at nextEntryPointer into zipEntry. - * - * Any memory held onto by zipEntry may be lost, and therefore - * MUST be freed with @ref zip_freeZipEntry first. - * - * @param[in] portLib the port library - * @param[in] zipFile The zip file being read - * @param[out] zipEntry compressed data is placed here - * @param[in] nextEntryPointer - * - * @return 0 on success - * @return ZIP_ERR_FILE_READ_ERROR if there is an error reading zipFile - * @return ZIP_ERR_FILE_CORRUPT if zipFile is corrupt - * @return ZIP_ERR_NO_MORE_ENTRIES if there are no more entries in zipFile - * @return ZIP_ERR_OUT_OF_MEMORY if there is not enough memory to complete this call - * - * @see zip_freeZipEntry - * -*/ -I_32 -zip_getNextZipEntry (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * zipEntry, IDATA * nextEntryPointer) -{ - PORT_ACCESS_FROM_PORT (portLib); -#if defined(HY_NO_THR) - THREAD_ACCESS_FROM_PORT(portLib); -#endif /* HY_NO_THR */ - IDATA result; - BOOLEAN retryAllowed = TRUE; - IDATA pointer; - IDATA entryStart; - I_64 seekResult; - - ENTER (); - -retry: - pointer = *nextEntryPointer; - - /* Seek to the entry's position in the file. */ - if (pointer != zipFile->pointer) - { - seekResult = hyfile_seek (zipFile->fd, pointer, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - EXIT (); - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer = (I_32) seekResult; - - if (pointer != zipFile->pointer) - { - zipFile->pointer = -1; - EXIT (); - return ZIP_ERR_FILE_READ_ERROR; - } - } - - /* Read the entry */ - entryStart = *nextEntryPointer; - result = - readZipEntry (portLib, zipFile, zipEntry, NULL, &pointer, &entryStart, - FALSE); - if (result != 0) - { - if (!retryAllowed || (result == ZIP_ERR_NO_MORE_ENTRIES)) - { - EXIT (); - return result; - } - zip_establishCache (portLib, zipFile); - retryAllowed = FALSE; - goto retry; - } - - if (zipFile->cache) - { - /* Validity check: look up filename in the cache... */ - result = - (IDATA) zipCache_findElement (zipFile->cache, - (const char *) zipEntry->filename, - FALSE); - if (result != entryStart) - { - if (result >= zipFile->cache->startCentralDir) - { - /* ! Cache contents are not valid. Invalidate it and make a new one */ - if (!retryAllowed) - { - EXIT (); - return ZIP_ERR_FILE_CORRUPT; /* should never happen! */ - } - result = zip_establishCache (portLib, zipFile); - if (!result) - { - /* (silently start operating without a cache if we couldn't make a new one) */ - } - else - { - retryAllowed = FALSE; - goto retry; - } - } - else - { - /* We know that the central header for this entry contains info that the - local header is missing (comment length and/or uncompressed size) */ - zipEntry->fileCommentPointer = -1; - } - } - } - - *nextEntryPointer = pointer; - EXIT (); - return 0; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_getZipEntry -/** - * Attempt to find and read the zip entry corresponding to filename. - * If found, read the entry into the parameter entry. - * - * If an uncached entry is found, the filename field will be filled in. This - * memory will have to be freed with @ref zip_freeZipEntry. - * - * @param[in] portLib the port library - * @param[in] zipFile the file being read from - * @param[out] entry the zip entry found in zipFile is read to here - * @param[in] filename the name of the file that corresponds to entry - * @param[in] findDirectory when true, match a directory even if filename does not end in '/'. - * Note findDirectory is only supported (for the JCL) when there is a cache - * - * @return 0 on success or one of the following: - * @return ZIP_ERR_FILE_READ_ERROR if there is an error reading from zipFile - * @return ZIP_ERR_FILE_CORRUPT if zipFile is corrupt - * @return ZIP_ERR_ENTRY_NOT_FOUND if a zip entry with name filename was not found - * @return ZIP_ERR_OUT_OF_MEMORY if there is not enough memory to complete this call - * - * @see zip_freeZipEntry -*/ - -I_32 -zip_getZipEntry (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, const char *filename, - BOOLEAN findDirectory) -{ - PORT_ACCESS_FROM_PORT (portLib); -#if defined(HY_NO_THR) - THREAD_ACCESS_FROM_PORT(portLib); -#endif /* HY_NO_THR */ - IDATA result, position; - BOOLEAN retryAllowed = TRUE; - I_64 seekResult; - - ENTER (); - -retry: - if (zipFile->cache) - { - /* Look up filename in the cache. */ - position = - (IDATA) zipCache_findElement (zipFile->cache, filename, - findDirectory); - if (position == -1) - { - /* Note: we assume the cache is still valid here */ - EXIT (); - return ZIP_ERR_ENTRY_NOT_FOUND; - } - - /* Seek to the entry's position in the file. */ - if (zipFile->pointer != position) - { - seekResult = hyfile_seek (zipFile->fd, position, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - EXIT (); - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer = (I_32) seekResult; - - if (zipFile->pointer != position) - { - zipFile->pointer = -1; - EXIT (); - return ZIP_ERR_FILE_READ_ERROR; - } - } - - /* Read the entry */ - result = - readZipEntry (portLib, zipFile, entry, filename, NULL, NULL, - findDirectory); - if (result != 0) - { - if (!retryAllowed) - { - EXIT (); - return result; - } - result = zip_establishCache (portLib, zipFile); /* invalidate existing cache */ - if (result) - { - EXIT (); - return result; - } - retryAllowed = FALSE; - goto retry; - } - EXIT (); - return 0; - } - else - { - /* Uh oh -- random access without a cache (SLOW!) */ - position = 0; - zip_resetZipFile (PORTLIB, zipFile, &position); - while (TRUE) - { - - if (zipFile->pointer != position) - { - seekResult = hyfile_seek (zipFile->fd, position, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - EXIT (); - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer = (I_32) seekResult; - - if (zipFile->pointer != position) - { - zipFile->pointer = -1; - EXIT (); - return ZIP_ERR_FILE_READ_ERROR; - } - } - - result = - readZipEntry (portLib, zipFile, entry, NULL, &position, NULL, - FALSE); - if (result || !strcmp ((const char *) entry->filename, filename)) - { - EXIT (); - return result; - } - - /* No match. Reset for next entry */ - zip_freeZipEntry (portLib, entry); - zip_initZipEntry (portLib, entry); - } - } -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_getZipEntryData -/** - * Attempt to read and uncompress the data for the zip entry entry. - * - * If buffer is non-NULL it is used, but not explicitly held onto by the entry. - * If buffer is NULL, memory is allocated and held onto by the entry, and thus - * should later be freed with @ref zip_freeZipEntry. - * - * @param[in] portLib the port library - * @param[in] zipFile the zip file being read from. - * @param[in,out] entry the zip entry - * @param[in] buffer may or may not be NULL - * @param[in] bufferSize - - * @return 0 on success - * @return ZIP_ERR_FILE_READ_ERROR if there is an error reading from zipEntry - * @return ZIP_ERR_FILE_CORRUPT if zipFile is corrupt - * @return ZIP_ERR_ENTRY_NOT_FOUND if entry is not found - * @return ZIP_ERR_OUT_OF_MEMORY if there is not enough memory to complete this call - * @return ZIP_ERR_BUFFER_TOO_SMALL if buffer is too small to hold the comment for zipFile - * - * @see zip_freeZipEntry - * -*/ -I_32 -zip_getZipEntryData (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, U_8 * buffer, U_32 bufferSize) -{ - PORT_ACCESS_FROM_PORT (portLib); -#if defined(HY_NO_THR) - THREAD_ACCESS_FROM_PORT(portLib); -#endif /* HY_NO_THR */ - - I_32 result; - U_8 *dataBuffer; - struct workBuffer wb; - I_64 seekResult; - - ENTER (); - - wb.portLib = portLib; - wb.bufferStart = wb.bufferEnd = wb.currentAlloc = 0; - - if (buffer) - { - if (bufferSize < entry->uncompressedSize) - { - EXIT (); - return ZIP_ERR_BUFFER_TOO_SMALL; - } - dataBuffer = buffer; - } - else - { - /* Note that this is the first zalloc. This memory must be available to the calling method and is freed explicitly in zip_freeZipEntry. */ - /* Note that other allocs freed in zip_freeZipEntry are not alloc'd using zalloc */ - dataBuffer = zdataalloc (&wb, 1, entry->uncompressedSize); - if (!dataBuffer) - { - EXIT (); - return ZIP_ERR_OUT_OF_MEMORY; - } - entry->data = dataBuffer; - } - - if (entry->compressionMethod == ZIP_CM_Stored) - { - /* No compression - just read the data in. */ - if (zipFile->pointer != entry->dataPointer) - { - seekResult = - hyfile_seek (zipFile->fd, entry->dataPointer, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer = (I_32) seekResult; - - if (zipFile->pointer != entry->dataPointer) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - } - result = hyfile_read (zipFile->fd, dataBuffer, entry->compressedSize); - if (result != (I_32) entry->compressedSize) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer += result; - EXIT (); - return 0; - } - - if (entry->compressionMethod == ZIP_CM_Deflated) - { - U_8 *readBuffer; - - /* Ensure that the library is loaded. */ - if (checkZipLibrary (portLib)) - { - result = ZIP_ERR_UNSUPPORTED_FILE_TYPE; - goto finished; - } - - /* Read the file contents. */ - readBuffer = zdataalloc (&wb, 1, entry->compressedSize); - if (!readBuffer) - { - result = ZIP_ERR_OUT_OF_MEMORY; - goto finished; - } - if (zipFile->pointer != entry->dataPointer) - { - seekResult = - hyfile_seek (zipFile->fd, entry->dataPointer, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - zdatafree (&wb, readBuffer); - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer = (I_32) seekResult; - - if (zipFile->pointer != entry->dataPointer) - { - zdatafree (&wb, readBuffer); - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - } - if (hyfile_read (zipFile->fd, readBuffer, entry->compressedSize) != - (I_32) entry->compressedSize) - { - zdatafree (&wb, readBuffer); - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer += (I_32) entry->compressedSize; - - /* Deflate the data. */ - result = - inflateData (&wb, readBuffer, entry->compressedSize, dataBuffer, - entry->uncompressedSize); - zdatafree (&wb, readBuffer); - if (result) - goto finished; - EXIT (); - return 0; - } - - /* Whatever this is, we can't decompress it */ - result = ZIP_ERR_UNSUPPORTED_FILE_TYPE; - -finished: - if (!buffer) - { - entry->data = NULL; - zdatafree (&wb, dataBuffer); - } - if (result == ZIP_ERR_FILE_READ_ERROR) - { - zipFile->pointer = -1; - } - EXIT (); - return result; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_getZipEntryExtraField -/** - * Read the extra field of entry from the zip file filename. - * - * buffer is used if non-NULL, but is not held onto by entry. - * - * If buffer is NULL, memory is allocated and held onto by entry, and MUST be freed later with - * @ref zip_freeZipEntry. - * - * @param[in] portLib the port library - * @param[in] zipFile the zip file being read from. - * @param[in,out] entry the zip entry concerned - * @param[in] buffer may or may not be NULL - * @param[in] bufferSize - * - * @return 0 on success or one of the following: - * @return ZIP_ERR_FILE_READ_ERROR if there is an error reading from zipFile - * @return ZIP_ERR_FILE_CORRUPT if zipFile is corrupt - * @return ZIP_ERR_OUT_OF_MEMORY if there is not enough memory to complete this call - * @return ZIP_ERR_BUFFER_TOO_SMALL if the buffer was non-Null but not large enough to hold the contents of entry - * - * @see zip_freeZipEntry -*/ -I_32 -zip_getZipEntryExtraField (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, U_8 * buffer, U_32 bufferSize) -{ - PORT_ACCESS_FROM_PORT (portLib); -#if defined(HY_NO_THR) - THREAD_ACCESS_FROM_PORT(portLib); -#endif /* HY_NO_THR */ - - I_32 result; - U_8 *extraFieldBuffer; - I_64 seekResult; - - ENTER (); - - if (entry->extraFieldLength == 0) - { - EXIT (); - return 0; - } - - if (buffer) - { - if (bufferSize < entry->extraFieldLength) - { - EXIT (); - return ZIP_ERR_BUFFER_TOO_SMALL; - } - extraFieldBuffer = buffer; - } - else - { - extraFieldBuffer = hymem_allocate_memory (entry->extraFieldLength); - if (!extraFieldBuffer) - { - EXIT (); - return ZIP_ERR_OUT_OF_MEMORY; - } - entry->extraField = extraFieldBuffer; - } - - if (zipFile->pointer != entry->extraFieldPointer) - { - seekResult = - hyfile_seek (zipFile->fd, entry->extraFieldPointer, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer = (I_32) seekResult; - if (zipFile->pointer != entry->extraFieldPointer) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - } - result = - hyfile_read (zipFile->fd, extraFieldBuffer, entry->extraFieldLength); - if (result != (I_32) entry->extraFieldLength) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer += result; - EXIT (); - return 0; - -finished: - if (!buffer) - { - entry->extraField = NULL; - hymem_free_memory (extraFieldBuffer); - } - if (result == ZIP_ERR_FILE_READ_ERROR) - zipFile->pointer = -1; - EXIT (); - return result; - -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_getZipEntryFilename - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_getZipEntryComment -/** - * Read the file comment for entry. - * - * If buffer is non-NULL, it is used, but not held onto by entry. - * - * If buffer is NULL, memory is allocated and - * held onto by entry, and thus should later be freed with @ref zip_freeZipEntry. - * - * @param[in] portLib the port library - * @param[in] zipFile the zip file concerned - * @param[in] entry the entry who's comment we want - * @param[in] buffer may or may not be NULL - * @param[in] bufferSize - - * @return 0 on success or one of the following - * @return ZIP_ERR_FILE_READ_ERROR if there is an error reading the file comment from zipEntry - * @return ZIP_ERR_FILE_CORRUPT if zipFile is corrupt - * @return ZIP_ERR_ENTRY_NOT_FOUND if entry is not found - * @return ZIP_ERR_OUT_OF_MEMORY if there is not enough memory to complete this call - * @return ZIP_ERR_BUFFER_TOO_SMALL if buffer is too small to hold the comment for zipFile -*/ - -I_32 -zip_getZipEntryComment (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, U_8 * buffer, U_32 bufferSize) -{ - PORT_ACCESS_FROM_PORT (portLib); -#if defined(HY_NO_THR) - THREAD_ACCESS_FROM_PORT(portLib); -#endif /* HY_NO_THR */ - - I_32 result; - U_8 *fileCommentBuffer; - I_64 seekResult; - - ENTER (); - - if (entry->fileCommentLength == 0) - { - if (entry->fileCommentPointer == -1) - { - /* TODO: we don't know where the comment is (or even if there is one)! This only happens if you're running - without a cache, so too bad for now */ - } - EXIT (); - return 0; - } - - if (buffer) - { - if (bufferSize < entry->fileCommentLength) - { - EXIT (); - return ZIP_ERR_BUFFER_TOO_SMALL; - } - fileCommentBuffer = buffer; - } - else - { - fileCommentBuffer = hymem_allocate_memory (entry->fileCommentLength); - if (!fileCommentBuffer) - { - EXIT (); - return ZIP_ERR_OUT_OF_MEMORY; - } - entry->fileComment = fileCommentBuffer; - } - - if (zipFile->pointer != entry->fileCommentPointer) - { - seekResult = - hyfile_seek (zipFile->fd, entry->fileCommentPointer, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer = (I_32) seekResult; - - if (zipFile->pointer != entry->fileCommentPointer) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - } - result = - hyfile_read (zipFile->fd, fileCommentBuffer, entry->fileCommentLength); - if (result != (I_32) entry->fileCommentLength) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - zipFile->pointer += result; - EXIT (); - return 0; - -finished: - if (!buffer) - { - entry->fileComment = NULL; - hymem_free_memory (fileCommentBuffer); - } - if (result == ZIP_ERR_FILE_READ_ERROR) - { - zipFile->pointer = -1; - } - EXIT (); - return result; - -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_openZipFile -/** - * Attempt to open a zip file. - * - * If the cache pool is non-NULL, the cachePool will be used to find a suitable cache, and if none can be found it will create one and add it to cachePool. - * Zip support is responsible for managing the lifetime of the cache. - * - * @note If cachePool is NULL, zipFile will be opened without a cache. - * - * @param[in] portLib the port library - * @param[in] filename the zip file to open - * @param[out] zipFile the zip file structure to populate - * @param[in] cachePool the cache pool - * - * @return 0 on success - * @return ZIP_ERR_FILE_OPEN_ERROR if is there is an error opening the file - * @return ZIP_ERR_FILE_READ_ERROR if there is an error reading the file - * @return ZIP_ERR_FILE_CORRUPT if the file is corrupt - * @return ZIP_ERR_UNKNOWN_FILE_TYPE if the file type is not known - * @return ZIP_ERR_UNSUPPORTED_FILE_TYPE if the file type is unsupported - * @return ZIP_ERR_OUT_OF_MEMORY if we are out of memory -*/ -I_32 -zip_openZipFile (HyPortLibrary * portLib, char *filename, HyZipFile * zipFile, - HyZipCachePool * cachePool) -{ - PORT_ACCESS_FROM_PORT (portLib); -#if defined(HY_NO_THR) - THREAD_ACCESS_FROM_PORT(portLib); -#endif /* HY_NO_THR */ - - IDATA fd = -1; - I_32 result = 0; - I_64 seekResult; - U_8 buffer[4]; - I_32 len; - - ENTER (); - - len = strlen (filename); - zipFile->fd = -1; - zipFile->type = ZIP_Unknown; - zipFile->cache = NULL; - zipFile->cachePool = NULL; - zipFile->pointer = -1; - /* Allocate space for filename */ - if (len >= ZIP_INTERNAL_MAX) - { - zipFile->filename = hymem_allocate_memory (len + 1); - if (!zipFile->filename) - { - EXIT (); - return ZIP_ERR_OUT_OF_MEMORY; - } - } - else - { - zipFile->filename = zipFile->internalFilename; - } - - strcpy ((char *) zipFile->filename, filename); - - fd = hyfile_open (filename, HyOpenRead, 0); - if (fd == -1) - { - result = ZIP_ERR_FILE_OPEN_ERROR; - goto finished; - } - - if (hyfile_read (fd, buffer, 4) != 4) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - - if ((buffer[0] == 'P') && (buffer[1] == 'K')) - { - /* If not the central header or local file header, its corrupt */ - if (! - ((buffer[2] == 1 && buffer[3] == 2) - || (buffer[2] == 3 && buffer[3] == 4))) - { - result = ZIP_ERR_FILE_CORRUPT; - goto finished; - } - /* PKZIP file. Back up the pointer to the beginning. */ - seekResult = hyfile_seek (fd, 0, HySeekSet); - if (seekResult != 0) - { - result = ZIP_ERR_FILE_READ_ERROR; - goto finished; - } - - zipFile->fd = fd; - zipFile->type = ZIP_PKZIP; - zipFile->pointer = 0; - } - - if ((buffer[0] == 0x1F) && (buffer[1] == 0x8B)) - { - /* GZIP - currently unsupported. - zipFile->fd = fd; - zipFile->type = ZIP_GZIP; - zipFile->pointer = 2; - */ - result = ZIP_ERR_UNSUPPORTED_FILE_TYPE; - goto finished; - } - - if (zipFile->type == ZIP_Unknown) - { - result = ZIP_ERR_UNKNOWN_FILE_TYPE; - goto finished; - } - - result = 0; - - if (cachePool) - { - zipFile->cachePool = cachePool; - result = zip_establishCache (portLib, zipFile); - } - -finished: - if (result == 0) - { - zipFile->fd = fd; - EXIT (); - return 0; - } - if (fd != -1) - { - hyfile_close (fd); - } - if ((zipFile->filename) && (zipFile->filename != zipFile->internalFilename)) - { - hymem_free_memory (zipFile->filename); - } - zipFile->filename = NULL; - EXIT (); - return result; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_resetZipFile -/** - * Reset nextEntryPointer to the first entry in the file. - * - * @param[in] portLib the port library - * @param[in] zipFile the zip being read from - * @param[out] nextEntryPointer will be reset to the first entry in the file - * - * @return none - * - * -*/ -void -zip_resetZipFile (HyPortLibrary * portLib, HyZipFile * zipFile, - IDATA * nextEntryPointer) -{ - *nextEntryPointer = 0; - if (zipFile) - { - if (zipFile->cache) - *nextEntryPointer = zipFile->cache->startCentralDir; - else - { - I_32 result; - HyZipCentralEnd endEntry; - result = scanForCentralEnd (portLib, zipFile, &endEntry); - if (result != 0) - return; - *nextEntryPointer = (IDATA) ((UDATA) endEntry.dirOffset); - } - } -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zip_getZipEntryFromOffset -/** - * Attempt to read a zip entry at offset from the zip file provided. - * If found, read into entry. - * - * @note If an uncached entry is found, the filename field will be filled in. This - * memory MUST be freed with @ref zip_freeZipEntry. - * - * @param[in] portLib the port library - * @param[in] zipFile the zip file being read - * @param[in] offset the offset into the zipFile of the desired zip entry - * @param[out] entry the compressed data - * - * @return 0 on success - * @return ZIP_ERR_FILE_READ_ERROR if there is an error reading from @ref zipFile - * @return ZIP_ERR_FILE_CORRUPT if @ref zipFile is corrupt - * @return ZIP_ERR_ENTRY_NOT_FOUND if the entry is not found - * @return ZIP_ERR_OUT_OF_MEMORY if there is not enough memory to complete this call - * - * @see zip_freeZipEntry -*/ -I_32 -zip_getZipEntryFromOffset (HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, IDATA offset) -{ - PORT_ACCESS_FROM_PORT (portLib); -#if defined(HY_NO_THR) - THREAD_ACCESS_FROM_PORT(portLib); -#endif /* HY_NO_THR */ - I_32 result; - I_64 seekResult; - - ENTER (); - - if (zipFile->pointer != offset) - { - seekResult = hyfile_seek (zipFile->fd, offset, HySeekSet); - if ((seekResult < 0) || (seekResult > HYCONST64 (0x7FFFFFFF))) - { - zipFile->pointer = -1; - EXIT (); - return ZIP_ERR_FILE_READ_ERROR; - } - zipFile->pointer = (I_32) seekResult; - if (zipFile->pointer != offset) - { - zipFile->pointer = -1; - EXIT (); - return ZIP_ERR_FILE_READ_ERROR; - } - } - - result = readZipEntry (portLib, zipFile, entry, NULL, NULL, NULL, FALSE); - EXIT (); - return result; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zdataalloc -/* - cached alloc management for zip_getZipEntryData. -*/ -void * -zdataalloc (void *opaque, U_32 items, U_32 size) -{ - UDATA *returnVal = 0; - U_32 byteSize = items * size; - U_32 allocSize = WORK_BUFFER_SIZE; - struct workBuffer *wb = (struct workBuffer *) opaque; - - PORT_ACCESS_FROM_PORT (wb->portLib); - - /* Round to UDATA multiple */ - byteSize = (byteSize + (sizeof (UDATA) - 1)) & ~(sizeof (UDATA) - 1); - - if (wb->bufferStart == 0) - { - if (byteSize > WORK_BUFFER_SIZE) - { - allocSize = byteSize; - } - wb->bufferStart = hymem_allocate_memory (allocSize); - if (wb->bufferStart) - { - wb->bufferEnd = (UDATA *) ((UDATA) wb->bufferStart + allocSize); - wb->currentAlloc = wb->bufferStart; - wb->cntr = 0; - } - } - - if ((wb->bufferStart == 0) - || (((UDATA) wb->currentAlloc + byteSize) > (UDATA) wb->bufferEnd)) - { - returnVal = hymem_allocate_memory (byteSize); - } - else - { - ++(wb->cntr); - returnVal = wb->currentAlloc; - wb->currentAlloc = (UDATA *) ((UDATA) wb->currentAlloc + byteSize); - } - return returnVal; -} - -#undef CDEV_CURRENT_FUNCTION - -#define CDEV_CURRENT_FUNCTION zdatafree -/* - cached alloc management for zip_getZipEntryData. -*/ -void -zdatafree (void *opaque, void *address) -{ - struct workBuffer *wb = (struct workBuffer *) opaque; - - PORT_ACCESS_FROM_PORT (wb->portLib); - - if ((address < (void *) wb->bufferStart) - || (address >= (void *) wb->bufferEnd)) - { - hymem_free_memory (address); - } - else if (--(wb->cntr) == 0) - { - hymem_free_memory (wb->bufferStart); - wb->bufferStart = wb->bufferEnd = wb->currentAlloc = 0; - } - -} - -#undef CDEV_CURRENT_FUNCTION diff --git a/luni/src/main/native/zipsup.h b/luni/src/main/native/zipsup.h deleted file mode 100644 index 67a2eda..0000000 --- a/luni/src/main/native/zipsup.h +++ /dev/null @@ -1,232 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** -* Zip Support Header -*/ - -#if !defined(ZIPSUP_H) -#define ZIPSUP_H -#if defined(__cplusplus) -extern "C" -{ -#endif -#include "hy2sie.h" - -#include <stdlib.h> -#include <unistd.h> -#include <memory.h> - -#include "zlib.h" - - -typedef struct HyZipCachePool HyZipCachePool; - -HyZipCachePool * -zipsup_GetZipCachePool(HyPortLibrary * portLib); - - -#if defined(HY_LOCAL_ZLIB) -#define HY_ZIP_DLL_NAME "z" -#else -#define HY_ZIP_DLL_NAME "hyzlib" -#endif - -#define ZIP_INTERNAL_MAX 80 -#define ZIP_CM_Reduced1 2 -#define ZIP_Unknown 0 -#define ZIP_GZIP 2 -#define ZIP_ERR_OUT_OF_MEMORY -3 -#define ZIP_ERR_FILE_CORRUPT -6 -#define ZIP_ERR_INTERNAL_ERROR -11 -#define ZIP_CM_Imploded 6 -#define ZIP_CM_Reduced4 5 -#define ZIP_CM_Shrunk 1 -#define ZIP_CM_Reduced2 3 -#define ZIP_ERR_FILE_READ_ERROR -1 -#define ZIP_CentralHeader 0x2014B50 -#define ZIP_ERR_FILE_CLOSE_ERROR -10 -#define ZIP_ERR_BUFFER_TOO_SMALL -7 -#define ZIP_CM_Reduced3 4 -#define ZIP_CM_Deflated 8 -#define ZIP_LocalHeader 0x4034B50 -#define ZIP_CM_Tokenized 7 -#define ZIP_PKZIP 1 -#define ZIP_CM_Stored 0 -#define ZIP_ERR_UNSUPPORTED_FILE_TYPE -5 -#define ZIP_ERR_NO_MORE_ENTRIES -2 -#define ZIP_CentralEnd 0x6054B50 -#define ZIP_ERR_FILE_OPEN_ERROR -9 -#define ZIP_ERR_UNKNOWN_FILE_TYPE -4 -#define ZIP_ERR_ENTRY_NOT_FOUND -8 -#define ZIP_DataDescriptor 0x8074B50 - - typedef struct HyZipCache - { - U_8 *zipFileName; - IDATA zipFileSize; - I_64 zipTimeStamp; - IDATA startCentralDir; - HyPortLibrary *portLib; - void *cachePool; - void *cachePoolEntry; - } HyZipCache; - - - typedef struct HyZipCentralEnd - { - U_16 diskNumber; - U_16 dirStartDisk; - U_16 thisDiskEntries; - U_16 totalEntries; - U_32 dirSize; - U_32 dirOffset; - U_16 commentLength; - char _hypadding0012[2]; /* 2 bytes of automatic padding */ - U_8 *comment; - } HyZipCentralEnd; - - - typedef struct HyZipDataDescriptor - { - U_32 crc32; - U_32 compressedSize; - U_32 uncompressedSize; - } HyZipDataDescriptor; - - - typedef struct HyZipEntry - { - U_8 *data; - U_8 *filename; - U_8 *extraField; - U_8 *fileComment; - I_32 dataPointer; - I_32 filenamePointer; - I_32 extraFieldPointer; - I_32 fileCommentPointer; - U_32 compressedSize; - U_32 uncompressedSize; - U_32 crc32; - U_16 filenameLength; - U_16 extraFieldLength; - U_16 fileCommentLength; - U_16 internalAttributes; - U_16 versionCreated; - U_16 versionNeeded; - U_16 flags; - U_16 compressionMethod; - U_16 lastModTime; - U_16 lastModDate; - U_8 internalFilename[80]; - } HyZipEntry; - - - typedef struct HyZipFile - { - U_8 *filename; - struct HyZipCache *cache; - void *cachePool; - I_32 fd; - I_32 pointer; - U_8 internalFilename[80]; - U_8 type; - char _hypadding0065[3]; /* 3 bytes of automatic padding */ - } HyZipFile; - - - -#include "hymutex.h" -extern MUTEX zip_GlobalMutex; - - - -#define jclmem_allocate_memory(env, byteCount) sieb_malloc(env, byteCount) -#define jclmem_free_memory(env, pointer) sieb_free(env, pointer) - - -/* HySourceZipSupport*/ - extern HY_CFUNC I_32 zip_getZipEntryData - PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, U_8 * buffer, U_32 bufferSize)); - extern HY_CFUNC I_32 zip_getZipEntryFromOffset - PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, IDATA offset)); - extern HY_CFUNC I_32 zip_establishCache - PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile)); - extern HY_CFUNC void zip_resetZipFile - PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - IDATA * nextEntryPointer)); - extern HY_CFUNC I_32 zip_getNextZipEntry - PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * zipEntry, IDATA * nextEntryPointer)); - extern HY_CFUNC I_32 zip_getZipEntry - PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, const char *filename, - BOOLEAN findDirectory)); - extern HY_CFUNC I_32 zip_getZipEntryExtraField - PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, U_8 * buffer, U_32 bufferSize)); - extern HY_CFUNC void zip_initZipEntry - PROTOTYPE ((HyPortLibrary * portLib, HyZipEntry * entry)); - extern HY_CFUNC I_32 zip_openZipFile - PROTOTYPE ((HyPortLibrary * portLib, char *filename, HyZipFile * zipFile, - HyZipCachePool * cachePool)); - extern HY_CFUNC void zip_freeZipEntry - PROTOTYPE ((HyPortLibrary * portLib, HyZipEntry * entry)); - struct HyZipFile; - extern HY_CFUNC I_32 VMCALL zip_closeZipFile - PROTOTYPE ((HyPortLibrary * portLib, struct HyZipFile * zipFile)); - extern HY_CFUNC I_32 zip_getZipEntryComment - PROTOTYPE ((HyPortLibrary * portLib, HyZipFile * zipFile, - HyZipEntry * entry, U_8 * buffer, U_32 bufferSize)); -/* HySourceZipCache*/ - extern HY_CFUNC UDATA zipCache_findElement - PROTOTYPE ((HyZipCache * zipCache, const char *elementName, - BOOLEAN searchDirList)); - extern HY_CFUNC void zipCache_kill PROTOTYPE ((HyZipCache * zipCache)); - extern HY_CFUNC IDATA zipCache_enumGetDirName - PROTOTYPE ((void *handle, char *nameBuf, UDATA nameBufSize)); - extern HY_CFUNC HyZipCache *zipCache_new - PROTOTYPE ((HyPortLibrary * portLib, char *zipName, IDATA zipNameLength)); - extern HY_CFUNC IDATA zipCache_enumNew - PROTOTYPE ((HyZipCache * zipCache, char *directoryName, void **handle)); - extern HY_CFUNC IDATA zipCache_enumElement - PROTOTYPE ((void *handle, char *nameBuf, UDATA nameBufSize, - UDATA * offset)); - extern HY_CFUNC void zipCache_enumKill PROTOTYPE ((void *handle)); - extern HY_CFUNC BOOLEAN zipCache_addElement - PROTOTYPE ((HyZipCache * zipCache, char *elementName, - UDATA elementOffset)); -/* HySourceZipCachePool*/ - extern HY_CFUNC BOOLEAN zipCachePool_release - PROTOTYPE ((HyZipCachePool * zcp, HyZipCache * zipCache)); - extern HY_CFUNC void zipCachePool_kill PROTOTYPE ((HyZipCachePool * zcp)); - extern HY_CFUNC HyZipCache *zipCachePool_findCache - PROTOTYPE ((HyZipCachePool * zcp, char const *zipFileName, - IDATA zipFileNameLength, IDATA zipFileSize, - I_64 zipTimeStamp)); - extern HY_CFUNC HyZipCachePool *zipCachePool_new - PROTOTYPE ((HyPortLibrary * portLib)); - extern HY_CFUNC BOOLEAN zipCachePool_addCache - PROTOTYPE ((HyZipCachePool * zcp, HyZipCache * zipCache)); - extern HY_CFUNC BOOLEAN zipCachePool_addRef - PROTOTYPE ((HyZipCachePool * zcp, HyZipCache * zipCache)); -#if defined(__cplusplus) -} -#endif -#endif /* ZIPSUP_H */ diff --git a/luni/src/test/java/java/text/AllTests.java b/luni/src/test/java/java/text/AllTests.java index 240b745..ca13ff8 100644 --- a/luni/src/test/java/java/text/AllTests.java +++ b/luni/src/test/java/java/text/AllTests.java @@ -28,6 +28,7 @@ public class AllTests { suite.addTestSuite(java.text.DecimalFormatSymbolsTest.class); suite.addTestSuite(java.text.NormalizerTest.class); suite.addTestSuite(java.text.NumberFormatTest.class); + suite.addTestSuite(java.text.SimpleDateFormatTest.class); return suite; } } diff --git a/luni/src/test/java/java/text/SimpleDateFormatTest.java b/luni/src/test/java/java/text/SimpleDateFormatTest.java new file mode 100644 index 0000000..9d34024 --- /dev/null +++ b/luni/src/test/java/java/text/SimpleDateFormatTest.java @@ -0,0 +1,39 @@ +/* + * Copyright (C) 2010 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package java.text; + +import java.util.Date; + +public class SimpleDateFormatTest extends junit.framework.TestCase { + // The RI fails this test. + public void test2DigitYearStartIsCloned() throws Exception { + // Test that get2DigitYearStart returns a clone. + SimpleDateFormat sdf = new SimpleDateFormat(); + Date originalDate = sdf.get2DigitYearStart(); + assertNotSame(sdf.get2DigitYearStart(), originalDate); + assertEquals(sdf.get2DigitYearStart(), originalDate); + originalDate.setTime(0); + assertFalse(sdf.get2DigitYearStart().equals(originalDate)); + // Test that set2DigitYearStart takes a clone. + Date newDate = new Date(); + sdf.set2DigitYearStart(newDate); + assertNotSame(sdf.get2DigitYearStart(), newDate); + assertEquals(sdf.get2DigitYearStart(), newDate); + newDate.setTime(0); + assertFalse(sdf.get2DigitYearStart().equals(newDate)); + } +} |