changeset 15197:42a74b67c5bb

Merge
author ddehaven
date Tue, 26 Jul 2016 14:45:11 -0700
parents b75e2210e090 4e3c848582d8
children e5e4cb35c92d
files test/java/net/URLPermission/policy.1 test/java/net/URLPermission/policy.2 test/java/net/URLPermission/policy.3 test/java/util/jar/JarFile/mrjar/MultiReleaseJarIterators.java
diffstat 170 files changed, 3667 insertions(+), 2090 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Mon Jul 25 15:09:23 2016 -0700
+++ b/.hgtags	Tue Jul 26 14:45:11 2016 -0700
@@ -370,3 +370,4 @@
 073ab1d4edf5590cf1af7b6d819350c14e425c1a jdk-9+125
 6fda66a5bdf2da8994032b9da2078a4137f4d954 jdk-9+126
 7a97b89ba83077ca62e4aa5a05437adc8f315343 jdk-9+127
+9446c534f0222b4eecfd9d9e25ab37c4fd4400a5 jdk-9+128
--- a/src/java.base/macosx/classes/java/lang/ClassLoaderHelper.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/macosx/classes/java/lang/ClassLoaderHelper.java	Tue Jul 26 14:45:11 2016 -0700
@@ -22,6 +22,7 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
+
 package java.lang;
 
 import java.io.File;
--- a/src/java.base/macosx/native/libjava/java_props_macosx.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/macosx/native/libjava/java_props_macosx.c	Tue Jul 26 14:45:11 2016 -0700
@@ -177,8 +177,14 @@
         OSVerStruct (*procInfoFn)(id rec, SEL sel) = (OSVerStruct(*)(id, SEL))objc_msgSend_stret;
         OSVerStruct osVer = procInfoFn([NSProcessInfo processInfo],
                                        @selector(operatingSystemVersion));
-        NSString *nsVerStr = [NSString stringWithFormat:@"%ld.%ld.%ld",
-                (long)osVer.majorVersion, (long)osVer.minorVersion, (long)osVer.patchVersion];
+        NSString *nsVerStr;
+        if (osVer.patchVersion == 0) { // Omit trailing ".0"
+            nsVerStr = [NSString stringWithFormat:@"%ld.%ld",
+                    (long)osVer.majorVersion, (long)osVer.minorVersion];
+        } else {
+            nsVerStr = [NSString stringWithFormat:@"%ld.%ld.%ld",
+                    (long)osVer.majorVersion, (long)osVer.minorVersion, (long)osVer.patchVersion];
+        }
         // Copy out the char*
         osVersionCStr = strdup([nsVerStr UTF8String]);
     }
--- a/src/java.base/share/classes/com/sun/crypto/provider/AESCipher.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/com/sun/crypto/provider/AESCipher.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -172,6 +172,11 @@
      */
     private final int fixedKeySize; // in bytes, -1 if no restriction
 
+    /*
+     * needed to enforce ISE thrown when updateAAD is called after update for GCM mode.
+     */
+    private boolean updateCalled;
+
     /**
      * Creates an instance of AES cipher with default ECB mode and
      * PKCS5Padding.
@@ -304,6 +309,7 @@
     protected void engineInit(int opmode, Key key, SecureRandom random)
         throws InvalidKeyException {
         checkKeySize(key, fixedKeySize);
+        updateCalled = false;
         core.init(opmode, key, random);
     }
 
@@ -336,6 +342,7 @@
                               SecureRandom random)
         throws InvalidKeyException, InvalidAlgorithmParameterException {
         checkKeySize(key, fixedKeySize);
+        updateCalled = false;
         core.init(opmode, key, params, random);
     }
 
@@ -344,6 +351,7 @@
                               SecureRandom random)
         throws InvalidKeyException, InvalidAlgorithmParameterException {
         checkKeySize(key, fixedKeySize);
+        updateCalled = false;
         core.init(opmode, key, params, random);
     }
 
@@ -368,6 +376,7 @@
      */
     protected byte[] engineUpdate(byte[] input, int inputOffset,
                                   int inputLen) {
+        updateCalled = true;
         return core.update(input, inputOffset, inputLen);
     }
 
@@ -397,6 +406,7 @@
     protected int engineUpdate(byte[] input, int inputOffset, int inputLen,
                                byte[] output, int outputOffset)
         throws ShortBufferException {
+        updateCalled = true;
         return core.update(input, inputOffset, inputLen, output,
                            outputOffset);
     }
@@ -433,7 +443,9 @@
      */
     protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
         throws IllegalBlockSizeException, BadPaddingException {
-        return core.doFinal(input, inputOffset, inputLen);
+        byte[] out = core.doFinal(input, inputOffset, inputLen);
+        updateCalled = false;
+        return out;
     }
 
     /**
@@ -476,8 +488,10 @@
                                 byte[] output, int outputOffset)
         throws IllegalBlockSizeException, ShortBufferException,
                BadPaddingException {
-        return core.doFinal(input, inputOffset, inputLen, output,
-                            outputOffset);
+        int outLen = core.doFinal(input, inputOffset, inputLen, output,
+                                  outputOffset);
+        updateCalled = false;
+        return outLen;
     }
 
     /**
@@ -574,6 +588,9 @@
      */
     @Override
     protected void engineUpdateAAD(byte[] src, int offset, int len) {
+        if (core.getMode() == CipherCore.GCM_MODE && updateCalled) {
+            throw new IllegalStateException("AAD must be supplied before encryption/decryption starts");
+        }
         core.updateAAD(src, offset, len);
     }
 
@@ -606,6 +623,9 @@
      */
     @Override
     protected void engineUpdateAAD(ByteBuffer src) {
+        if (core.getMode() == CipherCore.GCM_MODE && updateCalled) {
+            throw new IllegalStateException("AAD must be supplied before encryption/decryption starts");
+        }
         if (src != null) {
             int aadLen = src.limit() - src.position();
             if (aadLen != 0) {
--- a/src/java.base/share/classes/com/sun/crypto/provider/CipherCore.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/com/sun/crypto/provider/CipherCore.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -124,7 +124,7 @@
     private static final int PCBC_MODE = 4;
     private static final int CTR_MODE = 5;
     private static final int CTS_MODE = 6;
-    private static final int GCM_MODE = 7;
+    static final int GCM_MODE = 7;
 
     /*
      * variables used for performing the GCM (key+iv) uniqueness check.
@@ -196,7 +196,7 @@
             cipher = new CounterMode(rawImpl);
             unitBytes = 1;
             padding = null;
-        }  else if (modeUpperCase.startsWith("GCM")) {
+        }  else if (modeUpperCase.equals("GCM")) {
             // can only be used for block ciphers w/ 128-bit block size
             if (blockSize != 16) {
                 throw new NoSuchAlgorithmException
@@ -223,6 +223,15 @@
         }
     }
 
+    /**
+     * Returns the mode of this cipher.
+     *
+     * @return the parsed cipher mode
+     */
+    int getMode() {
+        return cipherMode;
+    }
+
     private static int getNumOfUnit(String mode, int offset, int blockSize)
         throws NoSuchAlgorithmException {
         int result = blockSize; // use blockSize as default value
--- a/src/java.base/share/classes/com/sun/crypto/provider/GaloisCounterMode.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/com/sun/crypto/provider/GaloisCounterMode.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,6 +49,16 @@
     static int DEFAULT_TAG_LEN = AES_BLOCK_SIZE;
     static int DEFAULT_IV_LEN = 12; // in bytes
 
+    // In NIST SP 800-38D, GCM input size is limited to be no longer
+    // than (2^36 - 32) bytes. Otherwise, the counter will wrap
+    // around and lead to a leak of plaintext.
+    // However, given the current GCM spec requirement that recovered
+    // text can only be returned after successful tag verification,
+    // we are bound by limiting the data size to the size limit of
+    // java byte array, e.g. Integer.MAX_VALUE, since all data
+    // can only be returned by the doFinal(...) call.
+    private static final int MAX_BUF_SIZE = Integer.MAX_VALUE;
+
     // buffer for AAD data; if null, meaning update has been called
     private ByteArrayOutputStream aadBuffer = new ByteArrayOutputStream();
     private int sizeOfAAD = 0;
@@ -89,9 +99,13 @@
         }
     }
 
-    // ivLen in bits
-    private static byte[] getLengthBlock(int ivLen) {
+    private static byte[] getLengthBlock(int ivLenInBytes) {
+        long ivLen = ((long)ivLenInBytes) << 3;
         byte[] out = new byte[AES_BLOCK_SIZE];
+        out[8] = (byte)(ivLen >>> 56);
+        out[9] = (byte)(ivLen >>> 48);
+        out[10] = (byte)(ivLen >>> 40);
+        out[11] = (byte)(ivLen >>> 32);
         out[12] = (byte)(ivLen >>> 24);
         out[13] = (byte)(ivLen >>> 16);
         out[14] = (byte)(ivLen >>> 8);
@@ -99,13 +113,22 @@
         return out;
     }
 
-    // aLen and cLen both in bits
-    private static byte[] getLengthBlock(int aLen, int cLen) {
+    private static byte[] getLengthBlock(int aLenInBytes, int cLenInBytes) {
+        long aLen = ((long)aLenInBytes) << 3;
+        long cLen = ((long)cLenInBytes) << 3;
         byte[] out = new byte[AES_BLOCK_SIZE];
+        out[0] = (byte)(aLen >>> 56);
+        out[1] = (byte)(aLen >>> 48);
+        out[2] = (byte)(aLen >>> 40);
+        out[3] = (byte)(aLen >>> 32);
         out[4] = (byte)(aLen >>> 24);
         out[5] = (byte)(aLen >>> 16);
         out[6] = (byte)(aLen >>> 8);
         out[7] = (byte)aLen;
+        out[8] = (byte)(cLen >>> 56);
+        out[9] = (byte)(cLen >>> 48);
+        out[10] = (byte)(cLen >>> 40);
+        out[11] = (byte)(cLen >>> 32);
         out[12] = (byte)(cLen >>> 24);
         out[13] = (byte)(cLen >>> 16);
         out[14] = (byte)(cLen >>> 8);
@@ -142,13 +165,20 @@
             } else {
                 g.update(iv);
             }
-            byte[] lengthBlock = getLengthBlock(iv.length*8);
+            byte[] lengthBlock = getLengthBlock(iv.length);
             g.update(lengthBlock);
             j0 = g.digest();
         }
         return j0;
     }
 
+    private static void checkDataLength(int processed, int len) {
+        if (processed > MAX_BUF_SIZE - len) {
+            throw new ProviderException("SunJCE provider only supports " +
+                "input size up to " + MAX_BUF_SIZE + " bytes");
+        }
+    }
+
     GaloisCounterMode(SymmetricCipher embeddedCipher) {
         super(embeddedCipher);
         aadBuffer = new ByteArrayOutputStream();
@@ -319,20 +349,22 @@
 
     // Feed the AAD data to GHASH, pad if necessary
     void processAAD() {
-        if (aadBuffer != null && aadBuffer.size() > 0) {
-            byte[] aad = aadBuffer.toByteArray();
-            sizeOfAAD = aad.length;
+        if (aadBuffer != null) {
+            if (aadBuffer.size() > 0) {
+                byte[] aad = aadBuffer.toByteArray();
+                sizeOfAAD = aad.length;
+
+                int lastLen = aad.length % AES_BLOCK_SIZE;
+                if (lastLen != 0) {
+                    ghashAllToS.update(aad, 0, aad.length - lastLen);
+                    byte[] padded = expandToOneBlock(aad, aad.length - lastLen,
+                                                     lastLen);
+                    ghashAllToS.update(padded);
+                } else {
+                    ghashAllToS.update(aad);
+                }
+            }
             aadBuffer = null;
-
-            int lastLen = aad.length % AES_BLOCK_SIZE;
-            if (lastLen != 0) {
-                ghashAllToS.update(aad, 0, aad.length - lastLen);
-                byte[] padded = expandToOneBlock(aad, aad.length - lastLen,
-                                                 lastLen);
-                ghashAllToS.update(padded);
-            } else {
-                ghashAllToS.update(aad);
-            }
         }
     }
 
@@ -384,6 +416,9 @@
         if ((len % blockSize) != 0) {
              throw new ProviderException("Internal error in input buffering");
         }
+
+        checkDataLength(processed, len);
+
         processAAD();
         if (len > 0) {
             gctrPAndC.update(in, inOfs, len, out, outOfs);
@@ -405,17 +440,23 @@
      */
     int encryptFinal(byte[] in, int inOfs, int len, byte[] out, int outOfs)
         throws IllegalBlockSizeException, ShortBufferException {
+        if (len > MAX_BUF_SIZE - tagLenBytes) {
+            throw new ShortBufferException
+                ("Can't fit both data and tag into one buffer");
+        }
         if (out.length - outOfs < (len + tagLenBytes)) {
             throw new ShortBufferException("Output buffer too small");
         }
 
+        checkDataLength(processed, len);
+
         processAAD();
         if (len > 0) {
             doLastBlock(in, inOfs, len, out, outOfs, true);
         }
 
         byte[] lengthBlock =
-            getLengthBlock(sizeOfAAD*8, processed*8);
+            getLengthBlock(sizeOfAAD, processed);
         ghashAllToS.update(lengthBlock);
         byte[] s = ghashAllToS.digest();
         byte[] sOut = new byte[s.length];
@@ -447,6 +488,9 @@
         if ((len % blockSize) != 0) {
              throw new ProviderException("Internal error in input buffering");
         }
+
+        checkDataLength(ibuffer.size(), len);
+
         processAAD();
 
         if (len > 0) {
@@ -481,10 +525,21 @@
         if (len < tagLenBytes) {
             throw new AEADBadTagException("Input too short - need tag");
         }
+        // do this check here can also catch the potential integer overflow
+        // scenario for the subsequent output buffer capacity check.
+        checkDataLength(ibuffer.size(), (len - tagLenBytes));
+
         if (out.length - outOfs < ((ibuffer.size() + len) - tagLenBytes)) {
             throw new ShortBufferException("Output buffer too small");
         }
+
         processAAD();
+
+        // get the trailing tag bytes from 'in'
+        byte[] tag = new byte[tagLenBytes];
+        System.arraycopy(in, inOfs + len - tagLenBytes, tag, 0, tagLenBytes);
+        len -= tagLenBytes;
+
         if (len != 0) {
             ibuffer.write(in, inOfs, len);
         }
@@ -495,17 +550,12 @@
         len = in.length;
         ibuffer.reset();
 
-        byte[] tag = new byte[tagLenBytes];
-        // get the trailing tag bytes from 'in'
-        System.arraycopy(in, len - tagLenBytes, tag, 0, tagLenBytes);
-        len -= tagLenBytes;
-
         if (len > 0) {
             doLastBlock(in, inOfs, len, out, outOfs, false);
         }
 
         byte[] lengthBlock =
-            getLengthBlock(sizeOfAAD*8, processed*8);
+            getLengthBlock(sizeOfAAD, processed);
         ghashAllToS.update(lengthBlock);
 
         byte[] s = ghashAllToS.digest();
--- a/src/java.base/share/classes/com/sun/security/ntlm/Server.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/com/sun/security/ntlm/Server.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/classes/java/lang/Class.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/lang/Class.java	Tue Jul 26 14:45:11 2016 -0700
@@ -238,15 +238,11 @@
 
             TypeVariable<?>[] typeparms = component.getTypeParameters();
             if (typeparms.length > 0) {
-                boolean first = true;
-                sb.append('<');
+                StringJoiner sj = new StringJoiner(",", "<", ">");
                 for(TypeVariable<?> typeparm: typeparms) {
-                    if (!first)
-                        sb.append(',');
-                    sb.append(typeparm.getTypeName());
-                    first = false;
+                    sj.add(typeparm.getTypeName());
                 }
-                sb.append('>');
+                sb.append(sj.toString());
             }
 
             for (int i = 0; i < arrayDepth; i++)
--- a/src/java.base/share/classes/java/lang/Runtime.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/lang/Runtime.java	Tue Jul 26 14:45:11 2016 -0700
@@ -945,7 +945,7 @@
     }
 
     /**
-     * A representation of a version string for an implemenation of the
+     * A representation of a version string for an implementation of the
      * Java&nbsp;SE Platform.  A version string contains a version number
      * optionally followed by pre-release and build information.
      *
@@ -1058,10 +1058,10 @@
      * <p> When comparing two version strings, the value of {@code $OPT}, if
      * present, may or may not be significant depending on the chosen
      * comparison method.  The comparison methods {@link #compareTo(Version)
-     * compareTo()} and {@link #compareToIgnoreOpt(Version)
-     * compareToIgnoreOpt()} should be used consistently with the
+     * compareTo()} and {@link #compareToIgnoreOptional(Version)
+     * compareToIgnoreOptional()} should be used consistently with the
      * corresponding methods {@link #equals(Object) equals()} and {@link
-     * #equalsIgnoreOpt(Object) equalsIgnoreOpt()}.  </p>
+     * #equalsIgnoreOptional(Object) equalsIgnoreOptional()}.  </p>
      *
      * <p> A <em>short version string</em>, {@code $SVSTR}, often useful in
      * less formal contexts, is a version number optionally followed by a
@@ -1249,7 +1249,7 @@
          * @throws  NullPointerException
          *          If the given object is {@code null}
          */
-        public int compareToIgnoreOpt(Version ob) {
+        public int compareToIgnoreOptional(Version ob) {
             return compare(ob, true);
         }
 
@@ -1270,7 +1270,7 @@
                 return ret;
 
             if (!ignoreOpt)
-                return compareOpt(ob);
+                return compareOptional(ob);
 
             return 0;
         }
@@ -1325,7 +1325,7 @@
             return 0;
         }
 
-        private int compareOpt(Version ob) {
+        private int compareOptional(Version ob) {
             Optional<String> oOpt = ob.optional();
             if (!optional.isPresent()) {
                 if (oOpt.isPresent())
@@ -1384,7 +1384,7 @@
          */
         @Override
         public boolean equals(Object ob) {
-            boolean ret = equalsIgnoreOpt(ob);
+            boolean ret = equalsIgnoreOptional(ob);
             if (!ret)
                 return false;
 
@@ -1407,7 +1407,7 @@
          *          ignoring the optinal build information
          *
          */
-        public boolean equalsIgnoreOpt(Object ob) {
+        public boolean equalsIgnoreOptional(Object ob) {
             if (this == ob)
                 return true;
             if (!(ob instanceof Version))
--- a/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Tue Jul 26 14:45:11 2016 -0700
@@ -155,7 +155,7 @@
     private static LambdaForm preparedLambdaForm(MemberName m) {
         assert(m.isInvocable()) : m;  // call preparedFieldLambdaForm instead
         MethodType mtype = m.getInvocationType().basicType();
-        assert(!m.isMethodHandleInvoke() || "invokeBasic".equals(m.getName())) : m;
+        assert(!m.isMethodHandleInvoke()) : m;
         int which;
         switch (m.getReferenceKind()) {
         case REF_invokeVirtual:    which = LF_INVVIRTUAL;    break;
--- a/src/java.base/share/classes/java/lang/invoke/LambdaForm.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/lang/invoke/LambdaForm.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1049,7 +1049,7 @@
             this.member = member;
             this.resolvedHandle = resolvedHandle;
              // The following assert is almost always correct, but will fail for corner cases, such as PrivateInvokeTest.
-             //assert(!isInvokeBasic());
+             //assert(!isInvokeBasic(member));
         }
         NamedFunction(MethodType basicInvokerType) {
             assert(basicInvokerType == basicInvokerType.basicType()) : basicInvokerType;
@@ -1060,13 +1060,13 @@
                 // necessary to pass BigArityTest
                 this.member = Invokers.invokeBasicMethod(basicInvokerType);
             }
-            assert(isInvokeBasic());
+            assert(isInvokeBasic(member));
         }
 
-        private boolean isInvokeBasic() {
+        private static boolean isInvokeBasic(MemberName member) {
             return member != null &&
-                   member.isMethodHandleInvoke() &&
-                   "invokeBasic".equals(member.getName());
+                   member.getDeclaringClass() == MethodHandle.class &&
+                  "invokeBasic".equals(member.getName());
         }
 
         // The next 2 constructors are used to break circular dependencies on MH.invokeStatic, etc.
@@ -1204,7 +1204,7 @@
             assert(mh.type().basicType() == MethodType.genericMethodType(arity).changeReturnType(rtype))
                     : Arrays.asList(mh, rtype, arity);
             MemberName member = mh.internalMemberName();
-            if (member != null && member.getName().equals("invokeBasic") && member.isMethodHandleInvoke()) {
+            if (isInvokeBasic(member)) {
                 assert(arity > 0);
                 assert(a[0] instanceof MethodHandle);
                 MethodHandle mh2 = (MethodHandle) a[0];
--- a/src/java.base/share/classes/java/lang/invoke/MemberName.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/lang/invoke/MemberName.java	Tue Jul 26 14:45:11 2016 -0700
@@ -346,7 +346,6 @@
     }
 
     /** Utility method to query if this member is a method handle invocation (invoke or invokeExact).
-     *  Also returns true for the non-public MH.invokeBasic.
      */
     public boolean isMethodHandleInvoke() {
         final int bits = MH_INVOKE_MODS &~ Modifier.PUBLIC;
@@ -361,7 +360,6 @@
         switch (name) {
         case "invoke":
         case "invokeExact":
-        case "invokeBasic":  // internal sig-poly method
             return true;
         default:
             return false;
--- a/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Tue Jul 26 14:45:11 2016 -0700
@@ -951,8 +951,6 @@
                 return invoker(type);
             if ("invokeExact".equals(name))
                 return exactInvoker(type);
-            if ("invokeBasic".equals(name))
-                return basicInvoker(type);
             assert(!MemberName.isMethodHandleInvokeName(name));
             return null;
         }
@@ -3268,6 +3266,16 @@
      */
     public static
     MethodHandle dropArguments(MethodHandle target, int pos, List<Class<?>> valueTypes) {
+        return dropArguments0(target, pos, copyTypes(valueTypes));
+    }
+
+    private static List<Class<?>> copyTypes(List<Class<?>> types) {
+        Object[] a = types.toArray();
+        return Arrays.asList(Arrays.copyOf(a, a.length, Class[].class));
+    }
+
+    private static
+    MethodHandle dropArguments0(MethodHandle target, int pos, List<Class<?>> valueTypes) {
         MethodType oldType = target.type();  // get NPE
         int dropped = dropArgumentChecks(oldType, pos, valueTypes);
         MethodType newType = oldType.insertParameterTypes(pos, valueTypes);
@@ -3348,6 +3356,7 @@
     // private version which allows caller some freedom with error handling
     private static MethodHandle dropArgumentsToMatch(MethodHandle target, int skip, List<Class<?>> newTypes, int pos,
                                       boolean nullOnFailure) {
+        newTypes = copyTypes(newTypes);
         List<Class<?>> oldTypes = target.type().parameterList();
         int match = oldTypes.size();
         if (skip != 0) {
@@ -3379,11 +3388,11 @@
         // target: ( S*[skip],        M*[match]  )
         MethodHandle adapter = target;
         if (add > 0) {
-            adapter = dropArguments(adapter, skip+ match, addTypes);
+            adapter = dropArguments0(adapter, skip+ match, addTypes);
         }
         // adapter: (S*[skip],        M*[match], A*[add] )
         if (pos > 0) {
-            adapter = dropArguments(adapter, skip, newTypes.subList(0, pos));
+            adapter = dropArguments0(adapter, skip, newTypes.subList(0, pos));
        }
         // adapter: (S*[skip], P*[pos], M*[match], A*[add] )
         return adapter;
@@ -3787,7 +3796,7 @@
         int filterValues = filterType.parameterCount();
         if (filterValues == 0
                 ? (rtype != void.class)
-                : (rtype != filterType.parameterType(0)))
+                : (rtype != filterType.parameterType(0) || filterValues != 1))
             throw newIllegalArgumentException("target and filter types do not match", targetType, filterType);
     }
 
@@ -4290,7 +4299,7 @@
                 step.set(i, dropArgumentsToMatch(identityOrVoid(t), 0, commonParameterSequence, i));
             }
             if (pred.get(i) == null) {
-                pred.set(i, dropArguments(constant(boolean.class, true), 0, commonParameterSequence));
+                pred.set(i, dropArguments0(constant(boolean.class, true), 0, commonParameterSequence));
             }
             if (fini.get(i) == null) {
                 fini.set(i, empty(methodType(t, commonParameterSequence)));
@@ -4315,7 +4324,7 @@
         return hs.stream().map(h -> {
             int pc = h.type().parameterCount();
             int tpsize = targetParams.size();
-            return pc < tpsize ? dropArguments(h, pc, targetParams.subList(pc, tpsize)) : h;
+            return pc < tpsize ? dropArguments0(h, pc, targetParams.subList(pc, tpsize)) : h;
         }).collect(Collectors.toList());
     }
 
--- a/src/java.base/share/classes/java/lang/module/ModulePath.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/lang/module/ModulePath.java	Tue Jul 26 14:45:11 2016 -0700
@@ -52,6 +52,7 @@
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 import java.util.zip.ZipEntry;
 import java.util.zip.ZipFile;
 
@@ -420,7 +421,7 @@
         // scan the entries in the JAR file to locate the .class and service
         // configuration file
         Map<Boolean, Set<String>> map =
-            jf.stream()
+            versionedStream(jf)
               .map(JarEntry::getName)
               .filter(s -> (s.endsWith(".class") ^ s.startsWith(SERVICES_PREFIX)))
               .collect(Collectors.partitioningBy(s -> s.endsWith(".class"),
@@ -503,8 +504,21 @@
         return mn;
     }
 
+    private Stream<JarEntry> versionedStream(JarFile jf) {
+        if (jf.isMultiRelease()) {
+            // a stream of JarEntries whose names are base names and whose
+            // contents are from the corresponding versioned entries in
+            // a multi-release jar file
+            return jf.stream().map(JarEntry::getName)
+                    .filter(name -> !name.startsWith("META-INF/versions/"))
+                    .map(jf::getJarEntry);
+        } else {
+            return jf.stream();
+        }
+    }
+
     private Set<String> jarPackages(JarFile jf) {
-        return jf.stream()
+        return versionedStream(jf)
             .filter(e -> e.getName().endsWith(".class"))
             .map(e -> toPackageName(e.getName()))
             .filter(pkg -> pkg.length() > 0)   // module-info
--- a/src/java.base/share/classes/java/lang/reflect/Executable.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/lang/reflect/Executable.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,7 @@
 import java.lang.annotation.*;
 import java.util.Map;
 import java.util.Objects;
+import java.util.StringJoiner;
 
 import jdk.internal.misc.SharedSecrets;
 import sun.reflect.annotation.AnnotationParser;
@@ -86,15 +87,6 @@
                getDeclaringClass());
     }
 
-    void separateWithCommas(Class<?>[] types, StringBuilder sb) {
-        for (int j = 0; j < types.length; j++) {
-            sb.append(types[j].getTypeName());
-            if (j < (types.length - 1))
-                sb.append(",");
-        }
-
-    }
-
     void printModifiersIfNonzero(StringBuilder sb, int mask, boolean isDefault) {
         int mod = getModifiers() & mask;
 
@@ -121,13 +113,20 @@
 
             printModifiersIfNonzero(sb, modifierMask, isDefault);
             specificToStringHeader(sb);
+            sb.append('(');
+            StringJoiner sj = new StringJoiner(",");
+            for (Class<?> parameterType : parameterTypes) {
+                sj.add(parameterType.getTypeName());
+            }
+            sb.append(sj.toString());
+            sb.append(')');
 
-            sb.append('(');
-            separateWithCommas(parameterTypes, sb);
-            sb.append(')');
             if (exceptionTypes.length > 0) {
-                sb.append(" throws ");
-                separateWithCommas(exceptionTypes, sb);
+                StringJoiner joiner = new StringJoiner(",", " throws ", "");
+                for (Class<?> exceptionType : exceptionTypes) {
+                    joiner.add(exceptionType.getTypeName());
+                }
+                sb.append(joiner.toString());
             }
             return sb.toString();
         } catch (Exception e) {
@@ -149,42 +148,34 @@
 
             TypeVariable<?>[] typeparms = getTypeParameters();
             if (typeparms.length > 0) {
-                boolean first = true;
-                sb.append('<');
+                StringJoiner sj = new StringJoiner(",", "<", "> ");
                 for(TypeVariable<?> typeparm: typeparms) {
-                    if (!first)
-                        sb.append(',');
-                    // Class objects can't occur here; no need to test
-                    // and call Class.getName().
-                    sb.append(typeparm.toString());
-                    first = false;
+                    sj.add(typeparm.getTypeName());
                 }
-                sb.append("> ");
+                sb.append(sj.toString());
             }
 
             specificToGenericStringHeader(sb);
 
             sb.append('(');
+            StringJoiner sj = new StringJoiner(",");
             Type[] params = getGenericParameterTypes();
             for (int j = 0; j < params.length; j++) {
                 String param = params[j].getTypeName();
                 if (isVarArgs() && (j == params.length - 1)) // replace T[] with T...
                     param = param.replaceFirst("\\[\\]$", "...");
-                sb.append(param);
-                if (j < (params.length - 1))
-                    sb.append(',');
+                sj.add(param);
             }
+            sb.append(sj.toString());
             sb.append(')');
-            Type[] exceptions = getGenericExceptionTypes();
-            if (exceptions.length > 0) {
-                sb.append(" throws ");
-                for (int k = 0; k < exceptions.length; k++) {
-                    sb.append((exceptions[k] instanceof Class)?
-                              ((Class)exceptions[k]).getName():
-                              exceptions[k].toString());
-                    if (k < (exceptions.length - 1))
-                        sb.append(',');
+
+            Type[] exceptionTypes = getGenericExceptionTypes();
+            if (exceptionTypes.length > 0) {
+                StringJoiner joiner = new StringJoiner(",", " throws ", "");
+                for (Type exceptionType : exceptionTypes) {
+                    joiner.add(exceptionType.getTypeName());
                 }
+                sb.append(joiner.toString());
             }
             return sb.toString();
         } catch (Exception e) {
--- a/src/java.base/share/classes/java/net/URLPermission.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/net/URLPermission.java	Tue Jul 26 14:45:11 2016 -0700
@@ -461,11 +461,10 @@
     }
 
     private String actions() {
-        String b = String.join(",", methods);
-        if (!requestHeaders.isEmpty()) {
-            b += ":" + String.join(",", requestHeaders);
-        }
-        return b;
+        // The colon separator is optional when the request headers list is
+        // empty.This implementation chooses to include it even when the request
+        // headers list is empty.
+        return String.join(",", methods) + ":" + String.join(",", requestHeaders);
     }
 
     /**
--- a/src/java.base/share/classes/java/security/ProtectionDomain.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/security/ProtectionDomain.java	Tue Jul 26 14:45:11 2016 -0700
@@ -132,7 +132,7 @@
 
     /* the PermissionCollection is static (pre 1.4 constructor)
        or dynamic (via a policy refresh) */
-    private boolean staticPermissions;
+    private final boolean staticPermissions;
 
     /*
      * An object used as a key when the ProtectionDomain is stored in a Map.
@@ -143,8 +143,12 @@
      * Creates a new ProtectionDomain with the given CodeSource and
      * Permissions. If the permissions object is not null, then
      *  {@code setReadOnly()} will be called on the passed in
-     * Permissions object. The only permissions granted to this domain
-     * are the ones specified; the current Policy will not be consulted.
+     * Permissions object.
+     * <p>
+     * The permissions granted to this domain are static, i.e.
+     * invoking the {@link #staticPermissionsOnly()} method returns true.
+     * They contain only the ones passed to this constructor and
+     * the current Policy will not be consulted.
      *
      * @param codesource the codesource associated with this domain
      * @param permissions the permissions granted to this domain
@@ -170,9 +174,11 @@
      * Permissions, ClassLoader and array of Principals. If the
      * permissions object is not null, then {@code setReadOnly()}
      * will be called on the passed in Permissions object.
-     * The permissions granted to this domain are dynamic; they include
-     * both the static permissions passed to this constructor, and any
-     * permissions granted to this domain by the current Policy at the
+     * <p>
+     * The permissions granted to this domain are dynamic, i.e.
+     * invoking the {@link #staticPermissionsOnly()} method returns false.
+     * They include both the static permissions passed to this constructor,
+     * and any permissions granted to this domain by the current Policy at the
      * time a permission is checked.
      * <p>
      * This constructor is typically used by
@@ -256,6 +262,19 @@
     }
 
     /**
+     * Returns true if this domain contains only static permissions
+     * and does not check the current {@code Policy} at the time of
+     * permission checking.
+     *
+     * @return true if this domain contains only static permissions.
+     *
+     * @since 9
+     */
+    public final boolean staticPermissionsOnly() {
+        return this.staticPermissions;
+    }
+
+    /**
      * Check and see if this ProtectionDomain implies the permissions
      * expressed in the Permission object.
      * <p>
@@ -263,25 +282,19 @@
      * ProtectionDomain was constructed with a static set of permissions
      * or it was bound to a dynamically mapped set of permissions.
      * <p>
-     * If the ProtectionDomain was constructed to a
-     * {@link #ProtectionDomain(CodeSource, PermissionCollection)
-     * statically bound} PermissionCollection then the permission will
-     * only be checked against the PermissionCollection supplied at
-     * construction.
+     * If the {@link #staticPermissionsOnly()} method returns
+     * true, then the permission will only be checked against the
+     * PermissionCollection supplied at construction.
      * <p>
-     * However, if the ProtectionDomain was constructed with
-     * the constructor variant which supports
-     * {@link #ProtectionDomain(CodeSource, PermissionCollection,
-     * ClassLoader, java.security.Principal[]) dynamically binding}
-     * permissions, then the permission will be checked against the
-     * combination of the PermissionCollection supplied at construction and
+     * Otherwise, the permission will be checked against the combination
+     * of the PermissionCollection supplied at construction and
      * the current Policy binding.
      *
-     * @param permission the Permission object to check.
+     * @param perm the Permission object to check.
      *
-     * @return true if "permission" is implicit to this ProtectionDomain.
+     * @return true if {@code perm} is implied by this ProtectionDomain.
      */
-    public boolean implies(Permission permission) {
+    public boolean implies(Permission perm) {
 
         if (hasAllPerm) {
             // internal permission collection already has AllPermission -
@@ -290,10 +303,10 @@
         }
 
         if (!staticPermissions &&
-            Policy.getPolicyNoCheck().implies(this, permission))
+            Policy.getPolicyNoCheck().implies(this, perm))
             return true;
         if (permissions != null)
-            return permissions.implies(permission);
+            return permissions.implies(perm);
 
         return false;
     }
--- a/src/java.base/share/classes/java/security/Provider.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/security/Provider.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/java.base/share/classes/java/util/ResourceBundle.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/ResourceBundle.java	Tue Jul 26 14:45:11 2016 -0700
@@ -660,6 +660,7 @@
 
         // ResourceBundleProviders for loading ResourceBundles
         private ServiceLoader<ResourceBundleProvider> providers;
+        private boolean providersChecked;
 
         // Boolean.TRUE if the factory method caller provides a ResourceBundleProvier.
         private Boolean callerHasProvider;
@@ -675,7 +676,6 @@
                 this.loaderRef = new KeyElementReference<>(loader, referenceQueue, this);
             }
             this.moduleRef = new KeyElementReference<>(module, referenceQueue, this);
-            this.providers = getServiceLoader(module, baseName);
             calculateHashCode();
         }
 
@@ -712,11 +712,15 @@
         }
 
         ServiceLoader<ResourceBundleProvider> getProviders() {
+            if (!providersChecked) {
+                providers = getServiceLoader(getModule(), name);
+                providersChecked = true;
+            }
             return providers;
         }
 
         boolean hasProviders() {
-            return providers != null;
+            return getProviders() != null;
         }
 
         boolean callerHasProvider() {
@@ -789,8 +793,9 @@
                 }
                 clone.moduleRef = new KeyElementReference<>(getModule(),
                                                             referenceQueue, clone);
-                // Clear the reference to ResourceBundleProviders
+                // Clear the reference to ResourceBundleProviders and the flag
                 clone.providers = null;
+                clone.providersChecked = false;
                 // Clear the reference to a Throwable
                 clone.cause = null;
                 // Clear callerHasProvider
@@ -1841,6 +1846,9 @@
 
     private static ServiceLoader<ResourceBundleProvider> getServiceLoader(Module module,
                                                                           String baseName) {
+        if (!module.isNamed()) {
+            return null;
+        }
         PrivilegedAction<ClassLoader> pa = module::getClassLoader;
         ClassLoader loader = AccessController.doPrivileged(pa);
         return getServiceLoader(module, loader, baseName);
--- a/src/java.base/share/classes/java/util/concurrent/CompletableFuture.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/concurrent/CompletableFuture.java	Tue Jul 26 14:45:11 2016 -0700
@@ -221,7 +221,10 @@
      *   across both while pushing actions.  The second completion is
      *   a CoCompletion pointing to the first, shared so that at most
      *   one performs the action.  The multiple-arity methods allOf
-     *   and anyOf do this pairwise to form trees of completions.
+     *   does this pairwise to form trees of completions.  Method
+     *   anyOf is handled differently from allOf because completion of
+     *   any source should trigger a cleanStack of other sources.
+     *   Each AnyOf completion can reach others via a shared array.
      *
      * Note that the generic type parameters of methods vary according
      * to whether "this" is a source, dependent, or completion.
@@ -588,9 +591,9 @@
     }
 
     /**
-     * Post-processing by dependent after successful UniCompletion
-     * tryFire.  Tries to clean stack of source a, and then either runs
-     * postComplete or returns this to caller, depending on mode.
+     * Post-processing by dependent after successful UniCompletion tryFire.
+     * Tries to clean stack of source a, and then either runs postComplete
+     * or returns this to caller, depending on mode.
      */
     final CompletableFuture<T> postFire(CompletableFuture<?> a, int mode) {
         if (a != null && a.stack != null) {
@@ -1003,12 +1006,12 @@
     }
 
     @SuppressWarnings("serial")
-    static final class UniRelay<T> extends UniCompletion<T,T> {
-        UniRelay(CompletableFuture<T> dep, CompletableFuture<T> src) {
+    static final class UniRelay<U, T extends U> extends UniCompletion<T,U> {
+        UniRelay(CompletableFuture<U> dep, CompletableFuture<T> src) {
             super(null, dep, src);
         }
-        final CompletableFuture<T> tryFire(int mode) {
-            CompletableFuture<T> d; CompletableFuture<T> a; Object r;
+        final CompletableFuture<U> tryFire(int mode) {
+            CompletableFuture<U> d; CompletableFuture<T> a; Object r;
             if ((d = dep) == null
                 || (a = src) == null || (r = a.result) == null)
                 return null;
@@ -1019,13 +1022,14 @@
         }
     }
 
-    private CompletableFuture<T> uniCopyStage() {
+    private static <U, T extends U> CompletableFuture<U> uniCopyStage(
+        CompletableFuture<T> src) {
         Object r;
-        CompletableFuture<T> d = newIncompleteFuture();
-        if ((r = result) != null)
+        CompletableFuture<U> d = src.newIncompleteFuture();
+        if ((r = src.result) != null)
             d.result = encodeRelay(r);
         else
-            unipush(new UniRelay<T>(d, this));
+            src.unipush(new UniRelay<U,T>(d, src));
         return d;
     }
 
@@ -1034,7 +1038,7 @@
         if ((r = result) != null)
             return new MinimalStage<T>(encodeRelay(r));
         MinimalStage<T> d = new MinimalStage<T>();
-        unipush(new UniRelay<T>(d, this));
+        unipush(new UniRelay<T,T>(d, this));
         return d;
     }
 
@@ -1069,7 +1073,7 @@
                     if ((r = g.result) != null)
                         d.completeRelay(r);
                     else {
-                        g.unipush(new UniRelay<V>(d, g));
+                        g.unipush(new UniRelay<V,V>(d, g));
                         if (d.result == null)
                             return null;
                     }
@@ -1103,7 +1107,7 @@
                 if ((s = g.result) != null)
                     d.result = encodeRelay(s);
                 else {
-                    g.unipush(new UniRelay<V>(d, g));
+                    g.unipush(new UniRelay<V,V>(d, g));
                 }
             } catch (Throwable ex) {
                 d.result = encodeThrowable(ex);
@@ -1637,45 +1641,40 @@
         return d;
     }
 
+    /** Completion for an anyOf input future. */
     @SuppressWarnings("serial")
-    static final class OrRelay<T,U> extends BiCompletion<T,U,Object> { // for Or
-        OrRelay(CompletableFuture<Object> dep,
-                CompletableFuture<T> src, CompletableFuture<U> snd) {
-            super(null, dep, src, snd);
+    static class AnyOf extends Completion {
+        CompletableFuture<Object> dep; CompletableFuture<?> src;
+        CompletableFuture<?>[] srcs;
+        AnyOf(CompletableFuture<Object> dep, CompletableFuture<?> src,
+              CompletableFuture<?>[] srcs) {
+            this.dep = dep; this.src = src; this.srcs = srcs;
         }
         final CompletableFuture<Object> tryFire(int mode) {
-            CompletableFuture<Object> d;
-            CompletableFuture<T> a;
-            CompletableFuture<U> b;
+            // assert mode != ASYNC;
+            CompletableFuture<Object> d; CompletableFuture<?> a;
+            CompletableFuture<?>[] as;
             Object r;
             if ((d = dep) == null
-                || (a = src) == null || (b = snd) == null
-                || ((r = a.result) == null && (r = b.result) == null))
+                || (a = src) == null || (r = a.result) == null
+                || (as = srcs) == null)
                 return null;
-            d.completeRelay(r);
-            src = null; snd = null; dep = null;
-            return d.postFire(a, b, mode);
+            dep = null; src = null; srcs = null;
+            if (d.completeRelay(r)) {
+                for (CompletableFuture<?> b : as)
+                    if (b != a)
+                        b.cleanStack();
+                if (mode < 0)
+                    return d;
+                else
+                    d.postComplete();
+            }
+            return null;
         }
-    }
-
-    /** Recursively constructs a tree of completions. */
-    static CompletableFuture<Object> orTree(CompletableFuture<?>[] cfs,
-                                            int lo, int hi) {
-        CompletableFuture<Object> d = new CompletableFuture<Object>();
-        if (lo <= hi) {
-            CompletableFuture<?> a, b; Object r;
-            int mid = (lo + hi) >>> 1;
-            if ((a = (lo == mid ? cfs[lo] :
-                      orTree(cfs, lo, mid))) == null ||
-                (b = (lo == hi ? a : (hi == mid+1) ? cfs[hi] :
-                      orTree(cfs, mid+1, hi))) == null)
-                throw new NullPointerException();
-            if ((r = a.result) != null && (r = b.result) != null)
-                d.result = encodeRelay(r);
-            else
-                a.orpush(b, new OrRelay<>(d, a, b));
+        final boolean isLive() {
+            CompletableFuture<Object> d;
+            return (d = dep) != null && d.result == null;
         }
-        return d;
     }
 
     /* ------------- Zero-input Async forms -------------- */
@@ -2354,7 +2353,28 @@
      * {@code null}
      */
     public static CompletableFuture<Object> anyOf(CompletableFuture<?>... cfs) {
-        return orTree(cfs, 0, cfs.length - 1);
+        int n; Object r;
+        if ((n = cfs.length) <= 1)
+            return (n == 0)
+                ? new CompletableFuture<Object>()
+                : uniCopyStage(cfs[0]);
+        for (CompletableFuture<?> cf : cfs)
+            if ((r = cf.result) != null)
+                return new CompletableFuture<Object>(encodeRelay(r));
+        cfs = cfs.clone();
+        CompletableFuture<Object> d = new CompletableFuture<>();
+        for (CompletableFuture<?> cf : cfs)
+            cf.unipush(new AnyOf(d, cf, cfs));
+        // If d was completed while we were adding completions, we should
+        // clean the stack of any sources that may have had completions
+        // pushed on their stack after d was completed.
+        if (d.result != null)
+            for (int i = 0, len = cfs.length; i < len; i++)
+                if (cfs[i].result != null)
+                    for (i++; i < len; i++)
+                        if (cfs[i].result == null)
+                            cfs[i].cleanStack();
+        return d;
     }
 
     /* ------------- Control and status methods -------------- */
@@ -2526,7 +2546,7 @@
      * @since 9
      */
     public CompletableFuture<T> copy() {
-        return uniCopyStage();
+        return uniCopyStage(this);
     }
 
     /**
--- a/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1023,7 +1023,7 @@
         int hash = spread(key.hashCode());
         int binCount = 0;
         for (Node<K,V>[] tab = table;;) {
-            Node<K,V> f; int n, i, fh;
+            Node<K,V> f; int n, i, fh; K fk; V fv;
             if (tab == null || (n = tab.length) == 0)
                 tab = initTable();
             else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) {
@@ -1032,6 +1032,10 @@
             }
             else if ((fh = f.hash) == MOVED)
                 tab = helpTransfer(tab, f);
+            else if (onlyIfAbsent && fh == hash &&  // check first node
+                     ((fk = f.key) == key || fk != null && key.equals(fk)) &&
+                     (fv = f.val) != null)
+                return fv;
             else {
                 V oldVal = null;
                 synchronized (f) {
@@ -1702,7 +1706,7 @@
         V val = null;
         int binCount = 0;
         for (Node<K,V>[] tab = table;;) {
-            Node<K,V> f; int n, i, fh;
+            Node<K,V> f; int n, i, fh; K fk; V fv;
             if (tab == null || (n = tab.length) == 0)
                 tab = initTable();
             else if ((f = tabAt(tab, i = (n - 1) & h)) == null) {
@@ -1724,6 +1728,10 @@
             }
             else if ((fh = f.hash) == MOVED)
                 tab = helpTransfer(tab, f);
+            else if (fh == h &&                  // check first node
+                     ((fk = f.key) == key || fk != null && key.equals(fk)) &&
+                     (fv = f.val) != null)
+                return fv;
             else {
                 boolean added = false;
                 synchronized (f) {
@@ -4553,14 +4561,21 @@
             return true;
         }
 
-        public final boolean removeAll(Collection<?> c) {
+        public boolean removeAll(Collection<?> c) {
             if (c == null) throw new NullPointerException();
             boolean modified = false;
-            for (Iterator<E> it = iterator(); it.hasNext();) {
-                if (c.contains(it.next())) {
-                    it.remove();
-                    modified = true;
+            // Use (c instanceof Set) as a hint that lookup in c is as
+            // efficient as this view
+            if (c instanceof Set<?> && c.size() > map.table.length) {
+                for (Iterator<?> it = iterator(); it.hasNext(); ) {
+                    if (c.contains(it.next())) {
+                        it.remove();
+                        modified = true;
+                    }
                 }
+            } else {
+                for (Object e : c)
+                    modified |= remove(e);
             }
             return modified;
         }
@@ -4747,6 +4762,18 @@
             throw new UnsupportedOperationException();
         }
 
+        @Override public boolean removeAll(Collection<?> c) {
+            if (c == null) throw new NullPointerException();
+            boolean modified = false;
+            for (Iterator<V> it = iterator(); it.hasNext();) {
+                if (c.contains(it.next())) {
+                    it.remove();
+                    modified = true;
+                }
+            }
+            return modified;
+        }
+
         public boolean removeIf(Predicate<? super V> filter) {
             return map.removeValueIf(filter);
         }
--- a/src/java.base/share/classes/java/util/concurrent/Exchanger.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/concurrent/Exchanger.java	Tue Jul 26 14:45:11 2016 -0700
@@ -235,22 +235,16 @@
      * As is too common in this sort of code, methods are monolithic
      * because most of the logic relies on reads of fields that are
      * maintained as local variables so can't be nicely factored --
-     * mainly, here, bulky spin->yield->block/cancel code), and
-     * heavily dependent on intrinsics (VarHandles) to use inlined
-     * embedded CAS and related memory access operations (that tend
-     * not to be as readily inlined by dynamic compilers when they are
-     * hidden behind other methods that would more nicely name and
-     * encapsulate the intended effects). This includes the use of
-     * setRelease to clear fields of the per-thread Nodes between
-     * uses. Note that field Node.item is not declared as volatile
-     * even though it is read by releasing threads, because they only
-     * do so after CAS operations that must precede access, and all
-     * uses by the owning thread are otherwise acceptably ordered by
-     * other operations. (Because the actual points of atomicity are
-     * slot CASes, it would also be legal for the write to Node.match
-     * in a release to be weaker than a full volatile write. However,
-     * this is not done because it could allow further postponement of
-     * the write, delaying progress.)
+     * mainly, here, bulky spin->yield->block/cancel code.  Note that
+     * field Node.item is not declared as volatile even though it is
+     * read by releasing threads, because they only do so after CAS
+     * operations that must precede access, and all uses by the owning
+     * thread are otherwise acceptably ordered by other operations.
+     * (Because the actual points of atomicity are slot CASes, it
+     * would also be legal for the write to Node.match in a release to
+     * be weaker than a full volatile write. However, this is not done
+     * because it could allow further postponement of the write,
+     * delaying progress.)
      */
 
     /**
--- a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicInteger.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicInteger.java	Tue Jul 26 14:45:11 2016 -0700
@@ -35,7 +35,6 @@
 
 package java.util.concurrent.atomic;
 
-import java.lang.invoke.MethodHandles;
 import java.lang.invoke.VarHandle;
 import java.util.function.IntBinaryOperator;
 import java.util.function.IntUnaryOperator;
@@ -54,11 +53,18 @@
  */
 public class AtomicInteger extends Number implements java.io.Serializable {
     private static final long serialVersionUID = 6214790243416807050L;
-    private static final VarHandle VALUE;
+
+    /*
+     * This class intended to be implemented using VarHandles, but there
+     * are unresolved cyclic startup dependencies.
+     */
+    private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
+    private static final long VALUE;
+
     static {
         try {
-            MethodHandles.Lookup l = MethodHandles.lookup();
-            VALUE = l.findVarHandle(AtomicInteger.class, "value", int.class);
+            VALUE = U.objectFieldOffset
+                (AtomicInteger.class.getDeclaredField("value"));
         } catch (ReflectiveOperationException e) {
             throw new Error(e);
         }
@@ -109,7 +115,7 @@
      * @since 1.6
      */
     public final void lazySet(int newValue) {
-        VALUE.setRelease(this, newValue);
+        U.putIntRelease(this, VALUE, newValue);
     }
 
     /**
@@ -120,7 +126,7 @@
      * @return the previous value
      */
     public final int getAndSet(int newValue) {
-        return (int)VALUE.getAndSet(this, newValue);
+        return U.getAndSetInt(this, VALUE, newValue);
     }
 
     /**
@@ -134,7 +140,7 @@
      * the actual value was not equal to the expected value.
      */
     public final boolean compareAndSet(int expectedValue, int newValue) {
-        return VALUE.compareAndSet(this, expectedValue, newValue);
+        return U.compareAndSwapInt(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -147,7 +153,7 @@
      * @return {@code true} if successful
      */
     public final boolean weakCompareAndSet(int expectedValue, int newValue) {
-        return VALUE.weakCompareAndSet(this, expectedValue, newValue);
+        return U.weakCompareAndSwapInt(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -159,7 +165,7 @@
      * @return the previous value
      */
     public final int getAndIncrement() {
-        return (int)VALUE.getAndAdd(this, 1);
+        return U.getAndAddInt(this, VALUE, 1);
     }
 
     /**
@@ -171,7 +177,7 @@
      * @return the previous value
      */
     public final int getAndDecrement() {
-        return (int)VALUE.getAndAdd(this, -1);
+        return U.getAndAddInt(this, VALUE, -1);
     }
 
     /**
@@ -182,7 +188,7 @@
      * @return the previous value
      */
     public final int getAndAdd(int delta) {
-        return (int)VALUE.getAndAdd(this, delta);
+        return U.getAndAddInt(this, VALUE, delta);
     }
 
     /**
@@ -194,7 +200,7 @@
      * @return the updated value
      */
     public final int incrementAndGet() {
-        return (int)VALUE.addAndGet(this, 1);
+        return U.getAndAddInt(this, VALUE, 1) + 1;
     }
 
     /**
@@ -206,7 +212,7 @@
      * @return the updated value
      */
     public final int decrementAndGet() {
-        return (int)VALUE.addAndGet(this, -1);
+        return U.getAndAddInt(this, VALUE, -1) - 1;
     }
 
     /**
@@ -217,7 +223,7 @@
      * @return the updated value
      */
     public final int addAndGet(int delta) {
-        return (int)VALUE.addAndGet(this, delta);
+        return U.getAndAddInt(this, VALUE, delta) + delta;
     }
 
     /**
@@ -373,7 +379,7 @@
      * @since 9
      */
     public final int getPlain() {
-        return (int)VALUE.get(this);
+        return U.getInt(this, VALUE);
     }
 
     /**
@@ -385,7 +391,7 @@
      * @since 9
      */
     public final void setPlain(int newValue) {
-        VALUE.set(this, newValue);
+        U.putInt(this, VALUE, newValue);
     }
 
     /**
@@ -396,7 +402,7 @@
      * @since 9
      */
     public final int getOpaque() {
-        return (int)VALUE.getOpaque(this);
+        return U.getIntOpaque(this, VALUE);
     }
 
     /**
@@ -407,7 +413,7 @@
      * @since 9
      */
     public final void setOpaque(int newValue) {
-        VALUE.setOpaque(this, newValue);
+        U.putIntOpaque(this, VALUE, newValue);
     }
 
     /**
@@ -418,7 +424,7 @@
      * @since 9
      */
     public final int getAcquire() {
-        return (int)VALUE.getAcquire(this);
+        return U.getIntAcquire(this, VALUE);
     }
 
     /**
@@ -429,7 +435,7 @@
      * @since 9
      */
     public final void setRelease(int newValue) {
-        VALUE.setRelease(this, newValue);
+        U.putIntRelease(this, VALUE, newValue);
     }
 
     /**
@@ -445,7 +451,7 @@
      * @since 9
      */
     public final int compareAndExchange(int expectedValue, int newValue) {
-        return (int)VALUE.compareAndExchange(this, expectedValue, newValue);
+        return U.compareAndExchangeIntVolatile(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -461,7 +467,7 @@
      * @since 9
      */
     public final int compareAndExchangeAcquire(int expectedValue, int newValue) {
-        return (int)VALUE.compareAndExchangeAcquire(this, expectedValue, newValue);
+        return U.compareAndExchangeIntAcquire(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -477,7 +483,7 @@
      * @since 9
      */
     public final int compareAndExchangeRelease(int expectedValue, int newValue) {
-        return (int)VALUE.compareAndExchangeRelease(this, expectedValue, newValue);
+        return U.compareAndExchangeIntRelease(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -492,7 +498,7 @@
      * @since 9
      */
     public final boolean weakCompareAndSetVolatile(int expectedValue, int newValue) {
-        return VALUE.weakCompareAndSetVolatile(this, expectedValue, newValue);
+        return U.weakCompareAndSwapIntVolatile(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -507,7 +513,7 @@
      * @since 9
      */
     public final boolean weakCompareAndSetAcquire(int expectedValue, int newValue) {
-        return VALUE.weakCompareAndSetAcquire(this, expectedValue, newValue);
+        return U.weakCompareAndSwapIntAcquire(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -522,7 +528,7 @@
      * @since 9
      */
     public final boolean weakCompareAndSetRelease(int expectedValue, int newValue) {
-        return VALUE.weakCompareAndSetRelease(this, expectedValue, newValue);
+        return U.weakCompareAndSwapIntRelease(this, VALUE, expectedValue, newValue);
     }
 
 }
--- a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicLong.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicLong.java	Tue Jul 26 14:45:11 2016 -0700
@@ -35,7 +35,6 @@
 
 package java.util.concurrent.atomic;
 
-import java.lang.invoke.MethodHandles;
 import java.lang.invoke.VarHandle;
 import java.util.function.LongBinaryOperator;
 import java.util.function.LongUnaryOperator;
@@ -54,7 +53,6 @@
  */
 public class AtomicLong extends Number implements java.io.Serializable {
     private static final long serialVersionUID = 1927816293512124184L;
-    private static final VarHandle VALUE;
 
     /**
      * Records whether the underlying JVM supports lockless
@@ -70,10 +68,17 @@
      */
     private static native boolean VMSupportsCS8();
 
+    /*
+     * This class intended to be implemented using VarHandles, but there
+     * are unresolved cyclic startup dependencies.
+     */
+    private static final jdk.internal.misc.Unsafe U = jdk.internal.misc.Unsafe.getUnsafe();
+    private static final long VALUE;
+
     static {
         try {
-            MethodHandles.Lookup l = MethodHandles.lookup();
-            VALUE = l.findVarHandle(AtomicLong.class, "value", long.class);
+            VALUE = U.objectFieldOffset
+                (AtomicLong.class.getDeclaredField("value"));
         } catch (ReflectiveOperationException e) {
             throw new Error(e);
         }
@@ -113,7 +118,9 @@
      * @param newValue the new value
      */
     public final void set(long newValue) {
-        VALUE.setVolatile(this, newValue);
+        // Use putLongVolatile instead of ordinary volatile store when
+        // using compareAndSwapLong, for sake of some 32bit systems.
+        U.putLongVolatile(this, VALUE, newValue);
     }
 
     /**
@@ -124,7 +131,7 @@
      * @since 1.6
      */
     public final void lazySet(long newValue) {
-        VALUE.setRelease(this, newValue);
+        U.putLongRelease(this, VALUE, newValue);
     }
 
     /**
@@ -135,7 +142,7 @@
      * @return the previous value
      */
     public final long getAndSet(long newValue) {
-        return (long)VALUE.getAndSet(this, newValue);
+        return U.getAndSetLong(this, VALUE, newValue);
     }
 
     /**
@@ -149,7 +156,7 @@
      * the actual value was not equal to the expected value.
      */
     public final boolean compareAndSet(long expectedValue, long newValue) {
-        return VALUE.compareAndSet(this, expectedValue, newValue);
+        return U.compareAndSwapLong(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -162,7 +169,7 @@
      * @return {@code true} if successful
      */
     public final boolean weakCompareAndSet(long expectedValue, long newValue) {
-        return VALUE.weakCompareAndSet(this, expectedValue, newValue);
+        return U.weakCompareAndSwapLong(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -174,7 +181,7 @@
      * @return the previous value
      */
     public final long getAndIncrement() {
-        return (long)VALUE.getAndAdd(this, 1L);
+        return U.getAndAddLong(this, VALUE, 1L);
     }
 
     /**
@@ -186,7 +193,7 @@
      * @return the previous value
      */
     public final long getAndDecrement() {
-        return (long)VALUE.getAndAdd(this, -1L);
+        return U.getAndAddLong(this, VALUE, -1L);
     }
 
     /**
@@ -197,7 +204,7 @@
      * @return the previous value
      */
     public final long getAndAdd(long delta) {
-        return (long)VALUE.getAndAdd(this, delta);
+        return U.getAndAddLong(this, VALUE, delta);
     }
 
     /**
@@ -209,7 +216,7 @@
      * @return the updated value
      */
     public final long incrementAndGet() {
-        return (long)VALUE.addAndGet(this, 1L);
+        return U.getAndAddLong(this, VALUE, 1L) + 1L;
     }
 
     /**
@@ -221,7 +228,7 @@
      * @return the updated value
      */
     public final long decrementAndGet() {
-        return (long)VALUE.addAndGet(this, -1L);
+        return U.getAndAddLong(this, VALUE, -1L) - 1L;
     }
 
     /**
@@ -232,7 +239,7 @@
      * @return the updated value
      */
     public final long addAndGet(long delta) {
-        return (long)VALUE.addAndGet(this, delta);
+        return U.getAndAddLong(this, VALUE, delta) + delta;
     }
 
     /**
@@ -386,7 +393,7 @@
      * @since 9
      */
     public final long getPlain() {
-        return (long)VALUE.get(this);
+        return U.getLong(this, VALUE);
     }
 
     /**
@@ -398,7 +405,7 @@
      * @since 9
      */
     public final void setPlain(long newValue) {
-        VALUE.set(this, newValue);
+        U.putLong(this, VALUE, newValue);
     }
 
     /**
@@ -409,7 +416,7 @@
      * @since 9
      */
     public final long getOpaque() {
-        return (long)VALUE.getOpaque(this);
+        return U.getLongOpaque(this, VALUE);
     }
 
     /**
@@ -420,7 +427,7 @@
      * @since 9
      */
     public final void setOpaque(long newValue) {
-        VALUE.setOpaque(this, newValue);
+        U.putLongOpaque(this, VALUE, newValue);
     }
 
     /**
@@ -431,7 +438,7 @@
      * @since 9
      */
     public final long getAcquire() {
-        return (long)VALUE.getAcquire(this);
+        return U.getLongAcquire(this, VALUE);
     }
 
     /**
@@ -442,7 +449,7 @@
      * @since 9
      */
     public final void setRelease(long newValue) {
-        VALUE.setRelease(this, newValue);
+        U.putLongRelease(this, VALUE, newValue);
     }
 
     /**
@@ -458,7 +465,7 @@
      * @since 9
      */
     public final long compareAndExchange(long expectedValue, long newValue) {
-        return (long)VALUE.compareAndExchange(this, expectedValue, newValue);
+        return U.compareAndExchangeLongVolatile(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -474,7 +481,7 @@
      * @since 9
      */
     public final long compareAndExchangeAcquire(long expectedValue, long newValue) {
-        return (long)VALUE.compareAndExchangeAcquire(this, expectedValue, newValue);
+        return U.compareAndExchangeLongAcquire(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -490,7 +497,7 @@
      * @since 9
      */
     public final long compareAndExchangeRelease(long expectedValue, long newValue) {
-        return (long)VALUE.compareAndExchangeRelease(this, expectedValue, newValue);
+        return U.compareAndExchangeLongRelease(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -505,7 +512,7 @@
      * @since 9
      */
     public final boolean weakCompareAndSetVolatile(long expectedValue, long newValue) {
-        return VALUE.weakCompareAndSetVolatile(this, expectedValue, newValue);
+        return U.weakCompareAndSwapLongVolatile(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -520,7 +527,7 @@
      * @since 9
      */
     public final boolean weakCompareAndSetAcquire(long expectedValue, long newValue) {
-        return VALUE.weakCompareAndSetAcquire(this, expectedValue, newValue);
+        return U.weakCompareAndSwapLongAcquire(this, VALUE, expectedValue, newValue);
     }
 
     /**
@@ -535,7 +542,7 @@
      * @since 9
      */
     public final boolean weakCompareAndSetRelease(long expectedValue, long newValue) {
-        return VALUE.weakCompareAndSetRelease(this, expectedValue, newValue);
+        return U.weakCompareAndSwapLongRelease(this, VALUE, expectedValue, newValue);
     }
 
 }
--- a/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReference.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/concurrent/atomic/AtomicReference.java	Tue Jul 26 14:45:11 2016 -0700
@@ -60,7 +60,7 @@
         }
     }
 
-    private volatile Object value;
+    private volatile V value;
 
     /**
      * Creates a new AtomicReference with the given initial value.
@@ -83,9 +83,8 @@
      *
      * @return the current value
      */
-    @SuppressWarnings("unchecked")
     public final V get() {
-        return (V)value;
+        return value;
     }
 
     /**
--- a/src/java.base/share/classes/java/util/concurrent/locks/StampedLock.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/concurrent/locks/StampedLock.java	Tue Jul 26 14:45:11 2016 -0700
@@ -256,8 +256,12 @@
      * method validate()) requires stricter ordering rules than apply
      * to normal volatile reads (of "state").  To force orderings of
      * reads before a validation and the validation itself in those
-     * cases where this is not already forced, we use
-     * VarHandle.acquireFence.
+     * cases where this is not already forced, we use acquireFence.
+     * Unlike in that paper, we allow writers to use plain writes.
+     * One would not expect reorderings of such writes with the lock
+     * acquisition CAS because there is a "control dependency", but it
+     * is theoretically possible, so we additionally add a
+     * storeStoreFence after lock acquisition CAS.
      *
      * The memory layout keeps lock state and queue pointers together
      * (normally on the same cache line). This usually works well for
@@ -355,6 +359,20 @@
         state = ORIGIN;
     }
 
+    private boolean casState(long expectedValue, long newValue) {
+        return STATE.compareAndSet(this, expectedValue, newValue);
+    }
+
+    private long tryWriteLock(long s) {
+        // assert (s & ABITS) == 0L;
+        long next;
+        if (casState(s, next = s | WBIT)) {
+            VarHandle.storeStoreFence();
+            return next;
+        }
+        return 0L;
+    }
+
     /**
      * Exclusively acquires the lock, blocking if necessary
      * until available.
@@ -363,10 +381,8 @@
      */
     @ReservedStackAccess
     public long writeLock() {
-        long s, next;  // bypass acquireWrite in fully unlocked case only
-        return ((((s = state) & ABITS) == 0L &&
-                 STATE.compareAndSet(this, s, next = s + WBIT)) ?
-                next : acquireWrite(false, 0L));
+        long next;
+        return ((next = tryWriteLock()) != 0L) ? next : acquireWrite(false, 0L);
     }
 
     /**
@@ -377,10 +393,8 @@
      */
     @ReservedStackAccess
     public long tryWriteLock() {
-        long s, next;
-        return ((((s = state) & ABITS) == 0L &&
-                 STATE.compareAndSet(this, s, next = s + WBIT)) ?
-                next : 0L);
+        long s;
+        return (((s = state) & ABITS) == 0L) ? tryWriteLock(s) : 0L;
     }
 
     /**
@@ -440,10 +454,13 @@
      */
     @ReservedStackAccess
     public long readLock() {
-        long s = state, next;  // bypass acquireRead on common uncontended case
-        return ((whead == wtail && (s & ABITS) < RFULL &&
-                 STATE.compareAndSet(this, s, next = s + RUNIT)) ?
-                next : acquireRead(false, 0L));
+        long s, next;
+        // bypass acquireRead on common uncontended case
+        return (whead == wtail
+                && ((s = state) & ABITS) < RFULL
+                && casState(s, next = s + RUNIT))
+            ? next
+            : acquireRead(false, 0L);
     }
 
     /**
@@ -457,7 +474,7 @@
         long s, m, next;
         while ((m = (s = state) & ABITS) != WBIT) {
             if (m < RFULL) {
-                if (STATE.compareAndSet(this, s, next = s + RUNIT))
+                if (casState(s, next = s + RUNIT))
                     return next;
             }
             else if ((next = tryIncReaderOverflow(s)) != 0L)
@@ -487,7 +504,7 @@
         if (!Thread.interrupted()) {
             if ((m = (s = state) & ABITS) != WBIT) {
                 if (m < RFULL) {
-                    if (STATE.compareAndSet(this, s, next = s + RUNIT))
+                    if (casState(s, next = s + RUNIT))
                         return next;
                 }
                 else if ((next = tryIncReaderOverflow(s)) != 0L)
@@ -514,10 +531,15 @@
      * before acquiring the lock
      */
     @ReservedStackAccess
-    public long readLockInterruptibly() throws InterruptedException {
-        long next;
-        if (!Thread.interrupted() &&
-            (next = acquireRead(true, 0L)) != INTERRUPTED)
+        public long readLockInterruptibly() throws InterruptedException {
+        long s, next;
+        if (!Thread.interrupted()
+            // bypass acquireRead on common uncontended case
+            && ((whead == wtail
+                 && ((s = state) & ABITS) < RFULL
+                 && casState(s, next = s + RUNIT))
+                ||
+                (next = acquireRead(true, 0L)) != INTERRUPTED))
             return next;
         throw new InterruptedException();
     }
@@ -598,7 +620,7 @@
                && (stamp & RBITS) > 0L
                && ((m = s & RBITS) > 0L)) {
             if (m < RFULL) {
-                if (STATE.compareAndSet(this, s, s - RUNIT)) {
+                if (casState(s, s - RUNIT)) {
                     if (m == RUNIT && (h = whead) != null && h.status != 0)
                         release(h);
                     return;
@@ -620,7 +642,7 @@
      */
     @ReservedStackAccess
     public void unlock(long stamp) {
-        if ((stamp & WBIT) != 0)
+        if ((stamp & WBIT) != 0L)
             unlockWrite(stamp);
         else
             unlockRead(stamp);
@@ -644,7 +666,7 @@
             if ((m = s & ABITS) == 0L) {
                 if (a != 0L)
                     break;
-                if (STATE.compareAndSet(this, s, next = s + WBIT))
+                if ((next = tryWriteLock(s)) != 0L)
                     return next;
             }
             else if (m == WBIT) {
@@ -653,8 +675,10 @@
                 return stamp;
             }
             else if (m == RUNIT && a != 0L) {
-                if (STATE.compareAndSet(this, s, next = s - RUNIT + WBIT))
+                if (casState(s, next = s - RUNIT + WBIT)) {
+                    VarHandle.storeStoreFence();
                     return next;
+                }
             }
             else
                 break;
@@ -688,7 +712,7 @@
             else if (a == 0L) {
                 // optimistic read stamp
                 if ((s & ABITS) < RFULL) {
-                    if (STATE.compareAndSet(this, s, next = s + RUNIT))
+                    if (casState(s, next = s + RUNIT))
                         return next;
                 }
                 else if ((next = tryIncReaderOverflow(s)) != 0L)
@@ -730,7 +754,7 @@
             else if ((m = s & ABITS) == 0L) // invalid read stamp
                 break;
             else if (m < RFULL) {
-                if (STATE.compareAndSet(this, s, next = s - RUNIT)) {
+                if (casState(s, next = s - RUNIT)) {
                     if (m == RUNIT && (h = whead) != null && h.status != 0)
                         release(h);
                     return next & SBITS;
@@ -771,7 +795,7 @@
         long s, m; WNode h;
         while ((m = (s = state) & ABITS) != 0L && m < WBIT) {
             if (m < RFULL) {
-                if (STATE.compareAndSet(this, s, s - RUNIT)) {
+                if (casState(s, s - RUNIT)) {
                     if (m == RUNIT && (h = whead) != null && h.status != 0)
                         release(h);
                     return true;
@@ -940,7 +964,7 @@
         long s, m; WNode h;
         while ((m = (s = state) & RBITS) > 0L) {
             if (m < RFULL) {
-                if (STATE.compareAndSet(this, s, s - RUNIT)) {
+                if (casState(s, s - RUNIT)) {
                     if (m == RUNIT && (h = whead) != null && h.status != 0)
                         release(h);
                     return;
@@ -971,7 +995,7 @@
     private long tryIncReaderOverflow(long s) {
         // assert (s & ABITS) >= RFULL;
         if ((s & ABITS) == RFULL) {
-            if (STATE.compareAndSet(this, s, s | RBITS)) {
+            if (casState(s, s | RBITS)) {
                 ++readerOverflow;
                 STATE.setVolatile(this, s);
                 return s;
@@ -993,7 +1017,7 @@
     private long tryDecReaderOverflow(long s) {
         // assert (s & ABITS) >= RFULL;
         if ((s & ABITS) == RFULL) {
-            if (STATE.compareAndSet(this, s, s | RBITS)) {
+            if (casState(s, s | RBITS)) {
                 int r; long next;
                 if ((r = readerOverflow) > 0) {
                     readerOverflow = r - 1;
@@ -1047,7 +1071,7 @@
         for (int spins = -1;;) { // spin while enqueuing
             long m, s, ns;
             if ((m = (s = state) & ABITS) == 0L) {
-                if (STATE.compareAndSet(this, s, ns = s + WBIT))
+                if ((ns = tryWriteLock(s)) != 0L)
                     return ns;
             }
             else if (spins < 0)
@@ -1082,7 +1106,7 @@
                 for (int k = spins; k > 0; --k) { // spin at head
                     long s, ns;
                     if (((s = state) & ABITS) == 0L) {
-                        if (STATE.compareAndSet(this, s, ns = s + WBIT)) {
+                        if ((ns = tryWriteLock(s)) != 0L) {
                             whead = node;
                             node.prev = null;
                             if (wasInterrupted)
@@ -1158,7 +1182,7 @@
             if ((h = whead) == (p = wtail)) {
                 for (long m, s, ns;;) {
                     if ((m = (s = state) & ABITS) < RFULL ?
-                        STATE.compareAndSet(this, s, ns = s + RUNIT) :
+                        casState(s, ns = s + RUNIT) :
                         (m < WBIT && (ns = tryIncReaderOverflow(s)) != 0L)) {
                         if (wasInterrupted)
                             Thread.currentThread().interrupt();
@@ -1208,7 +1232,7 @@
                         long m, s, ns;
                         do {
                             if ((m = (s = state) & ABITS) < RFULL ?
-                                STATE.compareAndSet(this, s, ns = s + RUNIT) :
+                                casState(s, ns = s + RUNIT) :
                                 (m < WBIT &&
                                  (ns = tryIncReaderOverflow(s)) != 0L)) {
                                 if (wasInterrupted)
@@ -1260,7 +1284,7 @@
                 for (int k = spins;;) { // spin at head
                     long m, s, ns;
                     if ((m = (s = state) & ABITS) < RFULL ?
-                        STATE.compareAndSet(this, s, ns = s + RUNIT) :
+                        casState(s, ns = s + RUNIT) :
                         (m < WBIT && (ns = tryIncReaderOverflow(s)) != 0L)) {
                         WNode c; Thread w;
                         whead = node;
--- a/src/java.base/share/classes/java/util/jar/JarFile.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/jar/JarFile.java	Tue Jul 26 14:45:11 2016 -0700
@@ -141,7 +141,6 @@
     private boolean verify;
     private final Runtime.Version version;  // current version
     private final int versionMajor;         // version.major()
-    private boolean notVersioned;           // legacy constructor called
     private boolean isMultiRelease;         // is jar multi-release?
 
     // indicates if Class-Path attribute present
@@ -290,7 +289,6 @@
      */
     public JarFile(File file, boolean verify, int mode) throws IOException {
         this(file, verify, mode, BASE_VERSION);
-        this.notVersioned = true;
     }
 
     /**
@@ -496,42 +494,14 @@
             Iterator<JarEntry>
     {
         final Enumeration<? extends ZipEntry> e = JarFile.super.entries();
-        ZipEntry ze;
 
         public boolean hasNext() {
-            if (notVersioned) {
-                return e.hasMoreElements();
-            }
-            if (ze != null) {
-                return true;
-            }
-            return findNext();
-        }
-
-        private boolean findNext() {
-            while (e.hasMoreElements()) {
-                ZipEntry ze2 = e.nextElement();
-                if (!ze2.getName().startsWith(META_INF_VERSIONS)) {
-                    ze = ze2;
-                    return true;
-                }
-            }
-            return false;
+            return e.hasMoreElements();
         }
 
         public JarEntry next() {
-            ZipEntry ze2;
-
-            if (notVersioned) {
-                ze2 = e.nextElement();
-                return new JarFileEntry(ze2.getName(), ze2);
-            }
-            if (ze != null || findNext()) {
-                ze2 = ze;
-                ze = null;
-                return new JarFileEntry(ze2);
-            }
-            throw new NoSuchElementException();
+            ZipEntry ze = e.nextElement();
+            return new JarFileEntry(ze.getName(), ze);
         }
 
         public boolean hasMoreElements() {
@@ -548,19 +518,7 @@
     }
 
     /**
-     * Returns an enumeration of the jar file entries.  The set of entries
-     * returned depends on whether or not the jar file is a multi-release jar
-     * file, and on the constructor used to create the {@code JarFile}.  If the
-     * jar file is not a multi-release jar file, all entries are returned,
-     * regardless of how the {@code JarFile} is created.  If the constructor
-     * does not take a {@code Release} argument, all entries are returned.
-     * If the jar file is a multi-release jar file and the constructor takes a
-     * {@code Release} argument, then the set of entries returned is equivalent
-     * to the set of entries that would be returned if the set was built by
-     * invoking {@link JarFile#getEntry(String)} or
-     * {@link JarFile#getJarEntry(String)} with the name of each base entry in
-     * the jar file.  A base entry is an entry whose path name does not start
-     * with "META-INF/versions/".
+     * Returns an enumeration of the jar file entries.
      *
      * @return an enumeration of the jar file entries
      * @throws IllegalStateException
@@ -571,24 +529,26 @@
     }
 
     /**
-     * Returns an ordered {@code Stream} over all the jar file entries.
+     * Returns an ordered {@code Stream} over the jar file entries.
      * Entries appear in the {@code Stream} in the order they appear in
-     * the central directory of the jar file.  The set of entries
-     * returned depends on whether or not the jar file is a multi-release jar
-     * file, and on the constructor used to create the {@code JarFile}.  If the
-     * jar file is not a multi-release jar file, all entries are returned,
-     * regardless of how the {@code JarFile} is created.  If the constructor
-     * does not take a {@code Release} argument, all entries are returned.
-     * If the jar file is a multi-release jar file and the constructor takes a
-     * {@code Release} argument, then the set of entries returned is equivalent
-     * to the set of entries that would be returned if the set was built by
-     * invoking {@link JarFile#getEntry(String)} or
-     * {@link JarFile#getJarEntry(String)} with the name of each base entry in
-     * the jar file.  A base entry is an entry whose path name does not start
-     * with "META-INF/versions/".
+     * the central directory of the jar file.
+     *
      * @return an ordered {@code Stream} of entries in this jar file
      * @throws IllegalStateException if the jar file has been closed
      * @since 1.8
+     *
+     * @apiNote  A versioned view of the stream obtained from a {@code JarFile}
+     * configured to process a multi-release jar file can be created with code
+     * similar to the following:
+     * <pre>
+     * {@code
+     *     Stream<JarEntry> versionedStream(JarFile jf) {
+     *         return jf.stream().map(JarEntry::getName)
+     *                  .filter(name -> !name.startsWith("META-INF/versions/"))
+     *                  .map(jf::getJarEntry);
+     *     }
+     * }
+     * </pre>
      */
     public Stream<JarEntry> stream() {
         return StreamSupport.stream(Spliterators.spliterator(
--- a/src/java.base/share/classes/java/util/zip/ZipEntry.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/zip/ZipEntry.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -568,9 +568,18 @@
                     int pos = off + 4;               // reserved 4 bytes
                     if (get16(extra, pos) !=  0x0001 || get16(extra, pos + 2) != 24)
                         break;
-                    mtime = winTimeToFileTime(get64(extra, pos + 4));
-                    atime = winTimeToFileTime(get64(extra, pos + 12));
-                    ctime = winTimeToFileTime(get64(extra, pos + 20));
+                    long wtime = get64(extra, pos + 4);
+                    if (wtime != WINDOWS_TIME_NOT_AVAILABLE) {
+                        mtime = winTimeToFileTime(wtime);
+                    }
+                    wtime = get64(extra, pos + 12);
+                    if (wtime != WINDOWS_TIME_NOT_AVAILABLE) {
+                        atime = winTimeToFileTime(wtime);
+                    }
+                    wtime = get64(extra, pos + 20);
+                    if (wtime != WINDOWS_TIME_NOT_AVAILABLE) {
+                        ctime = winTimeToFileTime(wtime);
+                    }
                     break;
                 case EXTID_EXTT:
                     int flag = Byte.toUnsignedInt(extra[off]);
--- a/src/java.base/share/classes/java/util/zip/ZipOutputStream.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/zip/ZipOutputStream.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -421,22 +421,36 @@
         byte[] nameBytes = zc.getBytes(e.name);
         writeShort(nameBytes.length);
 
-        int elenEXTT = 0;               // info-zip extended timestamp
+        int elenEXTT = 0;         // info-zip extended timestamp
         int flagEXTT = 0;
+        long umtime = -1;
+        long uatime = -1;
+        long uctime = -1;
         if (e.mtime != null) {
             elenEXTT += 4;
             flagEXTT |= EXTT_FLAG_LMT;
+            umtime = fileTimeToUnixTime(e.mtime);
         }
         if (e.atime != null) {
             elenEXTT += 4;
             flagEXTT |= EXTT_FLAG_LAT;
+            uatime = fileTimeToUnixTime(e.atime);
         }
         if (e.ctime != null) {
             elenEXTT += 4;
             flagEXTT |= EXTT_FLAT_CT;
+            uctime = fileTimeToUnixTime(e.ctime);
         }
-        if (flagEXTT != 0)
-            elen += (elenEXTT + 5);    // headid(2) + size(2) + flag(1) + data
+        if (flagEXTT != 0) {
+            // to use ntfs time if any m/a/ctime is beyond unixtime upper bound
+            if (umtime > UPPER_UNIXTIME_BOUND ||
+                uatime > UPPER_UNIXTIME_BOUND ||
+                uctime > UPPER_UNIXTIME_BOUND) {
+                elen += 36;                // NTFS time, total 36 bytes
+            } else {
+                elen += (elenEXTT + 5);    // headid(2) + size(2) + flag(1) + data
+            }
+        }
         writeShort(elen);
         writeBytes(nameBytes, 0, nameBytes.length);
         if (hasZip64) {
@@ -446,15 +460,31 @@
             writeLong(e.csize);
         }
         if (flagEXTT != 0) {
-            writeShort(EXTID_EXTT);
-            writeShort(elenEXTT + 1);      // flag + data
-            writeByte(flagEXTT);
-            if (e.mtime != null)
-                writeInt(fileTimeToUnixTime(e.mtime));
-            if (e.atime != null)
-                writeInt(fileTimeToUnixTime(e.atime));
-            if (e.ctime != null)
-                writeInt(fileTimeToUnixTime(e.ctime));
+            if (umtime > UPPER_UNIXTIME_BOUND ||
+                uatime > UPPER_UNIXTIME_BOUND ||
+                uctime > UPPER_UNIXTIME_BOUND) {
+                writeShort(EXTID_NTFS);    // id
+                writeShort(32);            // data size
+                writeInt(0);               // reserved
+                writeShort(0x0001);        // NTFS attr tag
+                writeShort(24);
+                writeLong(e.mtime == null ? WINDOWS_TIME_NOT_AVAILABLE
+                                          : fileTimeToWinTime(e.mtime));
+                writeLong(e.atime == null ? WINDOWS_TIME_NOT_AVAILABLE
+                                          : fileTimeToWinTime(e.atime));
+                writeLong(e.ctime == null ? WINDOWS_TIME_NOT_AVAILABLE
+                                          : fileTimeToWinTime(e.ctime));
+            } else {
+                writeShort(EXTID_EXTT);
+                writeShort(elenEXTT + 1);  // flag + data
+                writeByte(flagEXTT);
+                if (e.mtime != null)
+                    writeInt(umtime);
+                if (e.atime != null)
+                    writeInt(uatime);
+                if (e.ctime != null)
+                    writeInt(uctime);
+            }
         }
         writeExtra(e.extra);
         locoff = written;
@@ -528,18 +558,30 @@
         // cen info-zip extended timestamp only outputs mtime
         // but set the flag for a/ctime, if present in loc
         int flagEXTT = 0;
+        long umtime = -1;
+        long uatime = -1;
+        long uctime = -1;
         if (e.mtime != null) {
-            elen += 4;              // + mtime(4)
             flagEXTT |= EXTT_FLAG_LMT;
+            umtime = fileTimeToUnixTime(e.mtime);
         }
         if (e.atime != null) {
             flagEXTT |= EXTT_FLAG_LAT;
+            uatime = fileTimeToUnixTime(e.atime);
         }
         if (e.ctime != null) {
             flagEXTT |= EXTT_FLAT_CT;
+            uctime = fileTimeToUnixTime(e.ctime);
         }
         if (flagEXTT != 0) {
-            elen += 5;             // headid + sz + flag
+            // to use ntfs time if any m/a/ctime is beyond unixtime upper bound
+            if (umtime > UPPER_UNIXTIME_BOUND ||
+                uatime > UPPER_UNIXTIME_BOUND ||
+                uctime > UPPER_UNIXTIME_BOUND) {
+                elen += 36;         // NTFS time total 36 bytes
+            } else {
+                elen += 9;          // headid(2) + sz(2) + flag(1) + mtime (4)
+            }
         }
         writeShort(elen);
         byte[] commentBytes;
@@ -568,14 +610,30 @@
                 writeLong(xentry.offset);
         }
         if (flagEXTT != 0) {
-            writeShort(EXTID_EXTT);
-            if (e.mtime != null) {
-                writeShort(5);      // flag + mtime
-                writeByte(flagEXTT);
-                writeInt(fileTimeToUnixTime(e.mtime));
+            if (umtime > UPPER_UNIXTIME_BOUND ||
+                uatime > UPPER_UNIXTIME_BOUND ||
+                uctime > UPPER_UNIXTIME_BOUND) {
+                writeShort(EXTID_NTFS);    // id
+                writeShort(32);            // data size
+                writeInt(0);               // reserved
+                writeShort(0x0001);        // NTFS attr tag
+                writeShort(24);
+                writeLong(e.mtime == null ? WINDOWS_TIME_NOT_AVAILABLE
+                                          : fileTimeToWinTime(e.mtime));
+                writeLong(e.atime == null ? WINDOWS_TIME_NOT_AVAILABLE
+                                          : fileTimeToWinTime(e.atime));
+                writeLong(e.ctime == null ? WINDOWS_TIME_NOT_AVAILABLE
+                                          : fileTimeToWinTime(e.ctime));
             } else {
-                writeShort(1);      // flag only
-                writeByte(flagEXTT);
+                writeShort(EXTID_EXTT);
+                if (e.mtime != null) {
+                    writeShort(5);      // flag + mtime
+                    writeByte(flagEXTT);
+                    writeInt(umtime);
+                } else {
+                    writeShort(1);      // flag only
+                    writeByte(flagEXTT);
+                }
             }
         }
         writeExtra(e.extra);
--- a/src/java.base/share/classes/java/util/zip/ZipUtils.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/java/util/zip/ZipUtils.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,6 +38,9 @@
     // used to adjust values between Windows and java epoch
     private static final long WINDOWS_EPOCH_IN_MICROSECONDS = -11644473600000000L;
 
+    // used to indicate the corresponding windows time is not available
+    public static final long WINDOWS_TIME_NOT_AVAILABLE = Long.MIN_VALUE;
+
     /**
      * Converts Windows time (in microseconds, UTC/GMT) time to FileTime.
      */
@@ -54,6 +57,11 @@
     }
 
     /**
+     * The upper bound of the 32-bit unix time, the "year 2038 problem".
+     */
+    public static final long UPPER_UNIXTIME_BOUND = 0x7fffffff;
+
+    /**
      * Converts "standard Unix time"(in seconds, UTC/GMT) to FileTime
      */
     public static final FileTime unixTimeToFileTime(long utime) {
--- a/src/java.base/share/classes/javax/security/auth/SubjectDomainCombiner.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/javax/security/auth/SubjectDomainCombiner.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -110,16 +110,18 @@
      * {@code SubjectDomainCombiner}.
      *
      * <p> A new {@code ProtectionDomain} instance is created
-     * for each {@code ProtectionDomain} in the
-     * {@code currentDomains} array.  Each new {@code ProtectionDomain}
+     * for each non-static {@code ProtectionDomain} (
+     * (staticPermissionsOnly() == false)
+     * in the {@code currentDomains} array.  Each new {@code ProtectionDomain}
      * instance is created using the {@code CodeSource},
      * {@code Permission}s and {@code ClassLoader}
      * from the corresponding {@code ProtectionDomain} in
      * {@code currentDomains}, as well as with the Principals from
      * the {@code Subject} associated with this
-     * {@code SubjectDomainCombiner}.
+     * {@code SubjectDomainCombiner}. Static ProtectionDomains are
+     * combined as-is and no new instance is created.
      *
-     * <p> All of the newly instantiated ProtectionDomains are
+     * <p> All of the ProtectionDomains (static and newly instantiated) are
      * combined into a new array.  The ProtectionDomains from the
      * {@code assignedDomains} array are appended to this new array,
      * and the result is returned.
@@ -233,10 +235,15 @@
                 subjectPd = cachedPDs.getValue(pd);
 
                 if (subjectPd == null) {
-                    subjectPd = new ProtectionDomain(pd.getCodeSource(),
+                    if (pd.staticPermissionsOnly()) {
+                        // keep static ProtectionDomain objects static
+                        subjectPd = pd;
+                    } else {
+                        subjectPd = new ProtectionDomain(pd.getCodeSource(),
                                                 pd.getPermissions(),
                                                 pd.getClassLoader(),
                                                 principals);
+                    }
                     cachedPDs.putValue(pd, subjectPd);
                 } else {
                     allNew = false;
@@ -335,60 +342,62 @@
                 ProtectionDomain subjectPd = cachedPDs.getValue(pd);
 
                 if (subjectPd == null) {
+                    if (pd.staticPermissionsOnly()) {
+                        // keep static ProtectionDomain objects static
+                        subjectPd = pd;
+                    } else {
+                        // XXX
+                        // we must first add the original permissions.
+                        // that way when we later add the new JAAS permissions,
+                        // any unresolved JAAS-related permissions will
+                        // automatically get resolved.
 
-                    // XXX
-                    // we must first add the original permissions.
-                    // that way when we later add the new JAAS permissions,
-                    // any unresolved JAAS-related permissions will
-                    // automatically get resolved.
-
-                    // get the original perms
-                    Permissions perms = new Permissions();
-                    PermissionCollection coll = pd.getPermissions();
-                    java.util.Enumeration<Permission> e;
-                    if (coll != null) {
-                        synchronized (coll) {
-                            e = coll.elements();
-                            while (e.hasMoreElements()) {
-                                Permission newPerm =
+                        // get the original perms
+                        Permissions perms = new Permissions();
+                        PermissionCollection coll = pd.getPermissions();
+                        java.util.Enumeration<Permission> e;
+                        if (coll != null) {
+                            synchronized (coll) {
+                                e = coll.elements();
+                                while (e.hasMoreElements()) {
+                                    Permission newPerm =
                                         e.nextElement();
-                                 perms.add(newPerm);
+                                    perms.add(newPerm);
+                                }
                             }
                         }
-                    }
 
-                    // get perms from the policy
+                        // get perms from the policy
+                        final java.security.CodeSource finalCs = pd.getCodeSource();
+                        final Subject finalS = subject;
+                        PermissionCollection newPerms =
+                            java.security.AccessController.doPrivileged
+                            (new PrivilegedAction<PermissionCollection>() {
+                            @SuppressWarnings("deprecation")
+                            public PermissionCollection run() {
+                                return
+                                    javax.security.auth.Policy.getPolicy().getPermissions
+                                    (finalS, finalCs);
+                            }
+                        });
 
-                    final java.security.CodeSource finalCs = pd.getCodeSource();
-                    final Subject finalS = subject;
-                    PermissionCollection newPerms =
-                        java.security.AccessController.doPrivileged
-                        (new PrivilegedAction<PermissionCollection>() {
-                        @SuppressWarnings("deprecation")
-                        public PermissionCollection run() {
-                          return
-                          javax.security.auth.Policy.getPolicy().getPermissions
-                                (finalS, finalCs);
-                        }
-                    });
-
-                    // add the newly granted perms,
-                    // avoiding duplicates
-                    synchronized (newPerms) {
-                        e = newPerms.elements();
-                        while (e.hasMoreElements()) {
-                            Permission newPerm = e.nextElement();
-                            if (!perms.implies(newPerm)) {
-                                perms.add(newPerm);
-                                if (debug != null)
-                                    debug.println (
-                                        "Adding perm " + newPerm + "\n");
+                        // add the newly granted perms,
+                        // avoiding duplicates
+                        synchronized (newPerms) {
+                            e = newPerms.elements();
+                            while (e.hasMoreElements()) {
+                                Permission newPerm = e.nextElement();
+                                if (!perms.implies(newPerm)) {
+                                    perms.add(newPerm);
+                                    if (debug != null)
+                                        debug.println (
+                                            "Adding perm " + newPerm + "\n");
+                                }
                             }
                         }
+                        subjectPd = new ProtectionDomain
+                            (finalCs, perms, pd.getClassLoader(), principals);
                     }
-                    subjectPd = new ProtectionDomain
-                        (finalCs, perms, pd.getClassLoader(), principals);
-
                     if (allowCaching)
                         cachedPDs.putValue(pd, subjectPd);
                 }
--- a/src/java.base/share/classes/jdk/internal/jimage/ImageHeader.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/jdk/internal/jimage/ImageHeader.java	Tue Jul 26 14:45:11 2016 -0700
@@ -21,7 +21,7 @@
  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  * or visit www.oracle.com if you need additional information or have any
  * questions.
-*/
+ */
 
 package jdk.internal.jimage;
 
--- a/src/java.base/share/classes/jdk/internal/jimage/ImageStream.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/jdk/internal/jimage/ImageStream.java	Tue Jul 26 14:45:11 2016 -0700
@@ -3,18 +3,18 @@
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General License version 2 only, as
+ * under the terms of the GNU General Public License version 2 only, as
  * published by the Free Software Foundation.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
  * by Oracle in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General License
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
- * You should have received a copy of the GNU General License version
+ * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
--- a/src/java.base/share/classes/jdk/internal/misc/Unsafe.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/jdk/internal/misc/Unsafe.java	Tue Jul 26 14:45:11 2016 -0700
@@ -26,8 +26,6 @@
 package jdk.internal.misc;
 
 import jdk.internal.HotSpotIntrinsicCandidate;
-import jdk.internal.reflect.CallerSensitive;
-import jdk.internal.reflect.Reflection;
 import jdk.internal.vm.annotation.ForceInline;
 
 import java.lang.reflect.Field;
@@ -57,7 +55,6 @@
     private static native void registerNatives();
     static {
         registerNatives();
-        Reflection.registerMethodsToFilter(Unsafe.class, "getUnsafe");
     }
 
     private Unsafe() {}
@@ -87,16 +84,8 @@
      * }}</pre>
      *
      * (It may assist compilers to make the local variable {@code final}.)
-     *
-     * @throws  SecurityException if the class loader of the caller
-     *          class is not in the system domain in which all permissions
-     *          are granted.
      */
-    @CallerSensitive
     public static Unsafe getUnsafe() {
-        Class<?> caller = Reflection.getCallerClass();
-        if (!VM.isSystemDomainLoader(caller.getClassLoader()))
-            throw new SecurityException("Unsafe");
         return theUnsafe;
     }
 
--- a/src/java.base/share/classes/jdk/internal/ref/WeakCleanable.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/jdk/internal/ref/WeakCleanable.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,3 @@
-package jdk.internal.ref;
-
 /*
  * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -25,6 +23,8 @@
  * questions.
  */
 
+package jdk.internal.ref;
+
 import java.lang.ref.Cleaner;
 import java.lang.ref.Reference;
 import java.lang.ref.WeakReference;
--- a/src/java.base/share/classes/module-info.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/module-info.java	Tue Jul 26 14:45:11 2016 -0700
@@ -149,7 +149,6 @@
     exports jdk.internal.module to
         java.instrument,
         java.management,
-        java.xml,
         jdk.dynalink,
         jdk.jartool,
         jdk.jlink;
@@ -282,15 +281,18 @@
         jdk.security.auth;
     exports sun.text.resources to
         jdk.localedata;
-    exports sun.util.resources to
-        jdk.localedata;
+    exports sun.util.cldr to
+        jdk.jlink;
     exports sun.util.locale.provider to
         java.desktop,
+        jdk.jlink,
         jdk.localedata;
     exports sun.util.logging to
         java.desktop,
         java.logging,
         java.prefs;
+    exports sun.util.resources to
+        jdk.localedata;
 
     // JDK-internal service types
     uses jdk.internal.logger.DefaultLoggerFinder;
@@ -306,4 +308,3 @@
     provides java.nio.file.spi.FileSystemProvider with
         jdk.internal.jrtfs.JrtFileSystemProvider;
 }
-
--- a/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/sun/net/ftp/impl/FtpClient.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1707,7 +1707,7 @@
      */
     public InputStream nameList(String path) throws sun.net.ftp.FtpProtocolException, IOException {
         Socket s;
-        s = openDataConnection("NLST " + path);
+        s = openDataConnection(path == null ? "NLST" : "NLST " + path);
         if (s != null) {
             return createInputStream(s.getInputStream());
         }
--- a/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/GenericArrayTypeImpl.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/GenericArrayTypeImpl.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -65,15 +65,7 @@
     }
 
     public String toString() {
-        Type componentType = getGenericComponentType();
-        StringBuilder sb = new StringBuilder();
-
-        if (componentType instanceof Class)
-            sb.append(((Class)componentType).getName() );
-        else
-            sb.append(componentType.toString());
-        sb.append("[]");
-        return sb.toString();
+        return getGenericComponentType().getTypeName() + "[]";
     }
 
     @Override
--- a/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/ParameterizedTypeImpl.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/ParameterizedTypeImpl.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,6 +33,7 @@
 import java.lang.reflect.Type;
 import java.lang.reflect.TypeVariable;
 import java.util.Arrays;
+import java.util.StringJoiner;
 import java.util.Objects;
 
 /** Implementing class for ParameterizedType interface. */
@@ -207,12 +208,9 @@
         StringBuilder sb = new StringBuilder();
 
         if (ownerType != null) {
-            if (ownerType instanceof Class)
-                sb.append(((Class)ownerType).getName());
-            else
-                sb.append(ownerType.toString());
+            sb.append(ownerType.getTypeName());
 
-            sb.append(".");
+            sb.append("$");
 
             if (ownerType instanceof ParameterizedTypeImpl) {
                 // Find simple name of nested type by removing the
@@ -220,21 +218,17 @@
                 sb.append(rawType.getName().replace( ((ParameterizedTypeImpl)ownerType).rawType.getName() + "$",
                                          ""));
             } else
-                sb.append(rawType.getName());
+               sb.append(rawType.getSimpleName());
         } else
             sb.append(rawType.getName());
 
-        if (actualTypeArguments != null &&
-            actualTypeArguments.length > 0) {
-            sb.append("<");
-            boolean first = true;
+        if (actualTypeArguments != null) {
+            StringJoiner sj = new StringJoiner(", ", "<", ">");
+            sj.setEmptyValue("");
             for(Type t: actualTypeArguments) {
-                if (!first)
-                    sb.append(", ");
-                sb.append(t.getTypeName());
-                first = false;
+                sj.add(t.getTypeName());
             }
-            sb.append(">");
+            sb.append(sj.toString());
         }
 
         return sb.toString();
--- a/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/WildcardTypeImpl.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/sun/reflect/generics/reflectiveObjects/WildcardTypeImpl.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
 import sun.reflect.generics.tree.FieldTypeSignature;
 import sun.reflect.generics.visitor.Reifier;
 import java.util.Arrays;
+import java.util.StringJoiner;
 
 
 /**
@@ -156,14 +157,12 @@
 
         assert bounds.length > 0;
 
-        boolean first = true;
+        StringJoiner sj = new StringJoiner(" & ");
         for(Type bound: bounds) {
-            if (!first)
-                sb.append(" & ");
+            sj.add(bound.getTypeName());
+        }
+        sb.append(sj.toString());
 
-            first = false;
-            sb.append(bound.getTypeName());
-        }
         return sb.toString();
     }
 
--- a/src/java.base/share/classes/sun/security/provider/DSA.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/sun/security/provider/DSA.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -329,6 +329,10 @@
                 r = values[0].getBigInteger();
                 s = values[1].getBigInteger();
 
+                // Check for trailing signature data
+                if (in.available() != 0) {
+                    throw new IOException("Incorrect signature length");
+                }
             } catch (IOException e) {
                 throw new SignatureException("invalid encoding for signature");
             }
--- a/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/classes/sun/security/util/AbstractAlgorithmConstraints.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/java.base/share/conf/security/java.security	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/conf/security/java.security	Tue Jul 26 14:45:11 2016 -0700
@@ -652,8 +652,8 @@
 #   jdk.certpath.disabledAlgorithms=MD2, DSA, RSA keySize < 2048
 #
 #
-jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, \
-    DSA keySize < 1024, EC keySize < 224
+jdk.certpath.disabledAlgorithms=MD2, MD5, SHA1 jdkCA & denyAfter 2017-01-01, \
+    RSA keySize < 1024, DSA keySize < 1024, EC keySize < 224
 
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS/DTLS) processing
--- a/src/java.base/share/native/include/jvmti.h	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/include/jvmti.h	Tue Jul 26 14:45:11 2016 -0700
@@ -1217,8 +1217,11 @@
     jmethodID method,
     jlocation location);
 
-  /*   40 :  RESERVED */
-  void *reserved40;
+  /*   40 : Get Named Module */
+  jvmtiError (JNICALL *GetNamedModule) (jvmtiEnv* env,
+    jobject class_loader,
+    const char* package_name,
+    jobject* module_ptr);
 
   /*   41 : Set Field Access Watch */
   jvmtiError (JNICALL *SetFieldAccessWatch) (jvmtiEnv* env,
@@ -2146,6 +2149,12 @@
     return functions->GetAllModules(this, module_count_ptr, modules_ptr);
   }
 
+  jvmtiError GetNamedModule(jobject class_loader,
+            const char* package_name,
+            jobject* module_ptr) {
+    return functions->GetNamedModule(this, class_loader, package_name, module_ptr);
+  }
+
   jvmtiError GetLoadedClasses(jint* class_count_ptr,
             jclass** classes_ptr) {
     return functions->GetLoadedClasses(this, class_count_ptr, classes_ptr);
--- a/src/java.base/share/native/libfdlibm/e_acos.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_acos.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_asin.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_asin.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_atan2.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_atan2.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_atanh.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_atanh.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_cosh.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_cosh.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_exp.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_exp.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_fmod.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_fmod.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_log.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_log.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_log10.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_log10.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_rem_pio2.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_rem_pio2.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_remainder.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_remainder.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_scalb.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_scalb.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/e_sinh.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/e_sinh.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/fdlibm.h	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/fdlibm.h	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/k_cos.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/k_cos.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/k_rem_pio2.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/k_rem_pio2.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/k_sin.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/k_sin.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/k_standard.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/k_standard.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/k_tan.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/k_tan.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2004, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_atan.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_atan.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_ceil.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_ceil.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_copysign.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_copysign.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_cos.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_cos.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_expm1.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_expm1.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_fabs.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_fabs.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_finite.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_finite.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_floor.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_floor.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_frexp.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_frexp.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_ilogb.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_ilogb.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_isnan.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_isnan.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_ldexp.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_ldexp.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_lib_version.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_lib_version.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_log1p.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_log1p.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2003, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_logb.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_logb.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_matherr.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_matherr.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_modf.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_modf.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_nextafter.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_nextafter.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_rint.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_rint.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_scalbn.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_scalbn.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_significand.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_significand.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_sin.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_sin.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_tan.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_tan.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libfdlibm/s_tanh.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libfdlibm/s_tanh.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 1998, 2001, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.base/share/native/libjimage/NativeImageBuffer.cpp	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libjimage/NativeImageBuffer.cpp	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/src/java.base/share/native/libjimage/endian.cpp	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libjimage/endian.cpp	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/src/java.base/share/native/libjimage/imageDecompressor.hpp	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libjimage/imageDecompressor.hpp	Tue Jul 26 14:45:11 2016 -0700
@@ -74,8 +74,8 @@
  * meaning that the resource is equivalent to the not compressed resource.
  * In each iteration, the name of the compressor located in the current header
  * is used to retrieve the associated instance of ImageDecompressor.
- * For example “zip” is the name of the compressor that compresses resources
- * using the zip algorithm. The ZipDecompressor class name is also “zip”.
+ * For example "zip" is the name of the compressor that compresses resources
+ * using the zip algorithm. The ZipDecompressor class name is also "zip".
  * ImageDecompressor instances are retrieved from a static array in which
  * they are registered.
  */
--- a/src/java.base/share/native/libjimage/imageFile.cpp	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libjimage/imageFile.cpp	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/src/java.base/share/native/libjimage/jimage.cpp	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libjimage/jimage.cpp	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -85,7 +85,7 @@
  * Ex.
  *  const char* package = (*JImagePackageToModule)(image, "java/lang");
  *  tty->print_cr(package);
- *  —> java.base
+ *  -> java.base
  */
 extern "C" const char* JIMAGE_PackageToModule(JImageFile* image, const char* package_name) {
     return ((ImageFileReader*) image)->get_image_module_data()->package_to_module(package_name);
@@ -137,7 +137,7 @@
 }
 
 /*
- * JImageGetResource - Given an open image file (see JImageOpen), a resource’s
+ * JImageGetResource - Given an open image file (see JImageOpen), a resource's
  * location information (see JImageFindResource), a buffer of appropriate
  * size and the size, retrieve the bytes associated with the
  * resource. If the size is less than the resource size then the read is truncated.
@@ -168,7 +168,7 @@
  * Ex.
  *   bool ctw_visitor(JImageFile* jimage, const char* module_name, const char* version,
  *                  const char* package, const char* name, const char* extension, void* arg) {
- *     if (strcmp(extension, “class”) == 0) {
+ *     if (strcmp(extension, "class") == 0) {
  *       char path[JIMAGE_MAX_PATH];
  *       Thread* THREAD = Thread::current();
  *       jio_snprintf(path, JIMAGE_MAX_PATH - 1, "/%s/%s", package, name);
--- a/src/java.base/share/native/libjimage/jimage.hpp	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/share/native/libjimage/jimage.hpp	Tue Jul 26 14:45:11 2016 -0700
@@ -101,7 +101,7 @@
  * Ex.
  *  const char* package = (*JImagePackageToModule)(image, "java/lang");
  *  tty->print_cr(package);
- *  —> java.base
+ *  -> java.base
  */
 
 extern "C" const char * JIMAGE_PackageToModule(JImageFile* jimage, const char* package_name);
@@ -133,7 +133,7 @@
 
 
 /*
- * JImageGetResource - Given an open image file (see JImageOpen), a resource’s
+ * JImageGetResource - Given an open image file (see JImageOpen), a resource's
  * location information (see JImageFindResource), a buffer of appropriate
  * size and the size, retrieve the bytes associated with the
  * resource. If the size is less than the resource size then the read is truncated.
@@ -165,7 +165,7 @@
  * Ex.
  *   bool ctw_visitor(JImageFile* jimage, const char* module_name, const char* version,
  *                  const char* package, const char* name, const char* extension, void* arg) {
- *     if (strcmp(extension, “class”) == 0) {
+ *     if (strcmp(extension, "class") == 0) {
  *       char path[JIMAGE_MAX_PATH];
  *       Thread* THREAD = Thread::current();
  *       jio_snprintf(path, JIMAGE_MAX_PATH - 1, "/%s/%s", package, name);
--- a/src/java.base/unix/classes/java/lang/ClassLoaderHelper.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/unix/classes/java/lang/ClassLoaderHelper.java	Tue Jul 26 14:45:11 2016 -0700
@@ -22,6 +22,7 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
+
 package java.lang;
 
 import java.io.File;
--- a/src/java.base/unix/classes/java/net/DefaultDatagramSocketImplFactory.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/unix/classes/java/net/DefaultDatagramSocketImplFactory.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007,2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -22,6 +22,7 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
+
 package java.net;
 
 import sun.security.action.GetPropertyAction;
--- a/src/java.base/unix/native/libnet/NetworkInterface.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/unix/native/libnet/NetworkInterface.c	Tue Jul 26 14:45:11 2016 -0700
@@ -25,9 +25,6 @@
 
 #include <errno.h>
 #include <strings.h>
-#if defined(_ALLBSD_SOURCE) && defined(__OpenBSD__)
-#include <sys/types.h>
-#endif
 #include <netinet/in.h>
 #include <stdlib.h>
 #include <string.h>
@@ -46,7 +43,6 @@
 
 #if defined(__linux__)
 #include <sys/ioctl.h>
-#include <bits/ioctls.h>
 #include <sys/utsname.h>
 #include <stdio.h>
 #endif
@@ -76,9 +72,23 @@
 #include "net_util.h"
 
 #if defined(__linux__)
-#define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
+    #define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
+#elif defined(__solaris__)
+    #ifndef SIOCGLIFHWADDR
+        #define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
+    #endif
+    #define DEV_PREFIX "/dev/"
 #endif
 
+#define CHECKED_MALLOC3(_pointer, _type, _size) \
+    do { \
+        _pointer = (_type)malloc(_size); \
+        if (_pointer == NULL) { \
+            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
+            return ifs; /* return untouched list */ \
+        } \
+    } while(0)
+
 typedef struct _netaddr  {
     struct sockaddr *addr;
     struct sockaddr *brdcast;
@@ -130,40 +140,31 @@
 static netif  *enumInterfaces(JNIEnv *env);
 static netif  *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs);
 
-#ifdef AF_INET6
+#if defined(AF_INET6)
 static netif  *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs);
 #endif
 
 static netif  *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
-                     struct sockaddr *ifr_addrP, struct sockaddr *ifr_broadaddrP,
-                     struct sockaddr *ifr_subnetaddrP, int family, short prefix);
+                     struct sockaddr *ifr_addrP,
+                     struct sockaddr *ifr_broadaddrP,
+                     int family, short prefix);
 static void    freeif(netif *ifs);
 
 static int     openSocket(JNIEnv *env, int proto);
 static int     openSocketWithFallback(JNIEnv *env, const char *ifname);
 
+static short   translateIPv4AddressToPrefix(struct sockaddr_in *addr);
+static short   translateIPv6AddressToPrefix(struct sockaddr_in6 *addr);
 
-static struct  sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name,
-                                      struct sockaddr *brdcast_store);
-static short   getSubnet(JNIEnv *env, int sock, const char *ifname);
-static short   computeMaskFromAddress(struct sockaddr *ifr_subnetaddrP);
 static int     getIndex(int sock, const char *ifname);
-
 static int     getFlags(int sock, const char *ifname, int *flags);
-static int     getMacAddress(JNIEnv *env, int sock,  const char *ifname,
+static int     getMacAddress(JNIEnv *env, int sock, const char *ifname,
                              const struct in_addr *addr, unsigned char *buf);
 static int     getMTU(JNIEnv *env, int sock, const char *ifname);
 
-
 #if defined(__solaris__)
-static netif  *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family);
 static int     getMacFromDevice(JNIEnv *env, const char *ifname,
                                 unsigned char *retbuf);
-
-#ifndef SIOCGLIFHWADDR
-#define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
-#endif
-
 #endif
 
 /******************* Java entry points *****************************/
@@ -259,7 +260,7 @@
     }
 
     // if found create a NetworkInterface
-    if (curr != NULL) {;
+    if (curr != NULL) {
         obj = createNetworkInterface(env, curr);
     }
 
@@ -299,7 +300,7 @@
     }
 
     // if found create a NetworkInterface
-    if (curr != NULL) {;
+    if (curr != NULL) {
         obj = createNetworkInterface(env, curr);
     }
 
@@ -317,7 +318,7 @@
 {
     netif *ifs, *curr;
 
-#ifdef AF_INET6
+#if defined(AF_INET6)
     int family = (getInetAddress_family(env, iaObj) == IPv4) ? AF_INET : AF_INET6;
 #else
     int family =  AF_INET;
@@ -335,7 +336,7 @@
     while (curr != NULL) {
         netaddr *addrP = curr->addr;
 
-        // Iterate through each address on the interface
+        // iterate through each address on the interface
         while (addrP != NULL) {
 
             if (family == addrP->family) {
@@ -350,7 +351,7 @@
                     }
                 }
 
-#ifdef AF_INET6
+#if defined(AF_INET6)
                 if (family == AF_INET6) {
                     jbyte *bytes = (jbyte *)&(
                         ((struct sockaddr_in6*)addrP->addr)->sin6_addr);
@@ -385,7 +386,7 @@
     }
 
     // if found create a NetworkInterface
-    if (match) {;
+    if (match) {
         obj = createNetworkInterface(env, curr);
     }
 
@@ -634,7 +635,7 @@
  * populates the InetAddress array based on the IP addresses for this
  * interface.
  */
-jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
+static jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
     jobject netifObj;
     jobject name;
     jobjectArray addrArr;
@@ -712,7 +713,7 @@
             }
         }
 
-#ifdef AF_INET6
+#if defined(AF_INET6)
         if (addrP->family == AF_INET6) {
             int scope=0;
             iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
@@ -803,7 +804,7 @@
     // return partial list if an exception occurs in the middle of process ???
 
     // If IPv6 is available then enumerate IPv6 addresses.
-#ifdef AF_INET6
+#if defined(AF_INET6)
 
         // User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
         // so we have to call ipv6_available()
@@ -829,20 +830,10 @@
     return ifs;
 }
 
-#define CHECKED_MALLOC3(_pointer, _type, _size) \
-    do { \
-        _pointer = (_type)malloc(_size); \
-        if (_pointer == NULL) { \
-            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
-            return ifs; /* return untouched list */ \
-        } \
-    } while(0)
-
-
 /*
- * Frees an interface list (including any attached addresses)
+ * Frees an interface list (including any attached addresses).
  */
-void freeif(netif *ifs) {
+static void freeif(netif *ifs) {
     netif *currif = ifs;
     netif *child = NULL;
 
@@ -865,9 +856,10 @@
     }
 }
 
-netif *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
-             struct sockaddr *ifr_addrP, struct sockaddr *ifr_broadaddrP,
-             struct sockaddr *ifr_subnetaddrP, int family, short prefix)
+static netif *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
+                    struct sockaddr *ifr_addrP,
+                    struct sockaddr *ifr_broadaddrP,
+                    int family, short prefix)
 {
     netif *currif = ifs, *parent;
     netaddr *addrP;
@@ -881,7 +873,6 @@
 #endif
 
     char *name_colonP;
-    int mask;
     int isVirtual = 0;
     int addr_size;
     int flags = 0;
@@ -894,12 +885,12 @@
     name[ifnam_size - 1] = '\0';
     *vname = 0;
 
-     // Create and populate the netaddr node. If allocation fails
-     // return an un-updated list.
+    // Create and populate the netaddr node. If allocation fails
+    // return an un-updated list.
 
-     // Allocate for addr and brdcast at once
+    // Allocate for addr and brdcast at once
 
-#ifdef AF_INET6
+#if defined(AF_INET6)
     addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in)
                                     : sizeof(struct sockaddr_in6);
 #else
@@ -911,33 +902,16 @@
     memcpy(addrP->addr, ifr_addrP, addr_size);
 
     addrP->family = family;
-    addrP->brdcast = NULL;
     addrP->mask = prefix;
     addrP->next = 0;
-    if (family == AF_INET) {
-        // Deal with broadcast addr & subnet mask
-        if (ifr_broadaddrP != NULL) {  // just set it, if already known
-            addrP->brdcast =
-                (struct sockaddr *)((char *)addrP + sizeof(netaddr) + addr_size);
-            memcpy(addrP->brdcast, ifr_broadaddrP, addr_size);
-        } else {  // otherwise look it up
-            struct sockaddr *brdcast_to =
-                (struct sockaddr *)((char *)addrP + sizeof(netaddr) + addr_size);
-            addrP->brdcast = getBroadcast(env, sock, name, brdcast_to);
-            if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
-                return ifs;
-            }
-        }
 
-        if (ifr_subnetaddrP != NULL) {  // just compute the mask, if already known
-            addrP->mask = computeMaskFromAddress(ifr_subnetaddrP);
-        } else {   // otherwise look it up
-            if ((mask = getSubnet(env, sock, name)) != -1) {
-                addrP->mask = mask;
-            } else if((*env)->ExceptionCheck(env)) {
-                return ifs;
-            }
-        }
+    // for IPv4 add broadcast address
+    if (family == AF_INET && ifr_broadaddrP != NULL) {
+        addrP->brdcast = (struct sockaddr *)
+                             ((char *)addrP + sizeof(netaddr) + addr_size);
+        memcpy(addrP->brdcast, ifr_broadaddrP, addr_size);
+    } else {
+        addrP->brdcast = NULL;
     }
 
     // Deal with virtual interface with colon notation e.g. eth0:1
@@ -1037,18 +1011,55 @@
     return ifs;
 }
 
-static short computeMaskFromAddress(struct sockaddr *ifr_subnetaddrP) {
-    short ret = 0;
-    unsigned int mask;
+/*
+ * Determines the prefix value for an AF_INET subnet address.
+ */
+static short translateIPv4AddressToPrefix(struct sockaddr_in *addr) {
+    short prefix = 0;
+    unsigned int mask = ntohl(addr->sin_addr.s_addr);
+    while (mask) {
+        mask <<= 1;
+        prefix++;
+    }
+    return prefix;
+}
 
-    mask = ntohl(((struct sockaddr_in*)ifr_subnetaddrP)->sin_addr.s_addr);
+/*
+ * Determines the prefix value for an AF_INET6 subnet address.
+ */
+static short translateIPv6AddressToPrefix(struct sockaddr_in6 *addr) {
+    short prefix = 0;
+    u_char *addrBytes = (u_char *)&(addr->sin6_addr);
+    unsigned int byte, bit;
 
-    while (mask) {
-       mask <<= 1;
-       ret++;
+    for (byte = 0; byte < sizeof(struct in6_addr); byte++, prefix += 8) {
+        if (addrBytes[byte] != 0xff) {
+            break;
+        }
+    }
+    if (byte != sizeof(struct in6_addr)) {
+        for (bit = 7; bit != 0; bit--, prefix++) {
+            if (!(addrBytes[byte] & (1 << bit))) {
+                break;
+            }
+        }
+        for (; bit != 0; bit--) {
+            if (addrBytes[byte] & (1 << bit)) {
+                prefix = 0;
+                break;
+            }
+        }
+        if (prefix > 0) {
+            byte++;
+            for (; byte < sizeof(struct in6_addr); byte++) {
+                if (addrBytes[byte]) {
+                    prefix = 0;
+                }
+            }
+        }
     }
 
-    return ret;
+    return prefix;
 }
 
 /*
@@ -1070,19 +1081,16 @@
     return sock;
 }
 
+/** Linux **/
+#if defined(__linux__)
 
-/** Linux, AIX **/
-#if defined(__linux__) || defined(_AIX)
-
-#ifdef AF_INET6
+#if defined(AF_INET6)
 /*
- * Opens a socket for further ioct calls. Tries AF_INET socket first and
- * if it falls return AF_INET6 socket.
+ * Opens a socket for further ioctl calls. Tries AF_INET socket first and
+ * if it fails return AF_INET6 socket.
  */
-// unused arg ifname and struct if2
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock;
-    struct ifreq if2;
 
     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
         if (errno == EPROTONOSUPPORT) {
@@ -1102,23 +1110,22 @@
     // IPv6 socket regardless of type of address of an interface.
     return sock;
 }
-
 #else
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env,AF_INET);
+    return openSocket(env, AF_INET);
 }
 #endif
 
+/*
+ * Enumerates and returns all IPv4 interfaces on Linux.
+ */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifconf ifc;
     struct ifreq *ifreqP;
     char *buf = NULL;
-    int numifs;
     unsigned i;
-    int siocgifconfRequest = SIOCGIFCONF;
 
-#if defined(__linux__)
-    // need to do a dummy SIOCGIFCONF to determine the buffer size.
+    // do a dummy SIOCGIFCONF to determine the buffer size
     // SIOCGIFCOUNT doesn't work
     ifc.ifc_buf = NULL;
     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
@@ -1126,160 +1133,9 @@
             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
         return ifs;
     }
-#elif defined(_AIX)
-    ifc.ifc_buf = NULL;
-    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
-        return ifs;
-    }
-#endif /* __linux__ */
 
+    // call SIOCGIFCONF to enumerate the interfaces
     CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
-
-    ifc.ifc_buf = buf;
-#if defined(_AIX)
-    siocgifconfRequest = CSIOCGIFCONF;
-#endif
-    if (ioctl(sock, siocgifconfRequest, (char *)&ifc) < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
-        free(buf);
-        return ifs;
-    }
-
-    // Iterate through each interface
-    ifreqP = ifc.ifc_req;
-    struct sockaddr addr, broadaddr, netmask;
-    for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
-        struct sockaddr* broadaddrP = NULL;
-        struct sockaddr* subnetaddrP = NULL;
-
-        // Ignore non IPv4 Interfaces
-        if ((struct sockaddr *)&(ifreqP->ifr_addr) != NULL &&
-            ((struct sockaddr *)&(ifreqP->ifr_addr))->sa_family != AF_INET) {
-            continue;
-        }
-
-        memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
-
-        // set broadaddrP, if applicable
-        if ((ifreqP->ifr_flags & IFF_POINTOPOINT) == 0 &&
-            ifreqP->ifr_flags & IFF_BROADCAST) {
-
-            if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
-                memcpy(&broadaddr, &(ifreqP->ifr_broadaddr), sizeof(struct sockaddr));
-                broadaddrP = &broadaddr;
-            }
-            // restore the address, for subsequent calls
-            memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
-        }
-
-        if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
-#if defined(_AIX)
-            memcpy(&netmask, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
-#else
-            memcpy(&netmask, &(ifreqP->ifr_netmask), sizeof(struct sockaddr));
-#endif
-            subnetaddrP = &netmask;
-        }
-
-        // Add to the list
-        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
-                    &addr, broadaddrP, subnetaddrP, AF_INET, 0);
-
-        // If an exception occurred then free the list
-        if ((*env)->ExceptionOccurred(env)) {
-            free(buf);
-            freeif(ifs);
-            return NULL;
-        }
-    }
-
-    // Free socket and buffer
-    free(buf);
-    return ifs;
-}
-
-
-#if defined(AF_INET6) && defined(__linux__)
-
-/*
- * Enumerates and returns all IPv6 interfaces on Linux.
- */
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    FILE *f;
-    char addr6[40], devname[21];
-    char addr6p[8][5];
-    int prefix, scope, dad_status, if_idx;
-    uint8_t ipv6addr[16];
-
-    if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
-        while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
-                      addr6p[0], addr6p[1], addr6p[2], addr6p[3],
-                      addr6p[4], addr6p[5], addr6p[6], addr6p[7],
-                      &if_idx, &prefix, &scope, &dad_status, devname) != EOF) {
-
-            struct netif *ifs_ptr = NULL;
-            struct netif *last_ptr = NULL;
-            struct sockaddr_in6 addr;
-
-            sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
-                    addr6p[0], addr6p[1], addr6p[2], addr6p[3],
-                    addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
-            inet_pton(AF_INET6, addr6, ipv6addr);
-
-            memset(&addr, 0, sizeof(struct sockaddr_in6));
-            memcpy((void*)addr.sin6_addr.s6_addr, (const void*)ipv6addr, 16);
-
-            addr.sin6_scope_id = if_idx;
-
-            ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr,
-                        NULL, NULL, AF_INET6, (short)prefix);
-
-            // If an exception occurred then return the list as is.
-            if ((*env)->ExceptionOccurred(env)) {
-                fclose(f);
-                return ifs;
-            }
-       }
-       fclose(f);
-    }
-    return ifs;
-}
-#endif
-
-
-#if defined(AF_INET6) && defined(_AIX)
-
-/*
- * Enumerates and returns all IPv6 interfaces on AIX.
- */
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    struct ifconf ifc;
-    struct ifreq *ifreqP;
-    char *buf;
-    int numifs;
-    unsigned i;
-    unsigned bufsize;
-    char *cp, *cplimit;
-
-    // use SIOCGSIZIFCONF to get size for  SIOCGIFCONF
-
-    ifc.ifc_buf = NULL;
-    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
-        return ifs;
-    }
-    bufsize = ifc.ifc_len;
-
-    buf = (char *)malloc(bufsize);
-    if (!buf) {
-        JNU_ThrowOutOfMemoryError(env, "Network interface native buffer allocation failed");
-        return ifs;
-    }
-    ifc.ifc_len = bufsize;
     ifc.ifc_buf = buf;
     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
         JNU_ThrowByNameWithMessageAndLastError
@@ -1288,41 +1144,48 @@
         return ifs;
     }
 
-    // Iterate through each interface
+    // iterate through each interface
     ifreqP = ifc.ifc_req;
-    cp = (char *)ifc.ifc_req;
-    cplimit = cp + ifc.ifc_len;
+    for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
+        struct sockaddr addr, broadaddr, *broadaddrP = NULL;
+        short prefix = 0;
 
-    for (; cp < cplimit;
-        cp += (sizeof(ifreqP->ifr_name) +
-               MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr))))
-    {
-        ifreqP = (struct ifreq *)cp;
-        struct ifreq if2;
-        memset((char *)&if2, 0, sizeof(if2));
-        strncpy(if2.ifr_name, ifreqP->ifr_name, sizeof(if2.ifr_name) - 1);
+        // ignore non IPv4 interfaces
+        if (ifreqP->ifr_addr.sa_family != AF_INET) {
+            continue;
+        }
 
-        // Skip interface that aren't UP
-        if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) >= 0) {
-            if (!(if2.ifr_flags & IFF_UP)) {
-                continue;
+        // save socket address
+        memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
+
+        // determine broadcast address, if applicable
+        if ((ioctl(sock, SIOCGIFFLAGS, ifreqP) == 0) &&
+            ifreqP->ifr_flags & IFF_BROADCAST) {
+
+            // restore socket address to ifreqP
+            memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
+
+            if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
+                memcpy(&broadaddr, &(ifreqP->ifr_broadaddr),
+                       sizeof(struct sockaddr));
+                broadaddrP = &broadaddr;
             }
         }
 
-        if (ifreqP->ifr_addr.sa_family != AF_INET6)
-            continue;
+        // restore socket address to ifreqP
+        memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
 
-        if (ioctl(sock, SIOCGIFSITE6, (char *)&if2) >= 0) {
-            struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifreqP->ifr_addr);
-            s6->sin6_scope_id = if2.ifr_site6;
+        // determine netmask
+        if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
+            prefix = translateIPv4AddressToPrefix(
+                         (struct sockaddr_in *)&(ifreqP->ifr_netmask));
         }
 
-        // Add to the list
+        // add interface to the list
         ifs = addif(env, sock, ifreqP->ifr_name, ifs,
-                    (struct sockaddr *)&(ifreqP->ifr_addr),
-                    NULL, NULL, AF_INET6, 0);
+                    &addr, broadaddrP, AF_INET, prefix);
 
-        // If an exception occurred then free the list
+        // in case of exception, free interface list and buffer and return NULL
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             freeif(ifs);
@@ -1330,18 +1193,60 @@
         }
     }
 
-    // Free socket and buffer
+    // free buffer
     free(buf);
     return ifs;
 }
-#endif
 
+#if defined(AF_INET6)
 
+/*
+ * Enumerates and returns all IPv6 interfaces on Linux.
+ */
+static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    FILE *f;
+    char devname[21], addr6p[8][5];
+    int prefix, scope, dad_status, if_idx;
+
+    if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
+        while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
+                      addr6p[0], addr6p[1], addr6p[2], addr6p[3],
+                      addr6p[4], addr6p[5], addr6p[6], addr6p[7],
+                      &if_idx, &prefix, &scope, &dad_status, devname) != EOF) {
+
+            char addr6[40];
+            struct sockaddr_in6 addr;
+
+            sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
+                    addr6p[0], addr6p[1], addr6p[2], addr6p[3],
+                    addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
+
+            memset(&addr, 0, sizeof(struct sockaddr_in6));
+            inet_pton(AF_INET6, addr6, (void*)addr.sin6_addr.s6_addr);
+
+            // set scope ID to interface index
+            addr.sin6_scope_id = if_idx;
+
+            // add interface to the list
+            ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr,
+                        NULL, AF_INET6, (short)prefix);
+
+            // if an exception occurred then return the list as is
+            if ((*env)->ExceptionOccurred(env)) {
+                break;
+            }
+       }
+       fclose(f);
+    }
+    return ifs;
+}
+
+#endif /* AF_INET6 */
+
+/*
+ * Try to get the interface index.
+ */
 static int getIndex(int sock, const char *name) {
-     // Try to get the interface index
-#if defined(_AIX)
-    return if_nametoindex(name);
-#else
     struct ifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
@@ -1351,61 +1256,6 @@
     }
 
     return if2.ifr_ifindex;
-#endif
-}
-
-/*
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast
-  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
-{
-    struct sockaddr *ret = NULL;
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    // Let's make sure the interface does have a broadcast address.
-    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2)  < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFFLAGS) failed");
-        return ret;
-    }
-
-    if (if2.ifr_flags & IFF_BROADCAST) {
-        // It does, let's retrieve it
-        if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
-            JNU_ThrowByNameWithMessageAndLastError
-                (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFBRDADDR) failed");
-            return ret;
-        }
-
-        ret = brdcast_store;
-        memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
-    }
-
-    return ret;
-}
-
-/*
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
-    unsigned int mask;
-    short ret;
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFNETMASK) failed");
-        return -1;
-    }
-
-    return computeMaskFromAddress(&(if2.ifr_addr));
 }
 
 /*
@@ -1414,10 +1264,272 @@
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
 static int getMacAddress
-  (JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr,
+  (JNIEnv *env, int sock, const char *ifname, const struct in_addr *addr,
    unsigned char *buf)
 {
-#if defined (_AIX)
+    static struct ifreq ifr;
+    int i;
+    memset((char *)&ifr, 0, sizeof(ifr));
+    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
+    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
+        JNU_ThrowByNameWithMessageAndLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFHWADDR) failed");
+        return -1;
+    }
+
+    memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
+
+    // all bytes to 0 means no hardware address
+    for (i = 0; i < IFHWADDRLEN; i++) {
+        if (buf[i] != 0)
+            return IFHWADDRLEN;
+    }
+
+    return -1;
+}
+
+static int getMTU(JNIEnv *env, int sock, const char *ifname) {
+    struct ifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+
+    if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
+        JNU_ThrowByNameWithMessageAndLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
+        return -1;
+    }
+
+    return if2.ifr_mtu;
+}
+
+static int getFlags(int sock, const char *ifname, int *flags) {
+    struct ifreq if2;
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+
+    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
+        return -1;
+    }
+
+    if (sizeof(if2.ifr_flags) == sizeof(short)) {
+        *flags = (if2.ifr_flags & 0xffff);
+    } else {
+        *flags = if2.ifr_flags;
+    }
+    return 0;
+}
+
+#endif /* __linux__ */
+
+/** AIX **/
+#if defined(_AIX)
+
+#if defined(AF_INET6)
+/*
+ * Opens a socket for further ioctl calls. Tries AF_INET socket first and
+ * if it fails return AF_INET6 socket.
+ */
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
+    int sock;
+
+    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+        if (errno == EPROTONOSUPPORT) {
+            if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
+                JNU_ThrowByNameWithMessageAndLastError
+                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+                return -1;
+            }
+        } else { // errno is not NOSUPPORT
+            JNU_ThrowByNameWithMessageAndLastError
+                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
+            return -1;
+        }
+    }
+
+    return sock;
+}
+#else
+static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
+    return openSocket(env, AF_INET);
+}
+#endif
+
+/*
+ * Enumerates and returns all IPv4 interfaces on AIX.
+ */
+static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    struct ifconf ifc;
+    struct ifreq *ifreqP;
+    char *buf = NULL;
+    unsigned i;
+
+    // call SIOCGSIZIFCONF to get the size of SIOCGIFCONF buffer
+    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
+        JNU_ThrowByNameWithMessageAndLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
+        return ifs;
+    }
+
+    // call CSIOCGIFCONF instead of SIOCGIFCONF where interface
+    // records will always have sizeof(struct ifreq) length.
+    // Be aware that only IPv4 data is complete this way.
+    CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
+    ifc.ifc_buf = buf;
+    if (ioctl(sock, CSIOCGIFCONF, (char *)&ifc) < 0) {
+        JNU_ThrowByNameWithMessageAndLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(CSIOCGIFCONF) failed");
+        free(buf);
+        return ifs;
+    }
+
+    // iterate through each interface
+    ifreqP = ifc.ifc_req;
+    for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
+        struct sockaddr addr, broadaddr, *broadaddrP = NULL;
+        short prefix = 0;
+
+        // ignore non IPv4 interfaces
+        if (ifreqP->ifr_addr.sa_family != AF_INET) {
+            continue;
+        }
+
+        // save socket address
+        memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
+
+        // determine broadcast address, if applicable
+        if ((ioctl(sock, SIOCGIFFLAGS, ifreqP) == 0) &&
+            ifreqP->ifr_flags & IFF_BROADCAST) {
+
+            // restore socket address to ifreqP
+            memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
+
+            if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
+                memcpy(&broadaddr, &(ifreqP->ifr_broadaddr),
+                       sizeof(struct sockaddr));
+                broadaddrP = &broadaddr;
+            }
+        }
+
+        // restore socket address to ifreqP
+        memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
+
+        // determine netmask
+        if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
+            prefix = translateIPv4AddressToPrefix(
+                         (struct sockaddr_in *)&(ifreqP->ifr_addr));
+        }
+
+        // add interface to the list
+        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
+                    &addr, broadaddrP, AF_INET, prefix);
+
+        // in case of exception, free interface list and buffer and return NULL
+        if ((*env)->ExceptionOccurred(env)) {
+            free(buf);
+            freeif(ifs);
+            return NULL;
+        }
+    }
+
+    // free buffer
+    free(buf);
+    return ifs;
+}
+
+#if defined(AF_INET6)
+
+/*
+ * Enumerates and returns all IPv6 interfaces on AIX.
+ */
+static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    struct ifconf ifc;
+    struct ifreq *ifreqP;
+    char *buf;
+
+    // call SIOCGSIZIFCONF to get size for SIOCGIFCONF buffer
+    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
+        JNU_ThrowByNameWithMessageAndLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
+        return ifs;
+    }
+
+    // call SIOCGIFCONF to enumerate the interfaces
+    CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
+    ifc.ifc_buf = buf;
+    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
+        JNU_ThrowByNameWithMessageAndLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
+        free(buf);
+        return ifs;
+    }
+
+    // iterate through each interface
+    char *cp = (char *)ifc.ifc_req;
+    char *cplimit = cp + ifc.ifc_len;
+
+    for (; cp < cplimit;
+         cp += (sizeof(ifreqP->ifr_name) +
+                MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr))))
+    {
+        ifreqP = (struct ifreq *)cp;
+        short prefix = 0;
+
+        // ignore non IPv6 interfaces
+        if (ifreqP->ifr_addr.sa_family != AF_INET6) {
+            continue;
+        }
+
+        // determine netmask
+        struct in6_ifreq if6;
+        memset((char *)&if6, 0, sizeof(if6));
+        strncpy(if6.ifr_name, ifreqP->ifr_name, sizeof(if6.ifr_name) - 1);
+        memcpy(&(if6.ifr_Addr), &(ifreqP->ifr_addr),
+               sizeof(struct sockaddr_in6));
+        if (ioctl(sock, SIOCGIFNETMASK6, (char *)&if6) >= 0) {
+            prefix = translateIPv6AddressToPrefix(&(if6.ifr_Addr));
+        }
+
+        // set scope ID to interface index
+        ((struct sockaddr_in6 *)&(ifreqP->ifr_addr))->sin6_scope_id =
+            getIndex(sock, ifreqP->ifr_name);
+
+        // add interface to the list
+        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
+                    (struct sockaddr *)&(ifreqP->ifr_addr),
+                    NULL, AF_INET6, prefix);
+
+        // if an exception occurred then free the list
+        if ((*env)->ExceptionOccurred(env)) {
+            free(buf);
+            freeif(ifs);
+            return NULL;
+        }
+    }
+
+    // free buffer
+    free(buf);
+    return ifs;
+}
+
+#endif /* AF_INET6 */
+
+/*
+ * Try to get the interface index.
+ */
+static int getIndex(int sock, const char *name) {
+    int index = if_nametoindex(name);
+    return (index == 0) ? -1 : index;
+}
+
+/*
+ * Gets the Hardware address (usually MAC address) for the named interface.
+ * On return puts the data in buf, and returns the length, in byte, of the
+ * MAC address. Returns -1 if there is no hardware address on that interface.
+ */
+static int getMacAddress
+  (JNIEnv *env, int sock, const char *ifname, const struct in_addr *addr,
+   unsigned char *buf)
+{
     int size;
     struct kinfo_ndd *nddp;
     void *end;
@@ -1457,40 +1569,12 @@
     }
 
     return -1;
-#elif defined(__linux__)
-    static struct ifreq ifr;
-    int i;
-    memset((char *)&ifr, 0, sizeof(ifr));
-    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
-    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFHWADDR) failed");
-        return -1;
-    }
-
-    memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
-
-    // All bytes to 0 means no hardware address.
-
-    for (i = 0; i < IFHWADDRLEN; i++) {
-        if (buf[i] != 0)
-            return IFHWADDRLEN;
-    }
-
-    return -1;
-#endif
 }
 
-static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
+static int getMTU(JNIEnv *env, int sock, const char *ifname) {
     struct ifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
-
-    if (ifname != NULL) {
-        strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-    } else {
-        JNU_ThrowNullPointerException(env, "network interface name is NULL");
-        return -1;
-    }
+    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
         JNU_ThrowByNameWithMessageAndLastError
@@ -1498,7 +1582,7 @@
         return -1;
     }
 
-    return  if2.ifr_mtu;
+    return if2.ifr_mtu;
 }
 
 static int getFlags(int sock, const char *ifname, int *flags) {
@@ -1518,16 +1602,16 @@
   return 0;
 }
 
-#endif  /* defined(__linux__) || defined(_AIX) */
+#endif /* _AIX */
 
 /** Solaris **/
 #if defined(__solaris__)
 
+#if defined(AF_INET6)
 /*
- * Opens a socket for further ioct calls. Tries AF_INET socket first and
- * if it falls return AF_INET6 socket.
+ * Opens a socket for further ioctl calls. Tries AF_INET socket first and
+ * if it fails return AF_INET6 socket.
  */
-#ifdef AF_INET6
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock, alreadyV6 = 0;
     struct lifreq if2;
@@ -1539,8 +1623,7 @@
                     (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
                 return -1;
             }
-
-            alreadyV6=1;
+            alreadyV6 = 1;
         } else { // errno is not NOSUPPORT
             JNU_ThrowByNameWithMessageAndLastError
                 (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
@@ -1548,14 +1631,12 @@
         }
     }
 
-
     // Solaris requires that we have an IPv6 socket to query an  interface
     // without an IPv4 address - check it here. POSIX 1 require the kernel to
     // return ENOTTY if the call is inappropriate for a device e.g. the NETMASK
     // for a device having IPv6 only address but not all devices follow the
     // standard so fall back on any error. It's not an ecologically friendly
     // gesture but more reliable.
-
     if (!alreadyV6) {
         memset((char *)&if2, 0, sizeof(if2));
         strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
@@ -1571,40 +1652,24 @@
 
     return sock;
 }
-
 #else
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env,AF_INET);
+    return openSocket(env, AF_INET);
 }
 #endif
 
 /*
- * Enumerates and returns all IPv4 interfaces.
+ * Enumerates and returns all IPv4 interfaces on Solaris.
  */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    return enumIPvXInterfaces(env,sock, ifs, AF_INET);
-}
+    struct lifconf ifc;
+    struct lifreq *ifreqP;
+    struct lifnum numifs;
+    char *buf = NULL;
+    unsigned i;
 
-#ifdef AF_INET6
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    return enumIPvXInterfaces(env,sock, ifs, AF_INET6);
-}
-#endif
-
-/*
- * Enumerates and returns all interfaces on Solaris.
- * Uses the same code for IPv4 and IPv6.
- */
-static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family) {
-    struct lifconf ifc;
-    struct lifreq *ifr;
-    int n;
-    char *buf;
-    struct lifnum numifs;
-    unsigned bufsize;
-
-    // Get the interface count
-    numifs.lifn_family = family;
+    // call SIOCGLIFNUM to get the size of SIOCGIFCONF buffer
+    numifs.lifn_family = AF_INET;
     numifs.lifn_flags = 0;
     if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
         JNU_ThrowByNameWithMessageAndLastError
@@ -1612,14 +1677,12 @@
         return ifs;
     }
 
-    //  Enumerate the interface configurations
-    bufsize = numifs.lifn_count * sizeof (struct lifreq);
-    CHECKED_MALLOC3(buf, char *, bufsize);
-
-    ifc.lifc_family = family;
+    // call SIOCGLIFCONF to enumerate the interfaces
+    ifc.lifc_len = numifs.lifn_count * sizeof(struct lifreq);
+    CHECKED_MALLOC3(buf, char *, ifc.lifc_len);
+    ifc.lifc_buf = buf;
+    ifc.lifc_family = AF_INET;
     ifc.lifc_flags = 0;
-    ifc.lifc_len = bufsize;
-    ifc.lifc_buf = buf;
     if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
         JNU_ThrowByNameWithMessageAndLastError
             (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFCONF) failed");
@@ -1627,43 +1690,119 @@
         return ifs;
     }
 
-    // Iterate through each interface
-    ifr = ifc.lifc_req;
-    for (n=0; n<numifs.lifn_count; n++, ifr++) {
-        int index = -1;
-        struct lifreq if2;
+    // iterate through each interface
+    ifreqP = ifc.lifc_req;
+    for (i = 0; i < numifs.lifn_count; i++, ifreqP++) {
+        struct sockaddr addr, *broadaddrP = NULL;
 
-        // Ignore either IPv4 or IPv6 addresses
-        if (ifr->lifr_addr.ss_family != family) {
+        // ignore non IPv4 interfaces
+        if (ifreqP->lifr_addr.ss_family != AF_INET) {
             continue;
         }
 
-#ifdef AF_INET6
-        if (ifr->lifr_addr.ss_family == AF_INET6) {
-            struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifr->lifr_addr);
-            s6->sin6_scope_id = getIndex(sock, ifr->lifr_name);
+        // save socket address
+        memcpy(&addr, &(ifreqP->lifr_addr), sizeof(struct sockaddr));
+
+        // determine broadcast address, if applicable
+        if ((ioctl(sock, SIOCGLIFFLAGS, ifreqP) == 0) &&
+            ifreqP->lifr_flags & IFF_BROADCAST) {
+
+            // restore socket address to ifreqP
+            memcpy(&(ifreqP->lifr_addr), &addr, sizeof(struct sockaddr));
+
+            // query broadcast address and set pointer to it
+            if (ioctl(sock, SIOCGLIFBRDADDR, ifreqP) == 0) {
+                broadaddrP = (struct sockaddr *)&(ifreqP->lifr_broadaddr);
+            }
         }
-#endif
 
         // add to the list
-        ifs = addif(env, sock,ifr->lifr_name, ifs,
-                    (struct sockaddr *)&(ifr->lifr_addr),
-                    NULL, NULL, family, (short)ifr->lifr_addrlen);
+        ifs = addif(env, sock, ifreqP->lifr_name, ifs,
+                    &addr, broadaddrP, AF_INET, (short)ifreqP->lifr_addrlen);
 
-        // If an exception occurred we return immediately
+        // if an exception occurred we return immediately
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             return ifs;
         }
-
    }
 
+    // free buffer
     free(buf);
     return ifs;
 }
 
+#if defined(AF_INET6)
+
+/*
+ * Enumerates and returns all IPv6 interfaces on Solaris.
+ */
+static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    struct lifconf ifc;
+    struct lifreq *ifreqP;
+    struct lifnum numifs;
+    char *buf = NULL;
+    unsigned i;
+
+    // call SIOCGLIFNUM to get the size of SIOCGLIFCONF buffer
+    numifs.lifn_family = AF_INET6;
+    numifs.lifn_flags = 0;
+    if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
+        JNU_ThrowByNameWithMessageAndLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFNUM) failed");
+        return ifs;
+    }
+
+    // call SIOCGLIFCONF to enumerate the interfaces
+    ifc.lifc_len = numifs.lifn_count * sizeof(struct lifreq);
+    CHECKED_MALLOC3(buf, char *, ifc.lifc_len);
+    ifc.lifc_buf = buf;
+    ifc.lifc_family = AF_INET6;
+    ifc.lifc_flags = 0;
+    if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
+        JNU_ThrowByNameWithMessageAndLastError
+            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFCONF) failed");
+        free(buf);
+        return ifs;
+    }
+
+    // iterate through each interface
+    ifreqP = ifc.lifc_req;
+    for (i = 0; i < numifs.lifn_count; i++, ifreqP++) {
+
+        // ignore non IPv6 interfaces
+        if (ifreqP->lifr_addr.ss_family != AF_INET6) {
+            continue;
+        }
+
+        // set scope ID to interface index
+        ((struct sockaddr_in6 *)&(ifreqP->lifr_addr))->sin6_scope_id =
+            getIndex(sock, ifreqP->lifr_name);
+
+        // add to the list
+        ifs = addif(env, sock, ifreqP->lifr_name, ifs,
+                    (struct sockaddr *)&(ifreqP->lifr_addr),
+                    NULL, AF_INET6, (short)ifreqP->lifr_addrlen);
+
+        // if an exception occurred we return immediately
+        if ((*env)->ExceptionOccurred(env)) {
+            free(buf);
+            return ifs;
+        }
+   }
+
+    // free buffer
+    free(buf);
+    return ifs;
+}
+
+#endif /* AF_INET6 */
+
+/*
+ * Try to get the interface index.
+ * (Not supported on Solaris 2.6 or 7)
+ */
 static int getIndex(int sock, const char *name) {
-    // Try to get the interface index.  (Not supported on Solaris 2.6 or 7)
     struct lifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.lifr_name, name, sizeof(if2.lifr_name) - 1);
@@ -1676,69 +1815,12 @@
 }
 
 /*
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast
-  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
-{
-    struct sockaddr *ret = NULL;
-    struct lifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
-
-    // Let's make sure the interface does have a broadcast address
-    if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2)  < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFFLAGS) failed");
-        return ret;
-    }
-
-    if (if2.lifr_flags & IFF_BROADCAST) {
-        // It does, let's retrieve it
-        if (ioctl(sock, SIOCGLIFBRDADDR, (char *)&if2) < 0) {
-            JNU_ThrowByNameWithMessageAndLastError
-                (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFBRDADDR) failed");
-            return ret;
-        }
-
-        ret = brdcast_store;
-        memcpy(ret, &if2.lifr_broadaddr, sizeof(struct sockaddr));
-    }
-
-    return ret;
-}
-
-/*
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
-    unsigned int mask;
-    short ret;
-    struct lifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
-
-    if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFNETMASK) failed");
-        return -1;
-    }
-
-    return computeMaskFromAddress(&(if2.lifr_addr));
-}
-
-
-#define DEV_PREFIX  "/dev/"
-
-/*
  * Solaris specific DLPI code to get hardware address from a device.
  * Unfortunately, at least up to Solaris X, you have to have special
  * privileges (i.e. be root).
  */
 static int getMacFromDevice
-  (JNIEnv *env, const char* ifname, unsigned char* retbuf)
+  (JNIEnv *env, const char *ifname, unsigned char *retbuf)
 {
     char style1dev[MAXPATHLEN];
     int fd;
@@ -1796,23 +1878,20 @@
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
 static int getMacAddress
-  (JNIEnv *env, int sock, const char *ifname, const struct in_addr* addr,
+  (JNIEnv *env, int sock, const char *ifname, const struct in_addr *addr,
    unsigned char *buf)
 {
-    struct arpreq arpreq;
-    struct sockaddr_in* sin;
-    struct sockaddr_in ipAddr;
+    struct lifreq if2;
     int len, i;
-    struct lifreq lif;
 
     // First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
     // try the old way.
-    memset(&lif, 0, sizeof(lif));
-    strlcpy(lif.lifr_name, ifname, sizeof(lif.lifr_name));
+    memset((char *)&if2, 0, sizeof(if2));
+    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
 
-    if (ioctl(sock, SIOCGLIFHWADDR, &lif) != -1) {
+    if (ioctl(sock, SIOCGLIFHWADDR, &if2) != -1) {
         struct sockaddr_dl *sp;
-        sp = (struct sockaddr_dl *)&lif.lifr_addr;
+        sp = (struct sockaddr_dl *)&if2.lifr_addr;
         memcpy(buf, &sp->sdl_data[0], sp->sdl_alen);
         return sp->sdl_alen;
     }
@@ -1823,6 +1902,10 @@
     if ((len = getMacFromDevice(env, ifname, buf))  == 0) {
         // DLPI failed - trying to do arp lookup
 
+        struct arpreq arpreq;
+        struct sockaddr_in *sin;
+        struct sockaddr_in ipAddr;
+
         if (addr == NULL) {
              // No IPv4 address for that interface, so can't do an ARP lookup.
              return -1;
@@ -1830,8 +1913,8 @@
 
          len = 6; //???
 
-         sin = (struct sockaddr_in *) &arpreq.arp_pa;
-         memset((char *) &arpreq, 0, sizeof(struct arpreq));
+         sin = (struct sockaddr_in *)&arpreq.arp_pa;
+         memset((char *)&arpreq, 0, sizeof(struct arpreq));
          ipAddr.sin_port = 0;
          ipAddr.sin_family = AF_INET;
          memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
@@ -1842,19 +1925,19 @@
              return -1;
          }
 
-         memcpy(buf, &arpreq.arp_ha.sa_data[0], len );
+         memcpy(buf, &arpreq.arp_ha.sa_data[0], len);
     }
 
-    // All bytes to 0 means no hardware address.
+    // all bytes to 0 means no hardware address
     for (i = 0; i < len; i++) {
-      if (buf[i] != 0)
-         return len;
+        if (buf[i] != 0)
+            return len;
     }
 
     return -1;
 }
 
-static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
+static int getMTU(JNIEnv *env, int sock, const char *ifname) {
     struct lifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
@@ -1881,47 +1964,43 @@
     return 0;
 }
 
-
-#endif  /* __solaris__ */
-
+#endif /* __solaris__ */
 
 /** BSD **/
-#ifdef _ALLBSD_SOURCE
+#if defined(_ALLBSD_SOURCE)
 
+#if defined(AF_INET6)
 /*
- * Opens a socket for further ioct calls. Tries AF_INET socket first and
- * if it falls return AF_INET6 socket.
+ * Opens a socket for further ioctl calls. Tries AF_INET socket first and
+ * if it fails return AF_INET6 socket.
  */
-#ifdef AF_INET6
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
     int sock;
-    struct ifreq if2;
 
-     if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-         if (errno == EPROTONOSUPPORT) {
-              if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                 JNU_ThrowByNameWithMessageAndLastError
-                     (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                 return -1;
-              }
-         } else { // errno is not NOSUPPORT
-             JNU_ThrowByNameWithMessageAndLastError
-                 (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
-             return -1;
-         }
-   }
+    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+        if (errno == EPROTONOSUPPORT) {
+            if ((sock = socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
+                JNU_ThrowByNameWithMessageAndLastError
+                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+                return -1;
+            }
+        } else { // errno is not NOSUPPORT
+            JNU_ThrowByNameWithMessageAndLastError
+                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
+            return -1;
+        }
+    }
 
-   return sock;
+    return sock;
 }
-
 #else
 static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env,AF_INET);
+    return openSocket(env, AF_INET);
 }
 #endif
 
 /*
- * Enumerates and returns all IPv4 interfaces.
+ * Enumerates and returns all IPv4 interfaces on BSD.
  */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifaddrs *ifa, *origifa;
@@ -1933,23 +2012,25 @@
     }
 
     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
-        struct sockaddr* ifa_broadaddr = NULL;
+        struct sockaddr *broadaddrP = NULL;
 
-        // Skip non-AF_INET entries.
+        // ignore non IPv4 interfaces
         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
             continue;
 
         // set ifa_broadaddr, if there is one
         if ((ifa->ifa_flags & IFF_POINTOPOINT) == 0 &&
             ifa->ifa_flags & IFF_BROADCAST) {
-            ifa_broadaddr = ifa->ifa_broadaddr;
+            broadaddrP = ifa->ifa_dstaddr;
         }
 
-        // Add to the list.
+        // add interface to the list
         ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr,
-                    ifa_broadaddr, ifa->ifa_netmask, AF_INET, 0);
+                    broadaddrP, AF_INET,
+                    translateIPv4AddressToPrefix((struct sockaddr_in *)
+                                                 ifa->ifa_netmask));
 
-        // If an exception occurred then free the list.
+        // if an exception occurred then free the list
         if ((*env)->ExceptionOccurred(env)) {
             freeifaddrs(origifa);
             freeif(ifs);
@@ -1957,44 +2038,18 @@
         }
     }
 
-    // Free socket and buffer
+    // free ifaddrs buffer
     freeifaddrs(origifa);
     return ifs;
 }
 
-#ifdef AF_INET6
-/*
- * Determines the prefix on BSD for IPv6 interfaces.
- */
-static int prefix(void *val, int size) {
-    u_char *name = (u_char *)val;
-    int byte, bit, prefix = 0;
-
-    for (byte = 0; byte < size; byte++, prefix += 8)
-        if (name[byte] != 0xff)
-            break;
-    if (byte == size)
-        return prefix;
-    for (bit = 7; bit != 0; bit--, prefix++)
-        if (!(name[byte] & (1 << bit)))
-            break;
-    for (; bit != 0; bit--)
-        if (name[byte] & (1 << bit))
-            return (0);
-    byte++;
-    for (; byte < size; byte++)
-        if (name[byte])
-            return (0);
-    return prefix;
-}
+#if defined(AF_INET6)
 
 /*
  * Enumerates and returns all IPv6 interfaces on BSD.
  */
 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifaddrs *ifa, *origifa;
-    struct sockaddr_in6 *sin6;
-    struct in6_ifreq ifr6;
 
     if (getifaddrs(&origifa) != 0) {
         JNU_ThrowByNameWithMessageAndLastError
@@ -2003,31 +2058,21 @@
     }
 
     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
-
-        // Skip non-AF_INET6 entries.
+        // ignore non IPv6 interfaces
         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET6)
             continue;
 
-        memset(&ifr6, 0, sizeof(ifr6));
-        strlcpy(ifr6.ifr_name, ifa->ifa_name, sizeof(ifr6.ifr_name));
-        memcpy(&ifr6.ifr_addr, ifa->ifa_addr,
-               MIN(sizeof(ifr6.ifr_addr), ifa->ifa_addr->sa_len));
+        // set scope ID to interface index
+        ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id =
+            getIndex(sock, ifa->ifa_name);
 
-        if (ioctl(sock, SIOCGIFNETMASK_IN6, (caddr_t)&ifr6) < 0) {
-            JNU_ThrowByNameWithMessageAndLastError
-                (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFNETMASK_IN6) failed");
-            freeifaddrs(origifa);
-            freeif(ifs);
-            return NULL;
-        }
+        // add interface to the list
+        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, NULL,
+                    AF_INET6,
+                    translateIPv6AddressToPrefix((struct sockaddr_in6 *)
+                                                 ifa->ifa_netmask));
 
-        // Add to the list.
-        sin6 = (struct sockaddr_in6 *)&ifr6.ifr_addr;
-        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, NULL, NULL,
-                    AF_INET6,
-                    (short)prefix(&sin6->sin6_addr, sizeof(struct in6_addr)));
-
-        // If an exception occurred then free the list.
+        // if an exception occurred then free the list
         if ((*env)->ExceptionOccurred(env)) {
             freeifaddrs(origifa);
             freeif(ifs);
@@ -2035,16 +2080,21 @@
         }
     }
 
-    // Free socket and ifaddrs buffer
+    // free ifaddrs buffer
     freeifaddrs(origifa);
     return ifs;
 }
-#endif
 
+#endif /* AF_INET6 */
+
+/*
+ * Try to get the interface index.
+ */
 static int getIndex(int sock, const char *name) {
-#ifdef __FreeBSD__
-    // Try to get the interface index
-    // (Not supported on Solaris 2.6 or 7)
+#if !defined(__FreeBSD__)
+    int index = if_nametoindex(name);
+    return (index == 0) ? -1 : index;
+#else
     struct ifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
@@ -2054,74 +2104,16 @@
     }
 
     return if2.ifr_index;
-#else
-    // Try to get the interface index using BSD specific if_nametoindex
-    int index = if_nametoindex(name);
-    return (index == 0) ? -1 : index;
 #endif
 }
 
 /*
- * Returns the IPv4 broadcast address of a named interface, if it exists.
- * Returns 0 if it doesn't have one.
- */
-static struct sockaddr *getBroadcast
-  (JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store)
-{
-    struct sockaddr *ret = NULL;
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    // Make sure the interface does have a broadcast address
-    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFFLAGS) failed");
-        return ret;
-    }
-
-    if (if2.ifr_flags & IFF_BROADCAST) {
-        // It does, let's retrieve it
-        if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
-            JNU_ThrowByNameWithMessageAndLastError
-                (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFBRDADDR) failed");
-            return ret;
-        }
-
-        ret = brdcast_store;
-        memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
-    }
-
-    return ret;
-}
-
-/*
- * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
- * interface, if it has one, otherwise return -1.
- */
-static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
-    unsigned int mask;
-    short ret;
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
-        JNU_ThrowByNameWithMessageAndLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFNETMASK) failed");
-        return -1;
-    }
-
-    return computeMaskFromAddress(&(if2.ifr_addr));
-}
-
-/*
  * Gets the Hardware address (usually MAC address) for the named interface.
- * return puts the data in buf, and returns the length, in byte, of the
+ * On return puts the data in buf, and returns the length, in byte, of the
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
 static int getMacAddress
-  (JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr,
+  (JNIEnv *env, int sock, const char *ifname, const struct in_addr *addr,
    unsigned char *buf)
 {
     struct ifaddrs *ifa0, *ifa;
@@ -2150,7 +2142,7 @@
     return -1;
 }
 
-static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
+static int getMTU(JNIEnv *env, int sock, const char *ifname) {
     struct ifreq if2;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
@@ -2161,12 +2153,11 @@
         return -1;
     }
 
-    return  if2.ifr_mtu;
+    return if2.ifr_mtu;
 }
 
 static int getFlags(int sock, const char *ifname, int *flags) {
     struct ifreq if2;
-    int ret = -1;
     memset((char *)&if2, 0, sizeof(if2));
     strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
 
@@ -2181,4 +2172,4 @@
     }
     return 0;
 }
-#endif /* __ALLBSD_SOURCE__ */
+#endif /* _ALLBSD_SOURCE */
--- a/src/java.base/windows/classes/java/lang/ClassLoaderHelper.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/windows/classes/java/lang/ClassLoaderHelper.java	Tue Jul 26 14:45:11 2016 -0700
@@ -22,6 +22,7 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
+
 package java.lang;
 
 import java.io.File;
--- a/src/java.base/windows/classes/sun/nio/ch/PipeImpl.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/windows/classes/sun/nio/ch/PipeImpl.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -37,6 +37,7 @@
 import java.security.AccessController;
 import java.security.PrivilegedExceptionAction;
 import java.security.PrivilegedActionException;
+import java.security.SecureRandom;
 import java.util.Random;
 
 
@@ -47,24 +48,16 @@
 class PipeImpl
     extends Pipe
 {
+    // Number of bytes in the secret handshake.
+    private static final int NUM_SECRET_BYTES = 16;
+
+    // Random object for handshake values
+    private static final Random RANDOM_NUMBER_GENERATOR = new SecureRandom();
 
     // Source and sink channels
     private SourceChannel source;
     private SinkChannel sink;
 
-    // Random object for handshake values
-    private static final Random rnd;
-
-    static {
-        byte[] someBytes = new byte[8];
-        boolean resultOK = IOUtil.randomBytes(someBytes);
-        if (resultOK) {
-            rnd = new Random(ByteBuffer.wrap(someBytes).getLong());
-        } else {
-            rnd = new Random();
-        }
-    }
-
     private class Initializer
         implements PrivilegedExceptionAction<Void>
     {
@@ -112,6 +105,10 @@
                 SocketChannel sc2 = null;
 
                 try {
+                    // Create secret with a backing array.
+                    ByteBuffer secret = ByteBuffer.allocate(NUM_SECRET_BYTES);
+                    ByteBuffer bb = ByteBuffer.allocate(NUM_SECRET_BYTES);
+
                     // Loopback address
                     InetAddress lb = InetAddress.getByName("127.0.0.1");
                     assert(lb.isLoopbackAddress());
@@ -128,18 +125,22 @@
                         // Establish connection (assume connections are eagerly
                         // accepted)
                         sc1 = SocketChannel.open(sa);
-                        ByteBuffer bb = ByteBuffer.allocate(8);
-                        long secret = rnd.nextLong();
-                        bb.putLong(secret).flip();
-                        sc1.write(bb);
+                        RANDOM_NUMBER_GENERATOR.nextBytes(secret.array());
+                        do {
+                            sc1.write(secret);
+                        } while (secret.hasRemaining());
+                        secret.rewind();
 
                         // Get a connection and verify it is legitimate
                         sc2 = ssc.accept();
-                        bb.clear();
-                        sc2.read(bb);
+                        do {
+                            sc2.read(bb);
+                        } while (bb.hasRemaining());
                         bb.rewind();
-                        if (bb.getLong() == secret)
+
+                        if (bb.equals(secret))
                             break;
+
                         sc2.close();
                         sc1.close();
                     }
--- a/src/java.base/windows/native/libjava/jni_util_md.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/windows/native/libjava/jni_util_md.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/java.base/windows/native/libjli/java_md.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.base/windows/native/libjli/java_md.c	Tue Jul 26 14:45:11 2016 -0700
@@ -1006,10 +1006,11 @@
     // make a copy of the args which will be expanded in java if required.
     nargv = (char **)JLI_MemAlloc(argc * sizeof(char*));
     for (i = 0; i < argc; i++) {
+        jboolean arg_expand;
         j = appArgIdx[i];
-        jboolean arg_expand = (JLI_StrCmp(stdargs[j].arg, strv[i]) == 0)
-                                ? stdargs[j].has_wildcard
-                                : JNI_FALSE;
+        arg_expand = (JLI_StrCmp(stdargs[j].arg, strv[i]) == 0)
+            ? stdargs[j].has_wildcard
+            : JNI_FALSE;
         if (needs_expansion == JNI_FALSE)
             needs_expansion = arg_expand;
 
--- a/src/java.desktop/windows/native/libawt/windows/awt_Font.cpp	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.desktop/windows/native/libawt/windows/awt_Font.cpp	Tue Jul 26 14:45:11 2016 -0700
@@ -256,7 +256,7 @@
 
     AwtFont* awtFont = NULL;
     jobjectArray compFont = NULL;
-    int cfnum;
+    int cfnum = 0;
 
     try {
         if (env->EnsureLocalCapacity(3) < 0)
@@ -264,7 +264,9 @@
 
         if (IsMultiFont(env, font)) {
             compFont = GetComponentFonts(env, font);
-            cfnum = env->GetArrayLength(compFont);
+            if (compFont != NULL) {
+                cfnum = env->GetArrayLength(compFont);
+            }
         } else {
             compFont = NULL;
             cfnum = 0;
@@ -647,7 +649,9 @@
 
     if (IsMultiFont(env, font)) {
         array = GetComponentFonts(env, font);
-        num = env->GetArrayLength(array);
+        if (array != NULL) {
+            num = env->GetArrayLength(array);
+        }
     } else {
         array = NULL;
         num = 0;
@@ -705,14 +709,16 @@
 
     if (IsMultiFont(env, font)) {
         jobject peer = env->CallObjectMethod(font, AwtFont::peerMID);
-        array =  (jobjectArray)(env->CallObjectMethod(
-        peer, AwtFont::makeConvertedMultiFontStringMID, str));
-        DASSERT(!safe_ExceptionOccurred(env));
+        if (peer != NULL) {
+            array = (jobjectArray)(env->CallObjectMethod(
+            peer, AwtFont::makeConvertedMultiFontStringMID, str));
+            DASSERT(!safe_ExceptionOccurred(env));
 
-        if (array != NULL) {
-            arrayLength = env->GetArrayLength(array);
+            if (array != NULL) {
+                arrayLength = env->GetArrayLength(array);
+            }
+            env->DeleteLocalRef(peer);
         }
-        env->DeleteLocalRef(peer);
     } else {
         array = NULL;
         arrayLength = 0;
--- a/src/java.desktop/windows/native/libawt/windows/awt_Font.h	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.desktop/windows/native/libawt/windows/awt_Font.h	Tue Jul 26 14:45:11 2016 -0700
@@ -230,11 +230,14 @@
     INLINE static jobjectArray GetComponentFonts(JNIEnv *env,
                                                      jobject font) {
       jobject platformFont = env->CallObjectMethod(font, AwtFont::peerMID);
-      jobjectArray result =
-          (jobjectArray)(env->GetObjectField(platformFont,
-                                             AwtFont::componentFontsID));
-      env->DeleteLocalRef(platformFont);
-      return result;
+      if (platformFont != NULL) {
+          jobjectArray result =
+              (jobjectArray)(env->GetObjectField(platformFont,
+                                                 AwtFont::componentFontsID));
+          env->DeleteLocalRef(platformFont);
+          return result;
+      }
+      return NULL;
     }
 
    /*
--- a/src/java.httpclient/share/classes/java/net/http/Stream.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.httpclient/share/classes/java/net/http/Stream.java	Tue Jul 26 14:45:11 2016 -0700
@@ -467,7 +467,7 @@
 
         public synchronized void take(int amount) throws InterruptedException {
             assert permits >= 0;
-            while (permits < amount) {
+            while (amount > 0) {
                 int n = Math.min(amount, permits);
                 permits -= n;
                 amount -= n;
@@ -499,7 +499,7 @@
 
     DataFrame getDataFrame() throws IOException, InterruptedException {
         userRequestFlowController.take();
-        int maxpayloadLen = connection.getMaxSendFrameSize() - 9;
+        int maxpayloadLen = connection.getMaxSendFrameSize();
         ByteBuffer buffer = connection.getBuffer();
         buffer.limit(maxpayloadLen);
         boolean complete = requestProcessor.onRequestBodyChunk(buffer);
--- a/src/java.httpclient/share/classes/java/net/http/WSSharedPool.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.httpclient/share/classes/java/net/http/WSSharedPool.java	Tue Jul 26 14:45:11 2016 -0700
@@ -3,18 +3,18 @@
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General  License version 2 only, as
+ * under the terms of the GNU General Public License version 2 only, as
  * published by the Free Software Foundation.  Oracle designates this
  * particular file as subject to the "Classpath" exception as provided
  * by Oracle in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General  License
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
- * You should have received a copy of the GNU General  License version
+ * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
--- a/src/java.instrument/share/classes/java/lang/instrument/ClassFileTransformer.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.instrument/share/classes/java/lang/instrument/ClassFileTransformer.java	Tue Jul 26 14:45:11 2016 -0700
@@ -38,7 +38,7 @@
  * A transformer of class files. An agent registers an implementation of this
  * interface using the {@link Instrumentation#addTransformer addTransformer}
  * method so that the transformer's {@link
- * ClassFileTransformer#transform(Module,String,Class,ProtectionDomain,byte[])
+ * ClassFileTransformer#transform(Module,ClassLoader,String,Class,ProtectionDomain,byte[])
  * transform} method is invoked when classes are loaded,
  * {@link Instrumentation#redefineClasses redefined}, or
  * {@link Instrumentation#retransformClasses retransformed}. The implementation
@@ -170,13 +170,13 @@
     /**
      * Transforms the given class file and returns a new replacement class file.
      * This method is invoked when the {@link Module Module} bearing {@link
-     * ClassFileTransformer#transform(Module,String,Class,ProtectionDomain,byte[])
+     * ClassFileTransformer#transform(Module,ClassLoader,String,Class,ProtectionDomain,byte[])
      * transform} is not overridden.
      *
      * @implSpec The default implementation returns null.
      *
      * @param loader                the defining loader of the class to be transformed,
-     *                              may be <code>null</code> if the bootstrap loader
+     *                              may be {@code null} if the bootstrap loader
      * @param className             the name of the class in the internal form of fully
      *                              qualified class and interface names as defined in
      *                              <i>The Java Virtual Machine Specification</i>.
@@ -208,9 +208,11 @@
      *
      * @implSpec The default implementation of this method invokes the
      * {@link #transform(ClassLoader,String,Class,ProtectionDomain,byte[]) transform}
-     * method with the {@link Module#getClassLoader() ClassLoader} for the module.
+     * method.
      *
      * @param module                the module of the class to be transformed
+     * @param loader                the defining loader of the class to be transformed,
+     *                              may be {@code null} if the bootstrap loader
      * @param className             the name of the class in the internal form of fully
      *                              qualified class and interface names as defined in
      *                              <i>The Java Virtual Machine Specification</i>.
@@ -230,15 +232,13 @@
      */
     default byte[]
     transform(  Module              module,
+                ClassLoader         loader,
                 String              className,
                 Class<?>            classBeingRedefined,
                 ProtectionDomain    protectionDomain,
                 byte[]              classfileBuffer)
         throws IllegalClassFormatException {
 
-        PrivilegedAction<ClassLoader> pa = module::getClassLoader;
-        ClassLoader loader = AccessController.doPrivileged(pa);
-
         // invoke the legacy transform method
         return transform(loader,
                          className,
--- a/src/java.instrument/share/classes/java/lang/instrument/Instrumentation.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.instrument/share/classes/java/lang/instrument/Instrumentation.java	Tue Jul 26 14:45:11 2016 -0700
@@ -162,7 +162,7 @@
      *    </li>
      *    <li>for each transformer that was added with <code>canRetransform</code>
      *      false, the bytes returned by
-     *      {@link ClassFileTransformer#transform(Module,String,Class,ProtectionDomain,byte[])
+     *      {@link ClassFileTransformer#transform(Module,ClassLoader,String,Class,ProtectionDomain,byte[])
      *      transform} during the last class load or redefine are
      *      reused as the output of the transformation; note that this is
      *      equivalent to reapplying the previous transformation, unaltered;
@@ -170,7 +170,7 @@
      *    </li>
      *    <li>for each transformer that was added with <code>canRetransform</code>
      *      true, the
-     *      {@link ClassFileTransformer#transform(Module,String,Class,ProtectionDomain,byte[])
+     *      {@link ClassFileTransformer#transform(Module,ClassLoader,String,Class,ProtectionDomain,byte[])
      *      transform} method is called in these transformers
      *    </li>
      *    <li>the transformed class file bytes are installed as the new
--- a/src/java.instrument/share/classes/sun/instrument/InstrumentationImpl.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.instrument/share/classes/sun/instrument/InstrumentationImpl.java	Tue Jul 26 14:45:11 2016 -0700
@@ -420,8 +420,8 @@
 
     // WARNING: the native code knows the name & signature of this method
     private byte[]
-    transform(  ClassLoader         loader,
-                Module              module,
+    transform(  Module              module,
+                ClassLoader         loader,
                 String              classname,
                 Class<?>            classBeingRedefined,
                 ProtectionDomain    protectionDomain,
@@ -444,6 +444,7 @@
             return null; // no manager, no transform
         } else {
             return mgr.transform(   module,
+                                    loader,
                                     classname,
                                     classBeingRedefined,
                                     protectionDomain,
--- a/src/java.instrument/share/classes/sun/instrument/TransformerManager.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.instrument/share/classes/sun/instrument/TransformerManager.java	Tue Jul 26 14:45:11 2016 -0700
@@ -169,6 +169,7 @@
 
     public byte[]
     transform(  Module              module,
+                ClassLoader         loader,
                 String              classname,
                 Class<?>            classBeingRedefined,
                 ProtectionDomain    protectionDomain,
@@ -187,6 +188,7 @@
 
             try {
                 transformedBytes = transformer.transform(   module,
+                                                            loader,
                                                             classname,
                                                             classBeingRedefined,
                                                             protectionDomain,
--- a/src/java.instrument/share/native/libinstrument/JPLISAgent.c	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.instrument/share/native/libinstrument/JPLISAgent.c	Tue Jul 26 14:45:11 2016 -0700
@@ -771,12 +771,11 @@
 }
 
 static jobject
-getModuleObject(JNIEnv *                jnienv,
+getModuleObject(jvmtiEnv*               jvmti,
                 jobject                 loaderObject,
                 const char*             cname) {
-    jboolean errorOutstanding = JNI_FALSE;
+    jvmtiError err = JVMTI_ERROR_NONE;
     jobject moduleObject = NULL;
-    jstring package = NULL;
 
     /* find last slash in the class name */
     char* last_slash = (cname == NULL) ? NULL : strrchr(cname, '/');
@@ -789,14 +788,9 @@
     }
     pkg_name_buf[len] = '\0';
 
-    package = (*jnienv)->NewStringUTF(jnienv, pkg_name_buf);
-    jplis_assert_msg(package != NULL, "OOM error in NewStringUTF");
+    err = (*jvmti)->GetNamedModule(jvmti, loaderObject, pkg_name_buf, &moduleObject);
+    jplis_assert_msg(err == JVMTI_ERROR_NONE, "error in the JVMTI GetNamedModule");
 
-    moduleObject = JVM_GetModuleByPackageName(jnienv, loaderObject, package);
-
-    errorOutstanding = checkForAndClearThrowable(jnienv);
-    jplis_assert_msg(!errorOutstanding,
-                     "error in lookup of a module of the class being instrumented");
     free((void*)pkg_name_buf);
     return moduleObject;
 }
@@ -862,7 +856,7 @@
             jobject moduleObject = NULL;
 
             if (classBeingRedefined == NULL) {
-                moduleObject = getModuleObject(jnienv, loaderObject, name);
+                moduleObject = getModuleObject(jvmti(agent), loaderObject, name);
             } else {
                 // Redefine or retransform, InstrumentationImpl.transform() will use
                 // classBeingRedefined.getModule() to get the module.
@@ -873,8 +867,8 @@
                                                 jnienv,
                                                 agent->mInstrumentationImpl,
                                                 agent->mTransform,
+                                                moduleObject,
                                                 loaderObject,
-                                                moduleObject,
                                                 classNameStringObject,
                                                 classBeingRedefined,
                                                 protectionDomain,
--- a/src/java.instrument/share/native/libinstrument/JPLISAgent.h	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.instrument/share/native/libinstrument/JPLISAgent.h	Tue Jul 26 14:45:11 2016 -0700
@@ -66,7 +66,7 @@
 #define JPLIS_INSTRUMENTIMPL_AGENTMAININVOKER_METHODSIGNATURE "(Ljava/lang/String;Ljava/lang/String;)V"
 #define JPLIS_INSTRUMENTIMPL_TRANSFORM_METHODNAME           "transform"
 #define JPLIS_INSTRUMENTIMPL_TRANSFORM_METHODSIGNATURE      \
-    "(Ljava/lang/ClassLoader;Ljava/lang/reflect/Module;Ljava/lang/String;Ljava/lang/Class;Ljava/security/ProtectionDomain;[BZ)[B"
+    "(Ljava/lang/reflect/Module;Ljava/lang/ClassLoader;Ljava/lang/String;Ljava/lang/Class;Ljava/security/ProtectionDomain;[BZ)[B"
 
 
 /*
--- a/src/java.management/share/classes/com/sun/jmx/remote/security/JMXSubjectDomainCombiner.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.management/share/classes/com/sun/jmx/remote/security/JMXSubjectDomainCombiner.java	Tue Jul 26 14:45:11 2016 -0700
@@ -81,7 +81,7 @@
      * A ProtectionDomain with a null CodeSource and an empty permission set.
      */
     private static final ProtectionDomain pdNoPerms =
-        new ProtectionDomain(nullCodeSource, new Permissions());
+        new ProtectionDomain(nullCodeSource, new Permissions(), null, null);
 
     /**
      * Get the current AccessControlContext combined with the supplied subject.
--- a/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
--- a/src/java.management/share/classes/javax/management/ConstructorParameters.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/java.management/share/classes/javax/management/ConstructorParameters.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2015 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/jdk.crypto.ec/share/classes/sun/security/ec/ECDSASignature.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.crypto.ec/share/classes/sun/security/ec/ECDSASignature.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 
 package sun.security.ec;
 
+import java.io.IOException;
 import java.nio.ByteBuffer;
 import java.math.BigInteger;
 
@@ -461,6 +462,11 @@
             DerValue[] values = in.getSequence(2);
             BigInteger r = values[0].getPositiveBigInteger();
             BigInteger s = values[1].getPositiveBigInteger();
+
+            // Check for trailing signature data
+            if (in.available() != 0) {
+                throw new IOException("Incorrect signature length");
+            }
             // trim leading zeroes
             byte[] rBytes = trimZeroes(r.toByteArray());
             byte[] sBytes = trimZeroes(s.toByteArray());
--- a/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Signature.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/P11Signature.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -742,6 +742,11 @@
             DerValue[] values = in.getSequence(2);
             BigInteger r = values[0].getPositiveBigInteger();
             BigInteger s = values[1].getPositiveBigInteger();
+
+            // Check for trailing signature data
+            if (in.available() != 0) {
+                throw new IOException("Incorrect signature length");
+            }
             byte[] br = toByteArray(r, 20);
             byte[] bs = toByteArray(s, 20);
             if ((br == null) || (bs == null)) {
@@ -761,6 +766,11 @@
             DerValue[] values = in.getSequence(2);
             BigInteger r = values[0].getPositiveBigInteger();
             BigInteger s = values[1].getPositiveBigInteger();
+
+            // Check for trailing signature data
+            if (in.available() != 0) {
+                throw new IOException("Incorrect signature length");
+            }
             // trim leading zeroes
             byte[] br = KeyUtil.trimZeroes(r.toByteArray());
             byte[] bs = KeyUtil.trimZeroes(s.toByteArray());
--- a/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/LibMDMech.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/LibMDMech.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
--- a/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/NativeGCMCipher.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/NativeGCMCipher.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -57,12 +57,18 @@
 
     private static final int DEFAULT_TAG_LEN = 128; // same as SunJCE provider
 
+    // same as SunJCE provider, see GaloisCounterMode.java for details
+    private static final int MAX_BUF_SIZE = Integer.MAX_VALUE;
+
     // buffer for storing AAD data; if null, meaning buffer content has been
     // supplied to native context
-    private ByteArrayOutputStream aadBuffer = new ByteArrayOutputStream();
+    private ByteArrayOutputStream aadBuffer;
 
     // buffer for storing input in decryption, not used for encryption
-    private ByteArrayOutputStream ibuffer = null;
+    private ByteArrayOutputStream ibuffer;
+
+    // needed for checking against MAX_BUF_SIZE
+    private int processed;
 
     private int tagLen = DEFAULT_TAG_LEN;
 
@@ -75,10 +81,22 @@
      * key + iv values used in previous encryption.
      * For decryption operations, no checking is necessary.
      */
-    private boolean requireReinit = false;
+    private boolean requireReinit;
     private byte[] lastEncKey = null;
     private byte[] lastEncIv = null;
 
+    private void checkAndUpdateProcessed(int len) {
+        // Currently, cipher text and tag are packed in one byte array, so
+        // the impl-specific limit for input data size is (MAX_BUF_SIZE - tagLen)
+        int inputDataLimit = MAX_BUF_SIZE - tagLen;
+
+        if (processed > inputDataLimit - len) {
+            throw new ProviderException("OracleUcrypto provider only supports " +
+                "input size up to " + inputDataLimit + " bytes");
+        }
+        processed += len;
+    }
+
     NativeGCMCipher(int fixedKeySize) throws NoSuchAlgorithmException {
         super(UcryptoMech.CRYPTO_AES_GCM, fixedKeySize);
     }
@@ -86,12 +104,14 @@
     @Override
     protected void ensureInitialized() {
         if (!initialized) {
-            if (aadBuffer != null && aadBuffer.size() > 0) {
-                init(encrypt, keyValue, iv, tagLen, aadBuffer.toByteArray());
-                aadBuffer = null;
-            } else {
-                init(encrypt, keyValue, iv, tagLen, null);
+            byte[] aad = null;
+            if (aadBuffer != null) {
+                if (aadBuffer.size() > 0) {
+                    aad = aadBuffer.toByteArray();
+                }
             }
+            init(encrypt, keyValue, iv, tagLen, aad);
+            aadBuffer = null;
             if (!initialized) {
                 throw new UcryptoException("Cannot initialize Cipher");
             }
@@ -136,6 +156,7 @@
             ibuffer.reset();
         }
         if (!encrypt) requireReinit = false;
+        processed = 0;
     }
 
     // actual init() implementation - caller should clone key and iv if needed
@@ -185,6 +206,7 @@
             throw new InvalidAlgorithmParameterException
                 ("Unsupported mode: " + opmode);
         }
+        aadBuffer = new ByteArrayOutputStream();
         boolean doEncrypt = (opmode == Cipher.ENCRYPT_MODE || opmode == Cipher.WRAP_MODE);
         byte[] keyBytes = key.getEncoded().clone();
         byte[] ivBytes = null;
@@ -219,6 +241,7 @@
             }
             lastEncIv = ivBytes;
             lastEncKey = keyBytes;
+            ibuffer = null;
         } else {
             requireReinit = false;
             ibuffer = new ByteArrayOutputStream();
@@ -246,15 +269,18 @@
     // see JCE spec
     @Override
     protected synchronized byte[] engineUpdate(byte[] in, int inOfs, int inLen) {
-        if (aadBuffer != null && aadBuffer.size() > 0) {
-            // init again with AAD data
-            init(encrypt, keyValue, iv, tagLen, aadBuffer.toByteArray());
+        if (aadBuffer != null) {
+            if (aadBuffer.size() > 0) {
+                // init again with AAD data
+                init(encrypt, keyValue, iv, tagLen, aadBuffer.toByteArray());
+            }
             aadBuffer = null;
         }
         if (requireReinit) {
             throw new IllegalStateException
                 ("Must use either different key or iv for GCM encryption");
         }
+        checkAndUpdateProcessed(inLen);
         if (inLen > 0) {
             if (!encrypt) {
                 ibuffer.write(in, inOfs, inLen);
@@ -274,15 +300,18 @@
                  "(at least) " + len + " bytes long. Got: " +
                  (out.length - outOfs));
         }
-        if (aadBuffer != null && aadBuffer.size() > 0) {
-            // init again with AAD data
-            init(encrypt, keyValue, iv, tagLen, aadBuffer.toByteArray());
+        if (aadBuffer != null) {
+            if (aadBuffer.size() > 0) {
+                // init again with AAD data
+                init(encrypt, keyValue, iv, tagLen, aadBuffer.toByteArray());
+            }
             aadBuffer = null;
         }
         if (requireReinit) {
             throw new IllegalStateException
                 ("Must use either different key or iv for GCM encryption");
         }
+        checkAndUpdateProcessed(inLen);
         if (inLen > 0) {
             if (!encrypt) {
                 ibuffer.write(in, inOfs, inLen);
@@ -374,15 +403,19 @@
                 + "(at least) " + len + " bytes long. Got: " +
                 (out.length - outOfs));
         }
-        if (aadBuffer != null && aadBuffer.size() > 0) {
-            // init again with AAD data
-            init(encrypt, keyValue, iv, tagLen, aadBuffer.toByteArray());
+        if (aadBuffer != null) {
+            if (aadBuffer.size() > 0) {
+                // init again with AAD data
+                init(encrypt, keyValue, iv, tagLen, aadBuffer.toByteArray());
+            }
             aadBuffer = null;
         }
         if (requireReinit) {
             throw new IllegalStateException
                 ("Must use either different key or iv for GCM encryption");
         }
+
+        checkAndUpdateProcessed(inLen);
         if (!encrypt) {
             if (inLen > 0) {
                 ibuffer.write(in, inOfs, inLen);
--- a/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/NativeRSASignature.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/NativeRSASignature.java	Tue Jul 26 14:45:11 2016 -0700
@@ -330,9 +330,9 @@
     protected synchronized boolean engineVerify(byte[] sigBytes, int sigOfs, int sigLen)
         throws SignatureException {
         if (sigBytes == null || (sigOfs < 0) || (sigBytes.length < (sigOfs + this.sigLength))
-            || (sigLen < this.sigLength)) {
-            throw new SignatureException("Invalid signature buffer. sigOfs: " +
-                sigOfs + ". sigLen: " + sigLen + ". this.sigLength: " + this.sigLength);
+            || (sigLen != this.sigLength)) {
+            throw new SignatureException("Invalid signature length: got " +
+                sigLen + " but was expecting " + this.sigLength);
         }
 
         int rv = doFinal(sigBytes, sigOfs, sigLen);
--- a/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/UcryptoMech.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.crypto.ucrypto/solaris/classes/com/oracle/security/ucrypto/UcryptoMech.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,4 @@
-/**
+/*
  * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
--- a/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java	Tue Jul 26 14:45:11 2016 -0700
@@ -39,6 +39,8 @@
 import jdk.internal.jimage.BasicImageReader;
 import jdk.internal.jimage.ImageHeader;
 import jdk.internal.jimage.ImageLocation;
+import jdk.internal.org.objectweb.asm.ClassReader;
+import jdk.internal.org.objectweb.asm.tree.ClassNode;
 import jdk.tools.jlink.internal.ImageResourcesTree;
 import jdk.tools.jlink.internal.TaskHelper;
 import jdk.tools.jlink.internal.TaskHelper.BadArgs;
@@ -354,16 +356,14 @@
     }
 
       void verify(BasicImageReader reader, String name, ImageLocation location) {
-        if (name.endsWith(".class")) {
-            byte[] bytes = reader.getResource(location);
-
-            if (bytes == null || bytes.length <= 4 ||
-                (bytes[0] & 0xFF) != 0xCA ||
-                (bytes[1] & 0xFF) != 0xFE ||
-                (bytes[2] & 0xFF) != 0xBA ||
-                (bytes[3] & 0xFF) != 0xBE) {
-                log.print(" NOT A CLASS: ");
-                print(reader, name);
+        if (name.endsWith(".class") && !name.endsWith("module-info.class")) {
+            try {
+                byte[] bytes = reader.getResource(location);
+                ClassReader cr =new ClassReader(bytes);
+                ClassNode cn = new ClassNode();
+                cr.accept(cn, ClassReader.EXPAND_FRAMES);
+            } catch (Exception ex) {
+                log.println("Error(s) in Class: " + name);
             }
         }
     }
--- a/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties	Tue Jul 26 14:45:11 2016 -0700
@@ -63,7 +63,7 @@
 \  --dir                             Target directory for extract directive
 
 main.opt.include=\
-\  --include <pattern-list>          Pattern list for filtering list or extract entries.
+\  --include <pattern-list>          Pattern list for filtering entries.
 
 main.opt.footer=\
 \n\
--- a/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,4 +1,3 @@
-
 /*
  * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -23,6 +22,7 @@
  * or visit www.oracle.com if you need additional information or have any
  * questions.
  */
+
 package jdk.tools.jlink.builder;
 
 import java.io.BufferedOutputStream;
--- a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/BasicImageWriter.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/BasicImageWriter.java	Tue Jul 26 14:45:11 2016 -0700
@@ -21,7 +21,7 @@
  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  * or visit www.oracle.com if you need additional information or have any
  * questions.
-*/
+ */
 
 package jdk.tools.jlink.internal;
 
--- a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/PerfectHashBuilder.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/PerfectHashBuilder.java	Tue Jul 26 14:45:11 2016 -0700
@@ -21,7 +21,7 @@
  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  * or visit www.oracle.com if you need additional information or have any
  * questions.
-*/
+ */
 
 package jdk.tools.jlink.internal;
 
--- a/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/IncludeLocalesPlugin.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/IncludeLocalesPlugin.java	Tue Jul 26 14:45:11 2016 -0700
@@ -24,6 +24,7 @@
  */
 package jdk.tools.jlink.internal.plugins;
 
+import java.util.AbstractMap;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.IllformedLocaleException;
@@ -31,6 +32,7 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
+import static java.util.ResourceBundle.Control;
 import java.util.Set;
 import java.util.function.Predicate;
 import java.util.regex.Pattern;
@@ -45,6 +47,10 @@
 import jdk.tools.jlink.plugin.PluginException;
 import jdk.tools.jlink.plugin.ModulePool;
 import jdk.tools.jlink.plugin.Plugin;
+import sun.util.cldr.CLDRBaseLocaleDataMetaInfo;
+import sun.util.locale.provider.LocaleProviderAdapter;
+import sun.util.locale.provider.LocaleProviderAdapter.Type;
+import sun.util.locale.provider.ResourceBundleBasedAdapter;
 
 /**
  * Plugin to explicitly specify the locale data included in jdk.localedata
@@ -95,6 +101,42 @@
     private List<Locale> available;
     private List<String> filtered;
 
+    private static final ResourceBundleBasedAdapter CLDR_ADAPTER =
+        (ResourceBundleBasedAdapter)LocaleProviderAdapter.forType(Type.CLDR);
+    private static final Map<Locale, String[]> CLDR_PARENT_LOCALES =
+        new CLDRBaseLocaleDataMetaInfo().parentLocales();
+
+    // Equivalent map
+    private static final Map<String, List<String>> EQUIV_MAP =
+        Stream.concat(
+            // COMPAT equivalence
+            Map.of(
+                "zh-Hans", List.of("zh-Hans", "zh-CN", "zh-SG"),
+                "zh-Hant", List.of("zh-Hant", "zh-HK", "zh-MO", "zh-TW"))
+                .entrySet()
+                .stream(),
+
+            // CLDR parent locales
+            CLDR_PARENT_LOCALES.entrySet().stream()
+                .map(entry -> {
+                    String parent = entry.getKey().toLanguageTag();
+                    List<String> children = new ArrayList<>();
+                    children.add(parent);
+
+                    Arrays.stream(entry.getValue())
+                        .filter(child -> !child.isEmpty())
+                        .flatMap(child ->
+                            Stream.concat(
+                                Arrays.stream(CLDR_PARENT_LOCALES.getOrDefault(
+                                    Locale.forLanguageTag(child), new String[0]))
+                                        .filter(grandchild -> !grandchild.isEmpty()),
+                                List.of(child).stream()))
+                        .distinct()
+                        .forEach(children::add);
+                    return new AbstractMap.SimpleEntry<String, List<String>>(parent, children);
+                })
+        ).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+
     // Special COMPAT provider locales
     private static final String jaJPJPTag = "ja-JP-JP";
     private static final String noNONYTag = "no-NO-NY";
@@ -152,16 +194,14 @@
     @Override
     public void configure(Map<String, String> config) {
         userParam = config.get(NAME);
-        priorityList = Arrays.stream(userParam.split(","))
-            .map(s -> {
-                try {
-                    return new Locale.LanguageRange(s);
-                } catch (IllegalArgumentException iae) {
-                    throw new IllegalArgumentException(String.format(
-                        PluginsResourceBundle.getMessage(NAME + ".invalidtag"), s));
-                }
-            })
-            .collect(Collectors.toList());
+
+        try {
+            priorityList = Locale.LanguageRange.parse(userParam, EQUIV_MAP);
+        } catch (IllegalArgumentException iae) {
+            throw new IllegalArgumentException(String.format(
+                PluginsResourceBundle.getMessage(NAME + ".invalidtag"),
+                    iae.getMessage().replaceFirst("^range=", "")));
+        }
     }
 
     @Override
@@ -193,6 +233,7 @@
             // jdk.localedata is not added.
             throw new PluginException(PluginsResourceBundle.getMessage(NAME + ".localedatanotfound"));
         }
+
         filtered = filterLocales(available);
 
         if (filtered.isEmpty()) {
@@ -205,56 +246,26 @@
                 filtered.stream().flatMap(s -> includeLocaleFilePatterns(s).stream()))
             .map(s -> "regex:" + s)
             .collect(Collectors.toList());
+
         predicate = ResourceFilter.includeFilter(value);
     }
 
     private List<String> includeLocaleFilePatterns(String tag) {
-        List<String> files = new ArrayList<>();
-        String pTag = tag.replaceAll("-", "_");
-        int lastDelimiter = tag.length();
-        String isoSpecial = pTag.matches("^(he|yi|id).*") ?
-                            pTag.replaceFirst("he", "iw")
-                                .replaceFirst("yi", "ji")
-                                .replaceFirst("id", "in") : "";
-
-        // Add tag patterns including parents
-        while (true) {
-            pTag = pTag.substring(0, lastDelimiter);
-            files.addAll(includeLocaleFiles(pTag));
-
-            if (!isoSpecial.isEmpty()) {
-                isoSpecial = isoSpecial.substring(0, lastDelimiter);
-                files.addAll(includeLocaleFiles(isoSpecial));
-            }
-
-            lastDelimiter = pTag.lastIndexOf('_');
-            if (lastDelimiter == -1) {
-                break;
-            }
+        // Ignore extension variations
+        if (tag.matches(".+-[a-z]-.+")) {
+            return List.of();
         }
 
-        final String lang = pTag;
-
-        // Add possible special locales of the COMPAT provider
-        Set.of(jaJPJPTag, noNONYTag, thTHTHTag).stream()
-            .filter(stag -> lang.equals(stag.substring(0,2)))
-            .map(t -> includeLocaleFiles(t.replaceAll("-", "_")))
-            .forEach(files::addAll);
-
-        // Add possible UN.M49 files (unconditional for now) for each language
-        files.addAll(includeLocaleFiles(lang + "_[0-9]{3}"));
-        if (!isoSpecial.isEmpty()) {
-            files.addAll(includeLocaleFiles(isoSpecial + "_[0-9]{3}"));
-        }
+        List<String> files = new ArrayList<>(includeLocaleFiles(tag.replaceAll("-", "_")));
 
         // Add Thai BreakIterator related data files
-        if (lang.equals("th")) {
+        if (tag.equals("th")) {
             files.add(".+sun/text/resources/thai_dict");
             files.add(".+sun/text/resources/[^_]+BreakIteratorData_th");
         }
 
         // Add Taiwan resource bundles for Hong Kong
-        if (tag.startsWith("zh-HK")) {
+        if (tag.equals("zh-HK")) {
             files.addAll(includeLocaleFiles("zh_TW"));
         }
 
@@ -306,6 +317,11 @@
         byte[] filteredBytes = filterLocales(locales).stream()
             .collect(Collectors.joining(" "))
             .getBytes();
+
+        if (filteredBytes.length > b.length) {
+            throw new InternalError("Size of filtered locales is bigger than the original one");
+        }
+
         System.arraycopy(filteredBytes, 0, b, 0, filteredBytes.length);
         Arrays.fill(b, filteredBytes.length, b.length, (byte)' ');
         return true;
@@ -314,6 +330,9 @@
     private List<String> filterLocales(List<Locale> locales) {
         List<String> ret =
             Locale.filter(priorityList, locales, Locale.FilteringMode.EXTENDED_FILTERING).stream()
+                .flatMap(loc -> Stream.concat(Control.getNoFallbackControl(Control.FORMAT_DEFAULT)
+                                     .getCandidateLocales("", loc).stream(),
+                                CLDR_ADAPTER.getCandidateLocales("", loc).stream()))
                 .map(loc ->
                     // Locale.filter() does not preserve the case, which is
                     // significant for "variant" equality. Retrieve the original
@@ -321,15 +340,12 @@
                     locales.stream()
                         .filter(l -> l.toString().equalsIgnoreCase(loc.toString()))
                         .findAny()
-                        .orElse(Locale.ROOT)
-                        .toLanguageTag())
+                        .orElse(Locale.ROOT))
+                .filter(loc -> !loc.equals(Locale.ROOT))
+                .flatMap(IncludeLocalesPlugin::localeToTags)
+                .distinct()
                 .collect(Collectors.toList());
 
-        // no-NO-NY.toLanguageTag() returns "nn-NO", so specially handle it here
-        if (ret.contains("no-NO")) {
-            ret.add(noNONYTag);
-        }
-
         return ret;
     }
 
@@ -338,6 +354,7 @@
         // ISO3166 compatibility
         tag = tag.replaceFirst("^iw", "he").replaceFirst("^ji", "yi").replaceFirst("^in", "id");
 
+        // Special COMPAT provider locales
         switch (tag) {
             case jaJPJPTag:
                 return jaJPJP;
@@ -351,4 +368,42 @@
                 return LOCALE_BUILDER.build();
         }
     }
+
+    private static Stream<String> localeToTags(Locale loc) {
+        String tag = loc.toLanguageTag();
+        Stream<String> ret = null;
+
+        switch (loc.getLanguage()) {
+            // ISO3166 compatibility
+            case "iw":
+                ret = List.of(tag, tag.replaceFirst("^he", "iw")).stream();
+                break;
+            case "in":
+                ret = List.of(tag, tag.replaceFirst("^id", "in")).stream();
+                break;
+            case "ji":
+                ret = List.of(tag, tag.replaceFirst("^yi", "ji")).stream();
+                break;
+
+            // Special COMPAT provider locales
+            case "ja":
+                if (loc.getCountry() == "JP") {
+                    ret = List.of(tag, jaJPJPTag).stream();
+                }
+                break;
+            case "no":
+            case "nn":
+                if (loc.getCountry() == "NO") {
+                    ret = List.of(tag, noNONYTag).stream();
+                }
+                break;
+            case "th":
+                if (loc.getCountry() == "TH") {
+                    ret = List.of(tag, thTHTHTag).stream();
+                }
+                break;
+        }
+
+        return ret == null ? List.of(tag).stream() : ret;
+    }
 }
--- a/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/Device.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/Device.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,3 @@
-package checker;
-
 /*
  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
  *
@@ -31,6 +29,8 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+package checker;
+
 /*
  * This source code is provided to illustrate the usage of a given feature
  * or technique and has been deliberately simplified. Additional steps
--- a/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/Module.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/Module.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,3 @@
-package checker;
-
 /*
  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
  *
@@ -31,6 +29,8 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+package checker;
+
 /*
  * This source code is provided to illustrate the usage of a given feature
  * or technique and has been deliberately simplified. Additional steps
--- a/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/RequireContainer.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/annotations/DependencyChecker/PluginChecker/src/checker/RequireContainer.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,3 @@
-package checker;
-
 /*
  * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
  *
@@ -31,6 +29,8 @@
  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+package checker;
+
 /*
  * This source code is provided to illustrate the usage of a given feature
  * or technique and has been deliberately simplified. Additional steps
--- a/src/sample/share/nio/chatserver/ChatServer.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/nio/chatserver/ChatServer.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/src/sample/share/nio/chatserver/Client.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/nio/chatserver/Client.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/src/sample/share/nio/chatserver/ClientReader.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/nio/chatserver/ClientReader.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/src/sample/share/nio/chatserver/DataReader.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/nio/chatserver/DataReader.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/src/sample/share/nio/chatserver/MessageReader.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/nio/chatserver/MessageReader.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/src/sample/share/nio/chatserver/NameReader.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/src/sample/share/nio/chatserver/NameReader.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
--- a/test/ProblemList.txt	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/ProblemList.txt	Tue Jul 26 14:45:11 2016 -0700
@@ -138,6 +138,8 @@
 
 java/lang/instrument/BootClassPath/BootClassPathTest.sh         8072130 macosx-all
 
+java/lang/instrument/DaemonThread/TestDaemonThread.java         8161225 generic-all
+
 java/lang/management/MemoryMXBean/LowMemoryTest.java            8130339 generic-all
 
 java/lang/management/MemoryMXBean/Pending.java                  8158837 generic-all
@@ -171,6 +173,8 @@
 
 java/net/DatagramSocket/SendDatagramToBadAddress.java           7143960 macosx-all
 
+java/net/httpclient/SplitResponse.java                          8157533 generic-all 
+
 java/net/httpclient/http2/BasicTest.java                        8157408 linux-all
 java/net/httpclient/http2/ErrorTest.java                        8158127 solaris-all,windows-all
 java/net/httpclient/http2/TLSConnection.java                    8157482 macosx-all
--- a/test/java/lang/Class/GenericStringTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/lang/Class/GenericStringTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 6298888 6992705
+ * @bug 6298888 6992705 8161500
  * @summary Check Class.toGenericString()
  * @author Joseph D. Darcy
  */
@@ -58,15 +58,11 @@
         f = GenericStringTest.class.getDeclaredField("mixed2");
         failures += checkToGenericString(f.getType(), "java.util.Map<K,V>[][]");
 
-        Class<?>[] types = {
-            GenericStringTest.class,
-            AnInterface.class,
-            LocalMap.class,
-            AnEnum.class,
-            AnotherEnum.class,
-        };
-
-        for(Class<?> clazz : types) {
+        for(Class<?> clazz : List.of(GenericStringTest.class,
+                                     AnInterface.class,
+                                     LocalMap.class,
+                                     AnEnum.class,
+                                     AnotherEnum.class)) {
             failures += checkToGenericString(clazz, clazz.getAnnotation(ExpectedGenericString.class).value());
         }
 
--- a/test/java/lang/Runtime/Version/Basic.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/lang/Runtime/Version/Basic.java	Tue Jul 26 14:45:11 2016 -0700
@@ -24,7 +24,7 @@
 /*
  * @test
  * @summary Unit test for java.lang.Runtime.Version.
- * @bug 8072379 8144062
+ * @bug 8072379 8144062 8161236
  */
 
 import java.lang.reflect.InvocationTargetException;
@@ -55,7 +55,7 @@
     public static void main(String ... args) {
 
         //// Tests for parse(), major(), minor(), security(), pre(),
-        //// build(), opt(), version(), toString()
+        //// build(), optional(), version(), toString()
         //   v                          M     m sec pre bld opt
 
         // $VNUM
@@ -119,7 +119,8 @@
         //// Test for Runtime.version()
         testVersion();
 
-        //// Test for equals{IgnoreOpt}?(), hashCode(), compareTo{IgnoreOpt}?()
+        //// Test for equals{IgnoreOptional}?(), hashCode(),
+        //// compareTo{IgnoreOptional}?()
         // compare: after "<" == -1, equal == 0, before ">" == 1
         //      v0            v1                  eq     eqNO  cmp  cmpNO
         testEHC("9",          "9",                true,  true,   0,    0);
@@ -293,9 +294,9 @@
     }
 
     private static void testEqualsNO(Version v0, Version v1, boolean eq) {
-        if ((eq && !v0.equalsIgnoreOpt(v1))
-            || (!eq && v0.equalsIgnoreOpt(v1))) {
-            fail("equalsIgnoreOpt() " + Boolean.toString(eq),
+        if ((eq && !v0.equalsIgnoreOptional(v1))
+            || (!eq && v0.equalsIgnoreOptional(v1))) {
+            fail("equalsIgnoreOptional() " + Boolean.toString(eq),
                  v0.toString(), v1.toString());
         } else {
             pass();
@@ -328,12 +329,12 @@
     private static void testCompareNO(Version v0, Version v1, int compare)
     {
         try {
-            Method m = VERSION.getMethod("compareToIgnoreOpt", VERSION);
+            Method m = VERSION.getMethod("compareToIgnoreOptional", VERSION);
             int cmp = (int) m.invoke(v0, v1);
             checkCompare(v0, v1, compare, cmp);
         } catch (IllegalAccessException | InvocationTargetException |
                  NoSuchMethodException ex) {
-            fail(String.format("compareToIgnoreOpt() invocation: %s",
+            fail(String.format("compareToIgnoreOptional() invocation: %s",
                                ex.getClass()),
                  null);
         }
--- a/test/java/lang/instrument/ATransformerManagementTestCase.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/lang/instrument/ATransformerManagementTestCase.java	Tue Jul 26 14:45:11 2016 -0700
@@ -302,6 +302,7 @@
         public byte[]
         transform(
             Module module,
+            ClassLoader loader,
             String className,
             Class<?> classBeingRedefined,
             ProtectionDomain    protectionDomain,
@@ -311,6 +312,7 @@
             if (classBeingRedefined != null) checkInTransformer(MyClassFileTransformer.this);
 
             return super.transform(     module,
+                                        loader,
                                         className,
                                         classBeingRedefined,
                                         protectionDomain,
--- a/test/java/lang/instrument/RetransformAgent.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/lang/instrument/RetransformAgent.java	Tue Jul 26 14:45:11 2016 -0700
@@ -69,6 +69,7 @@
         }
 
         public byte[] transform(Module module,
+                                ClassLoader loader,
                                 String className,
                                 Class<?> classBeingRedefined,
                                 ProtectionDomain    protectionDomain,
--- a/test/java/lang/instrument/SimpleIdentityTransformer.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/lang/instrument/SimpleIdentityTransformer.java	Tue Jul 26 14:45:11 2016 -0700
@@ -63,6 +63,7 @@
     public byte[]
     transform(
         Module module,
+        ClassLoader loader,
         String className,
         Class<?> classBeingRedefined,
         ProtectionDomain    protectionDomain,
--- a/test/java/lang/reflect/Constructor/GenericStringTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/lang/reflect/Constructor/GenericStringTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 5033583 6316717 6470106
+ * @bug 5033583 6316717 6470106 8161500 8162539
  * @summary Check toGenericString() and toString() methods
  * @author Joseph D. Darcy
  */
@@ -35,30 +35,17 @@
 public class GenericStringTest {
     public static void main(String argv[]) throws Exception{
         int failures = 0;
-        List<Class<?>> classList = new LinkedList<Class<?>>();
-        classList.add(TestClass1.class);
-        classList.add(TestClass2.class);
 
-
-        for(Class<?> clazz: classList)
+        for(Class<?> clazz: List.of(TestClass1.class, TestClass2.class))
             for(Constructor<?> ctor: clazz.getDeclaredConstructors()) {
                 ExpectedGenericString egs = ctor.getAnnotation(ExpectedGenericString.class);
                 String actual = ctor.toGenericString();
                 System.out.println(actual);
-                if (! egs.value().equals(actual)) {
-                    failures++;
-                    System.err.printf("ERROR: Expected generic string ''%s''; got ''%s''.\n",
-                                      egs.value(), actual);
-                }
+                failures += checkForFailure(egs.value(), actual);
 
                 if (ctor.isAnnotationPresent(ExpectedString.class)) {
-                    ExpectedString es = ctor.getAnnotation(ExpectedString.class);
-                    String result = ctor.toString();
-                    if (! es.value().equals(result)) {
-                        failures++;
-                        System.err.printf("ERROR: Expected ''%s''; got ''%s''.\n",
-                                          es.value(), result);
-                    }
+                    failures += checkForFailure(ctor.getAnnotation(ExpectedString.class).value(),
+                                                ctor.toString());
                 }
             }
 
@@ -67,6 +54,15 @@
             throw new RuntimeException();
         }
     }
+
+    private static int checkForFailure(String expected, String actual) {
+        if (!expected.equals(actual)) {
+            System.err.printf("ERROR: Expected ''%s'';%ngot             ''%s''.\n",
+                              expected, actual);
+            return 1;
+        } else
+            return 0;
+    }
 }
 
 class TestClass1 {
@@ -80,13 +76,23 @@
 
     @ExpectedGenericString(
    "private TestClass1(java.lang.Object) throws java.lang.RuntimeException")
+    @ExpectedString(
+   "private TestClass1(java.lang.Object) throws java.lang.RuntimeException")
     private TestClass1(Object o) throws RuntimeException {}
 
     @ExpectedGenericString(
    "protected <S,T> TestClass1(S,T) throws java.lang.Exception")
+    @ExpectedString(
+   "protected TestClass1(java.lang.Object,java.lang.Object) throws java.lang.Exception")
     protected <S, T> TestClass1(S s, T t) throws Exception{}
 
     @ExpectedGenericString(
+   "<E> TestClass1() throws E")
+    @ExpectedString(
+   "TestClass1() throws java.lang.Exception")
+    <E extends Exception> TestClass1() throws E {}
+
+    @ExpectedGenericString(
    "TestClass1(java.lang.Object...)")
     @ExpectedString(
    "TestClass1(java.lang.Object[])")
--- a/test/java/lang/reflect/Field/GenericStringTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/lang/reflect/Field/GenericStringTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 5033583
+ * @bug 5033583 8161500
  * @summary Check toGenericString() method
  * @author Joseph D. Darcy
  */
@@ -35,12 +35,8 @@
 public class GenericStringTest {
     public static void main(String argv[]) throws Exception {
         int failures = 0;
-        List<Class> classList = new LinkedList<Class>();
-        classList.add(TestClass1.class);
-        classList.add(TestClass2.class);
 
-
-        for(Class clazz: classList)
+        for(Class clazz: List.of(TestClass1.class, TestClass2.class))
             for(Field field: clazz.getDeclaredFields()) {
                 ExpectedString es = field.getAnnotation(ExpectedString.class);
                 String genericString = field.toGenericString();
@@ -61,15 +57,15 @@
 
 class TestClass1 {
     @ExpectedString("int TestClass1.field1")
-        int field1;
+    int field1;
 
     @ExpectedString("private static java.lang.String TestClass1.field2")
-        private static String field2;
+    private static String field2;
 }
 
 class TestClass2<E> {
     @ExpectedString("public E TestClass2.field1")
-        public E field1;
+    public E field1;
 }
 
 @Retention(RetentionPolicy.RUNTIME)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/lang/reflect/Generics/TestGenericReturnTypeToString.java	Tue Jul 26 14:45:11 2016 -0700
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8054213
+ * @summary Check that toString method works properly for generic return type
+ * obtained via reflection
+ * @run main TestGenericReturnTypeToString
+ */
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.reflect.Method;
+import java.util.List;
+
+public class TestGenericReturnTypeToString {
+
+    public static void main(String[] args) {
+        boolean hasFailures = false;
+        for (Method method : TestGenericReturnTypeToString.class.getMethods()) {
+            if (method.isAnnotationPresent(ExpectedGenericString.class)) {
+                ExpectedGenericString es = method.getAnnotation
+                        (ExpectedGenericString.class);
+                String result = method.getGenericReturnType().toString();
+                if (!es.value().equals(result)) {
+                    hasFailures = true;
+                    System.err.println("Unexpected result of " +
+                            "getGenericReturnType().toString() " +
+                            " for " + method.getName()
+                            + " expected: " + es.value() + " actual: " + result);
+                }
+            }
+            if (hasFailures) {
+                throw new RuntimeException("Test failed");
+            }
+        }
+    }
+
+    @ExpectedGenericString("TestGenericReturnTypeToString$" +
+          "FirstInnerClassGeneric<Dummy>$SecondInnerClassGeneric<Dummy>")
+    public FirstInnerClassGeneric<Dummy>.SecondInnerClassGeneric<Dummy> foo1() {
+        return null;
+    }
+
+    @ExpectedGenericString("TestGenericReturnTypeToString$" +
+          "FirstInnerClassGeneric<Dummy>$SecondInnerClass")
+    public FirstInnerClassGeneric<Dummy>.SecondInnerClass foo2() {
+        return null;
+    }
+
+    @ExpectedGenericString("TestGenericReturnTypeToString$" +
+          "FirstInnerClass$SecondInnerClassGeneric<Dummy>")
+    public FirstInnerClass.SecondInnerClassGeneric<Dummy> foo3() {
+        return null;
+    }
+
+    @ExpectedGenericString("class TestGenericReturnTypeToString$" +
+          "FirstInnerClass$SecondInnerClass")
+    public FirstInnerClass.SecondInnerClass foo4() {
+        return null;
+    }
+
+    @ExpectedGenericString(
+          "java.util.List<java.lang.String>")
+    public java.util.List<java.lang.String> foo5() {
+        return null;
+    }
+
+    @ExpectedGenericString("interface TestGenericReturnTypeToString$" +
+          "FirstInnerClass$Interface")
+    public FirstInnerClass.Interface foo6() {
+        return null;
+    }
+
+    @ExpectedGenericString("TestGenericReturnTypeToString$" +
+          "FirstInnerClass$InterfaceGeneric<Dummy>")
+    public FirstInnerClass.InterfaceGeneric<Dummy> foo7() {
+        return null;
+    }
+
+    public static class FirstInnerClass {
+
+        public class SecondInnerClassGeneric<T> {
+        }
+
+        public class SecondInnerClass {
+        }
+
+        interface Interface {
+        }
+
+        interface InterfaceGeneric<T> {
+        }
+    }
+
+    public class FirstInnerClassGeneric<T> {
+
+        public class SecondInnerClassGeneric<T> {
+        }
+
+        public class SecondInnerClass {
+        }
+    }
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ExpectedGenericString {
+    String value();
+}
+
+class Dummy {
+}
--- a/test/java/lang/reflect/Method/GenericStringTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/lang/reflect/Method/GenericStringTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 5033583 6316717 6470106 8004979
+ * @bug 5033583 6316717 6470106 8004979 8161500 8162539
  * @summary Check toGenericString() and toString() methods
  * @author Joseph D. Darcy
  */
@@ -35,42 +35,25 @@
 public class GenericStringTest {
     public static void main(String argv[]) throws Exception {
         int failures = 0;
-        List<Class<?>> classList = new LinkedList<Class<?>>();
-        classList.add(TestClass1.class);
-        classList.add(TestClass2.class);
-        classList.add(Roebling.class);
-        classList.add(TestInterface1.class);
 
-
-        for(Class<?> clazz: classList)
+        for(Class<?> clazz: List.of(TestClass1.class, TestClass2.class,
+                                    Roebling.class, TestInterface1.class))
             for(Method method: clazz.getDeclaredMethods()) {
                 ExpectedGenericString egs = method.getAnnotation(ExpectedGenericString.class);
                 if (egs != null) {
                     String actual = method.toGenericString();
                     System.out.println(actual);
                     if (method.isBridge()) {
-                        if (! egs.bridgeValue().equals(actual)) {
-                            failures++;
-                            System.err.printf("ERROR: Expected ''%s''; got ''%s''.\n",
-                                              egs.value(), actual);
-                        }
+                        failures += checkForFailure(egs.bridgeValue(), actual);
                     } else {
-                        if (! egs.value().equals(actual)) {
-                            failures++;
-                            System.err.printf("ERROR: Expected ''%s''; got ''%s''.\n",
-                                              egs.value(), actual);
-                        }
+                        failures += checkForFailure(egs.value(), actual);
                     }
                 }
 
                 if (method.isAnnotationPresent(ExpectedString.class)) {
                     ExpectedString es = method.getAnnotation(ExpectedString.class);
                     String actual = method.toString();
-                    if (! es.value().equals(actual)) {
-                        failures++;
-                        System.err.printf("ERROR: Expected ''%s''; got ''%s''.\n",
-                                          es.value(), actual);
-                    }
+                    failures += checkForFailure(es.value(), actual);
                 }
 
             }
@@ -93,6 +76,15 @@
             throw new RuntimeException();
         }
     }
+
+    private static int checkForFailure(String expected, String actual) {
+        if (!expected.equals(actual)) {
+            System.err.printf("ERROR: Expected ''%s'';%ngot             ''%s''.\n",
+                              expected, actual);
+            return 1;
+        } else
+            return 0;
+    }
 }
 
 class TestClass1 {
@@ -120,7 +112,33 @@
 
     @ExpectedGenericString(
    "public void TestClass2.method2() throws F")
+    @ExpectedString(
+   "public void TestClass2.method2() throws java.lang.Exception")
     public void method2() throws F {return;}
+
+    @ExpectedGenericString(
+   "public E[] TestClass2.method3()")
+    public E[] method3() {return null;}
+
+    @ExpectedGenericString(
+   "public E[][] TestClass2.method4()")
+    public E[][] method4() {return null;}
+
+    @ExpectedGenericString(
+   "public java.util.List<E[]> TestClass2.method5()")
+    public List<E[]> method5() {return null;}
+
+    @ExpectedGenericString(
+   "public java.util.List<?> TestClass2.method6()")
+    public List<?> method6() {return null;}
+
+    @ExpectedGenericString(
+   "public java.util.List<?>[] TestClass2.method7()")
+    public List<?>[] method7() {return null;}
+
+    @ExpectedGenericString(
+   "public <K,V> java.util.Map<K, V> TestClass2.method8()")
+    public <K, V> Map<K, V> method8() {return null;}
 }
 
 class Roebling implements Comparable<Roebling> {
@@ -157,7 +175,6 @@
     @ExpectedGenericString(
     "public default strictfp double TestInterface1.quux()")
     strictfp default double quux(){return 1.0;}
-
 }
 
 @Retention(RetentionPolicy.RUNTIME)
--- a/test/java/net/URLPermission/URLPermissionTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/net/URLPermission/URLPermissionTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -26,7 +26,7 @@
 
 /**
  * @test
- * @bug 8010464 8027570 8027687 8029354 8114860 8071660
+ * @bug 8010464 8027570 8027687 8029354 8114860 8071660 8161291
  */
 
 public class URLPermissionTest {
@@ -355,15 +355,16 @@
     };
 
     static Test[] actionsStringTest = {
-        actionstest("", ""),
+        actionstest("", ":"),
+        actionstest(":", ":"),
         actionstest(":X-Bar", ":X-Bar"),
-        actionstest("GET", "GET"),
-        actionstest("get", "GET"),
-        actionstest("GET,POST", "GET,POST"),
-        actionstest("GET,post", "GET,POST"),
-        actionstest("get,post", "GET,POST"),
-        actionstest("get,post,DELETE", "DELETE,GET,POST"),
-        actionstest("GET,POST:", "GET,POST"),
+        actionstest("GET", "GET:"),
+        actionstest("get", "GET:"),
+        actionstest("GET,POST", "GET,POST:"),
+        actionstest("GET,post", "GET,POST:"),
+        actionstest("get,post", "GET,POST:"),
+        actionstest("get,post,DELETE", "DELETE,GET,POST:"),
+        actionstest("GET,POST:", "GET,POST:"),
         actionstest("GET:X-Foo,X-bar", "GET:X-Bar,X-Foo"),
         actionstest("GET,POST,DELETE:X-Bar,X-Foo,X-Bar,Y-Foo", "DELETE,GET,POST:X-Bar,X-Bar,X-Foo,Y-Foo")
     };
--- a/test/java/net/URLPermission/URLTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/net/URLPermission/URLTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -23,167 +23,194 @@
 
 import java.net.URLPermission;
 /*
- * Run the tests once without security manager and once with
- *
  * @test
  * @bug 8010464
  * @modules jdk.httpserver
- * @key intermittent
  * @library /lib/testlibrary/
  * @build jdk.testlibrary.SimpleSSLContext
- * @run main/othervm/java.security.policy=policy.1 URLTest one
- * @run main/othervm URLTest one
- * @run main/othervm/java.security.policy=policy.2 URLTest two
- * @run main/othervm URLTest two
- * @run main/othervm/java.security.policy=policy.3 URLTest three
- * @run main/othervm URLTest three
+ * @run main/othervm URLTest
+ * @summary check URLPermission with Http(s)URLConnection
  */
 
 import java.net.*;
 import java.io.*;
-import java.util.*;
+import java.security.*;
 import java.util.concurrent.*;
-import java.util.logging.*;
 import com.sun.net.httpserver.*;
 import javax.net.ssl.*;
 import jdk.testlibrary.SimpleSSLContext;
 
 public class URLTest {
-    static boolean failed = false;
+
+    static boolean failed;
 
     public static void main (String[] args) throws Exception {
-        boolean no = false, yes = true;
+        createServers();
 
-        if (System.getSecurityManager() == null) {
-            yes = false;
-        }
-        createServers();
-        InetSocketAddress addr1 = httpServer.getAddress();
-        int port1 = addr1.getPort();
-        InetSocketAddress addr2 = httpsServer.getAddress();
-        int port2 = addr2.getPort();
+        try {
+            // Verify without a Security Manager
+            test1();
+            test2();
+            test3();
 
-          // each of the following cases is run with a different policy file
+            // Set the security manager. Each test will set its own policy.
+            Policy.setPolicy(new CustomPolicy());
+            System.setSecurityManager(new SecurityManager());
+            System.out.println("\n Security Manager has been set.");
 
-        switch (args[0]) {
-          case "one":
-            String url1 = "http://127.0.0.1:"+ port1 + "/foo.html";
-            String url2 = "https://127.0.0.1:"+ port2 + "/foo.html";
-            String url3 = "http://127.0.0.1:"+ port1 + "/bar.html";
-            String url4 = "https://127.0.0.1:"+ port2 + "/bar.html";
+            test1();
+            test2();
+            test3();
 
-            // simple positive test. Should succceed
-            test(url1, "GET", "X-Foo", no);
-            test(url1, "GET", "Z-Bar", "X-Foo", no);
-            test(url1, "GET", "X-Foo", "Z-Bar", no);
-            test(url1, "GET", "Z-Bar", no);
-            test(url2, "POST", "X-Fob", no);
-
-            // reverse the methods, should fail
-            test(url1, "POST", "X-Foo", yes);
-            test(url2, "GET", "X-Fob", yes);
-
-            // different URLs, should fail
-            test(url3, "GET", "X-Foo", yes);
-            test(url4, "POST", "X-Fob", yes);
-            break;
-
-          case "two":
-            url1 = "http://127.0.0.1:"+ port1 + "/foo.html";
-            url2 = "https://127.0.0.1:"+ port2 + "/foo.html";
-            url3 = "http://127.0.0.1:"+ port1 + "/bar.html";
-            url4 = "https://127.0.0.1:"+ port2 + "/bar.html";
-
-            // simple positive test. Should succceed
-            test(url1, "GET", "X-Foo", no);
-            test(url2, "POST", "X-Fob", no);
-            test(url3, "GET", "X-Foo", no);
-            test(url4, "POST", "X-Fob", no);
-            break;
-
-          case "three":
-            url1 = "http://127.0.0.1:"+ port1 + "/foo.html";
-            url2 = "https://127.0.0.1:"+ port2 + "/a/c/d/e/foo.html";
-            url3 = "http://127.0.0.1:"+ port1 + "/a/b/c";
-            url4 = "https://127.0.0.1:"+ port2 + "/a/b/c";
-
-            test(url1, "GET", "X-Foo", yes);
-            test(url2, "POST", "X-Zxc", no);
-            test(url3, "DELETE", "Y-Foo", no);
-            test(url4, "POST", "Y-Foo", yes);
-            break;
-        }
-        shutdown();
-        if (failed) {
-            throw new RuntimeException("Test failed");
+            if (failed)
+                throw new RuntimeException("Test failed");
+        } finally {
+            shutdown();
         }
     }
 
-    public static void test (
-        String u, String method,
-        String header, boolean exceptionExpected
-    )
-        throws Exception
-    {
-        test(u, method, header, null, exceptionExpected);
+    static void test1() throws IOException {
+        System.out.println("\n--- Test 1 ---");
+
+        boolean expectException = false;
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            expectException = true;
+            Policy.setPolicy(new CustomPolicy(
+                new URLPermission("http://127.0.0.1:"+httpPort+"/foo.html", "GET:X-Foo,Z-Bar"),
+                new URLPermission("https://127.0.0.1:"+httpsPort+"/foo.html", "POST:X-Fob,T-Bar")));
+        }
+
+        String url1 = "http://127.0.0.1:"+httpPort+"/foo.html";
+        String url2 = "https://127.0.0.1:"+httpsPort+"/foo.html";
+        String url3 = "http://127.0.0.1:"+httpPort+"/bar.html";
+        String url4 = "https://127.0.0.1:"+httpsPort+"/bar.html";
+
+        // simple positive test. Should succeed
+        test(url1, "GET", "X-Foo");
+        test(url1, "GET", "Z-Bar", "X-Foo");
+        test(url1, "GET", "X-Foo", "Z-Bar");
+        test(url1, "GET", "Z-Bar");
+        test(url2, "POST", "X-Fob");
+
+        // reverse the methods, should fail
+        test(url1, "POST", "X-Foo", expectException);
+        test(url2, "GET", "X-Fob", expectException);
+
+        // different URLs, should fail
+        test(url3, "GET", "X-Foo", expectException);
+        test(url4, "POST", "X-Fob", expectException);
     }
 
-    public static void test (
-        String u, String method,
-        String header1, String header2, boolean exceptionExpected
-    )
-        throws Exception
+    static void test2() throws IOException {
+        System.out.println("\n--- Test 2 ---");
+
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            Policy.setPolicy(new CustomPolicy(
+                new URLPermission("http://127.0.0.1:"+httpPort+"/*", "GET:X-Foo"),
+                new URLPermission("https://127.0.0.1:"+httpsPort+"/*", "POST:X-Fob")));
+        }
+
+        String url1 = "http://127.0.0.1:"+httpPort+"/foo.html";
+        String url2 = "https://127.0.0.1:"+httpsPort+"/foo.html";
+        String url3 = "http://127.0.0.1:"+httpPort+"/bar.html";
+        String url4 = "https://127.0.0.1:"+httpsPort+"/bar.html";
+
+        // simple positive test. Should succeed
+        test(url1, "GET", "X-Foo");
+        test(url2, "POST", "X-Fob");
+        test(url3, "GET", "X-Foo");
+        test(url4, "POST", "X-Fob");
+    }
+
+    static void test3() throws IOException {
+        System.out.println("\n--- Test 3 ---");
+
+        boolean expectException = false;
+        SecurityManager sm = System.getSecurityManager();
+        if (sm != null) {
+            expectException = true;
+            Policy.setPolicy(new CustomPolicy(
+                new URLPermission("http://127.0.0.1:"+httpPort+"/a/b/-", "DELETE,GET:X-Foo,Y-Foo"),
+                new URLPermission("https://127.0.0.1:"+httpsPort+"/a/c/-", "POST:*")));
+        }
+
+        String url1 = "http://127.0.0.1:"+httpPort+"/foo.html";
+        String url2 = "https://127.0.0.1:"+httpsPort+"/a/c/d/e/foo.html";
+        String url3 = "http://127.0.0.1:"+httpPort+"/a/b/c";
+        String url4 = "https://127.0.0.1:"+httpsPort+"/a/b/c";
+
+        test(url1, "GET", "X-Foo", expectException);
+        test(url2, "POST", "X-Zxc");
+        test(url3, "DELETE", "Y-Foo");
+        test(url4, "POST", "Y-Foo", expectException);
+    }
+
+    // Convenience methods to simplify previous explicit test scenarios.
+    static void test(String u, String method, String header) throws IOException {
+        test(u, method, header, null, false);
+    }
+
+    static void test(String u, String method, String header, boolean expectException)
+        throws IOException
+    {
+        test(u, method, header, null, expectException);
+    }
+
+    static void test(String u, String method, String header1, String header2)
+        throws IOException
+    {
+        test(u, method, header1, header2, false);
+    }
+
+    static void test(String u,
+                     String method,
+                     String header1,
+                     String header2,
+                     boolean expectException)
+        throws IOException
     {
         URL url = new URL(u);
-        System.out.println ("url=" + u + " method="+method + " header1="+header1
-                +" header2 = " + header2
-                +" exceptionExpected="+exceptionExpected);
+        System.out.println("url=" + u + " method=" + method +
+                           " header1=" + header1 + " header2=" + header2 +
+                           " expectException=" + expectException);
         HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
         if (urlc instanceof HttpsURLConnection) {
             HttpsURLConnection ssl = (HttpsURLConnection)urlc;
-            ssl.setHostnameVerifier(new HostnameVerifier() {
-                public boolean verify(String host, SSLSession sess) {
-                    return true;
-                }
-            });
-            ssl.setSSLSocketFactory (ctx.getSocketFactory());
+            ssl.setHostnameVerifier((host, sess) -> true);
+            ssl.setSSLSocketFactory(ctx.getSocketFactory());
         }
         urlc.setRequestMethod(method);
-        if (header1 != null) {
+        if (header1 != null)
             urlc.addRequestProperty(header1, "foo");
-        }
-        if (header2 != null) {
+        if (header2 != null)
             urlc.addRequestProperty(header2, "bar");
-        }
+
         try {
-            int g = urlc.getResponseCode();
-            if (exceptionExpected) {
+            int code = urlc.getResponseCode();
+            if (expectException) {
                 failed = true;
-                System.out.println ("FAIL");
+                System.out.println("FAIL");
                 return;
             }
-            if (g != 200) {
-                String s = Integer.toString(g);
-                throw new RuntimeException("unexpected response "+ s);
-            }
+            if (code != 200)
+                throw new RuntimeException("Unexpected response " + code);
+
             InputStream is = urlc.getInputStream();
-            int c,count=0;
-            byte[] buf = new byte[1024];
-            while ((c=is.read(buf)) != -1) {
-                count += c;
-            }
+            is.readAllBytes();
             is.close();
         } catch (RuntimeException e) {
-            if (! (e instanceof SecurityException) &&
-                        !(e.getCause() instanceof SecurityException)  ||
-                        !exceptionExpected)
-            {
-                System.out.println ("FAIL");
-                //e.printStackTrace();
+            if (!expectException || !(e.getCause() instanceof SecurityException)) {
+                System.out.println ("FAIL. Unexpected: " + e.getMessage());
+                e.printStackTrace();
                 failed = true;
+                return;
+            } else {
+                System.out.println("Got expected exception: " + e.getMessage());
             }
         }
-        System.out.println ("OK");
+        System.out.println ("PASS");
     }
 
     static HttpServer httpServer;
@@ -191,33 +218,31 @@
     static HttpContext c, cs;
     static ExecutorService e, es;
     static SSLContext ctx;
-
-    // These ports need to be hard-coded until we support port number
-    // ranges in the permission class
-
-    static final int PORT1 = 12567;
-    static final int PORT2 = 12568;
+    static int httpPort;
+    static int httpsPort;
 
     static void createServers() throws Exception {
-        InetSocketAddress addr1 = new InetSocketAddress (PORT1);
-        InetSocketAddress addr2 = new InetSocketAddress (PORT2);
-        httpServer = HttpServer.create (addr1, 0);
-        httpsServer = HttpsServer.create (addr2, 0);
+        InetSocketAddress any = new InetSocketAddress(0);
+        httpServer = HttpServer.create(any, 0);
+        httpsServer = HttpsServer.create(any, 0);
 
-        MyHandler h = new MyHandler();
+        OkHandler h = new OkHandler();
 
-        c = httpServer.createContext ("/", h);
-        cs = httpsServer.createContext ("/", h);
+        c = httpServer.createContext("/", h);
+        cs = httpsServer.createContext("/", h);
         e = Executors.newCachedThreadPool();
         es = Executors.newCachedThreadPool();
-        httpServer.setExecutor (e);
-        httpsServer.setExecutor (es);
+        httpServer.setExecutor(e);
+        httpsServer.setExecutor(es);
 
         ctx = new SimpleSSLContext().get();
         httpsServer.setHttpsConfigurator(new HttpsConfigurator (ctx));
 
         httpServer.start();
         httpsServer.start();
+
+        httpPort = httpServer.getAddress().getPort();
+        httpsPort = httpsServer.getAddress().getPort();
     }
 
     static void shutdown() {
@@ -227,15 +252,38 @@
         es.shutdown();
     }
 
-    static class MyHandler implements HttpHandler {
-
-        MyHandler() {
-        }
-
+    static class OkHandler implements HttpHandler {
         public void handle(HttpExchange x) throws IOException {
             x.sendResponseHeaders(200, -1);
             x.close();
         }
     }
 
+    static class CustomPolicy extends Policy {
+        final PermissionCollection perms = new Permissions();
+        CustomPolicy(Permission... permissions) {
+            java.util.Arrays.stream(permissions).forEach(perms::add);
+
+            // needed for the HTTP(S) server
+            perms.add(new SocketPermission("localhost:1024-", "listen,resolve,accept"));
+            // needed by the test to reset the policy, per testX method
+            perms.add(new SecurityPermission("setPolicy"));
+            // needed to shutdown the ThreadPoolExecutor ( used by the servers )
+            perms.add(new RuntimePermission("modifyThread"));
+            // needed by the client code forHttpsURLConnection.setSSLSocketFactory
+            perms.add(new RuntimePermission("setFactory"));
+        }
+
+        public PermissionCollection getPermissions(ProtectionDomain domain) {
+            return perms;
+        }
+
+        public PermissionCollection getPermissions(CodeSource codesource) {
+            return perms;
+        }
+
+        public boolean implies(ProtectionDomain domain, Permission perm) {
+            return perms.implies(perm);
+        }
+    }
 }
--- a/test/java/net/URLPermission/policy.1	Mon Jul 25 15:09:23 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,39 +0,0 @@
-//
-// Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
-// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-//
-// This code is free software; you can redistribute it and/or modify it
-// under the terms of the GNU General Public License version 2 only, as
-// published by the Free Software Foundation.
-//
-// This code is distributed in the hope that it will be useful, but WITHOUT
-// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-// version 2 for more details (a copy is included in the LICENSE file that
-// accompanied this code).
-//
-// You should have received a copy of the GNU General Public License version
-// 2 along with this work; if not, write to the Free Software Foundation,
-// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-// or visit www.oracle.com if you need additional information or have any
-// questions.
-//
-
-grant {
-    permission java.net.URLPermission "http://127.0.0.1:12567/foo.html", "GET:X-Foo,Z-Bar";
-    permission java.net.URLPermission "https://127.0.0.1:12568/foo.html", "POST:X-Fob,T-Bar";
-
-    // needed for HttpServer
-    permission "java.net.SocketPermission" "localhost:1024-", "listen,resolve,accept";
-    permission "java.util.PropertyPermission" "test.src", "read";
-    permission java.io.FilePermission "${test.src}/../../../lib/testlibrary/jdk/testlibrary/testkeys", "read";
-
-    //permission "java.util.logging.LoggingPermission" "control";
-    //permission "java.io.FilePermission" "/tmp/-", "read,write";
-    permission "java.lang.RuntimePermission" "modifyThread";
-    permission "java.lang.RuntimePermission" "setFactory";
-    permission "java.util.PropertyPermission" "test.src.path", "read";
-};
-
--- a/test/java/net/URLPermission/policy.2	Mon Jul 25 15:09:23 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,39 +0,0 @@
-//
-// Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
-// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-//
-// This code is free software; you can redistribute it and/or modify it
-// under the terms of the GNU General Public License version 2 only, as
-// published by the Free Software Foundation.
-//
-// This code is distributed in the hope that it will be useful, but WITHOUT
-// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-// version 2 for more details (a copy is included in the LICENSE file that
-// accompanied this code).
-//
-// You should have received a copy of the GNU General Public License version
-// 2 along with this work; if not, write to the Free Software Foundation,
-// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-// or visit www.oracle.com if you need additional information or have any
-// questions.
-//
-
-grant {
-    permission java.net.URLPermission "http://127.0.0.1:12567/*", "GET:X-Foo";
-    permission java.net.URLPermission "https://127.0.0.1:12568/*", "POST:X-Fob";
-
-    // needed for HttpServer
-    permission "java.net.SocketPermission" "localhost:1024-", "listen,resolve,accept";
-    permission "java.util.PropertyPermission" "test.src", "read";
-    permission java.io.FilePermission "${test.src}/../../../lib/testlibrary/jdk/testlibrary/testkeys", "read";
-
-    //permission "java.util.logging.LoggingPermission" "control";
-    //permission "java.io.FilePermission" "/tmp/-", "read,write";
-    permission "java.lang.RuntimePermission" "modifyThread";
-    permission "java.lang.RuntimePermission" "setFactory";
-    permission "java.util.PropertyPermission" "test.src.path", "read";
-};
-
--- a/test/java/net/URLPermission/policy.3	Mon Jul 25 15:09:23 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,38 +0,0 @@
-//
-// Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
-// DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-//
-// This code is free software; you can redistribute it and/or modify it
-// under the terms of the GNU General Public License version 2 only, as
-// published by the Free Software Foundation.
-//
-// This code is distributed in the hope that it will be useful, but WITHOUT
-// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-// FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-// version 2 for more details (a copy is included in the LICENSE file that
-// accompanied this code).
-//
-// You should have received a copy of the GNU General Public License version
-// 2 along with this work; if not, write to the Free Software Foundation,
-// Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-//
-// Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-// or visit www.oracle.com if you need additional information or have any
-// questions.
-//
-
-grant {
-    permission java.net.URLPermission "http://127.0.0.1:12567/a/b/-", "DELETE,GET:X-Foo,Y-Foo";
-    permission java.net.URLPermission "https://127.0.0.1:12568/a/c/-", "POST:*";
-
-    // needed for HttpServer
-    permission "java.net.SocketPermission" "localhost:1024-", "listen,resolve,accept";
-    permission "java.util.PropertyPermission" "test.src", "read";
-    permission java.io.FilePermission "${test.src}/../../../lib/testlibrary/jdk/testlibrary/testkeys", "read";
-
-    //permission "java.util.logging.LoggingPermission" "control";
-    //permission "java.io.FilePermission" "/tmp/-", "read,write";
-    permission "java.lang.RuntimePermission" "modifyThread";
-    permission "java.lang.RuntimePermission" "setFactory";
-    permission "java.util.PropertyPermission" "test.src.path", "read";
-};
--- a/test/java/security/Provider/SecurityProviderModularTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/security/Provider/SecurityProviderModularTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -63,8 +63,7 @@
             "TestSecurityProviderClient.java");
     private static final String C_PKG = "client";
     private static final String C_JAR_NAME = C_PKG + JAR_EXTN;
-    private static final String MC_DEPENDS_ON_AUTO_SERVICE_JAR_NAME = MODULAR
-            + C_PKG + AUTO + JAR_EXTN;
+    private static final String MCN_JAR_NAME = MODULAR + C_PKG + "N" + JAR_EXTN;
     private static final String MC_JAR_NAME = MODULAR + C_PKG + JAR_EXTN;
 
     private static final Path BUILD_DIR = Paths.get(".").resolve("build");
@@ -72,7 +71,7 @@
     private static final Path S_BUILD_DIR = COMPILE_DIR.resolve(S_PKG);
     private static final Path S_WITH_META_DESCR_BUILD_DIR = COMPILE_DIR.resolve(
             S_PKG + DESCRIPTOR);
-    private static final Path C_BUILD_DIR = COMPILE_DIR.resolve(C_PKG);
+    private static final Path C_BLD_DIR = COMPILE_DIR.resolve(C_PKG);
     private static final Path M_BASE_PATH = BUILD_DIR.resolve("mbase");
     private static final Path ARTIFACTS_DIR = BUILD_DIR.resolve("artifacts");
 
@@ -88,8 +87,7 @@
     private static final Path C_ARTIFACTS_DIR = ARTIFACTS_DIR.resolve(C_PKG);
     private static final Path C_JAR = C_ARTIFACTS_DIR.resolve(C_JAR_NAME);
     private static final Path MC_JAR = C_ARTIFACTS_DIR.resolve(MC_JAR_NAME);
-    private static final Path MC_DEPENDS_ON_AUTO_SERVICE_JAR = C_ARTIFACTS_DIR
-            .resolve(MC_DEPENDS_ON_AUTO_SERVICE_JAR_NAME);
+    private static final Path MCN_JAR = C_ARTIFACTS_DIR.resolve(MCN_JAR_NAME);
 
     private static final String MAIN = C_PKG + ".TestSecurityProviderClient";
     private static final String S_INTERFACE = "java.security.Provider";
@@ -102,8 +100,6 @@
 
     private static final boolean WITH_S_DESCR = true;
     private static final boolean WITHOUT_S_DESCR = false;
-    private static final String CLASS_NOT_FOUND_MSG = "NoClassDefFoundError:"
-            + " provider/TestSecurityProvider";
     private static final String PROVIDER_NOT_FOUND_MSG = "Unable to find Test"
             + " Security Provider";
     private static final String CAN_NOT_ACCESS_MSG = "cannot access class";
@@ -126,10 +122,10 @@
             boolean useCLoader = CLASS_LOADER.equals(mechanism);
             boolean useSLoader = SERVICE_LOADER.equals(mechanism);
             String[] args = new String[]{mechanism};
-            //PARAMETER ORDERS -
-            //client Module Type, Service Module Type,
-            //Service META Descriptor Required,
-            //Expected Failure message, mech used to find the provider
+            // PARAMETER ORDERS -
+            // Client Module Type, Service Module Type,
+            // If Service META Descriptor Required,
+            // Expected Failure message, mechanism used to find the provider
             params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.EXPLICIT,
                     WITH_S_DESCR, NO_FAILURE, args));
             params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.EXPLICIT,
@@ -138,7 +134,8 @@
                     WITH_S_DESCR, ((useCLoader) ? CAN_NOT_ACCESS_MSG
                             : NO_FAILURE), args));
             params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.AUTO,
-                    WITHOUT_S_DESCR, CLASS_NOT_FOUND_MSG, args));
+                    WITHOUT_S_DESCR, ((useCLoader) ? CAN_NOT_ACCESS_MSG
+                            : PROVIDER_NOT_FOUND_MSG), args));
             params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.UNNAMED,
                     WITH_S_DESCR, ((useCLoader) ? CAN_NOT_ACCESS_MSG
                             : NO_FAILURE), args));
@@ -150,11 +147,12 @@
             params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.EXPLICIT,
                     WITH_S_DESCR, NO_FAILURE, args));
             params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.EXPLICIT,
-                    WITH_S_DESCR, NO_FAILURE, args));
+                    WITHOUT_S_DESCR, NO_FAILURE, args));
             params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.AUTO,
                     WITH_S_DESCR, NO_FAILURE, args));
             params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.AUTO,
-                    WITHOUT_S_DESCR, CLASS_NOT_FOUND_MSG, args));
+                    WITHOUT_S_DESCR,
+                    (useCLoader) ? NO_FAILURE : PROVIDER_NOT_FOUND_MSG, args));
             params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.UNNAMED,
                     WITH_S_DESCR, NO_FAILURE, args));
             params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.UNNAMED,
@@ -168,7 +166,8 @@
             params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.AUTO,
                     WITH_S_DESCR, NO_FAILURE, args));
             params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.AUTO,
-                    WITHOUT_S_DESCR, CLASS_NOT_FOUND_MSG, args));
+                    WITHOUT_S_DESCR,
+                    (useCLoader) ? NO_FAILURE : PROVIDER_NOT_FOUND_MSG, args));
             params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.UNNAMED,
                     WITH_S_DESCR, NO_FAILURE, args));
             params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.UNNAMED,
@@ -191,22 +190,23 @@
             done &= CompilerUtils.compile(S_SRC, S_BUILD_DIR);
             done &= CompilerUtils.compile(S_SRC, S_WITH_META_DESCR_BUILD_DIR);
             done &= createMetaInfServiceDescriptor(S_META_DESCR_FPATH, S_IMPL);
-            //Generate regular/modular jars with(out) META-INF
-            //Service descriptor
+            // Generate modular/regular jars with(out) META-INF
+            // service descriptor
             generateJar(true, MODULE_TYPE.EXPLICIT, MS_JAR, S_BUILD_DIR, false);
             generateJar(true, MODULE_TYPE.EXPLICIT, MS_WITH_DESCR_JAR,
                     S_WITH_META_DESCR_BUILD_DIR, false);
             generateJar(true, MODULE_TYPE.UNNAMED, S_JAR, S_BUILD_DIR, false);
             generateJar(true, MODULE_TYPE.UNNAMED, S_WITH_DESCRIPTOR_JAR,
                     S_WITH_META_DESCR_BUILD_DIR, false);
-            //Generate regular/modular(depends on explicit/auto Service)
-            //jars for client
-            done &= CompilerUtils.compile(C_SRC, C_BUILD_DIR, "-cp",
+            // Compile client source codes.
+            done &= CompilerUtils.compile(C_SRC, C_BLD_DIR, "-cp",
                     S_JAR.toFile().getCanonicalPath());
-            generateJar(false, MODULE_TYPE.EXPLICIT, MC_JAR, C_BUILD_DIR, true);
-            generateJar(false, MODULE_TYPE.EXPLICIT,
-                    MC_DEPENDS_ON_AUTO_SERVICE_JAR, C_BUILD_DIR, false);
-            generateJar(false, MODULE_TYPE.UNNAMED, C_JAR, C_BUILD_DIR, false);
+            // Generate modular client jar with explicit dependency
+            generateJar(false, MODULE_TYPE.EXPLICIT, MC_JAR, C_BLD_DIR, true);
+            // Generate modular client jar without any dependency
+            generateJar(false, MODULE_TYPE.EXPLICIT, MCN_JAR, C_BLD_DIR, false);
+            // Generate regular client jar
+            generateJar(false, MODULE_TYPE.UNNAMED, C_JAR, C_BLD_DIR, false);
             System.out.format("%nArtifacts generated successfully? %s", done);
             if (!done) {
                 throw new RuntimeException("Artifacts generation failed");
@@ -244,10 +244,9 @@
 
         OutputAnalyzer output = null;
         try {
-
-            //For automated/explicit module type copy the corresponding
-            //jars to module base folder, which will be considered as
-            //module base path during execution.
+            // For automated/explicit module types, copy the corresponding
+            // jars to module base folder, which will be considered as
+            // module base path during execution.
             if (!(cModuleType == MODULE_TYPE.UNNAMED
                     && sModuletype == MODULE_TYPE.UNNAMED)) {
                 copyJarsToModuleBase(cModuleType, cJarPath, M_BASE_PATH);
@@ -262,15 +261,14 @@
             String cPath = buildClassPath(cModuleType, cJarPath, sModuletype,
                     sJarPath);
 
-            Map<String, String> VM_ARGS = getVMArgs(sModuletype, args);
+            Map<String, String> vmArgs = getVMArgs(sModuletype,
+                    getModuleName(sModuletype, sJarPath, S_PKG), args);
             output = ProcessTools.executeTestJava(
-                    getJavaCommand(cmBasePath, cPath, mName, MAIN, VM_ARGS,
+                    getJavaCommand(cmBasePath, cPath, mName, MAIN, vmArgs,
                             args)).outputTo(System.out).errorTo(System.out);
         } finally {
-            //clean module path so that the modulepath can hold only
-            //the required jars for next run.
+            // Clean module path to hold required jars for next run.
             cleanModuleBasePath(M_BASE_PATH);
-            System.out.println("--------------------------------------------");
         }
         return output;
     }
@@ -297,11 +295,12 @@
                 }
             }
         } else {
+            // Choose corresponding client jar to use dependent module
             if (moduleType == MODULE_TYPE.EXPLICIT) {
                 if (dependsOnServiceModule) {
                     return MC_JAR;
                 } else {
-                    return MC_DEPENDS_ON_AUTO_SERVICE_JAR;
+                    return MCN_JAR;
                 }
             } else {
                 return C_JAR;
@@ -313,13 +312,16 @@
      * VM argument required for the test.
      */
     private Map<String, String> getVMArgs(MODULE_TYPE sModuletype,
-            String... args) throws IOException {
-        final Map<String, String> VM_ARGS = new LinkedHashMap<>();
-        VM_ARGS.put("-Duser.language=", "en");
-        VM_ARGS.put("-Duser.region=", "US");
-        //If mechanism selected to find the provider through
-        //Security.getProvider() then use providerName/ProviderClassName based
-        //on modular/regular provider jar in security configuration file.
+            String addModName, String... args) throws IOException {
+        final Map<String, String> vmArgs = new LinkedHashMap<>();
+        vmArgs.put("-Duser.language=", "en");
+        vmArgs.put("-Duser.region=", "US");
+        if (addModName != null && sModuletype == MODULE_TYPE.AUTO) {
+            vmArgs.put("-addmods ", addModName);
+        }
+        // If mechanism selected to find the provider through
+        // Security.getProvider() then use providerName/ProviderClassName based
+        // on modular/regular provider jar in security configuration file.
         if (args != null && args.length > 0 && SECURITY_PROP.equals(args[0])) {
             if (sModuletype == MODULE_TYPE.UNNAMED) {
                 Files.write(SECURE_PROP_EXTN, ("security.provider.10=" + S_IMPL)
@@ -328,10 +330,10 @@
                 Files.write(SECURE_PROP_EXTN, "security.provider.10=TEST"
                         .getBytes());
             }
-            VM_ARGS.put("-Djava.security.properties=", SECURE_PROP_EXTN.toFile()
+            vmArgs.put("-Djava.security.properties=", SECURE_PROP_EXTN.toFile()
                     .getCanonicalPath());
         }
-        return VM_ARGS;
+        return vmArgs;
     }
 
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/java/security/Signature/SignatureLength.java	Tue Jul 26 14:45:11 2016 -0700
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.security.*;
+
+/*
+ * @test
+ * @bug 8161571
+ * @summary Reject signatures presented for verification that contain extra
+ *          bytes.
+ * @run main SignatureLength
+ */
+public class SignatureLength {
+
+    public static void main(String[] args) throws Exception {
+        main0("EC", 256, "SHA256withECDSA", "SunEC");
+        main0("RSA", 2048, "SHA256withRSA", "SunRsaSign");
+        main0("DSA", 2048, "SHA256withDSA", "SUN");
+
+        if (System.getProperty("os.name").equals("SunOS")) {
+            main0("EC", 256, "SHA256withECDSA", null);
+            main0("RSA", 2048, "SHA256withRSA", null);
+        }
+    }
+
+    private static void main0(String keyAlgorithm, int keysize,
+            String signatureAlgorithm, String provider) throws Exception {
+        byte[] plaintext = "aaa".getBytes("UTF-8");
+
+        // Generate
+        KeyPairGenerator generator =
+            provider == null ?
+                (KeyPairGenerator) KeyPairGenerator.getInstance(keyAlgorithm) :
+                (KeyPairGenerator) KeyPairGenerator.getInstance(
+                                       keyAlgorithm, provider);
+        generator.initialize(keysize);
+        System.out.println("Generating " + keyAlgorithm + " keypair using " +
+            generator.getProvider().getName() + " JCE provider");
+        KeyPair keypair = generator.generateKeyPair();
+
+        // Sign
+        Signature signer =
+            provider == null ?
+                Signature.getInstance(signatureAlgorithm) :
+                Signature.getInstance(signatureAlgorithm, provider);
+        signer.initSign(keypair.getPrivate());
+        signer.update(plaintext);
+        System.out.println("Signing using " + signer.getProvider().getName() +
+            " JCE provider");
+        byte[] signature = signer.sign();
+
+        // Invalidate
+        System.out.println("Invalidating signature ...");
+        byte[] badSignature = new byte[signature.length + 5];
+        System.arraycopy(signature, 0, badSignature, 0, signature.length);
+        badSignature[signature.length] = 0x01;
+        badSignature[signature.length + 1] = 0x01;
+        badSignature[signature.length + 2] = 0x01;
+        badSignature[signature.length + 3] = 0x01;
+        badSignature[signature.length + 4] = 0x01;
+
+        // Verify
+        Signature verifier =
+            provider == null ?
+                Signature.getInstance(signatureAlgorithm) :
+                Signature.getInstance(signatureAlgorithm, provider);
+        verifier.initVerify(keypair.getPublic());
+        verifier.update(plaintext);
+        System.out.println("Verifying using " +
+            verifier.getProvider().getName() + " JCE provider");
+
+        try {
+            System.out.println("Valid? " + verifier.verify(badSignature));
+            throw new Exception(
+                "ERROR: expected a SignatureException but none was thrown");
+        } catch (SignatureException e) {
+            System.out.println("OK: caught expected exception: " + e);
+        }
+        System.out.println();
+    }
+}
--- a/test/java/security/modules/ModularTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/security/modules/ModularTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -82,7 +82,7 @@
 
         String testName = new StringJoiner("_").add(cModuleType.toString())
                 .add(sModuletype.toString()).add(
-                        (addMetaDesc) ? "DESCRIPTOR" : "NO_DESCRIPTOR")
+                        (addMetaDesc) ? "WITH_SERVICE" : "NO_SERVICE")
                 .toString();
 
         System.out.format("%nStarting Test case: '%s'", testName);
@@ -165,10 +165,12 @@
         if (moduleType == MODULE_TYPE.EXPLICIT) {
             System.out.format(" %nGenerating ModuleDescriptor object");
             builder = new Builder(moduleName).exports(pkg);
-            if (isService) {
+            if (isService && serviceInterface != null && serviceImpl != null) {
                 builder.provides(serviceInterface, serviceImpl);
             } else {
-                builder.uses(serviceInterface);
+                if (serviceInterface != null) {
+                    builder.uses(serviceInterface);
+                }
                 if (depends) {
                     builder.requires(serviceModuleName);
                 }
@@ -261,7 +263,7 @@
         String jarName = jarPath.toFile().getName();
         return (moduleType == MODULE_TYPE.EXPLICIT) ? mName
                 : ((moduleType == MODULE_TYPE.AUTO) ? jarName.substring(0,
-                                jarName.indexOf(JAR_EXTN)) : "");
+                                jarName.indexOf(JAR_EXTN)) : null);
     }
 
     /**
--- a/test/java/util/concurrent/BlockingQueue/PollMemoryLeak.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/util/concurrent/BlockingQueue/PollMemoryLeak.java	Tue Jul 26 14:45:11 2016 -0700
@@ -42,6 +42,7 @@
 
 import java.util.concurrent.ArrayBlockingQueue;
 import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.LinkedBlockingDeque;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.concurrent.LinkedTransferQueue;
 import java.util.concurrent.SynchronousQueue;
@@ -50,9 +51,11 @@
 public class PollMemoryLeak {
     public static void main(String[] args) throws InterruptedException {
         final BlockingQueue[] qs = {
+            new LinkedBlockingDeque(10),
             new LinkedBlockingQueue(10),
             new LinkedTransferQueue(),
             new ArrayBlockingQueue(10),
+            new ArrayBlockingQueue(10, true),
             new SynchronousQueue(),
             new SynchronousQueue(true),
         };
--- a/test/java/util/concurrent/forkjoin/FJExceptionTableLeak.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/util/concurrent/forkjoin/FJExceptionTableLeak.java	Tue Jul 26 14:45:11 2016 -0700
@@ -35,6 +35,7 @@
  * @test
  * @author Doug Lea
  * @bug 8004138
+ * @key intermittent
  * @summary Check if ForkJoinPool table leaks thrown exceptions.
  * @run main/othervm -Xmx8m -Djava.util.concurrent.ForkJoinPool.common.parallelism=4 FJExceptionTableLeak
  */
--- a/test/java/util/concurrent/tck/CompletableFutureTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/util/concurrent/tck/CompletableFutureTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -4269,12 +4269,11 @@
         }
     }
 
-    /*
-     * Tests below currently fail in stress mode due to memory retention.
-     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest tck
+    /**
+     * Reproduction recipe for:
+     * 8160402: Garbage retention with CompletableFuture.anyOf
+     * cvs update -D '2016-05-01' ./src/main/java/util/concurrent/CompletableFuture.java && ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testAnyOfGarbageRetention tck; cvs update -A
      */
-
-    /** Checks for garbage retention with anyOf. */
     public void testAnyOfGarbageRetention() throws Throwable {
         for (Integer v : new Integer[] { 1, null })
     {
@@ -4288,7 +4287,12 @@
             checkCompletedNormally(CompletableFuture.anyOf(fs), v);
     }}
 
-    /** Checks for garbage retention with allOf. */
+    /**
+     * Checks for garbage retention with allOf.
+     *
+     * As of 2016-07, fails with OOME:
+     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledAllOfGarbageRetention tck
+     */
     public void testCancelledAllOfGarbageRetention() throws Throwable {
         final int n = expensiveTests ? 100_000 : 10;
         CompletableFuture<Integer>[] fs
@@ -4299,6 +4303,21 @@
             assertTrue(CompletableFuture.allOf(fs).cancel(false));
     }
 
+    /**
+     * Checks for garbage retention when a dependent future is
+     * cancelled and garbage-collected.
+     * 8161600: Garbage retention when source CompletableFutures are never completed
+     *
+     * As of 2016-07, fails with OOME:
+     * ant -Dvmoptions=-Xmx8m -Djsr166.expensiveTests=true -Djsr166.tckTestClass=CompletableFutureTest -Djsr166.methodFilter=testCancelledGarbageRetention tck
+     */
+    public void testCancelledGarbageRetention() throws Throwable {
+        final int n = expensiveTests ? 100_000 : 10;
+        CompletableFuture<Integer> neverCompleted = new CompletableFuture<>();
+        for (int i = 0; i < n; i++)
+            assertTrue(neverCompleted.thenRun(() -> {}).cancel(true));
+    }
+
 //     static <U> U join(CompletionStage<U> stage) {
 //         CompletableFuture<U> f = new CompletableFuture<>();
 //         stage.whenComplete((v, ex) -> {
--- a/test/java/util/concurrent/tck/ConcurrentHashMapTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/util/concurrent/tck/ConcurrentHashMapTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -43,6 +43,8 @@
 import java.util.Random;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 
 import junit.framework.Test;
 import junit.framework.TestSuite;
@@ -830,4 +832,47 @@
         }
     }
 
+    /**
+     * Tests performance of removeAll when the other collection is much smaller.
+     * ant -Djsr166.tckTestClass=ConcurrentHashMapTest -Djsr166.methodFilter=testRemoveAll_performance -Djsr166.expensiveTests=true tck
+     */
+    public void testRemoveAll_performance() {
+        final int mapSize = expensiveTests ? 1_000_000 : 100;
+        final int iterations = expensiveTests ? 500 : 2;
+        final ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
+        for (int i = 0; i < mapSize; i++)
+            map.put(i, i);
+        Set<Integer> keySet = map.keySet();
+        Collection<Integer> removeMe = Arrays.asList(new Integer[] { -99, -86 });
+        for (int i = 0; i < iterations; i++)
+            assertFalse(keySet.removeAll(removeMe));
+        assertEquals(mapSize, map.size());
+    }
+
+    /**
+     * Tests performance of computeIfAbsent when the element is present.
+     * See JDK-8161372
+     * ant -Djsr166.tckTestClass=ConcurrentHashMapTest -Djsr166.methodFilter=testcomputeIfAbsent_performance -Djsr166.expensiveTests=true tck
+     */
+    public void testcomputeIfAbsent_performance() {
+        final int mapSize = 20;
+        final int iterations = expensiveTests ? (1 << 23) : mapSize * 2;
+        final int threads = expensiveTests ? 10 : 2;
+        final ConcurrentHashMap<Integer, Integer> map = new ConcurrentHashMap<>();
+        for (int i = 0; i < mapSize; i++)
+            map.put(i, i);
+        final ExecutorService pool = Executors.newFixedThreadPool(2);
+        try (PoolCleaner cleaner = cleaner(pool)) {
+            Runnable r = new CheckedRunnable() {
+                public void realRun() {
+                    int result = 0;
+                    for (int i = 0; i < iterations; i++)
+                        result += map.computeIfAbsent(i % mapSize, (k) -> k + k);
+                    if (result == -42) throw new Error();
+                }};
+            for (int i = 0; i < threads; i++)
+                pool.execute(r);
+        }
+    }
+
 }
--- a/test/java/util/concurrent/tck/StampedLockTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/util/concurrent/tck/StampedLockTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -32,11 +32,18 @@
  * http://creativecommons.org/publicdomain/zero/1.0/
  */
 
+import static java.util.concurrent.TimeUnit.DAYS;
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 
+import java.util.ArrayList;
+import java.util.List;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.StampedLock;
+import java.util.function.BiConsumer;
+import java.util.function.Consumer;
+import java.util.function.Function;
 
 import junit.framework.Test;
 import junit.framework.TestSuite;
@@ -1078,4 +1085,121 @@
         assertThrows(IllegalMonitorStateException.class, actions);
     }
 
+    static long writeLockInterruptiblyUninterrupted(StampedLock sl) {
+        try { return sl.writeLockInterruptibly(); }
+        catch (InterruptedException ex) { throw new AssertionError(ex); }
+    }
+
+    static long tryWriteLockUninterrupted(StampedLock sl, long time, TimeUnit unit) {
+        try { return sl.tryWriteLock(time, unit); }
+        catch (InterruptedException ex) { throw new AssertionError(ex); }
+    }
+
+    static long readLockInterruptiblyUninterrupted(StampedLock sl) {
+        try { return sl.readLockInterruptibly(); }
+        catch (InterruptedException ex) { throw new AssertionError(ex); }
+    }
+
+    static long tryReadLockUninterrupted(StampedLock sl, long time, TimeUnit unit) {
+        try { return sl.tryReadLock(time, unit); }
+        catch (InterruptedException ex) { throw new AssertionError(ex); }
+    }
+
+    /**
+     * Invalid write stamps result in IllegalMonitorStateException
+     */
+    public void testInvalidWriteStampsThrowIllegalMonitorStateException() {
+        List<Function<StampedLock, Long>> writeLockers = new ArrayList<>();
+        writeLockers.add((sl) -> sl.writeLock());
+        writeLockers.add((sl) -> writeLockInterruptiblyUninterrupted(sl));
+        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
+        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, 0, DAYS));
+
+        List<BiConsumer<StampedLock, Long>> writeUnlockers = new ArrayList<>();
+        writeUnlockers.add((sl, stamp) -> sl.unlockWrite(stamp));
+        writeUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockWrite()));
+        writeUnlockers.add((sl, stamp) -> sl.asWriteLock().unlock());
+        writeUnlockers.add((sl, stamp) -> sl.unlock(stamp));
+
+        List<Consumer<StampedLock>> mutaters = new ArrayList<>();
+        mutaters.add((sl) -> {});
+        mutaters.add((sl) -> sl.readLock());
+        for (Function<StampedLock, Long> writeLocker : writeLockers)
+            mutaters.add((sl) -> writeLocker.apply(sl));
+
+        for (Function<StampedLock, Long> writeLocker : writeLockers)
+        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers)
+        for (Consumer<StampedLock> mutater : mutaters) {
+            final StampedLock sl = new StampedLock();
+            final long stamp = writeLocker.apply(sl);
+            assertTrue(stamp != 0L);
+            assertThrows(IllegalMonitorStateException.class,
+                         () -> sl.unlockRead(stamp));
+            writeUnlocker.accept(sl, stamp);
+            mutater.accept(sl);
+            assertThrows(IllegalMonitorStateException.class,
+                         () -> sl.unlock(stamp),
+                         () -> sl.unlockRead(stamp),
+                         () -> sl.unlockWrite(stamp));
+        }
+    }
+
+    /**
+     * Invalid read stamps result in IllegalMonitorStateException
+     */
+    public void testInvalidReadStampsThrowIllegalMonitorStateException() {
+        List<Function<StampedLock, Long>> readLockers = new ArrayList<>();
+        readLockers.add((sl) -> sl.readLock());
+        readLockers.add((sl) -> readLockInterruptiblyUninterrupted(sl));
+        readLockers.add((sl) -> tryReadLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
+        readLockers.add((sl) -> tryReadLockUninterrupted(sl, 0, DAYS));
+
+        List<BiConsumer<StampedLock, Long>> readUnlockers = new ArrayList<>();
+        readUnlockers.add((sl, stamp) -> sl.unlockRead(stamp));
+        readUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockRead()));
+        readUnlockers.add((sl, stamp) -> sl.asReadLock().unlock());
+        readUnlockers.add((sl, stamp) -> sl.unlock(stamp));
+
+        List<Function<StampedLock, Long>> writeLockers = new ArrayList<>();
+        writeLockers.add((sl) -> sl.writeLock());
+        writeLockers.add((sl) -> writeLockInterruptiblyUninterrupted(sl));
+        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, Long.MIN_VALUE, DAYS));
+        writeLockers.add((sl) -> tryWriteLockUninterrupted(sl, 0, DAYS));
+
+        List<BiConsumer<StampedLock, Long>> writeUnlockers = new ArrayList<>();
+        writeUnlockers.add((sl, stamp) -> sl.unlockWrite(stamp));
+        writeUnlockers.add((sl, stamp) -> assertTrue(sl.tryUnlockWrite()));
+        writeUnlockers.add((sl, stamp) -> sl.asWriteLock().unlock());
+        writeUnlockers.add((sl, stamp) -> sl.unlock(stamp));
+
+
+        for (Function<StampedLock, Long> readLocker : readLockers)
+        for (BiConsumer<StampedLock, Long> readUnlocker : readUnlockers)
+        for (Function<StampedLock, Long> writeLocker : writeLockers)
+        for (BiConsumer<StampedLock, Long> writeUnlocker : writeUnlockers) {
+            final StampedLock sl = new StampedLock();
+            final long stamp = readLocker.apply(sl);
+            assertTrue(stamp != 0L);
+            assertThrows(IllegalMonitorStateException.class,
+                         () -> sl.unlockWrite(stamp));
+            readUnlocker.accept(sl, stamp);
+            assertThrows(IllegalMonitorStateException.class,
+                         () -> sl.unlock(stamp),
+                         () -> sl.unlockRead(stamp),
+                         () -> sl.unlockWrite(stamp));
+            final long writeStamp = writeLocker.apply(sl);
+            assertTrue(writeStamp != 0L);
+            assertTrue(writeStamp != stamp);
+            assertThrows(IllegalMonitorStateException.class,
+                         () -> sl.unlock(stamp),
+                         () -> sl.unlockRead(stamp),
+                         () -> sl.unlockWrite(stamp));
+            writeUnlocker.accept(sl, writeStamp);
+            assertThrows(IllegalMonitorStateException.class,
+                         () -> sl.unlock(stamp),
+                         () -> sl.unlockRead(stamp),
+                         () -> sl.unlockWrite(stamp));
+        }
+    }
+
 }
--- a/test/java/util/jar/JarFile/mrjar/MultiReleaseJarIterators.java	Mon Jul 25 15:09:23 2016 -0700
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,228 +0,0 @@
-/*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-/*
- * @test
- * @bug 8132734 8144062
- * @summary Test the extended API and the aliasing additions in JarFile that
- *          support multi-release jar files
- * @library /lib/testlibrary/java/util/jar
- * @build Compiler JarBuilder CreateMultiReleaseTestJars
- * @run testng MultiReleaseJarIterators
- */
-
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.nio.file.Files;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.jar.JarEntry;
-import java.util.jar.JarFile;
-import java.util.stream.Collectors;
-import java.util.zip.ZipFile;
-
-import org.testng.Assert;
-import org.testng.annotations.AfterClass;
-import org.testng.annotations.BeforeClass;
-import org.testng.annotations.Test;
-
-
-public class MultiReleaseJarIterators {
-
-    static final int MAJOR_VERSION = Runtime.version().major();
-
-    String userdir = System.getProperty("user.dir", ".");
-    File unversioned = new File(userdir, "unversioned.jar");
-    File multirelease = new File(userdir, "multi-release.jar");
-    Map<String,JarEntry> uvEntries = new HashMap<>();
-    Map<String,JarEntry> mrEntries = new HashMap<>();
-    Map<String,JarEntry> baseEntries = new HashMap<>();
-    Map<String,JarEntry> v9Entries = new HashMap<>();
-    Map<String, JarEntry> v10Entries = new HashMap<>();
-
-    @BeforeClass
-    public void initialize() throws Exception {
-        CreateMultiReleaseTestJars creator = new CreateMultiReleaseTestJars();
-        creator.compileEntries();
-        creator.buildUnversionedJar();
-        creator.buildMultiReleaseJar();
-
-        try (JarFile jf = new JarFile(multirelease)) {
-            for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements(); ) {
-                JarEntry je = e.nextElement();
-                String name = je.getName();
-                mrEntries.put(name, je);
-                if (name.startsWith("META-INF/versions/")) {
-                    if (name.startsWith("META-INF/versions/9/")) {
-                        v9Entries.put(name.substring(20), je);
-                    } else if (name.startsWith("META-INF/versions/10/")) {
-                        v10Entries.put(name.substring(21), je);
-                    }
-                } else {
-                    baseEntries.put(name, je);
-                }
-            }
-        }
-        Assert.assertEquals(mrEntries.size(), 14);
-        Assert.assertEquals(baseEntries.size(), 6);
-        Assert.assertEquals(v9Entries.size(), 5);
-        Assert.assertEquals(v10Entries.size(), 3);
-
-        try (JarFile jf = new JarFile(unversioned)) {
-            jf.entries().asIterator().forEachRemaining(je -> uvEntries.put(je.getName(), je));
-        }
-        Assert.assertEquals(uvEntries.size(), 6);
-    }
-
-    @AfterClass
-    public void close() throws IOException {
-        Files.delete(unversioned.toPath());
-        Files.delete(multirelease.toPath());
-    }
-
-    @Test
-    public void testMultiReleaseJar() throws IOException {
-        try (JarFile jf = new JarFile(multirelease, true, ZipFile.OPEN_READ)) {
-            testEnumeration(jf, mrEntries);
-            testStream(jf, mrEntries);
-        }
-
-        try (JarFile jf = new JarFile(multirelease, true, ZipFile.OPEN_READ, JarFile.baseVersion())) {
-            testEnumeration(jf, baseEntries);
-            testStream(jf, baseEntries);
-        }
-
-        try (JarFile jf = new JarFile(multirelease, true, ZipFile.OPEN_READ, Runtime.Version.parse("9"))) {
-            testEnumeration(jf, v9Entries);
-            testStream(jf, v9Entries);
-        }
-
-        try (JarFile jf = new JarFile(multirelease, true, ZipFile.OPEN_READ, Runtime.version())) {
-            Map<String,JarEntry> expectedEntries;
-            switch (MAJOR_VERSION) {
-                case 9:
-                    expectedEntries = v9Entries;
-                    break;
-                case 10:  // won't get here until JDK 10
-                    expectedEntries = v10Entries;
-                    break;
-                default:
-                    expectedEntries = baseEntries;
-                    break;
-            }
-
-            testEnumeration(jf, expectedEntries);
-            testStream(jf, expectedEntries);
-        }
-    }
-
-    @Test
-    public void testUnversionedJar() throws IOException {
-        try (JarFile jf = new JarFile(unversioned, true, ZipFile.OPEN_READ)) {
-            testEnumeration(jf, uvEntries);
-            testStream(jf, uvEntries);
-        }
-
-        try (JarFile jf = new JarFile(unversioned, true, ZipFile.OPEN_READ, JarFile.baseVersion())) {
-            testEnumeration(jf, uvEntries);
-            testStream(jf, uvEntries);
-        }
-
-        try (JarFile jf = new JarFile(unversioned, true, ZipFile.OPEN_READ, Runtime.Version.parse("9"))) {
-            testEnumeration(jf, uvEntries);
-            testStream(jf, uvEntries);
-        }
-
-        try (JarFile jf = new JarFile(unversioned, true, ZipFile.OPEN_READ, Runtime.version())) {
-            testEnumeration(jf, uvEntries);
-            testStream(jf, uvEntries);
-        }
-    }
-
-    private void testEnumeration(JarFile jf, Map<String,JarEntry> expectedEntries) {
-        Map<String, JarEntry> actualEntries = new HashMap<>();
-        for (Enumeration<JarEntry> e = jf.entries(); e.hasMoreElements(); ) {
-            JarEntry je = e.nextElement();
-            actualEntries.put(je.getName(), je);
-        }
-
-        testEntries(jf, actualEntries, expectedEntries);
-    }
-
-
-    private void testStream(JarFile jf, Map<String,JarEntry> expectedEntries) {
-        Map<String,JarEntry> actualEntries = jf.stream().collect(Collectors.toMap(je -> je.getName(), je -> je));
-
-        testEntries(jf, actualEntries, expectedEntries);
-    }
-
-    private void testEntries(JarFile jf, Map<String,JarEntry> actualEntries, Map<String,JarEntry> expectedEntries) {
-        /* For multi-release jar files constructed with a Release object,
-         * actualEntries contain versionedEntries that are considered part of the
-         * public API.  They have a 1-1 correspondence with baseEntries,
-         * so entries that are not part of the public API won't be present,
-         * i.e. those entries with a name that starts with version/PackagePrivate
-         * in this particular jar file (multi-release.jar)
-         */
-
-        Map<String,JarEntry> entries;
-        if (expectedEntries == mrEntries) {
-            Assert.assertEquals(actualEntries.size(), mrEntries.size());
-            entries = mrEntries;
-        } else if (expectedEntries == uvEntries) {
-            Assert.assertEquals(actualEntries.size(), uvEntries.size());
-            entries = uvEntries;
-        } else {
-            Assert.assertEquals(actualEntries.size(), baseEntries.size());  // this is correct
-            entries = baseEntries;
-        }
-
-        entries.keySet().forEach(name -> {
-            JarEntry ee = expectedEntries.get(name);
-            if (ee == null) ee = entries.get(name);
-            JarEntry ae = actualEntries.get(name);
-            try {
-                compare(jf, ae, ee);
-            } catch (IOException x) {
-                throw new RuntimeException(x);
-            }
-        });
-    }
-
-    private void compare(JarFile jf, JarEntry actual, JarEntry expected) throws IOException {
-        byte[] abytes;
-        byte[] ebytes;
-
-        try (InputStream is = jf.getInputStream(actual)) {
-            abytes = is.readAllBytes();
-        }
-
-        try (InputStream is = jf.getInputStream(expected)) {
-            ebytes = is.readAllBytes();
-        }
-
-        Assert.assertEquals(abytes, ebytes);
-    }
-}
--- a/test/java/util/zip/TestExtraTime.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/util/zip/TestExtraTime.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /**
  * @test
- * @bug 4759491 6303183 7012868 8015666 8023713 8068790 8076641 8075526 8130914
+ * @bug 4759491 6303183 7012868 8015666 8023713 8068790 8076641 8075526 8130914 8161942
  * @summary Test ZOS and ZIS timestamp in extra field correctly
  */
 
@@ -32,6 +32,7 @@
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.nio.file.attribute.FileTime;
+import java.time.Instant;
 import java.util.Arrays;
 import java.util.TimeZone;
 import java.util.concurrent.TimeUnit;
@@ -40,37 +41,52 @@
 import java.util.zip.ZipInputStream;
 import java.util.zip.ZipOutputStream;
 
+
+
 public class TestExtraTime {
 
     public static void main(String[] args) throws Throwable{
 
         File src = new File(System.getProperty("test.src", "."), "TestExtraTime.java");
-        if (src.exists()) {
+        if (!src.exists()) {
+            return;
+        }
+
+        TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
+
+        for (byte[] extra : new byte[][] { null, new byte[] {1, 2, 3}}) {
+
+            // ms-dos 1980 epoch problem
+            test0(FileTime.from(10, TimeUnit.MILLISECONDS), null, null, null, extra);
+            // negative epoch time
+            test0(FileTime.from(-100, TimeUnit.DAYS), null, null, null, extra);
+
             long time = src.lastModified();
-            FileTime mtime = FileTime.from(time, TimeUnit.MILLISECONDS);
-            FileTime atime = FileTime.from(time + 300000, TimeUnit.MILLISECONDS);
-            FileTime ctime = FileTime.from(time - 300000, TimeUnit.MILLISECONDS);
-            TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
+            test(FileTime.from(time, TimeUnit.MILLISECONDS),
+                 FileTime.from(time + 300000, TimeUnit.MILLISECONDS),
+                 FileTime.from(time - 300000, TimeUnit.MILLISECONDS),
+                 tz, extra);
 
-            for (byte[] extra : new byte[][] { null, new byte[] {1, 2, 3}}) {
-                test(mtime, null, null, null, extra);
+            // now
+            time = Instant.now().toEpochMilli();
+            test(FileTime.from(time, TimeUnit.MILLISECONDS),
+                 FileTime.from(time + 300000, TimeUnit.MILLISECONDS),
+                 FileTime.from(time - 300000, TimeUnit.MILLISECONDS),
+                 tz, extra);
 
-                // ms-dos 1980 epoch problem
-                test(FileTime.from(10, TimeUnit.MILLISECONDS), null, null, null, extra);
-                // negative epoch time
-                test(FileTime.from(-100, TimeUnit.DAYS), null, null, null, extra);
+            // unix 2038
+            time = 0x80000000L;
+            test(FileTime.from(time, TimeUnit.SECONDS),
+                 FileTime.from(time, TimeUnit.SECONDS),
+                 FileTime.from(time, TimeUnit.SECONDS),
+                 tz, extra);
 
-                // non-default tz
-                test(mtime, null, null, tz, extra);
-
-                test(mtime, atime, null, null, extra);
-                test(mtime, null, ctime, null, extra);
-                test(mtime, atime, ctime, null, extra);
-
-                test(mtime, atime, null, tz, extra);
-                test(mtime, null, ctime, tz, extra);
-                test(mtime, atime, ctime, tz, extra);
-            }
+            // mtime < unix 2038
+            time = 0x7fffffffL;
+            test(FileTime.from(time, TimeUnit.SECONDS),
+                 FileTime.from(time + 30000, TimeUnit.SECONDS),
+                 FileTime.from(time + 30000, TimeUnit.SECONDS),
+                 tz, extra);
         }
 
         testNullHandling();
@@ -80,6 +96,18 @@
 
     static void test(FileTime mtime, FileTime atime, FileTime ctime,
                      TimeZone tz, byte[] extra) throws Throwable {
+        test0(mtime, null, null, null, extra);
+        test0(mtime, null, null, tz, extra);    // non-default tz
+        test0(mtime, atime, null, null, extra);
+        test0(mtime, null, ctime, null, extra);
+        test0(mtime, atime, ctime, null, extra);
+        test0(mtime, atime, null, tz, extra);
+        test0(mtime, null, ctime, tz, extra);
+        test0(mtime, atime, ctime, tz, extra);
+    }
+
+    static void test0(FileTime mtime, FileTime atime, FileTime ctime,
+                     TimeZone tz, byte[] extra) throws Throwable {
         System.out.printf("--------------------%nTesting: [%s]/[%s]/[%s]%n",
                           mtime, atime, ctime);
         TimeZone tz0 = TimeZone.getDefault();
@@ -120,13 +148,14 @@
         Path zpath = Paths.get(System.getProperty("test.dir", "."),
                                "TestExtraTime.zip");
         Files.copy(new ByteArrayInputStream(baos.toByteArray()), zpath);
-        ZipFile zf = new ZipFile(zpath.toFile());
-        ze = zf.getEntry("TestExtraTime.java");
-        // ZipFile read entry from cen, which does not have a/ctime,
-        // for now.
-        check(mtime, null, null, ze, extra);
-        zf.close();
-        Files.delete(zpath);
+        try (ZipFile zf = new ZipFile(zpath.toFile())) {
+            ze = zf.getEntry("TestExtraTime.java");
+            // ZipFile read entry from cen, which does not have a/ctime,
+            // for now.
+            check(mtime, null, null, ze, extra);
+        } finally {
+            Files.delete(zpath);
+        }
     }
 
     static void check(FileTime mtime, FileTime atime, FileTime ctime,
--- a/test/java/util/zip/TestLocalTime.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/java/util/zip/TestLocalTime.java	Tue Jul 26 14:45:11 2016 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8075526 8135108
+ * @bug 8075526 8135108 8155616 8161942
  * @summary Test timestamp via ZipEntry.get/setTimeLocal()
  */
 
@@ -39,14 +39,13 @@
     public static void main(String[] args) throws Throwable{
         try {
             LocalDateTime ldt = LocalDateTime.now();
-            test(getBytes(ldt), ldt);    // now
-
-            ldt = ldt.withYear(1968); test(getBytes(ldt), ldt);
-            ldt = ldt.withYear(1970); test(getBytes(ldt), ldt);
-            ldt = ldt.withYear(1982); test(getBytes(ldt), ldt);
-            ldt = ldt.withYear(2037); test(getBytes(ldt), ldt);
-            ldt = ldt.withYear(2100); test(getBytes(ldt), ldt);
-            ldt = ldt.withYear(2106); test(getBytes(ldt), ldt);
+            test(ldt);    // now
+            test(ldt.withYear(1968));
+            test(ldt.withYear(1970));
+            test(ldt.withYear(1982));
+            test(ldt.withYear(2037));
+            test(ldt.withYear(2100));
+            test(ldt.withYear(2106));
 
             TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
             // dos time does not support < 1980, have to use
@@ -57,10 +56,17 @@
             testWithTZ(tz, ldt.withYear(2106));
 
             // for #8135108
-            ldt = LocalDateTime.of(2100, 12, 06, 12, 34, 34, 973);
-            test(getBytes(ldt), ldt);
-            ldt = LocalDateTime.of(2106, 12, 06, 12, 34, 34, 973);
-            test(getBytes(ldt), ldt);
+            test(LocalDateTime.of(2100, 12, 06, 12, 34, 34, 973));
+            test(LocalDateTime.of(2106, 12, 06, 12, 34, 34, 973));
+
+            // for #8155616
+            test(LocalDateTime.of(2016, 03, 13, 2, 50, 00));  // gap
+            test(LocalDateTime.of(2015, 11, 1,  1, 30, 00));  // overlap
+            test(LocalDateTime.of(1968, 04, 28, 2, 51, 25));
+            test(LocalDateTime.of(1970, 04, 26, 2, 31, 52));
+
+            // for #8161942
+            test(LocalDateTime.of(2200, 04, 26, 2, 31, 52));  // unix 2038
 
         } finally {
             TimeZone.setDefault(tz0);
@@ -73,7 +79,6 @@
         ZipEntry ze = new ZipEntry("TestLocalTime.java");
         ze.setTimeLocal(mtime);
         check(ze, mtime);
-
         zos.putNextEntry(ze);
         zos.write(new byte[] { 1, 2, 3, 4});
         zos.close();
@@ -87,6 +92,10 @@
        test(zbytes, ldt);
     }
 
+    static void test(LocalDateTime ldt) throws Throwable {
+        test(getBytes(ldt), ldt);
+    }
+
     static void test(byte[] zbytes, LocalDateTime expected) throws Throwable {
         System.out.printf("--------------------%nTesting: [%s]%n", expected);
         // ZipInputStream
@@ -113,6 +122,23 @@
         LocalDateTime ldt = ze.getTimeLocal();
         if (ldt.atOffset(ZoneOffset.UTC).toEpochSecond() >> 1
             != expected.atOffset(ZoneOffset.UTC).toEpochSecond() >> 1) {
+            // if the LDT is out of the range of the standard ms-dos date-time
+            // format ( < 1980 ) AND the date-time is within the daylight saving
+            // time gap (which means the LDT is actually "invalid"), the LDT will
+            // be adjusted accordingly when ZipEntry.setTimeLocal() converts the
+            // date-time via ldt -> zdt -> Instant -> FileTime.
+            // See ZonedDateTime.of(LocalDateTime, ZoneId) for more details.
+            if (ldt.getYear() < 1980 || ldt.getYear() > (1980 + 0x7f)) {
+                System.out.println(" Non-MSDOS    ldt : " + ldt);
+                System.out.println("         expected : " + expected);
+                // try to adjust the "expected", assume daylight saving gap
+                expected = ZonedDateTime.of(expected, ZoneId.systemDefault())
+                                        .toLocalDateTime();
+                if (ldt.atOffset(ZoneOffset.UTC).toEpochSecond() >> 1
+                    == expected.atOffset(ZoneOffset.UTC).toEpochSecond() >> 1) {
+                    return;
+                }
+            }
             throw new RuntimeException("Timestamp: storing mtime failed!");
         }
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/net/ssl/templates/SSLSocketSample.java	Tue Jul 26 14:45:11 2016 -0700
@@ -0,0 +1,404 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+// Please run in othervm mode.  SunJSSE does not support dynamic system
+// properties, no way to re-use system properties in samevm/agentvm mode.
+
+/*
+ * @test
+ * @bug 8161106
+ * @summary Improve SSLSocket test template
+ * @run main/othervm SSLSocketSample
+ */
+
+import java.io.*;
+import javax.net.ssl.*;
+import java.net.*;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Template to help speed your client/server tests.
+ */
+public final class SSLSocketSample {
+
+    /*
+     * =============================================================
+     * Set the various variables needed for the tests, then
+     * specify what tests to run on each side.
+     */
+
+    /*
+     * Should we run the client or server in a separate thread?
+     * Both sides can throw exceptions, but do you have a preference
+     * as to which side should be the main thread.
+     */
+    private static final boolean separateServerThread = false;
+
+    /*
+     * Where do we find the keystores?
+     */
+    private static final String pathToStores = "../etc";
+    private static final String keyStoreFile = "keystore";
+    private static final String trustStoreFile = "truststore";
+    private static final String passwd = "passphrase";
+
+    /*
+     * Turn on SSL debugging?
+     */
+    private static final boolean debug = false;
+
+    /*
+     * Is the server ready to serve?
+     */
+    private static final CountDownLatch serverCondition = new CountDownLatch(1);
+
+    /*
+     * Is the client ready to handshake?
+     */
+    private static final CountDownLatch clientCondition = new CountDownLatch(1);
+
+    /*
+     * What's the server port?  Use any free port by default
+     */
+    private volatile int serverPort = 0;
+
+    /*
+     * If the client or server is doing some kind of object creation
+     * that the other side depends on, and that thread prematurely
+     * exits, you may experience a hang.  The test harness will
+     * terminate all hung threads after its timeout has expired,
+     * currently 3 minutes by default, but you might try to be
+     * smart about it....
+     */
+
+    /*
+     * Define the server side of the test.
+     */
+    void doServerSide() throws Exception {
+        SSLServerSocket sslServerSocket;
+
+        // kick start the server side service
+        SSLServerSocketFactory sslssf =
+                (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
+        sslServerSocket =
+                (SSLServerSocket)sslssf.createServerSocket(serverPort);
+
+        serverPort = sslServerSocket.getLocalPort();
+
+        // Signal the client, the server is ready to accept connection.
+        serverCondition.countDown();
+
+
+        // Try to accept a connection in 30 seconds.
+        SSLSocket sslSocket;
+        try {
+            sslServerSocket.setSoTimeout(30000);
+            sslSocket = (SSLSocket)sslServerSocket.accept();
+        } catch (SocketTimeoutException ste) {
+            sslServerSocket.close();
+
+            // Ignore the test case if no connection within 30 seconds.
+            System.out.println(
+                "No incoming client connection in 30 seconds. " +
+                "Ignore in server side.");
+            return;
+        }
+
+        // handle the connection
+        try {
+            // Is it the expected client connection?
+            //
+            // Naughty test cases or third party routines may try to
+            // connection to this server port unintentionally.  In
+            // order to mitigate the impact of unexpected client
+            // connections and avoid intermittent failure, it should
+            // be checked that the accepted connection is really linked
+            // to the expected client.
+            boolean clientIsReady =
+                    clientCondition.await(30L, TimeUnit.SECONDS);
+
+            if (clientIsReady) {
+                // Run the application in server side.
+                runServerApplication(sslSocket);
+            } else {    // Otherwise, ignore
+                // We don't actually care about plain socket connections
+                // for TLS communication testing generally.  Just ignore
+                // the test if the accepted connection is not linked to
+                // the expected client or the client connection timeout
+                // in 30 seconds.
+                System.out.println(
+                        "The client is not the expected one or timeout. " +
+                        "Ignore in server side.");
+            }
+        } finally {
+            sslSocket.close();
+            sslServerSocket.close();
+        }
+    }
+
+    /*
+     * Define the server side application of the test for the specified socket.
+     */
+    void runServerApplication(SSLSocket socket) throws Exception {
+        // here comes the test logic
+        InputStream sslIS = socket.getInputStream();
+        OutputStream sslOS = socket.getOutputStream();
+
+        sslIS.read();
+        sslOS.write(85);
+        sslOS.flush();
+    }
+
+    /*
+     * Define the client side of the test.
+     */
+    void doClientSide() throws Exception {
+
+        // Wait for server to get started.
+        //
+        // The server side takes care of the issue if the server cannot
+        // get started in 90 seconds.  The client side would just ignore
+        // the test case if the serer is not ready.
+        boolean serverIsReady =
+                serverCondition.await(90L, TimeUnit.SECONDS);
+        if (!serverIsReady) {
+            System.out.println(
+                    "The server is not ready yet in 90 seconds. " +
+                    "Ignore in client side.");
+            return;
+        }
+
+        SSLSocketFactory sslsf =
+            (SSLSocketFactory)SSLSocketFactory.getDefault();
+        try (SSLSocket sslSocket = (SSLSocket)sslsf.createSocket()) {
+            try {
+                sslSocket.connect(
+                        new InetSocketAddress("localhost", serverPort), 15000);
+            } catch (IOException ioe) {
+                // The server side may be impacted by naughty test cases or
+                // third party routines, and cannot accept connections.
+                //
+                // Just ignore the test if the connection cannot be
+                // established.
+                System.out.println(
+                        "Cannot make a connection in 15 seconds. " +
+                        "Ignore in client side.");
+                return;
+            }
+
+            // OK, here the client and server get connected.
+
+            // Signal the server, the client is ready to communicate.
+            clientCondition.countDown();
+
+            // There is still a chance in theory that the server thread may
+            // wait client-ready timeout and then quit.  The chance should
+            // be really rare so we don't consider it until it becomes a
+            // real problem.
+
+            // Run the application in client side.
+            runClientApplication(sslSocket);
+        }
+    }
+
+    /*
+     * Define the server side application of the test for the specified socket.
+     */
+    void runClientApplication(SSLSocket socket) throws Exception {
+        InputStream sslIS = socket.getInputStream();
+        OutputStream sslOS = socket.getOutputStream();
+
+        sslOS.write(280);
+        sslOS.flush();
+        sslIS.read();
+    }
+
+    /*
+     * =============================================================
+     * The remainder is just support stuff
+     */
+
+    private volatile Exception serverException = null;
+    private volatile Exception clientException = null;
+
+    public static void main(String[] args) throws Exception {
+        String keyFilename =
+            System.getProperty("test.src", ".") + "/" + pathToStores +
+                "/" + keyStoreFile;
+        String trustFilename =
+            System.getProperty("test.src", ".") + "/" + pathToStores +
+                "/" + trustStoreFile;
+
+        System.setProperty("javax.net.ssl.keyStore", keyFilename);
+        System.setProperty("javax.net.ssl.keyStorePassword", passwd);
+        System.setProperty("javax.net.ssl.trustStore", trustFilename);
+        System.setProperty("javax.net.ssl.trustStorePassword", passwd);
+
+        if (debug) {
+            System.setProperty("javax.net.debug", "all");
+        }
+
+        /*
+         * Start the tests.
+         */
+        new SSLSocketSample();
+    }
+
+    private Thread clientThread = null;
+    private Thread serverThread = null;
+
+    /*
+     * Primary constructor, used to drive remainder of the test.
+     *
+     * Fork off the other side, then do your work.
+     */
+    SSLSocketSample() throws Exception {
+        Exception startException = null;
+        try {
+            if (separateServerThread) {
+                startServer(true);
+                startClient(false);
+            } else {
+                startClient(true);
+                startServer(false);
+            }
+        } catch (Exception e) {
+            startException = e;
+        }
+
+        /*
+         * Wait for other side to close down.
+         */
+        if (separateServerThread) {
+            if (serverThread != null) {
+                serverThread.join();
+            }
+        } else {
+            if (clientThread != null) {
+                clientThread.join();
+            }
+        }
+
+        /*
+         * When we get here, the test is pretty much over.
+         * Which side threw the error?
+         */
+        Exception local;
+        Exception remote;
+
+        if (separateServerThread) {
+            remote = serverException;
+            local = clientException;
+        } else {
+            remote = clientException;
+            local = serverException;
+        }
+
+        Exception exception = null;
+
+        /*
+         * Check various exception conditions.
+         */
+        if ((local != null) && (remote != null)) {
+            // If both failed, return the curthread's exception.
+            local.initCause(remote);
+            exception = local;
+        } else if (local != null) {
+            exception = local;
+        } else if (remote != null) {
+            exception = remote;
+        } else if (startException != null) {
+            exception = startException;
+        }
+
+        /*
+         * If there was an exception *AND* a startException,
+         * output it.
+         */
+        if (exception != null) {
+            if (exception != startException && startException != null) {
+                exception.addSuppressed(startException);
+            }
+            throw exception;
+        }
+
+        // Fall-through: no exception to throw!
+    }
+
+    void startServer(boolean newThread) throws Exception {
+        if (newThread) {
+            serverThread = new Thread() {
+                @Override
+                public void run() {
+                    try {
+                        doServerSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our server thread just died.
+                         *
+                         * Release the client, if not active already...
+                         */
+                        System.out.println("Server died: " + e);
+                        serverException = e;
+                    }
+                }
+            };
+            serverThread.start();
+        } else {
+            try {
+                doServerSide();
+            } catch (Exception e) {
+                System.out.println("Server failed: " + e);
+                serverException = e;
+            }
+        }
+    }
+
+    void startClient(boolean newThread) throws Exception {
+        if (newThread) {
+            clientThread = new Thread() {
+                @Override
+                public void run() {
+                    try {
+                        doClientSide();
+                    } catch (Exception e) {
+                        /*
+                         * Our client thread just died.
+                         */
+                        System.out.println("Client died: " + e);
+                        clientException = e;
+                    }
+                }
+            };
+            clientThread.start();
+        } else {
+            try {
+                doClientSide();
+            } catch (Exception e) {
+                System.out.println("Client failed: " + e);
+                clientException = e;
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/security/auth/login/modules/JaasClientWithDefaultHandler.java	Tue Jul 26 14:45:11 2016 -0700
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package login;
+
+import java.security.Principal;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+import com.sun.security.auth.UnixPrincipal;
+
+public class JaasClientWithDefaultHandler {
+
+    private static final String USER_NAME = "testUser";
+    private static final String LOGIN_CONTEXT = "ModularLoginConf";
+    private static final String CBH_PROP = "auth.login.defaultCallbackHandler";
+
+    public static void main(String[] args) {
+        try {
+            java.security.Security.setProperty(CBH_PROP, args[0]);
+            LoginContext lc = new LoginContext(LOGIN_CONTEXT);
+            lc.login();
+            checkPrincipal(lc, true);
+            lc.logout();
+            checkPrincipal(lc, false);
+        } catch (LoginException le) {
+            throw new RuntimeException(le);
+        }
+        System.out.println("Test passed.");
+
+    }
+
+    /*
+     * Verify principal for the test user.
+     */
+    private static void checkPrincipal(LoginContext loginContext,
+            boolean principalShouldExist) {
+        if (!principalShouldExist) {
+            if (loginContext.getSubject().getPrincipals().size() != 0) {
+                throw new RuntimeException("Test failed. Principal was not "
+                        + "cleared.");
+            }
+            return;
+        }
+        for (Principal p : loginContext.getSubject().getPrincipals()) {
+            if (p instanceof UnixPrincipal
+                    && USER_NAME.equals(p.getName())) {
+                //Proper principal was found, return.
+                return;
+            }
+        }
+        throw new RuntimeException("Test failed. UnixPrincipal "
+                + USER_NAME + " expected.");
+    }
+
+}
--- a/test/javax/security/auth/login/modules/JaasModularClientTest.java	Mon Jul 25 15:09:23 2016 -0700
+++ b/test/javax/security/auth/login/modules/JaasModularClientTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -59,8 +59,7 @@
     private static final Path C_SRC = SRC.resolve("JaasClient.java");
     private static final String C_PKG = "client";
     private static final String C_JAR_NAME = C_PKG + JAR_EXTN;
-    private static final String MC_DEPENDS_ON_AUTO_SERVICE_JAR_NAME = MODULAR
-            + C_PKG + AUTO + JAR_EXTN;
+    private static final String MCN_JAR_NAME = MODULAR + C_PKG + "N" + JAR_EXTN;
     private static final String MC_JAR_NAME = MODULAR + C_PKG + JAR_EXTN;
 
     private static final Path BUILD_DIR = Paths.get(".").resolve("build");
@@ -68,7 +67,7 @@
     private static final Path S_BUILD_DIR = COMPILE_DIR.resolve(S_PKG);
     private static final Path S_WITH_META_DESCR_BUILD_DIR = COMPILE_DIR.resolve(
             S_PKG + DESCRIPTOR);
-    private static final Path C_BUILD_DIR = COMPILE_DIR.resolve(C_PKG);
+    private static final Path C_BLD_DIR = COMPILE_DIR.resolve(C_PKG);
     private static final Path M_BASE_PATH = BUILD_DIR.resolve("mbase");
     private static final Path ARTIFACTS_DIR = BUILD_DIR.resolve("artifacts");
 
@@ -83,8 +82,7 @@
     private static final Path C_ARTIFACTS_DIR = ARTIFACTS_DIR.resolve(C_PKG);
     private static final Path C_JAR = C_ARTIFACTS_DIR.resolve(C_JAR_NAME);
     private static final Path MC_JAR = C_ARTIFACTS_DIR.resolve(MC_JAR_NAME);
-    private static final Path MC_DEPENDS_ON_AUTO_SERVICE_JAR = C_ARTIFACTS_DIR
-            .resolve(MC_DEPENDS_ON_AUTO_SERVICE_JAR_NAME);
+    private static final Path MCN_JAR = C_ARTIFACTS_DIR.resolve(MCN_JAR_NAME);
 
     private static final String MAIN = C_PKG + ".JaasClient";
     private static final String S_INTERFACE
@@ -99,10 +97,7 @@
 
     private static final boolean WITH_S_DESCR = true;
     private static final boolean WITHOUT_S_DESCR = false;
-    private static final String LOGIN_MODULE_NOT_FOUND_MSG
-            = "No LoginModule found";
     private static final String NO_FAILURE = null;
-    private static final Map<String, String> VM_ARGS = new LinkedHashMap<>();
 
     /**
      * Generates Test specific input parameters.
@@ -112,10 +107,10 @@
 
         List<List<Object>> params = new ArrayList<>();
         String[] args = new String[]{};
-        //PARAMETER ORDERS -
-        //client Module Type, Service Module Type,
-        //Service META Descriptor Required,
-        //Expected Failure message, mechanism used to find the provider
+        // PARAMETER ORDERS -
+        // Client Module Type, Service Module Type,
+        // If Service META descriptor Required,
+        // Expected Failure message, Client arguments
         params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.EXPLICIT,
                 WITH_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.EXPLICIT,
@@ -123,7 +118,7 @@
         params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.AUTO,
                 WITH_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.AUTO,
-                WITHOUT_S_DESCR, LOGIN_MODULE_NOT_FOUND_MSG, args));
+                WITHOUT_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.UNNAMED,
                 WITH_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.UNNAMED,
@@ -136,7 +131,7 @@
         params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.AUTO,
                 WITH_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.AUTO,
-                WITHOUT_S_DESCR, LOGIN_MODULE_NOT_FOUND_MSG, args));
+                WITHOUT_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.UNNAMED,
                 WITH_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.UNNAMED,
@@ -149,7 +144,7 @@
         params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.AUTO,
                 WITH_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.AUTO,
-                WITHOUT_S_DESCR, LOGIN_MODULE_NOT_FOUND_MSG, args));
+                WITHOUT_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.UNNAMED,
                 WITH_S_DESCR, NO_FAILURE, args));
         params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.UNNAMED,
@@ -166,29 +161,25 @@
 
         boolean done = true;
         try {
-            VM_ARGS.put("-Duser.language=", "en");
-            VM_ARGS.put("-Duser.region", "US");
-            VM_ARGS.put("-Djava.security.auth.login.config=", SRC.resolve(
-                    "jaas.conf").toFile().getCanonicalPath());
-
             done = CompilerUtils.compile(S_SRC, S_BUILD_DIR);
             done &= CompilerUtils.compile(S_SRC, S_WITH_META_DESCR_BUILD_DIR);
             done &= createMetaInfServiceDescriptor(S_META_DESCR_FPATH, S_IMPL);
-            //Generate regular/modular jars with(out) META-INF
-            //service descriptor
+            // Generate modular/regular jars with(out) META-INF
+            // service descriptor
             generateJar(true, MODULE_TYPE.EXPLICIT, MS_JAR, S_BUILD_DIR, false);
             generateJar(true, MODULE_TYPE.EXPLICIT, MS_WITH_DESCR_JAR,
                     S_WITH_META_DESCR_BUILD_DIR, false);
             generateJar(true, MODULE_TYPE.UNNAMED, S_JAR, S_BUILD_DIR, false);
             generateJar(true, MODULE_TYPE.UNNAMED, S_WITH_DESCRIPTOR_JAR,
                     S_WITH_META_DESCR_BUILD_DIR, false);
-            //Generate regular/modular(depends on explicit/auto service)
-            //jars for client
-            done &= CompilerUtils.compile(C_SRC, C_BUILD_DIR);
-            generateJar(false, MODULE_TYPE.EXPLICIT, MC_JAR, C_BUILD_DIR, true);
-            generateJar(false, MODULE_TYPE.EXPLICIT,
-                    MC_DEPENDS_ON_AUTO_SERVICE_JAR, C_BUILD_DIR, false);
-            generateJar(false, MODULE_TYPE.UNNAMED, C_JAR, C_BUILD_DIR, false);
+            // Compile client source codes.
+            done &= CompilerUtils.compile(C_SRC, C_BLD_DIR);
+            // Generate modular client jar with explicit dependency
+            generateJar(false, MODULE_TYPE.EXPLICIT, MC_JAR, C_BLD_DIR, true);
+            // Generate modular client jar without any dependency
+            generateJar(false, MODULE_TYPE.EXPLICIT, MCN_JAR, C_BLD_DIR, false);
+            // Generate regular client jar
+            generateJar(false, MODULE_TYPE.UNNAMED, C_JAR, C_BLD_DIR, false);
             System.out.format("%nArtifacts generated successfully? %s", done);
             if (!done) {
                 throw new RuntimeException("Artifact generation failed");
@@ -226,9 +217,9 @@
 
         OutputAnalyzer output = null;
         try {
-            //For automated/explicit module type copy the corresponding
-            //jars to module base folder, which will be considered as
-            //module base path during execution.
+            // For automated/explicit module types, copy the corresponding
+            // jars to module base folder, which will be considered as
+            // module base path during execution.
             if (!(cModuleType == MODULE_TYPE.UNNAMED
                     && sModuletype == MODULE_TYPE.UNNAMED)) {
                 copyJarsToModuleBase(cModuleType, cJarPath, M_BASE_PATH);
@@ -237,20 +228,19 @@
 
             System.out.format("%nExecuting java client with required"
                     + " custom service in class/module path.");
-            String mName = getModuleName(cModuleType, cJarPath,
-                    C_PKG);
+            String mName = getModuleName(cModuleType, cJarPath, C_PKG);
             Path cmBasePath = (cModuleType != MODULE_TYPE.UNNAMED
                     || sModuletype != MODULE_TYPE.UNNAMED) ? M_BASE_PATH : null;
             String cPath = buildClassPath(cModuleType, cJarPath, sModuletype,
                     sJarPath);
+            Map<String, String> vmArgs = getVMArgs(sModuletype,
+                    getModuleName(sModuletype, sJarPath, S_PKG));
             output = ProcessTools.executeTestJava(
-                    getJavaCommand(cmBasePath, cPath, mName, MAIN, VM_ARGS,
+                    getJavaCommand(cmBasePath, cPath, mName, MAIN, vmArgs,
                             args)).outputTo(System.out).errorTo(System.out);
         } finally {
-            //clean module path so that the modulepath can hold only
-            //the required jars for next run.
+            // Clean module path to hold required jars for next run.
             cleanModuleBasePath(M_BASE_PATH);
-            System.out.println("--------------------------------------------");
         }
         return output;
     }
@@ -260,9 +250,9 @@
      * based on client/service module type.
      */
     @Override
-    public Path findJarPath(boolean service, MODULE_TYPE moduleType,
+    public Path findJarPath(boolean isService, MODULE_TYPE moduleType,
             boolean addMetaDesc, boolean dependsOnServiceModule) {
-        if (service) {
+        if (isService) {
             if (moduleType == MODULE_TYPE.EXPLICIT) {
                 if (addMetaDesc) {
                     return MS_WITH_DESCR_JAR;
@@ -277,11 +267,12 @@
                 }
             }
         } else {
+            // Choose corresponding client jar using dependent module
             if (moduleType == MODULE_TYPE.EXPLICIT) {
                 if (dependsOnServiceModule) {
                     return MC_JAR;
                 } else {
-                    return MC_DEPENDS_ON_AUTO_SERVICE_JAR;
+                    return MCN_JAR;
                 }
             } else {
                 return C_JAR;
@@ -289,4 +280,20 @@
         }
     }
 
+    /**
+     * VM argument required for the test.
+     */
+    private Map<String, String> getVMArgs(MODULE_TYPE sModuletype,
+            String addModName) throws IOException {
+        final Map<String, String> vmArgs = new LinkedHashMap<>();
+        vmArgs.put("-Duser.language=", "en");
+        vmArgs.put("-Duser.region=", "US");
+        vmArgs.put("-Djava.security.auth.login.config=", SRC.resolve(
+                "jaas.conf").toFile().getCanonicalPath());
+        if (addModName != null && sModuletype == MODULE_TYPE.AUTO) {
+            vmArgs.put("-addmods ", addModName);
+        }
+        return vmArgs;
+    }
+
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/security/auth/login/modules/JaasModularDefaultHandlerTest.java	Tue Jul 26 14:45:11 2016 -0700
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Arrays;
+import java.io.IOException;
+import java.lang.module.ModuleDescriptor;
+import java.util.ArrayList;
+import jdk.testlibrary.ProcessTools;
+import jdk.testlibrary.OutputAnalyzer;
+import org.testng.annotations.BeforeTest;
+
+/**
+ * @test
+ * @bug 8151654
+ * @library /lib/testlibrary
+ * @library /java/security/modules
+ * @build CompilerUtils JarUtils
+ * @summary Test custom JAAS callback handler with all possible modular option.
+ * @run testng JaasModularDefaultHandlerTest
+ */
+public class JaasModularDefaultHandlerTest extends ModularTest {
+
+    private static final Path S_SRC = SRC.resolve("TestCallbackHandler.java");
+    private static final String MODULAR = "M";
+    private static final String S_PKG = "handler";
+    private static final String S_JAR_NAME = S_PKG + JAR_EXTN;
+    private static final String MS_JAR_NAME = MODULAR + S_PKG + JAR_EXTN;
+    private static final String HANDLER = S_PKG + ".TestCallbackHandler";
+
+    private static final Path C_SRC
+            = SRC.resolve("JaasClientWithDefaultHandler.java");
+    private static final Path CL_SRC = SRC.resolve("TestLoginModule.java");
+    private static final String C_PKG = "login";
+    private static final String C_JAR_NAME = C_PKG + JAR_EXTN;
+    private static final String MCN_JAR_NAME
+            = MODULAR + C_PKG + "NoMUse" + JAR_EXTN;
+    private static final String MC_JAR_NAME = MODULAR + C_PKG + JAR_EXTN;
+
+    private static final Path BUILD_DIR = Paths.get(".").resolve("build");
+    private static final Path COMPILE_DIR = BUILD_DIR.resolve("bin");
+    private static final Path S_BUILD_DIR = COMPILE_DIR.resolve(S_PKG);
+    private static final Path C_BLD_DIR = COMPILE_DIR.resolve(C_PKG);
+    private static final Path M_BASE_PATH = BUILD_DIR.resolve("mbase");
+    private static final Path ARTIFACTS_DIR = BUILD_DIR.resolve("artifacts");
+
+    private static final Path S_ARTIFACTS_DIR = ARTIFACTS_DIR.resolve(S_PKG);
+    private static final Path S_JAR = S_ARTIFACTS_DIR.resolve(S_JAR_NAME);
+    private static final Path MS_JAR = S_ARTIFACTS_DIR.resolve(MS_JAR_NAME);
+
+    private static final Path C_ARTIFACTS_DIR = ARTIFACTS_DIR.resolve(C_PKG);
+    private static final Path C_JAR = C_ARTIFACTS_DIR.resolve(C_JAR_NAME);
+    private static final Path MC_JAR = C_ARTIFACTS_DIR.resolve(MC_JAR_NAME);
+    private static final Path MCN_JAR = C_ARTIFACTS_DIR.resolve(MCN_JAR_NAME);
+
+    private static final String MAIN = C_PKG + ".JaasClientWithDefaultHandler";
+    private static final List<String> M_REQUIRED = Arrays.asList("java.base",
+            "jdk.security.auth");
+
+    private static final String CLASS_NOT_FOUND_MSG
+            = "java.lang.ClassNotFoundException: handler.TestCallbackHandler";
+    private static final String NO_FAILURE = null;
+
+    /**
+     * Generates Test specific input parameters.
+     */
+    @Override
+    public Object[][] getTestInput() {
+
+        List<List<Object>> params = new ArrayList<>();
+        String[] args = new String[]{HANDLER};
+        // PARAMETER ORDERS -
+        // Client Module Type, Service Module Type,
+        // Service META Descriptor Required,
+        // Expected Failure message, Client arguments
+        params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.EXPLICIT,
+                false, NO_FAILURE, args));
+        params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.AUTO,
+                false, NO_FAILURE, args));
+        params.add(Arrays.asList(MODULE_TYPE.EXPLICIT, MODULE_TYPE.UNNAMED,
+                false, NO_FAILURE, args));
+
+        params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.EXPLICIT,
+                false, NO_FAILURE, args));
+        params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.AUTO,
+                false, NO_FAILURE, args));
+        params.add(Arrays.asList(MODULE_TYPE.AUTO, MODULE_TYPE.UNNAMED,
+                false, NO_FAILURE, args));
+
+        params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.EXPLICIT,
+                false, NO_FAILURE, args));
+        params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.AUTO,
+                false, NO_FAILURE, args));
+        params.add(Arrays.asList(MODULE_TYPE.UNNAMED, MODULE_TYPE.UNNAMED,
+                false, NO_FAILURE, args));
+        return params.stream().map(p -> p.toArray()).toArray(Object[][]::new);
+    }
+
+    /**
+     * Pre-compile and generate the artifacts required to run this test before
+     * running each test cases.
+     */
+    @BeforeTest
+    public void buildArtifacts() {
+
+        boolean done = true;
+        try {
+            done = CompilerUtils.compile(S_SRC, S_BUILD_DIR);
+            // Generate modular/regular handler jars.
+            generateJar(true, MODULE_TYPE.EXPLICIT, MS_JAR, S_BUILD_DIR, false);
+            generateJar(true, MODULE_TYPE.UNNAMED, S_JAR, S_BUILD_DIR, false);
+            // Compile client source codes.
+            done &= CompilerUtils.compile(C_SRC, C_BLD_DIR);
+            done &= CompilerUtils.compile(CL_SRC, C_BLD_DIR);
+            // Generate modular client jar with explicit dependency
+            generateJar(false, MODULE_TYPE.EXPLICIT, MC_JAR, C_BLD_DIR, true);
+            // Generate modular client jar without any dependency
+            generateJar(false, MODULE_TYPE.EXPLICIT, MCN_JAR, C_BLD_DIR, false);
+            // Generate regular client jar
+            generateJar(false, MODULE_TYPE.UNNAMED, C_JAR, C_BLD_DIR, false);
+            System.out.format("%nArtifacts generated successfully? %s", done);
+            if (!done) {
+                throw new RuntimeException("Artifact generation failed");
+            }
+        } catch (IOException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    /**
+     * Generate modular/regular jar based on module type for this test.
+     */
+    private void generateJar(boolean isService, MODULE_TYPE moduleType,
+            Path jar, Path compilePath, boolean depends) throws IOException {
+
+        ModuleDescriptor mDescriptor = null;
+        if (isService) {
+            mDescriptor = generateModuleDescriptor(isService, moduleType, S_PKG,
+                    S_PKG, null, null, null, M_REQUIRED, depends);
+        } else {
+            mDescriptor = generateModuleDescriptor(isService, moduleType, C_PKG,
+                    C_PKG, null, null, S_PKG, M_REQUIRED, depends);
+        }
+        generateJar(mDescriptor, jar, compilePath);
+    }
+
+    /**
+     * Holds Logic for the test client. This method will get called with each
+     * test parameter.
+     */
+    @Override
+    public OutputAnalyzer executeTestClient(MODULE_TYPE cModuleType,
+            Path cJarPath, MODULE_TYPE sModuletype, Path sJarPath,
+            String... args) throws Exception {
+
+        OutputAnalyzer output = null;
+        try {
+            // For automated/explicit module types, copy the corresponding
+            // jars to module base folder, which will be considered as
+            // module base path during execution.
+            if (!(cModuleType == MODULE_TYPE.UNNAMED
+                    && sModuletype == MODULE_TYPE.UNNAMED)) {
+                copyJarsToModuleBase(cModuleType, cJarPath, M_BASE_PATH);
+                copyJarsToModuleBase(sModuletype, sJarPath, M_BASE_PATH);
+            }
+
+            System.out.format("%nExecuting java client with required"
+                    + " custom service in class/module path.");
+            String mName = getModuleName(cModuleType, cJarPath, C_PKG);
+            Path cmBasePath = (cModuleType != MODULE_TYPE.UNNAMED
+                    || sModuletype != MODULE_TYPE.UNNAMED) ? M_BASE_PATH : null;
+            String cPath = buildClassPath(cModuleType, cJarPath, sModuletype,
+                    sJarPath);
+            Map<String, String> vmArgs = getVMArgs(sModuletype, cModuleType,
+                    getModuleName(sModuletype, sJarPath, S_PKG));
+            output = ProcessTools.executeTestJava(
+                    getJavaCommand(cmBasePath, cPath, mName, MAIN, vmArgs,
+                            args)).outputTo(System.out).errorTo(System.out);
+        } finally {
+            // Clean module path to hold required jars for next run.
+            cleanModuleBasePath(M_BASE_PATH);
+        }
+        return output;
+    }
+
+    /**
+     * Decide the pre-generated client/service jar path for each test case
+     * based on client/service module type.
+     */
+    @Override
+    public Path findJarPath(boolean depends, MODULE_TYPE moduleType,
+            boolean addMetaDesc, boolean dependsOnServiceModule) {
+        if (depends) {
+            if (moduleType == MODULE_TYPE.EXPLICIT) {
+                return MS_JAR;
+            } else {
+                return S_JAR;
+            }
+        } else {
+            // Choose corresponding client jar using dependent module
+            if (moduleType == MODULE_TYPE.EXPLICIT) {
+                if (dependsOnServiceModule) {
+                    return MC_JAR;
+                } else {
+                    return MCN_JAR;
+                }
+            } else {
+                return C_JAR;
+            }
+        }
+    }
+
+    /**
+     * VM argument required for the test.
+     */
+    private Map<String, String> getVMArgs(MODULE_TYPE sModuletype,
+            MODULE_TYPE cModuleType, String addModName) throws IOException {
+        final Map<String, String> vmArgs = new LinkedHashMap<>();
+        vmArgs.put("-Duser.language=", "en");
+        vmArgs.put("-Duser.region=", "US");
+        vmArgs.put("-Djava.security.auth.login.config=", SRC.resolve(
+                "jaas.conf").toFile().getCanonicalPath());
+        if (addModName != null
+                && !(cModuleType == MODULE_TYPE.EXPLICIT
+                && sModuletype == MODULE_TYPE.EXPLICIT)) {
+            vmArgs.put("-addmods ", addModName);
+        }
+        return vmArgs;
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/javax/security/auth/login/modules/TestCallbackHandler.java	Tue Jul 26 14:45:11 2016 -0700
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package handler;
+
+import java.io.IOException;
+import javax.security.auth.callback.Callback;
+import javax.security.auth.callback.CallbackHandler;
+import javax.security.auth.callback.NameCallback;
+import javax.security.auth.callback.PasswordCallback;
+import javax.security.auth.callback.UnsupportedCallbackException;
+
+public class TestCallbackHandler implements CallbackHandler {
+
+    private static final String USER_NAME = "testUser";
+    private static final String PASSWORD = "testPassword";
+
+    @Override
+    public void handle(Callback[] callbacks) throws IOException,
+            UnsupportedCallbackException {
+        System.out.println("TestCallbackHandler will get resolved through"
+                + " auth.login.defaultCallbackHandler property.");
+        for (Callback callback : callbacks) {
+            if (callback instanceof NameCallback) {
+                ((NameCallback) callback).setName(USER_NAME);
+            } else if (callback instanceof PasswordCallback) {
+                ((PasswordCallback) callback).setPassword(
+                        PASSWORD.toCharArray());
+            } else {
+                throw new UnsupportedCallbackException(callback);
+            }
+        }
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000